prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
<|fim_middle|>
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus)) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
<|fim_middle|>
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus)) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
<|fim_middle|>
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus)) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
<|fim_middle|>
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus)) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
<|fim_middle|>
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | self.tick_mark.draw(can, x_pos, y_pos) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
<|fim_middle|>
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1)) |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def <|fim_middle|>(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | check_integrity |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def <|fim_middle|>(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | get_data_range |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def <|fim_middle|>(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | get_legend_entry |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def <|fim_middle|>(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def init():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | draw |
<|file_name|>line_plot.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2000-2005 by Yasushi Saito ([email protected])
#
# Jockey is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# Jockey is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
import tick_mark
import line_style
import pychart_util
import error_bar
import chart_object
import legend
import object_set
import line_plot_doc
import theme
from pychart_types import *
from types import *
default_width = 1.2
line_style_itr = None
_keys = {
'data' : (AnyType, None, pychart_util.data_desc),
'label': (StringType, '???', pychart_util.label_desc),
'data_label_offset': (CoordType, (0, 5),
"""The location of data labels relative to the sample point. Meaningful only when data_label_format != None."""),
'data_label_format': (FormatType, None,
"""The format string for the label printed
beside a sample point.
It can be a `printf' style format string, or
a two-parameter function that takes the (x, y)
values and returns a string. """
+ pychart_util.string_desc),
'xcol' : (IntType, 0, pychart_util.xcol_desc),
'ycol': (IntType, 1, pychart_util.ycol_desc),
'y_error_minus_col': (IntType, 2,
"""The column (within "data") from which the depth of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_error_plus_col': (IntType, -1,
"""The column (within "data") from which the height of the errorbar is extracted. Meaningful only when error_bar != None. <<error_bar>>"""),
'y_qerror_minus_col': (IntType, -1, '<<error_bar>>'),
'y_qerror_plus_col': (IntType, -1, '<<error_bar>>'),
'line_style': (line_style.T, lambda: line_style_itr.next(), pychart_util.line_desc,
"By default, a style is picked from standard styles round-robin. <<line_style>>"),
'tick_mark': (tick_mark.T, None, pychart_util.tick_mark_desc),
'error_bar': (error_bar.T, None,
'The style of the error bar. <<error_bar>>'),
}
class T(chart_object.T):
__doc__ = line_plot_doc.doc
keys = _keys
def check_integrity(self):
assert chart_object.T.check_integrity(self)
##AUTOMATICALLY GENERATED
##END AUTOMATICALLY GENERATED
def get_data_range(self, which):
if which == 'X':
return pychart_util.get_data_range(self.data, self.xcol)
else:
return pychart_util.get_data_range(self.data, self.ycol)
def get_legend_entry(self):
if self.label:
line_style = self.line_style
if not line_style and self.error_bar:
line_style = getattr(self.error_bar, 'line_style', None) or \
getattr(self.error_bar, 'hline_style', None) or \
getattr(self.error_bar, 'vline_style', None)
if not line_style:
raise Exception, 'Line plot has label, but an empty line style and error bar.'
return legend.Entry(line_style=line_style,
tick_mark=self.tick_mark,
fill_style=None,
label=self.label)
return None
def draw(self, ar, can):
# Draw the line
clipbox = theme.adjust_bounding_box([ar.loc[0], ar.loc[1],
ar.loc[0] + ar.size[0],
ar.loc[1] + ar.size[1]]);
can.clip(clipbox[0],clipbox[1],clipbox[2],clipbox[3])
if self.line_style:
points = []
for pair in self.data:
yval = pychart_util.get_sample_val(pair, self.ycol)
xval = pair[self.xcol]
if None not in (xval, yval):
points.append((ar.x_pos(xval), ar.y_pos(yval)))
can.lines(self.line_style, points)
can.endclip()
# Draw tick marks and error bars
can.clip(ar.loc[0] - 10, ar.loc[1] - 10,
ar.loc[0] + ar.size[0] + 10,
ar.loc[1] + ar.size[1] + 10)
for pair in self.data:
x = pair[self.xcol]
y = pychart_util.get_sample_val(pair, self.ycol)
if None in (x, y): continue
x_pos = ar.x_pos(x)
y_pos = ar.y_pos(y)
if self.error_bar:
plus = pair[self.y_error_plus_col or self.y_error_minus_col]
minus = pair[self.y_error_minus_col or self.y_error_plus_col]
if self.y_qerror_minus_col or self.y_qerror_plus_col:
q_plus = pair[self.y_qerror_plus_col or self.y_qerror_minus_col]
q_minus = pair[self.y_qerror_minus_col or self.y_qerror_plus_col]
if None not in (minus,plus,q_minus,q_plus):
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus),
ar.y_pos(y - q_minus),
ar.y_pos(y + q_plus))
else:
if None not in (minus,plus): #PDS
self.error_bar.draw(can, (x_pos, y_pos),
ar.y_pos(y - minus),
ar.y_pos(y + plus))
if self.tick_mark:
self.tick_mark.draw(can, x_pos, y_pos)
if self.data_label_format:
can.show(x_pos + self.data_label_offset[0],
y_pos + self.data_label_offset[1],
'/hC' + pychart_util.apply_format(self.data_label_format, (x, y), 1))
can.endclip()
def <|fim_middle|>():
global line_style_itr
line_styles = object_set.T()
for org_style in line_style.standards.list():
style = line_style.T(width = default_width, color = org_style.color,
dash = org_style.dash)
line_styles.add(style)
line_style_itr = line_styles.iterate()
theme.add_reinitialization_hook(init)
<|fim▁end|> | init |
<|file_name|>shared_cll_8_binary_load_lifter_advanced.py<|end_file_name|><|fim▁begin|>#### NOTICE: THIS FILE IS AUTOGENERATED<|fim▁hole|>
def create(kernel):
result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_cll_8_binary_load_lifter_advanced.iff"
result.attribute_template_id = 3
result.stfName("droid_name","cll_8_binary_load_lifter_crafted_advanced")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result<|fim▁end|> | #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import * |
<|file_name|>shared_cll_8_binary_load_lifter_advanced.py<|end_file_name|><|fim▁begin|>#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
<|fim_middle|>
<|fim▁end|> | result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_cll_8_binary_load_lifter_advanced.iff"
result.attribute_template_id = 3
result.stfName("droid_name","cll_8_binary_load_lifter_crafted_advanced")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
<|file_name|>shared_cll_8_binary_load_lifter_advanced.py<|end_file_name|><|fim▁begin|>#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def <|fim_middle|>(kernel):
result = Creature()
result.template = "object/creature/npc/droid/crafted/shared_cll_8_binary_load_lifter_advanced.iff"
result.attribute_template_id = 3
result.stfName("droid_name","cll_8_binary_load_lifter_crafted_advanced")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result<|fim▁end|> | create |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
<|fim▁hole|>
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)<|fim▁end|> | else:
processed_value = value
return processed_value |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
<|fim_middle|>
<|fim▁end|> | @staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
<|fim_middle|>
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | """
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
<|fim_middle|>
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | """
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
<|fim_middle|>
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | """
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
<|fim_middle|>
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | """
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
<|fim_middle|>
<|fim▁end|> | """
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
<|fim_middle|>
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | return Encoding.to_ascii(value) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
<|fim_middle|>
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | return Encoding.to_unicode(value) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
<|fim_middle|>
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key]) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
<|fim_middle|>
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_key = key.encode('ascii') |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
<|fim_middle|>
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_key = key |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
<|fim_middle|>
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value)) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
<|fim_middle|>
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = value.encode('ascii') |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
<|fim_middle|>
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = value |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
<|fim_middle|>
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key]) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
<|fim_middle|>
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_key = key.decode('utf-8') |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
<|fim_middle|>
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_key = key |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
<|fim_middle|>
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value)) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
<|fim_middle|>
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = value.decode('utf-8') |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
<|fim_middle|>
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | processed_value = value |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
<|fim_middle|>
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | return isinstance(value, str) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
<|fim_middle|>
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | return isinstance(value, bytes) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
<|fim_middle|>
else:
return isinstance(value, str)
<|fim▁end|> | return isinstance(value, unicode) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
<|fim_middle|>
<|fim▁end|> | return isinstance(value, str) |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def <|fim_middle|>(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | normalize |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def <|fim_middle|>(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | to_ascii |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def <|fim_middle|>(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | to_unicode |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def <|fim_middle|>(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def _is_unicode(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | _is_ascii |
<|file_name|>encoding.py<|end_file_name|><|fim▁begin|>
import sys
class Encoding(object):
@staticmethod
def normalize(value):
"""
Normalize value
:param value: The value
:return: The processed value
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return Encoding.to_ascii(value)
else:
return Encoding.to_unicode(value)
@staticmethod
def to_ascii(value):
"""
To ascii
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_unicode(key):
processed_key = key.encode('ascii')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_ascii(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_ascii(value))
# Unicode
elif Encoding._is_unicode(value):
processed_value = value.encode('ascii')
else:
processed_value = value
return processed_value
@staticmethod
def to_unicode(value):
"""
To unicode
:param value: The value
:return: The processed value
"""
# Dict
if isinstance(value, dict):
processed_value = {}
for key in value:
if Encoding._is_ascii(key):
processed_key = key.decode('utf-8')
else:
processed_key = key
processed_value[processed_key] = Encoding.to_unicode(value[key])
# List
elif isinstance(value, list):
processed_value = []
for value in value:
processed_value.append(Encoding.to_unicode(value))
# Unicode
elif Encoding._is_ascii(value):
processed_value = value.decode('utf-8')
else:
processed_value = value
return processed_value
@staticmethod
def _is_ascii(value):
"""
Check if ascii
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, str)
else:
return isinstance(value, bytes)
@staticmethod
def <|fim_middle|>(value):
"""
Check if unicode
:param value: The value
:return: Ascii or not
"""
# Python 2 vs Python 3
if sys.version_info < (3, 0):
return isinstance(value, unicode)
else:
return isinstance(value, str)
<|fim▁end|> | _is_unicode |
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def get(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name)
<|fim▁hole|> LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition']<|fim▁end|> | @expose(content_type="text/plain")
def put(self, workbook_name):
text = request.text
|
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
<|fim_middle|>
<|fim▁end|> | @expose()
def get(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name)
@expose(content_type="text/plain")
def put(self, workbook_name):
text = request.text
LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition'] |
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def get(self, workbook_name):
<|fim_middle|>
@expose(content_type="text/plain")
def put(self, workbook_name):
text = request.text
LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition']
<|fim▁end|> | LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name) |
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def get(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name)
@expose(content_type="text/plain")
def put(self, workbook_name):
<|fim_middle|>
<|fim▁end|> | text = request.text
LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition'] |
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def <|fim_middle|>(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name)
@expose(content_type="text/plain")
def put(self, workbook_name):
text = request.text
LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition']
<|fim▁end|> | get |
<|file_name|>workbook_definition.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pecan import rest
from pecan import expose
from pecan import request
from mistral.openstack.common import log as logging
from mistral.db import api as db_api
from mistral.services import scheduler
LOG = logging.getLogger(__name__)
class WorkbookDefinitionController(rest.RestController):
@expose()
def get(self, workbook_name):
LOG.debug("Fetch workbook definition [workbook_name=%s]" %
workbook_name)
return db_api.workbook_definition_get(workbook_name)
@expose(content_type="text/plain")
def <|fim_middle|>(self, workbook_name):
text = request.text
LOG.debug("Update workbook definition [workbook_name=%s, text=%s]" %
(workbook_name, text))
wb = db_api.workbook_definition_put(workbook_name, text)
scheduler.create_associated_triggers(wb)
return wb['definition']
<|fim▁end|> | put |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for ross project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'jtn=n8&nq9jgir8_z1ck40^c1s22d%=)z5qsm*q(bku*_=^sg&'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'ross.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',<|fim▁hole|> },
},
]
WSGI_APPLICATION = 'ross.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'<|fim▁end|> | 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
], |
<|file_name|>0012_auto_20160212_1210.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('characters', '0011_auto_20160212_1144'),
]
operations = [
migrations.CreateModel(
name='CharacterSpells',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')),
],
options={
'verbose_name': 'Karakt\xe4rers magi',
'verbose_name_plural': 'Karakt\xe4rers magi',
},
),
migrations.AlterModelOptions(
name='spellextras',
options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'},
),
migrations.AlterModelOptions(
name='spellinfo',
options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'},
),
migrations.AddField(
model_name='spellinfo',<|fim▁hole|> ),
migrations.AlterField(
model_name='spellinfo',
name='parent',
field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'),
),
migrations.AddField(
model_name='characterspells',
name='spells',
field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'),
),
]<|fim▁end|> | name='name',
field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'), |
<|file_name|>0012_auto_20160212_1210.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
<|fim_middle|>
<|fim▁end|> | dependencies = [
('characters', '0011_auto_20160212_1144'),
]
operations = [
migrations.CreateModel(
name='CharacterSpells',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('character', models.ForeignKey(verbose_name='Karakt\xe4r', to='characters.Character')),
],
options={
'verbose_name': 'Karakt\xe4rers magi',
'verbose_name_plural': 'Karakt\xe4rers magi',
},
),
migrations.AlterModelOptions(
name='spellextras',
options={'verbose_name': 'Magi extra', 'verbose_name_plural': 'Magi extra'},
),
migrations.AlterModelOptions(
name='spellinfo',
options={'verbose_name': 'Magi information', 'verbose_name_plural': 'Magi information'},
),
migrations.AddField(
model_name='spellinfo',
name='name',
field=models.CharField(default='Magins namn', max_length=256, verbose_name='Namn'),
),
migrations.AlterField(
model_name='spellinfo',
name='parent',
field=models.ForeignKey(verbose_name='Tillh\xf6righet', to='characters.SpellParent'),
),
migrations.AddField(
model_name='characterspells',
name='spells',
field=models.ManyToManyField(to='characters.SpellInfo', verbose_name='Magier och besv\xe4rjelser'),
),
] |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert<|fim▁hole|> alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()<|fim▁end|> | """
|
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
<|fim_middle|>
<|fim▁end|> | """Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all() |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
<|fim_middle|>
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | """Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])] |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
<|fim_middle|>
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | """Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid) |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
<|fim_middle|>
<|fim▁end|> | """Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all() |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
<|fim_middle|>
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | alert = self.service.create(uuid=alert_id, alert=kwargs['alert']) |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
<|fim_middle|>
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | alert = self.service.create(uuid=alert_id) |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
<|fim_middle|>
else:
self.service.remove_all()
<|fim▁end|> | self.service.remove(uuid.UUID(args[0])) |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
<|fim_middle|>
<|fim▁end|> | self.service.remove_all() |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def <|fim_middle|>(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | get |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def <|fim_middle|>(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def delete(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | post |
<|file_name|>alertshandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# Copyright (c) 2022 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Exposes a RESTful interface ."""
import uuid
import empower_core.apimanager.apimanager as apimanager
# pylint: disable=W0223
class AlertsHandler(apimanager.APIHandler):
"""Alerts handler"""
URLS = [r"/api/v1/alerts/?",
r"/api/v1/alerts/([a-zA-Z0-9-]*)/?"]
@apimanager.validate(min_args=0, max_args=1)
def get(self, *args, **kwargs):
"""Lists all the alerts.
Args:
[0], the alert id (optional)
Example URLs:
GET /api/v1/alerts
GET /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
return self.service.alerts \
if not args else self.service.alerts[uuid.UUID(args[0])]
@apimanager.validate(returncode=201, min_args=0, max_args=1)
def post(self, *args, **kwargs):
"""Create a new alert.
Args:
[0], the alert id (optional)
Request:
version: protocol version (1.0)
alert: the alert
"""
alert_id = uuid.UUID(args[0]) if args else uuid.uuid4()
if 'alert' in kwargs:
alert = self.service.create(uuid=alert_id, alert=kwargs['alert'])
else:
alert = self.service.create(uuid=alert_id)
self.set_header("Location", "/api/v1/alerts/%s" % alert.uuid)
@apimanager.validate(returncode=204, min_args=0, max_args=1)
def <|fim_middle|>(self, *args, **kwargs):
"""Delete one or all alerts.
Args:
[0], the alert id (optional)
Example URLs:
DELETE /api/v1/alerts
DELETE /api/v1/alerts/52313ecb-9d00-4b7d-b873-b55d3d9ada26
"""
if args:
self.service.remove(uuid.UUID(args[0]))
else:
self.service.remove_all()
<|fim▁end|> | delete |
<|file_name|>create_proposals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example creates new proposals.
To determine which proposals exist, run get_all_proposals.py.
"""
import uuid
# Import appropriate modules from the client library.
from googleads import ad_manager
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
def main(client, advertiser_id, primary_salesperson_id,
secondary_salesperson_id, primary_trafficker_id):
# Initialize appropriate services.
proposal_service = client.GetService('ProposalService', version='v201811')
network_service = client.GetService('NetworkService', version='v201811')
# Create proposal objects.
proposal = {
'name': 'Proposal #%s' % uuid.uuid4(),
'advertiser': {
'companyId': advertiser_id,
'type': 'ADVERTISER'
},
'primarySalesperson': {
'userId': primary_salesperson_id,
'split': '75000'
},
'secondarySalespeople': [{
'userId': secondary_salesperson_id,
'split': '25000'
}],
'primaryTraffickerId': primary_trafficker_id,
'probabilityOfClose': '100000',
'budget': {
'microAmount': '100000000',
'currencyCode': network_service.getCurrentNetwork()['currencyCode']
},
'billingCap': 'CAPPED_CUMULATIVE',<|fim▁hole|> proposals = proposal_service.createProposals([proposal])
# Display results.
for proposal in proposals:
print ('Proposal with id "%s" and name "%s" was created.'
% (proposal['id'], proposal['name']))
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)<|fim▁end|> | 'billingSource': 'DFP_VOLUME'
}
# Add proposals. |
<|file_name|>create_proposals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example creates new proposals.
To determine which proposals exist, run get_all_proposals.py.
"""
import uuid
# Import appropriate modules from the client library.
from googleads import ad_manager
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
def main(client, advertiser_id, primary_salesperson_id,
secondary_salesperson_id, primary_trafficker_id):
# Initialize appropriate services.
<|fim_middle|>
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)
<|fim▁end|> | proposal_service = client.GetService('ProposalService', version='v201811')
network_service = client.GetService('NetworkService', version='v201811')
# Create proposal objects.
proposal = {
'name': 'Proposal #%s' % uuid.uuid4(),
'advertiser': {
'companyId': advertiser_id,
'type': 'ADVERTISER'
},
'primarySalesperson': {
'userId': primary_salesperson_id,
'split': '75000'
},
'secondarySalespeople': [{
'userId': secondary_salesperson_id,
'split': '25000'
}],
'primaryTraffickerId': primary_trafficker_id,
'probabilityOfClose': '100000',
'budget': {
'microAmount': '100000000',
'currencyCode': network_service.getCurrentNetwork()['currencyCode']
},
'billingCap': 'CAPPED_CUMULATIVE',
'billingSource': 'DFP_VOLUME'
}
# Add proposals.
proposals = proposal_service.createProposals([proposal])
# Display results.
for proposal in proposals:
print ('Proposal with id "%s" and name "%s" was created.'
% (proposal['id'], proposal['name'])) |
<|file_name|>create_proposals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example creates new proposals.
To determine which proposals exist, run get_all_proposals.py.
"""
import uuid
# Import appropriate modules from the client library.
from googleads import ad_manager
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
def main(client, advertiser_id, primary_salesperson_id,
secondary_salesperson_id, primary_trafficker_id):
# Initialize appropriate services.
proposal_service = client.GetService('ProposalService', version='v201811')
network_service = client.GetService('NetworkService', version='v201811')
# Create proposal objects.
proposal = {
'name': 'Proposal #%s' % uuid.uuid4(),
'advertiser': {
'companyId': advertiser_id,
'type': 'ADVERTISER'
},
'primarySalesperson': {
'userId': primary_salesperson_id,
'split': '75000'
},
'secondarySalespeople': [{
'userId': secondary_salesperson_id,
'split': '25000'
}],
'primaryTraffickerId': primary_trafficker_id,
'probabilityOfClose': '100000',
'budget': {
'microAmount': '100000000',
'currencyCode': network_service.getCurrentNetwork()['currencyCode']
},
'billingCap': 'CAPPED_CUMULATIVE',
'billingSource': 'DFP_VOLUME'
}
# Add proposals.
proposals = proposal_service.createProposals([proposal])
# Display results.
for proposal in proposals:
print ('Proposal with id "%s" and name "%s" was created.'
% (proposal['id'], proposal['name']))
if __name__ == '__main__':
# Initialize client object.
<|fim_middle|>
<|fim▁end|> | ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID) |
<|file_name|>create_proposals.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example creates new proposals.
To determine which proposals exist, run get_all_proposals.py.
"""
import uuid
# Import appropriate modules from the client library.
from googleads import ad_manager
ADVERTISER_ID = 'INSERT_ADVERTISER_ID_HERE'
PRIMARY_SALESPERSON_ID = 'INSERT_PRIMARY_SALESPERSON_ID_HERE'
SECONDARY_SALESPERSON_ID = 'INSERT_SECONDARY_SALESPERSON_ID_HERE'
PRIMARY_TRAFFICKER_ID = 'INSERT_PRIMARY_TRAFFICKER_ID_HERE'
def <|fim_middle|>(client, advertiser_id, primary_salesperson_id,
secondary_salesperson_id, primary_trafficker_id):
# Initialize appropriate services.
proposal_service = client.GetService('ProposalService', version='v201811')
network_service = client.GetService('NetworkService', version='v201811')
# Create proposal objects.
proposal = {
'name': 'Proposal #%s' % uuid.uuid4(),
'advertiser': {
'companyId': advertiser_id,
'type': 'ADVERTISER'
},
'primarySalesperson': {
'userId': primary_salesperson_id,
'split': '75000'
},
'secondarySalespeople': [{
'userId': secondary_salesperson_id,
'split': '25000'
}],
'primaryTraffickerId': primary_trafficker_id,
'probabilityOfClose': '100000',
'budget': {
'microAmount': '100000000',
'currencyCode': network_service.getCurrentNetwork()['currencyCode']
},
'billingCap': 'CAPPED_CUMULATIVE',
'billingSource': 'DFP_VOLUME'
}
# Add proposals.
proposals = proposal_service.createProposals([proposal])
# Display results.
for proposal in proposals:
print ('Proposal with id "%s" and name "%s" was created.'
% (proposal['id'], proposal['name']))
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client, ADVERTISER_ID, PRIMARY_SALESPERSON_ID,
SECONDARY_SALESPERSON_ID, PRIMARY_TRAFFICKER_ID)
<|fim▁end|> | main |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod<|fim▁hole|> :param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()<|fim▁end|> | def sweeper( cls ):
""" move cached request to the central request manager
|
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
<|fim_middle|>
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
<|fim_middle|>
<|fim▁end|> | """
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
<|fim_middle|>
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
<|fim_middle|>
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
<|fim_middle|>
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
<|fim_middle|>
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
<|fim_middle|>
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
<|fim_middle|>
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
<|fim_middle|>
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | """ forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
<|fim_middle|>
<|fim▁end|> | """ check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
<|fim_middle|>
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | cls.__requestManager = RPCClient( "RequestManagement/ReqManager" ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
<|fim_middle|>
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
<|fim_middle|>
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | os.mkdir( cls.__cacheDir ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
<|fim_middle|>
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
<|fim_middle|>
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK() |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
<|fim_middle|>
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
<|fim_middle|>
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | gLogger.warn( "setRequest: %s" % forwardable["Message"] ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
<|fim_middle|>
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
<|fim_middle|>
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
<|fim_middle|>
return S_OK()
<|fim▁end|> | return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) ) |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def <|fim_middle|>( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | initializeReqProxyHandler |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def <|fim_middle|>( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | initialize |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def <|fim_middle|>( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | requestManager |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def <|fim_middle|>( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | cacheDir |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def <|fim_middle|>( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | sweeper |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def <|fim_middle|>( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | __saveRequest |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def <|fim_middle|>( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | export_getStatus |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def <|fim_middle|>( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | export_putRequest |
<|file_name|>ReqProxyHandler.py<|end_file_name|><|fim▁begin|>########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: [email protected]
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: [email protected]
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author [email protected]
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def <|fim_middle|>( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
<|fim▁end|> | __forwardable |
<|file_name|>rule_008.py<|end_file_name|><|fim▁begin|>from vsg.rules import token_prefix
from vsg import token
lTokens = []<|fim▁hole|>class rule_008(token_prefix):
'''
This rule checks for valid prefixes on signal identifiers.
Default signal prefix is *s\_*.
|configuring_prefix_and_suffix_rules_link|
**Violation**
.. code-block:: vhdl
signal wr_en : std_logic;
signal rd_en : std_logic;
**Fix**
.. code-block:: vhdl
signal s_wr_en : std_logic;
signal s_rd_en : std_logic;
'''
def __init__(self):
token_prefix.__init__(self, 'signal', '008', lTokens)
self.prefixes = ['s_']
self.solution = 'Signal identifiers'<|fim▁end|> | lTokens.append(token.signal_declaration.identifier)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.