desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Return a list of all classes that are ancestors of *classes*.'
def _all_classes(self, classes):
all_classes = {} def recurse(cls): all_classes[cls] = None for c in cls.__bases__: if (c not in all_classes): recurse(c) for cls in classes: recurse(cls) return all_classes.keys()
'Given a class object, return a fully-qualified name. This works for things I\'ve tested in matplotlib so far, but may not be completely general.'
def class_name(self, cls, parts=0):
module = cls.__module__ if (module == '__builtin__'): fullname = cls.__name__ else: fullname = ('%s.%s' % (module, cls.__name__)) if (parts == 0): return fullname name_parts = fullname.split('.') return '.'.join(name_parts[(- parts):])
'Get all of the class names involved in the graph.'
def get_all_class_names(self):
return [self.class_name(x) for x in self.all_classes]
'Generate a graphviz dot graph from the classes that were passed in to __init__. *fd* is a Python file-like object to write to. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls *graph_options*, *node_options*, *edge_options* are dictionaries containing key/value pairs to pass on a...
def generate_dot(self, fd, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}):
g_options = self.default_graph_options.copy() g_options.update(graph_options) n_options = self.default_node_options.copy() n_options.update(node_options) e_options = self.default_edge_options.copy() e_options.update(edge_options) fd.write(('digraph %s {\n' % name)) fd.write(self._f...
'Run graphviz \'dot\' over this graph, returning whatever \'dot\' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls Raises DotException for any of the many os and installation-related errors that may occur.'
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}):
try: dot = subprocess.Popen((['dot'] + list(args)), stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) except OSError: raise DotException("Could not execute 'dot'. Are you sure you have 'graphviz' installed?") except ValueError: raise Dot...
'Initialize package for parsing Parameters package_name : string Name of the top-level package. *package_name* must be the name of an importable package rst_extension : string, optional Extension for reST files, default \'.rst\' package_skip_patterns : None or sequence of {strings, regexps} Sequence of strings giving ...
def __init__(self, package_name, rst_extension='.rst', package_skip_patterns=None, module_skip_patterns=None):
if (package_skip_patterns is None): package_skip_patterns = ['\\.tests$'] if (module_skip_patterns is None): module_skip_patterns = ['\\.setup$', '\\._'] self.package_name = package_name self.rst_extension = rst_extension self.package_skip_patterns = package_skip_patterns self.mo...
'Set package_name >>> docwriter = ApiDocWriter(\'sphinx\') >>> import sphinx >>> docwriter.root_path == sphinx.__path__[0] True >>> docwriter.package_name = \'docutils\' >>> import docutils >>> docwriter.root_path == docutils.__path__[0] True'
def set_package_name(self, package_name):
self._package_name = package_name self.root_module = __import__(package_name) self.root_path = self.root_module.__path__[0] self.written_modules = None
'Get second token in line >>> docwriter = ApiDocWriter(\'sphinx\') >>> docwriter._get_object_name(" def func(): ") \'func\' >>> docwriter._get_object_name(" class Klass(object): ") \'Klass\' >>> docwriter._get_object_name(" class Klass: ") \'Klass\''
def _get_object_name(self, line):
if line.startswith('cdef'): line = line.split(None, 1)[1] name = line.split()[1].split('(')[0].strip() return name.rstrip(':')
'Convert uri to absolute filepath Parameters uri : string URI of python module to return path for Returns path : None or string Returns None if there is no valid path for this URI Otherwise returns absolute file system path for URI Examples >>> docwriter = ApiDocWriter(\'sphinx\') >>> import sphinx >>> modpath = sphinx...
def _uri2path(self, uri):
if (uri == self.package_name): return os.path.join(self.root_path, '__init__.py') path = uri.replace('.', os.path.sep) path = path.replace((self.package_name + os.path.sep), '') path = os.path.join(self.root_path, path) if os.path.exists((path + '.py')): path += '.py' elif os.pat...
'Convert directory path to uri'
def _path2uri(self, dirpath):
relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, '.')
'Parse module defined in *uri*'
def _parse_module(self, uri):
filename = self._uri2path(uri) if (filename is None): return ([], []) f = open(filename, 'rt') (functions, classes) = self._parse_lines(f) f.close() return (functions, classes)
'Parse lines of text for functions and classes'
def _parse_lines(self, linesource):
functions = [] classes = [] for line in linesource: if (line.startswith('def ') and line.count('(')): name = self._get_object_name(line) if (not name.startswith('_')): functions.append(name) elif line.startswith('class '): name = self...
'Make autodoc documentation template string for a module Parameters uri : string python location of module - e.g \'sphinx.builder\' Returns S : string Contents of API doc'
def generate_api_doc(self, uri):
(functions, classes) = self._parse_module(uri) if ((not len(functions)) and (not len(classes))): print('WARNING: Empty -', uri) return '' uri_short = re.sub(('^%s\\.' % self.package_name), '', uri) ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n' chap_title =...
'Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples >>> dw = ApiDocWriter(\'sphinx\') >>> dw._survives_exclude(\'sphinx.okpkg\', \'package\') True >>> dw.package_skip_patterns.append(\'^\.badpkg$\') >>> dw._survives_exclude(\'sphinx.badpkg\', \'pack...
def _survives_exclude(self, matchstr, match_type):
if (match_type == 'module'): patterns = self.module_skip_patterns elif (match_type == 'package'): patterns = self.package_skip_patterns else: raise ValueError(('Cannot interpret match type "%s"' % match_type)) L = len(self.package_name) if (matchstr[:L] == self.pa...
'Return module sequence discovered from ``self.package_name`` Parameters None Returns mods : sequence Sequence of module names within ``self.package_name`` Examples >>> dw = ApiDocWriter(\'sphinx\') >>> mods = dw.discover_modules() >>> \'sphinx.util\' in mods True >>> dw.package_skip_patterns.append(\'\.util$\') >>> \'...
def discover_modules(self):
modules = [self.package_name] for (dirpath, dirnames, filenames) in os.walk(self.root_path): root_uri = self._path2uri(os.path.join(self.root_path, dirpath)) for dirname in dirnames[:]: package_uri = '.'.join((root_uri, dirname)) if (self._uri2path(package_uri) and self._...
'Generate API reST files. Parameters outdir : string Directory name in which to store files We create automatic filenames for each module Returns None Notes Sets self.written_modules to list of written modules'
def write_api_docs(self, outdir):
if (not os.path.exists(outdir)): os.mkdir(outdir) modules = self.discover_modules() self.write_modules_api(modules, outdir)
'Make a reST API index file from written files Parameters path : string Filename to write index to outdir : string Directory to which to write generated index file froot : string, optional root (filename without extension) of filename to write to Defaults to \'gen\'. We add ``self.rst_extension``. relative_to : string...
def write_index(self, outdir, froot='gen', relative_to=None):
if (self.written_modules is None): raise ValueError('No modules written') path = os.path.join(outdir, (froot + self.rst_extension)) if (relative_to is not None): relpath = outdir.replace((relative_to + os.path.sep), '') else: relpath = outdir idx = open(path, 'wt') ...
'Initialization in the style of Glorot 2010. stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs'
def _glorot_initializer(self, prev_units, num_units, stddev_factor=1.0):
stddev = np.sqrt((stddev_factor / np.sqrt((prev_units * num_units)))) return tf.truncated_normal([prev_units, num_units], mean=0.0, stddev=stddev)
'Initialization in the style of Glorot 2010. stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs'
def _glorot_initializer_conv2d(self, prev_units, num_units, mapsize, stddev_factor=1.0):
stddev = np.sqrt((stddev_factor / ((np.sqrt((prev_units * num_units)) * mapsize) * mapsize))) return tf.truncated_normal([mapsize, mapsize, prev_units, num_units], mean=0.0, stddev=stddev)
'Adds a batch normalization layer to this model. See ArXiv 1502.03167v3 for details.'
def add_batch_norm(self, scale=False):
with tf.variable_scope(self._get_layer_str()): out = tf.contrib.layers.batch_norm(self.get_output(), scale=scale) self.outputs.append(out) return self
'Transforms the output of this network to a 1D tensor'
def add_flatten(self):
with tf.variable_scope(self._get_layer_str()): batch_size = int(self.get_output().get_shape()[0]) out = tf.reshape(self.get_output(), [batch_size, (-1)]) self.outputs.append(out) return self
'Adds a dense linear layer to this model. Uses Glorot 2010 initialization assuming linear activation.'
def add_dense(self, num_units, stddev_factor=1.0):
assert (len(self.get_output().get_shape()) == 2), 'Previous layer must be 2-dimensional (batch, channels)' with tf.variable_scope(self._get_layer_str()): prev_units = self._get_num_inputs() initw = self._glorot_initializer(prev_units, num_units, stddev_factor=stddev_factor) ...
'Adds a sigmoid (0,1) activation function layer to this model.'
def add_sigmoid(self):
with tf.variable_scope(self._get_layer_str()): prev_units = self._get_num_inputs() out = tf.nn.sigmoid(self.get_output()) self.outputs.append(out) return self
'Adds a softmax operation to this model'
def add_softmax(self):
with tf.variable_scope(self._get_layer_str()): this_input = tf.square(self.get_output()) reduction_indices = list(range(1, len(this_input.get_shape()))) acc = tf.reduce_sum(this_input, reduction_indices=reduction_indices, keep_dims=True) out = (this_input / (acc + FLAGS.epsilon)) ...
'Adds a ReLU activation function to this model'
def add_relu(self):
with tf.variable_scope(self._get_layer_str()): out = tf.nn.relu(self.get_output()) self.outputs.append(out) return self
'Adds a ELU activation function to this model'
def add_elu(self):
with tf.variable_scope(self._get_layer_str()): out = tf.nn.elu(self.get_output()) self.outputs.append(out) return self
'Adds a leaky ReLU (LReLU) activation function to this model'
def add_lrelu(self, leak=0.2):
with tf.variable_scope(self._get_layer_str()): t1 = (0.5 * (1 + leak)) t2 = (0.5 * (1 - leak)) out = ((t1 * self.get_output()) + (t2 * tf.abs(self.get_output()))) self.outputs.append(out) return self
'Adds a 2D convolutional layer.'
def add_conv2d(self, num_units, mapsize=1, stride=1, stddev_factor=1.0):
assert ((len(self.get_output().get_shape()) == 4) and 'Previous layer must be 4-dimensional (batch, width, height, channels)') with tf.variable_scope(self._get_layer_str()): prev_units = self._get_num_inputs() initw = self._glorot_initializer_conv2d(prev_units, num_units,...
'Adds a transposed 2D convolutional layer'
def add_conv2d_transpose(self, num_units, mapsize=1, stride=1, stddev_factor=1.0):
assert ((len(self.get_output().get_shape()) == 4) and 'Previous layer must be 4-dimensional (batch, width, height, channels)') with tf.variable_scope(self._get_layer_str()): prev_units = self._get_num_inputs() initw = self._glorot_initializer_conv2d(prev_units, num_units,...
'Adds a residual block as per Arxiv 1512.03385, Figure 3'
def add_residual_block(self, num_units, mapsize=3, num_layers=2, stddev_factor=0.001):
assert ((len(self.get_output().get_shape()) == 4) and 'Previous layer must be 4-dimensional (batch, width, height, channels)') if (num_units != int(self.get_output().get_shape()[3])): self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=1.0) bypass = self.get_output(...
'Adds a bottleneck residual block as per Arxiv 1512.03385, Figure 3'
def add_bottleneck_residual_block(self, num_units, mapsize=3, stride=1, transpose=False):
assert ((len(self.get_output().get_shape()) == 4) and 'Previous layer must be 4-dimensional (batch, width, height, channels)') if ((num_units != int(self.get_output().get_shape()[3])) or (stride != 1)): ms = (1 if (stride == 1) else mapsize) if transpose: self...
'Adds a layer that sums the top layer with the given term'
def add_sum(self, term):
with tf.variable_scope(self._get_layer_str()): prev_shape = self.get_output().get_shape() term_shape = term.get_shape() assert ((prev_shape == term_shape) and "Can't sum terms with a different size") out = tf.add(self.get_output(), term) self.outputs.append(out)...
'Adds a layer that averages the inputs from the previous layer'
def add_mean(self):
with tf.variable_scope(self._get_layer_str()): prev_shape = self.get_output().get_shape() reduction_indices = list(range(len(prev_shape))) assert ((len(reduction_indices) > 2) and "Can't average a (batch, activation) tensor") reduction_indices = reduction_indices[1:(-1...
'Adds a layer that upscales the output by 2x through nearest neighbor interpolation'
def add_upscale(self):
prev_shape = self.get_output().get_shape() size = [(2 * int(s)) for s in prev_shape[1:3]] out = tf.image.resize_nearest_neighbor(self.get_output(), size) self.outputs.append(out) return self
'Returns the output from the topmost layer of the network'
def get_output(self):
return self.outputs[(-1)]
'Returns a variable given its layer and name. The variable must already exist.'
def get_variable(self, layer, name):
scope = self._get_layer_str(layer) collection = tf.get_collection(tf.GraphKeys.VARIABLES, scope=scope) for var in collection: if (var.name[:(-2)] == ((scope + '/') + name)): return var return None
'Returns all variables in the given layer'
def get_all_layer_variables(self, layer):
scope = self._get_layer_str(layer) return tf.get_collection(tf.GraphKeys.VARIABLES, scope=scope)
'Connect to an arbiter daemon Syntax: connect [host]:[port] Ex: for Connecting to server, port 7770 > connect server:7770 Ex: connect to localhost, port 7770 > connect'
def do_connect(self, verbose=False):
if verbose: print ('Connection to %s:%s' % (self.addr, self.port)) ArbiterLink.use_ssl = False self.arb = ArbiterLink({'arbiter_name': self.arb_name, 'address': self.addr, 'port': self.port}) self.arb.fill_default() self.arb.pythonize() self.arb.update_infos() if (not self.arb....
'Get the data in the arbiter for a table and some properties like hosts host_name realm'
def getconf(self, config):
files = [config] conf = Config() conf.read_config_silent = 1 properties = ['host_name', 'use', 'act_depend_of'] hosts = self.arb.get_objects_properties('hosts', properties) svcdep_buf = conf.read_config(files) svc_dep = conf.read_config_buf(svcdep_buf)['servicedependency'] return (hosts,...
'Make tuples mapping service dependencies. Return a list of tuples and need hosts and service dependencies parameter.'
def load_svc_mapping(self, hosts, svc_dep, verbose=False):
r = [] for dep in svc_dep: parent_host_name = self.split_and_merge(dep['host_name']) try: dependent_host_name = self.split_and_merge(dep['dependent_host_name']) except KeyError: dependent_host_name = parent_host_name if verbose: print '' ...
'List imbrication : List_by_services : [ List_by_hosts : [ Service_dependency_tuples : ( ) ] ]'
def make_all_dep_tuples(self, hosts, parent_tuples=[()], dependent_tuples=[[()]]):
res = [] for ptuple in parent_tuples: parent = {'host_name': self.get_dependency_tuple_host_name(ptuple), 'svc_desc': self.get_dependency_tuple_service_description(ptuple)} for dtuple in dependent_tuples: dependent = {'host_name': self.get_dependency_tuple_host_name(dtuple), 'svc_des...
'Search host dependency and make tuple according to it.'
def make_dep_tuple(self, parent, dependent, ptuple, dtuple, res):
try: dependent_host_parent = self.get_host_dependency(dependent['host_object']) if (parent['host_name'] == dependent_host_parent): res = (ptuple, dtuple) except IndexError: if (parent['host_name'] == dependent['host_name']): res = (ptuple, dtuple) return res
'Get parent host_name attribute of host.'
def get_host_dependency(self, dependent_host):
return dependent_host[2][0][0].host_name
'Just get the host name part of a dependency tuple. A dependency tuples is : ( \'service\', \'host_name, service_description\' )'
def get_dependency_tuple_host_name(self, tuple):
return tuple[1].split(',')[0]
'Just get the service description part of a dependency tuple. A dependency tuples is : ( \'service\', \'host_name, service_description\' )'
def get_dependency_tuple_service_description(self, tuple):
return tuple[1].split(',')[1]
'Split a list on comma separator and merge resulting lists into an uniq list then return it'
def split_and_merge(self, list, split=True):
res = [] for elt in list: if split: res += elt.split(',') else: res += elt return res
'Empty value comes from unused config pack and then service dep is created but without nothing...'
def clean_empty_value(self, r):
r_cleaned = [] for elt in r: if (elt != []): r_cleaned.append(elt) return r_cleaned
'Set level of logger and handlers. The logger need the lowest level (see link above)'
def setLevel(self, level):
if (not isinstance(level, int)): level = getattr(logging, level, None) if ((not level) or (not isinstance(level, int))): raise TypeError('log level must be an integer') self.level = min(level, logging.INFO) for handler in self.handlers: if isinstance(handle...
'We load the object where we will put log broks with the \'add\' method'
def load_obj(self, object, name_=None):
global _brokhandler_ _brokhandler_ = BrokHandler(object) if ((name_ is not None) or (self.name is not None)): if (name_ is not None): self.name = name_ for handler in self.handlers: handler.setFormatter(defaultFormatter_named) _brokhandler_.setFormatter(defaul...
'The shinken logging wrapper can write to a local file if needed and return the file descriptor so we can avoid to close it. Add logging to a local log-file. The file will be rotated once a day'
def register_local_log(self, path, level=None, purge_buffer=True):
self.log_set = True if (os.path.exists(path) and (not stat.S_ISREG(os.stat(path).st_mode))): handler = FileHandler(path) else: handler = TimedRotatingFileHandler(path, 'midnight', backupCount=5) if (level is not None): handler.setLevel(level) if (self.name is not None): ...
'Set the output as human format. If the optional parameter `on` is False, the timestamps format will be reset to the default format.'
def set_human_format(self, on=True):
global human_timestamp_log human_timestamp_log = bool(on) for handler in self.handlers: if isinstance(handler, BrokHandler): continue if (self.name is not None): handler.setFormatter(((human_timestamp_log and humanFormatter_named) or defaultFormatter_named)) e...
'Get a unicode from a value'
def stringify(self, val):
if isinstance(val, str): val = val.decode('utf8', 'ignore').replace("'", "''") elif isinstance(val, unicode): val = val.replace("'", "''") else: val = unicode(str(val)) val = val.replace("'", "''") return val
'Create a INSERT query in table with all data of data (a dict)'
def create_insert_query(self, table, data):
query = (u'INSERT INTO %s ' % (self.table_prefix + table)) props_str = u' (' values_str = u' (' i = 0 for prop in data: i += 1 val = data[prop] if isinstance(val, bool): if val: val = 1 else: val = 0 ...
'Create a update query of table with data, and use where data for the WHERE clause'
def create_update_query(self, table, data, where_data):
query = (u'UPDATE %s set ' % (self.table_prefix + table)) query_follow = '' i = 0 for prop in data: if (prop not in where_data): i += 1 val = data[prop] if isinstance(val, bool): if val: val = 1 else...
'Just get an entry'
def fetchone(self):
return self.db_cursor.fetchone()
'Get all entry'
def fetchall(self):
return self.db_cursor.fetchall()
'Get objects from "from" queues and add them. :return: True if we got some objects, False otherwise.'
def get_objects_from_from_queues(self):
had_some_objects = False for queue in self.modules_manager.get_external_from_queues(): while True: try: o = queue.get(block=False) except (Empty, IOError, EOFError) as err: if (not isinstance(err, Empty)): logger.error("An ex...
'Create the database connection TODO: finish (begin :) ) error catch and conf parameters...'
def connect_database(self):
connstr = ('%s/%s@%s' % (self.user, self.password, self.database)) self.db = connect_function(connstr) self.db_cursor = self.db.cursor() self.db_cursor.arraysize = 50
'Execute a query against an Oracle database.'
def execute_query(self, query):
logger.debug('[DBOracle] Execute Oracle query %s\n', query) try: self.db_cursor.execute(query) self.db.commit() except IntegrityError_exp as exp: logger.warning('[DBOracle] Warning: a query raise an integrity error: %s, %s', query, exp) exce...
'Like with the ordinary dict: from a mapping, from an iterable of (key, value) pairs, or from keyword arguments.'
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs) self._sorted_keys = sorted(dict.iterkeys(self))
'D.__iter__() <==> iter(D) <==> D.iterkeys() -> an iterator over sorted keys (add reverse=True for reverse ordering).'
def __iter__(self, reverse=False):
if reverse: return reversed(self._sorted_keys) else: return iter(self._sorted_keys)
'D.itervalues() -> an iterator over values sorted by keys (add reverse=True for reverse ordering).'
def itervalues(self, reverse=False):
return (self[key] for key in self.iterkeys(reverse))
'D.iteritems() -> an iterator over (key, value) pairs sorted by keys (add reverse=True for reverse ordering).'
def iteritems(self, reverse=False):
return ((key, self[key]) for key in self.iterkeys(reverse))
'D.keys() -> a sorted list of keys (add reverse=True for reverse ordering).'
def keys(self, reverse=False):
return list(self.iterkeys(reverse))
'D.values() -> a list of values sorted by keys (add reverse=True for reverse ordering).'
def values(self, reverse=False):
return list(self.itervalues(reverse))
'D.items() -> a list of (key, value) pairs sorted by keys (add reverse=True for reverse ordering).'
def items(self, reverse=False):
return list(self.iteritems(reverse))
'D.copy() -> a shallow copy of D (still as a SortedDict).'
def copy(self):
return self.__class__(self)
'D.popitem() -> (k, v). Remove and return a (key, value) pair with the largest key; raise KeyError if D is empty.'
def popitem(self):
try: key = self._sorted_keys.pop() except IndexError: raise KeyError('popitem(): dictionary is empty') else: return (key, dict.pop(self, key))
'D.largest_key() -> the largest key; raise KeyError if D is empty.'
def largest_key(self):
try: return self._sorted_keys[(-1)] except IndexError: raise KeyError('largest_key(): dictionary is empty')
'D.largest_item() -> a (key, value) pair with the largest key; raise KeyError if D is empty.'
def largest_item(self):
key = self.largest_key() return (key, self[key])
'D.smallest_key() -> the smallest key; raise KeyError if D is empty.'
def smallest_key(self):
try: return self._sorted_keys[0] except IndexError: raise KeyError('smallest_key(): dictionary is empty')
'D.smallest_item() -> a (key, value) pair with the smallest key; raise KeyError if D is empty.'
def smallest_item(self):
key = self.smallest_key() return (key, self[key])
'Instanciate a new module. There can be many instance of the same type. \'mod_conf\' is module configuration object for this new module instance.'
def __init__(self, mod_conf):
self.myconf = mod_conf self.name = mod_conf.get_name() self.modules = getattr(mod_conf, 'modules', []) self.props = mod_conf.properties.copy() self.interrupted = False self.properties = self.props self.is_external = self.props.get('external', False) self.phases = self.props.get('phases',...
'Handle this module "post" init ; just before it\'ll be started. Like just open necessaries file(s), database(s), or whatever the module will need.'
def init(self):
pass
'The manager is None on android, but a true Manager() elsewhere Create the shared queues that will be used by shinken daemon process and this module process. But clear queues if they were already set before recreating new one.'
def create_queues(self, manager=None):
self.clear_queues(manager) if (not manager): self.from_q = Queue() self.to_q = Queue() else: self.from_q = manager.Queue() self.to_q = manager.Queue()
'Release the resources associated to the queues of this instance'
def clear_queues(self, manager):
for q in (self.to_q, self.from_q): if (q is None): continue if (not manager): q.close() q.join_thread() self.to_q = self.from_q = None
'Sometime terminate() is not enough, we must "help" external modules to die...'
def __kill(self):
if (os.name == 'nt'): self.process.terminate() else: os.kill(self.process.pid, signal.SIGTERM) time.sleep(1) if self.process.is_alive(): os.kill(self.process.pid, signal.SIGKILL)
'Request the module process to stop and release it'
def stop_process(self):
if self.process: logger.info("I'm stopping module %r (pid=%s)", self.get_name(), self.process.pid) self.process.terminate() self.process.join(timeout=1) if self.process.is_alive(): logger.warning('%r is still alive normal kill, I help i...
'The classic has: do we have a prop or not?'
def has(self, prop):
return hasattr(self, prop)
'Request the module to manage the given brok. There a lot of different possible broks to manage.'
def manage_brok(self, brok):
manage = getattr(self, (('manage_' + brok.type) + '_brok'), None) if manage: brok.prepare() return manage(brok)
'Called just before the module will exit Put in this method all you need to cleanly release all open resources used by your module'
def do_stop(self):
pass
'For external modules only: implement in this method the body of you main loop'
def do_loop_turn(self):
raise NotImplementedError()
'module "main" method. Only used by external modules.'
def _main(self):
self.set_proctitle(self.name) if shinken.http_daemon.daemon_inst: shinken.http_daemon.daemon_inst.shutdown() self.set_signal_handler() logger.info('[%s[%d]]: Now running..', self.name, os.getpid()) self.main() self.do_stop() logger.info('[%s]: exiting now..', self.name)
'return a copy of the check but just what is important for execution So we remove the ref and all'
def copy_shell(self):
return self.copy_shell__(Check('', '', '', '', '', id=self.id))
'Look for a manager function for a brok, and call it'
def manage_brok(self, brok):
manage = getattr(self, (('manage_' + brok.type) + '_brok'), None) if (manage and self.want_brok(brok)): if (brok.type not in ('service_next_schedule', 'host_next_schedule', 'service_check_result', 'host_check_result', 'update_service_status', 'update_host_status', 'update_poller_status', 'update_broker_...
'This can be used by derived classes to compare the data in the brok with the object which will be updated by these data. For example, it is possible to find out in this method whether the state of a host or service has changed.'
def before_after_hook(self, brok, obj):
pass
':type scheduler_daemon: shinken.daemons.schedulerdaemon.Shinken'
def __init__(self, scheduler_daemon):
self.sched_daemon = scheduler_daemon self.must_run = True self.waiting_results_lock = threading.RLock() self.waiting_results = [] self.recurrent_works = {0: ('update_downtimes_and_comments', self.update_downtimes_and_comments, 1), 1: ('schedule', self.schedule, 1), 2: ('consume_results', self.consum...
'Same behavior than Daemon.get_objects_from_from_queues().'
def get_objects_from_from_queues(self):
return self.sched_daemon.get_objects_from_from_queues()
'We want to get the command and the args with ! splitting. but don\'t forget to protect against the \! to do not split them'
def get_command_and_args(self):
p_call = self.call.replace('\\!', '___PROTECT_EXCLAMATION___') tab = p_call.split('!') self.command = tab[0] self.args = [s.replace('___PROTECT_EXCLAMATION___', '!') for s in tab[1:]]
'Call by pickle to dataify the comment because we DO NOT WANT REF in this pickleisation!'
def __getstate__(self):
cls = self.__class__ res = {'id': self.id} for prop in cls.properties: if hasattr(self, prop): res[prop] = getattr(self, prop) if (self.command and (not isinstance(self.command, basestring))): res['command'] = self.command.get_name() elif (self.command and isinstance(self...
'Inverted function of getstate'
def __setstate__(self, state):
cls = self.__class__ if isinstance(state, tuple): self.__setstate_pre_1_0__(state) return self.id = state['id'] for prop in cls.properties: if (prop in state): setattr(self, prop, state[prop])
'In 1.0 we move to a dict save. Before, it was a tuple save, like ({\'id\': 11}, {\'poller_tag\': \'None\', \'reactionner_tag\': \'None\', \'command_line\': u\'/usr/local/nagios/bin/rss-multiuser\', \'module_type\': \'fork\', \'command_name\': u\'notify-by-rss\'})'
def __setstate_pre_1_0__(self, state):
for d in state: for (k, v) in d.items(): setattr(self, k, v)
'arb_satmap is the satellitemap in current context: - A SatelliteLink is owned by an Arbiter - satellitemap attribute of SatelliteLink is the map defined IN THE satellite configuration but for creating connections, we need the have the satellitemap of the Arbiter'
def set_arbiter_satellitemap(self, satellitemap):
self.arb_satmap = {'address': self.address, 'port': self.port, 'use_ssl': self.use_ssl, 'hard_ssl_name_check': self.hard_ssl_name_check} self.arb_satmap.update(satellitemap)
'fill the macro dict will all value from self.resource_macros_names'
def fill_resource_macros_names_macros(self):
properties = self.__class__.properties macros = self.__class__.macros for macro_name in self.resource_macros_names: properties[(('$' + macro_name) + '$')] = StringProp(default='') macros[macro_name] = (('$' + macro_name) + '$')
'Create real \'object\' from dicts of prop/value'
def create_objects(self, raw_objects):
types_creations = self.__class__.types_creations early_created_types = self.__class__.early_created_types self.add_ghost_objects(raw_objects) for t in types_creations: if (t not in early_created_types): self.create_objects_for_type(raw_objects, t)
'Prepare the arbiter for early operations'
def early_arbiter_linking(self):
if (len(self.arbiters) == 0): logger.warning('There is no arbiter, I add one in localhost:7770') a = ArbiterLink({'arbiter_name': 'Default-Arbiter', 'host_name': socket.gethostname(), 'address': 'localhost', 'port': '7770', 'spare': '0'}) self.arbiters = ArbiterLinks(...
'Make \'links\' between elements, like a host got a services list with all it\'s services in it'
def linkify(self):
self.services.optimize_service_search(self.hosts) self.linkify_one_command_with_commands(self.commands, 'ocsp_command') self.linkify_one_command_with_commands(self.commands, 'ochp_command') self.linkify_one_command_with_commands(self.commands, 'host_perfdata_command') self.linkify_one_command_with_c...
'Sets services and hosts initial states.'
def set_initial_state(self):
self.hosts.set_initial_state() self.services.set_initial_state()
'Create some \'modules\' from all nagios parameters if they are set and the modules are not created'
def hack_old_nagios_parameters(self):
mod_to_add = [] mod_to_add_to_schedulers = [] if (hasattr(self, 'status_file') and (self.status_file != '') and hasattr(self, 'object_cache_file')): got_status_dat_module = self.got_broker_module_type_defined('status_dat') if (not got_status_dat_module): data = {'object_cache_fil...
'Create some \'modules\' from all nagios parameters if they are set and the modules are not created'
def hack_old_nagios_parameters_for_arbiter(self):
mod_to_add = [] if (getattr(self, 'command_file', '') != ''): got_named_pipe_module = self.got_arbiter_module_type_defined('named_pipe') if (not got_named_pipe_module): data = {'command_file': self.command_file, 'module_name': 'NamedPipe-Autogenerated', 'module_type': 'named_pipe'} ...