Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def linkify_templates(self):
# First we create a list of all templates
for i in itertools.chain(iter(list(self.items.values())),
iter(list(self.templates.values()))):
self.linkify_item_templates(i)
... | [
"\n Link all templates, and create the template graph too\n\n :return: None\n "
] |
Please provide a description of the function:def is_correct(self):
# we are ok at the beginning. Hope we are still ok at the end...
valid = True
# Better check individual items before displaying the global items list errors and warnings
for i in self:
# Alias and di... | [
"\n Check if the items list configuration is correct ::\n\n * check if duplicate items exist in the list and warn about this\n * set alias and display_name property for each item in the list if they do not exist\n * check each item in the list\n * log all previous warnings\n ... |
Please provide a description of the function:def serialize(self):
res = {}
for key, item in list(self.items.items()):
res[key] = item.serialize()
return res | [
"This function serialize items into a simple dict object.\n It is used when transferring data to other daemons over the network (http)\n\n Here is the generic function that simply serialize each item of the items object\n\n :return: Dictionary containing item's uuid as key and item as value\n ... |
Please provide a description of the function:def apply_partial_inheritance(self, prop):
for i in itertools.chain(iter(list(self.items.values())),
iter(list(self.templates.values()))):
self.get_property_by_inheritance(i, prop)
# If a "null" attrib... | [
"\n Define property with inheritance value of the property\n\n :param prop: property\n :type prop: str\n :return: None\n "
] |
Please provide a description of the function:def apply_inheritance(self):
# We check for all Class properties if the host has it
# if not, it check all host templates for a value
cls = self.inner_class
for prop in cls.properties:
self.apply_partial_inheritance(prop)
... | [
"\n For all items and templates inherit properties and custom variables.\n\n :return: None\n "
] |
Please provide a description of the function:def linkify_with_contacts(self, contacts):
for i in self:
if not hasattr(i, 'contacts'):
continue
links_list = strip_and_uniq(i.contacts)
new = []
for name in [e for e in links_list if e]:
... | [
"\n Link items with contacts items\n\n :param contacts: all contacts object\n :type contacts: alignak.objects.contact.Contacts\n :return: None\n "
] |
Please provide a description of the function:def linkify_with_escalations(self, escalations):
for i in self:
if not hasattr(i, 'escalations'):
continue
links_list = strip_and_uniq(i.escalations)
new = []
for name in [e for e in links_list... | [
"\n Link with escalations\n\n :param escalations: all escalations object\n :type escalations: alignak.objects.escalation.Escalations\n :return: None\n "
] |
Please provide a description of the function:def explode_contact_groups_into_contacts(item, contactgroups):
if not hasattr(item, 'contact_groups'):
return
# TODO : See if we can remove this if
cgnames = ''
if item.contact_groups:
if isinstance(item.conta... | [
"\n Get all contacts of contact_groups and put them in contacts container\n\n :param item: item where have contact_groups property\n :type item: object\n :param contactgroups: all contactgroups object\n :type contactgroups: alignak.objects.contactgroup.Contactgroups\n :retu... |
Please provide a description of the function:def linkify_with_timeperiods(self, timeperiods, prop):
for i in self:
if not hasattr(i, prop):
continue
tpname = getattr(i, prop).strip()
# some default values are '', so set None
if not tpname... | [
"\n Link items with timeperiods items\n\n :param timeperiods: all timeperiods object\n :type timeperiods: alignak.objects.timeperiod.Timeperiods\n :param prop: property name\n :type prop: str\n :return: None\n "
] |
Please provide a description of the function:def linkify_with_checkmodulations(self, checkmodulations):
for i in self:
if not hasattr(i, 'checkmodulations'):
continue
links_list = strip_and_uniq(i.checkmodulations)
new = []
for name in [e... | [
"\n Link checkmodulation object\n\n :param checkmodulations: checkmodulations object\n :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations\n :return: None\n "
] |
Please provide a description of the function:def linkify_s_by_module(self, modules):
for i in self:
links_list = strip_and_uniq(i.modules)
new = []
for name in [e for e in links_list if e]:
module = modules.find_by_name(name)
if modul... | [
"\n Link modules to items\n\n :param modules: Modules object (list of all the modules found in the configuration)\n :type modules: alignak.objects.module.Modules\n :return: None\n "
] |
Please provide a description of the function:def evaluate_hostgroup_expression(expr, hosts, hostgroups, look_in='hostgroups'):
# Maybe exp is a list, like numerous hostgroups entries in a service, link them
if isinstance(expr, list):
expr = '|'.join(expr)
if look_in == 'host... | [
"\n Evaluate hostgroup expression\n\n :param expr: an expression\n :type expr: str\n :param hosts: hosts object (all hosts)\n :type hosts: alignak.objects.host.Hosts\n :param hostgroups: hostgroups object (all hostgroups)\n :type hostgroups: alignak.objects.hostgroup... |
Please provide a description of the function:def get_hosts_from_hostgroups(hgname, hostgroups):
if not isinstance(hgname, list):
hgname = [e.strip() for e in hgname.split(',') if e.strip()]
host_names = []
for name in hgname:
hostgroup = hostgroups.find_by_name... | [
"\n Get hosts of hostgroups\n\n :param hgname: hostgroup name\n :type hgname: str\n :param hostgroups: hostgroups object (all hostgroups)\n :type hostgroups: alignak.objects.hostgroup.Hostgroups\n :return: list of hosts\n :rtype: list\n "
] |
Please provide a description of the function:def explode_host_groups_into_hosts(self, item, hosts, hostgroups):
hnames_list = []
# Gets item's hostgroup_name
hgnames = getattr(item, "hostgroup_name", '') or ''
# Defines if hostgroup is a complex expression
# Expands hos... | [
"\n Get all hosts of hostgroups and add all in host_name container\n\n :param item: the item object\n :type item: alignak.objects.item.Item\n :param hosts: hosts object\n :type hosts: alignak.objects.host.Hosts\n :param hostgroups: hostgroups object\n :type hostgroup... |
Please provide a description of the function:def no_loop_in_parents(self, attr1, attr2):
# pylint: disable=too-many-branches
# Ok, we say "from now, no loop :) "
# in_loop = []
# Create parent graph
parents = Graph()
# Start with all items as nodes
for ... | [
"\n Find loop in dependencies.\n For now, used with the following attributes :\n :(self, parents):\n host dependencies from host object\n :(host_name, dependent_host_name):\\\n host dependencies from hostdependencies object\n :(service_description, dependent_... |
Please provide a description of the function:def get_property_by_inheritance(self, obj, prop):
# pylint: disable=too-many-branches, too-many-nested-blocks
if prop == 'register':
# We do not inherit the register property
return None
# If I have the property, I ta... | [
"\n Get the property asked in parameter to this object or from defined templates of this\n object\n\n todo: rewrite this function which is really too complex!\n\n :param obj: the object to search the property\n :type obj: alignak.objects.item.Item\n :param prop: name of pro... |
Please provide a description of the function:def get_customs_properties_by_inheritance(self, obj):
for t_id in obj.templates:
template = self.templates[t_id]
tpl_cv = self.get_customs_properties_by_inheritance(template)
if tpl_cv:
for prop in tpl_cv:
... | [
"\n Get custom properties from the templates defined in this object\n\n :param obj: the oject to search the property\n :type obj: alignak.objects.item.Item\n :return: list of custom properties\n :rtype: list\n "
] |
Please provide a description of the function:def add_edge(self, from_node, to_node):
# Maybe to_node is unknown
if to_node not in self.nodes:
self.add_node(to_node)
try:
self.nodes[from_node]["sons"].append(to_node)
# If from_node does not exist, add it ... | [
"Add edge between two node\n The edge is oriented\n\n :param from_node: node where edge starts\n :type from_node: object\n :param to_node: node where edge ends\n :type to_node: object\n :return: None\n "
] |
Please provide a description of the function:def loop_check(self):
in_loop = []
# Add the tag for dfs check
for node in list(self.nodes.values()):
node['dfs_loop_status'] = 'DFS_UNCHECKED'
# Now do the job
for node_id, node in self.nodes.items():
... | [
"Check if we have a loop in the graph\n\n :return: Nodes in loop\n :rtype: list\n "
] |
Please provide a description of the function:def dfs_loop_search(self, root):
# Make the root temporary checked
self.nodes[root]['dfs_loop_status'] = 'DFS_TEMPORARY_CHECKED'
# We are scanning the sons
for child in self.nodes[root]["sons"]:
child_status = self.nodes[... | [
"Main algorithm to look for loop.\n It tags nodes and find ones stuck in loop.\n\n * Init all nodes with DFS_UNCHECKED value\n * DFS_TEMPORARY_CHECKED means we found it once\n * DFS_OK : this node (and all sons) are fine\n * DFS_NEAR_LOOP : One problem was found in of of the son\n... |
Please provide a description of the function:def get_accessibility_packs(self):
packs = []
# Add the tag for dfs check
for node in list(self.nodes.values()):
node['dfs_loop_status'] = 'DFS_UNCHECKED'
for node_id, node in self.nodes.items():
# Run the dfs... | [
"Get accessibility packs of the graph:\n in one pack element are related in a way. Between packs, there is no relation at all.\n TODO: Make it work for directional graph too\n Because for now, edge must be father->son AND son->father\n\n :return: packs of nodes\n :rtype: list\n ... |
Please provide a description of the function:def dfs_get_all_childs(self, root):
self.nodes[root]['dfs_loop_status'] = 'DFS_CHECKED'
ret = set()
# Me
ret.add(root)
# And my sons
ret.update(self.nodes[root]['sons'])
for child in self.nodes[root]['sons']:... | [
"Recursively get all sons of this node\n\n :param root: node to get sons\n :type root:\n :return: sons\n :rtype: list\n "
] |
Please provide a description of the function:def identity(self):
res = self.app.get_id()
res.update({"start_time": self.start_time})
res.update({"running_id": self.running_id})
return res | [
"Get the daemon identity\n\n This will return an object containing some properties:\n - alignak: the Alignak instance name\n - version: the Alignak version\n - type: the daemon type\n - name: the daemon name\n\n :return: daemon identity\n :rtype: dict\n "
] |
Please provide a description of the function:def api(self):
functions = [x[0]for x in inspect.getmembers(self, predicate=inspect.ismethod)
if not x[0].startswith('_')]
full_api = {
'doc': u"When posting data you have to use the JSON format.",
'api':... | [
"List the methods available on the daemon Web service interface\n\n :return: a list of methods and parameters\n :rtype: dict\n "
] |
Please provide a description of the function:def stop_request(self, stop_now='0'):
self.app.interrupted = (stop_now == '1')
self.app.will_stop = True
return True | [
"Request the daemon to stop\n\n If `stop_now` is set to '1' the daemon will stop now. Else, the daemon\n will enter the stop wait mode. In this mode the daemon stops its activity and\n waits until it receives a new `stop_now` request to stop really.\n\n :param stop_now: stop now or go to... |
Please provide a description of the function:def get_log_level(self):
level_names = {
logging.DEBUG: 'DEBUG', logging.INFO: 'INFO', logging.WARNING: 'WARNING',
logging.ERROR: 'ERROR', logging.CRITICAL: 'CRITICAL'
}
alignak_logger = logging.getLogger(ALIGNAK_LOGGE... | [
"Get the current daemon log level\n\n Returns an object with the daemon identity and a `log_level` property.\n\n running_id\n :return: current log level\n :rtype: str\n "
] |
Please provide a description of the function:def set_log_level(self, log_level=None):
if log_level is None:
log_level = cherrypy.request.json['log_level']
if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
return {'_status': u'ERR',
... | [
"Set the current log level for the daemon\n\n The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]\n\n In case of any error, this function returns an object containing some properties:\n '_status': 'ERR' because of the error\n `_message`: some more explanations ab... |
Please provide a description of the function:def stats(self, details=False):
if details is not False:
details = bool(details)
res = self.identity()
res.update(self.app.get_daemon_stats(details=details))
return res | [
"Get statistics and information from the daemon\n\n Returns an object with the daemon identity, the daemon start_time\n and some extra properties depending upon the daemon type.\n\n All daemons provide these ones:\n - program_start: the Alignak start timestamp\n - spare: to indica... |
Please provide a description of the function:def _wait_new_conf(self):
with self.app.conf_lock:
logger.debug("My Arbiter wants me to wait for a new configuration.")
# Clear can occur while setting up a new conf and lead to error.
self.app.schedulers.clear()
... | [
"Ask the daemon to drop its configuration and wait for a new one\n\n :return: None\n "
] |
Please provide a description of the function:def _push_configuration(self, pushed_configuration=None):
if pushed_configuration is None:
confs = cherrypy.request.json
pushed_configuration = confs['conf']
# It is safer to lock this part
with self.app.conf_lock:
... | [
"Send a new configuration to the daemon\n\n This function is not intended for external use. It is quite complex to\n build a configuration for a daemon and it is the arbiter dispatcher job ;)\n\n :param pushed_configuration: new conf to send\n :return: None\n "
] |
Please provide a description of the function:def _have_conf(self, magic_hash=None):
self.app.have_conf = getattr(self.app, 'cur_conf', None) not in [None, {}]
if magic_hash is not None:
# Beware, we got an str in entry, not an int
magic_hash = int(magic_hash)
... | [
"Get the daemon current configuration state\n\n If the daemon has received a configuration from its arbiter, this will\n return True\n\n If a `magic_hash` is provided it is compared with the one included in the\n daemon configuration and this function returns True only if they match!\n\n... |
Please provide a description of the function:def _push_actions(self):
data = cherrypy.request.json
with self.app.lock:
self.app.add_actions(data['actions'], data['scheduler_instance_id']) | [
"Push actions to the poller/reactionner\n\n This function is used by the scheduler to send the actions to get executed to\n the poller/reactionner\n\n {'actions': actions, 'instance_id': scheduler_instance_id}\n\n :return:None\n "
] |
Please provide a description of the function:def _results(self, scheduler_instance_id):
with self.app.lock:
res = self.app.get_results_from_passive(scheduler_instance_id)
return serialize(res, True) | [
"Get the results of the executed actions for the scheduler which instance id is provided\n\n Calling this method for daemons that are not configured as passive do not make sense.\n Indeed, this service should only be exposed on poller and reactionner daemons.\n\n :param scheduler_instance_id: i... |
Please provide a description of the function:def _broks(self, broker_name): # pylint: disable=unused-argument
with self.app.broks_lock:
res = self.app.get_broks()
return serialize(res, True) | [
"Get the broks from the daemon\n\n This is used by the brokers to get the broks list of a daemon\n\n :return: Brok list serialized\n :rtype: dict\n "
] |
Please provide a description of the function:def _events(self):
with self.app.events_lock:
res = self.app.get_events()
return serialize(res, True) | [
"Get the monitoring events from the daemon\n\n This is used by the arbiter to get the monitoring events from all its satellites\n\n :return: Events list serialized\n :rtype: list\n "
] |
Please provide a description of the function:def serialize(self):
return {'operand': self.operand, 'sons': [serialize(elem) for elem in self.sons],
'of_values': self.of_values, 'is_of_mul': self.is_of_mul,
'not_value': self.not_value} | [
"This function serialize into a simple dict object.\n It is used when transferring data to other daemons over the network (http)\n\n Here we directly return all attributes\n\n :return: json representation of a DependencyNode\n :rtype: dict\n "
] |
Please provide a description of the function:def get_state(self, hosts, services):
# If we are a host or a service, we just got the host/service
# hard state
if self.operand == 'host':
host = hosts[self.sons[0]]
return self.get_host_node_state(host.last_hard_stat... | [
"Get node state by looking recursively over sons and applying operand\n\n :param hosts: list of available hosts to search for\n :param services: list of available services to search for\n :return: Node state\n :rtype: int\n "
] |
Please provide a description of the function:def get_host_node_state(self, state, problem_has_been_acknowledged, in_scheduled_downtime):
# Make DOWN look as CRITICAL (2 instead of 1)
if state == 1:
state = 2
# If our node is acknowledged or in downtime, state is ok/up
... | [
"Get host node state, simplest case ::\n\n * Handle not value (revert) for host and consider 1 as 2\n\n :return: 0, 1 or 2\n :rtype: int\n "
] |
Please provide a description of the function:def get_service_node_state(self, state, problem_has_been_acknowledged, in_scheduled_downtime):
# If our node is acknowledged or in downtime, state is ok/up
if problem_has_been_acknowledged or in_scheduled_downtime:
state = 0
# Ma... | [
"Get service node state, simplest case ::\n\n * Handle not value (revert) for service\n\n :return: 0, 1 or 2\n :rtype: int\n "
] |
Please provide a description of the function:def get_complex_or_node_state(self, hosts, services):
# First we get the state of all our sons
states = [s.get_state(hosts, services) for s in self.sons]
# Next we calculate the best state
best_state = min(states)
# Then we ha... | [
"Get state , handle OR aggregation ::\n\n * Get the best state (min of sons)\n * Revert if it's a not node\n\n :param hosts: host objects\n :param services: service objects\n :return: 0, 1 or 2\n :rtype: int\n "
] |
Please provide a description of the function:def get_complex_and_node_state(self, hosts, services):
# First we get the state of all our sons
states = [s.get_state(hosts, services) for s in self.sons]
# Next we calculate the worst state
if 2 in states:
worst_state = 2... | [
"Get state , handle AND aggregation ::\n\n * Get the worst state. 2 or max of sons (3 <=> UNKNOWN < CRITICAL <=> 2)\n * Revert if it's a not node\n\n :param hosts: host objects\n :param services: service objects\n :return: 0, 1 or 2\n :rtype: int\n "
] |
Please provide a description of the function:def get_complex_xof_node_state(self, hosts, services):
# pylint: disable=too-many-locals, too-many-return-statements, too-many-branches
# First we get the state of all our sons
states = [s.get_state(hosts, services) for s in self.sons]
... | [
"Get state , handle X of aggregation ::\n\n * Count the number of OK, WARNING, CRITICAL\n * Try too apply, in this order, Critical, Warning, OK rule\n * Return the code for first match (2, 1, 0)\n * If no rule apply, return OK for simple X of and worst state for multiple X of... |
Please provide a description of the function:def list_all_elements(self):
res = []
# We are a host/service
if self.operand in ['host', 'service']:
return [self.sons[0]]
for son in self.sons:
res.extend(son.list_all_elements())
# and returns a l... | [
"Get all host/service uuid in our node and below\n\n :return: list of hosts/services uuids\n :rtype: list\n "
] |
Please provide a description of the function:def switch_zeros_of_values(self):
nb_sons = len(self.sons)
# Need a list for assignment
new_values = list(self.of_values)
for i in [0, 1, 2]:
if new_values[i] == '0':
new_values[i] = str(nb_sons)
se... | [
"If we are a of: rule, we can get some 0 in of_values,\n if so, change them with NB sons instead\n\n :return: None\n "
] |
Please provide a description of the function:def is_valid(self):
valid = True
if not self.sons:
valid = False
else:
for son in self.sons:
if isinstance(son, DependencyNode) and not son.is_valid():
self.configuration_errors.ext... | [
"Check if all leaves are correct (no error)\n\n :return: True if correct, otherwise False\n :rtype: bool\n "
] |
Please provide a description of the function:def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
pattern = pattern.strip()
complex_node = False
# Look if it's a complex pattern (with rule) or
# if it's a leaf of it, like a host/servic... | [
"Parse and build recursively a tree of DependencyNode from pattern\n\n :param pattern: pattern to parse\n :type pattern: str\n :param hosts: hosts list, used to find a specific host\n :type hosts: alignak.objects.host.Host\n :param services: services list, used to find a specific ... |
Please provide a description of the function:def eval_xof_pattern(node, pattern):
xof_pattern = r"^(-?\d+%?),*(-?\d*%?),*(-?\d*%?) *of: *(.+)"
regex = re.compile(xof_pattern)
matches = regex.search(pattern)
if matches is not None:
node.operand = 'of:'
gro... | [
"Parse a X of pattern\n * Set is_of_mul attribute\n * Set of_values attribute\n\n :param node: node to edit\n :type node:\n :param pattern: line to match\n :type pattern: str\n :return: end of the line (without X of :)\n :rtype: str\n "
] |
Please provide a description of the function:def eval_complex_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
# pylint: disable=too-many-branches
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern... | [
"Parse and build recursively a tree of DependencyNode from a complex pattern\n\n :param pattern: pattern to parse\n :type pattern: str\n :param hosts: hosts list, used to find a specific host\n :type hosts: alignak.objects.host.Host\n :param services: services list, used to find a... |
Please provide a description of the function:def eval_simple_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern)
# If it's a not value, tag the node... | [
"Parse and build recursively a tree of DependencyNode from a simple pattern\n\n :param pattern: pattern to parse\n :type pattern: str\n :param hosts: hosts list, used to find a specific host\n :type hosts: alignak.objects.host.Host\n :param services: services list, used to find a ... |
Please provide a description of the function:def find_object(self, pattern, hosts, services):
obj = None
error = None
is_service = False
# h_name, service_desc are , separated
elts = pattern.split(',')
host_name = elts[0].strip()
# If host_name is empty, ... | [
"Find object from pattern\n\n :param pattern: text to search (host1,service1)\n :type pattern: str\n :param hosts: hosts list, used to find a specific host\n :type hosts: alignak.objects.host.Host\n :param services: services list, used to find a specific service\n :type ser... |
Please provide a description of the function:def expand_expression(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
# pylint: disable=too-many-locals
error = None
node = DependencyNode()
node.operand = '&'
elts = [e.strip() for e in pattern.spli... | [
"Expand a host or service expression into a dependency node tree\n using (host|service)group membership, regex, or labels as item selector.\n\n :param pattern: pattern to parse\n :type pattern: str\n :param hosts: hosts list, used to find a specific host\n :type hosts: alignak.obj... |
Please provide a description of the function:def get_host_filters(self, expr):
# pylint: disable=too-many-return-statements
if expr == "*":
return [filter_any]
match = re.search(r"^([%s]+):(.*)" % self.host_flags, expr)
if match is None:
return [filter_h... | [
"Generates host filter list corresponding to the expression ::\n\n * '*' => any\n * 'g' => group filter\n * 'r' => regex name filter\n * 'l' => bp rule label filter\n * 't' => tag filter\n * '' => none filter\n * No flag match => host name filter\n\n :param e... |
Please provide a description of the function:def get_srv_host_filters(self, expr):
# pylint: disable=too-many-return-statements
if expr == "*":
return [filter_any]
match = re.search(r"^([%s]+):(.*)" % self.host_flags, expr)
if match is None:
return [filt... | [
"Generates service filter list corresponding to the expression ::\n\n * '*' => any\n * 'g' => hostgroup filter\n * 'r' => host regex name filter\n * 'l' => host bp rule label filter\n * 't' => tag filter\n * '' => none filter\n * No flag match => host name filter\n\... |
Please provide a description of the function:def get_srv_service_filters(self, expr):
if expr == "*":
return [filter_any]
match = re.search(r"^([%s]+):(.*)" % self.service_flags, expr)
if match is None:
return [filter_service_by_name(expr)]
flags, expr ... | [
"Generates service filter list corresponding to the expression ::\n\n * '*' => any\n * 'g' => servicegroup filter\n * 'r' => service regex name filter\n * 'l' => service bp rule label filter\n * 't' => tag filter\n * '' => none filter\n * No flag match => service na... |
Please provide a description of the function:def serialize(self):
res = super(Timeperiod, self).serialize()
res['dateranges'] = []
for elem in self.dateranges:
res['dateranges'].append({'__sys_python_module__': "%s.%s" % (elem.__module__,
... | [
"This function serialize into a simple dict object.\n It is used when transferring data to other daemons over the network (http)\n\n Here we directly return all attributes\n\n :return: json representation of a Timeperiod\n :rtype: dict\n "
] |
Please provide a description of the function:def get_raw_import_values(self): # pragma: no cover, deprecation
properties = ['timeperiod_name', 'alias', 'use', 'register']
res = {}
for prop in properties:
if hasattr(self, prop):
val = getattr(self, prop)
... | [
"\n Get some properties of timeperiod (timeperiod is a bit different\n from classic item)\n\n TODO: never called anywhere, still useful?\n\n :return: a dictionnary of some properties\n :rtype: dict\n "
] |
Please provide a description of the function:def is_time_valid(self, timestamp):
if hasattr(self, 'exclude'):
for daterange in self.exclude:
if daterange.is_time_valid(timestamp):
return False
for daterange in self.dateranges:
if dater... | [
"\n Check if a time is valid or not\n\n :return: time is valid or not\n :rtype: bool\n "
] |
Please provide a description of the function:def get_min_from_t(self, timestamp):
mins_incl = []
for daterange in self.dateranges:
mins_incl.append(daterange.get_min_from_t(timestamp))
return min(mins_incl) | [
"\n Get the first time > timestamp which is valid\n\n :param timestamp: number of seconds\n :type timestamp: int\n :return: number of seconds\n :rtype: int\n TODO: not used, so delete it\n "
] |
Please provide a description of the function:def check_and_log_activation_change(self):
now = int(time.time())
was_active = self.is_active
self.is_active = self.is_time_valid(now)
# If we got a change, log it!
if self.is_active != was_active:
_from = 0
... | [
"\n Will look for active/un-active change of timeperiod.\n In case it change, we log it like:\n [1327392000] TIMEPERIOD TRANSITION: <name>;<from>;<to>\n\n States of is_active:\n -1: default value when start\n 0: when timeperiod end\n 1: when timeperiod start\n\n ... |
Please provide a description of the function:def clean_cache(self):
now = int(time.time())
t_to_del = []
for timestamp in self.cache:
if timestamp < now:
t_to_del.append(timestamp)
for timestamp in t_to_del:
del self.cache[timestamp]
... | [
"\n Clean cache with entries older than now because not used in future ;)\n\n :return: None\n "
] |
Please provide a description of the function:def get_next_valid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
timestamp = int(timestamp)
original_t = timestamp
res_from_cache = self.find_next_valid_time_from_cache(timestamp)
if res_from_cache is not ... | [
"\n Get next valid time. If it's in cache, get it, otherwise define it.\n The limit to find it is 1 year.\n\n :param timestamp: number of seconds\n :type timestamp: int or float\n :return: Nothing or time in seconds\n :rtype: None or int\n "
] |
Please provide a description of the function:def get_next_invalid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
timestamp = int(timestamp)
original_t = timestamp
dr_mins = []
for daterange in self.dateranges:
timestamp = original_t
... | [
"\n Get the next invalid time\n\n :param timestamp: timestamp in seconds (of course)\n :type timestamp: int or float\n :return: timestamp of next invalid time\n :rtype: int or float\n "
] |
Please provide a description of the function:def is_correct(self):
state = True
for daterange in self.dateranges:
good = daterange.is_correct()
if not good:
self.add_error("[timeperiod::%s] invalid daterange '%s'"
% (self.ge... | [
"Check if this object configuration is correct ::\n\n * Check if dateranges of timeperiod are valid\n * Call our parent class is_correct checker\n\n :return: True if the configuration is correct, otherwise False if at least one daterange\n is not correct\n :rtype: bool\n "
... |
Please provide a description of the function:def resolve_daterange(self, dateranges, entry):
# pylint: disable=too-many-return-statements,too-many-statements,
# pylint: disable=too-many-branches,too-many-locals
res = re.search(
r'(\d{4})-(\d{2})-(\d{2}) - (\d{4})-(\d{2})-(\d... | [
"\n Try to solve dateranges (special cases)\n\n :param dateranges: dateranges\n :type dateranges: list\n :param entry: property of timeperiod\n :type entry: string\n :return: None\n "
] |
Please provide a description of the function:def explode(self):
for entry in self.unresolved:
self.resolve_daterange(self.dateranges, entry)
self.unresolved = [] | [
"\n Try to resolve all unresolved elements\n\n :return: None\n "
] |
Please provide a description of the function:def linkify(self, timeperiods):
new_exclude = []
if hasattr(self, 'exclude') and self.exclude != []:
logger.debug("[timeentry::%s] have excluded %s", self.get_name(), self.exclude)
excluded_tps = self.exclude
for t... | [
"\n Will make timeperiod in exclude with id of the timeperiods\n\n :param timeperiods: Timeperiods object\n :type timeperiods:\n :return: None\n "
] |
Please provide a description of the function:def check_exclude_rec(self):
# pylint: disable=access-member-before-definition
if self.rec_tag:
msg = "[timeentry::%s] is in a loop in exclude parameter" % (self.get_name())
self.add_error(msg)
return False
... | [
"\n Check if this timeperiod is tagged\n\n :return: if tagged return false, if not true\n :rtype: bool\n "
] |
Please provide a description of the function:def explode(self):
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.explode() | [
"\n Try to resolve each timeperiod\n\n :return: None\n "
] |
Please provide a description of the function:def linkify(self):
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.linkify(self) | [
"\n Check exclusion for each timeperiod\n\n :return: None\n "
] |
Please provide a description of the function:def get_unresolved_properties_by_inheritance(self, timeperiod):
# Ok, I do not have prop, Maybe my templates do?
# Same story for plus
for i in timeperiod.templates:
template = self.templates[i]
timeperiod.unresolved.e... | [
"\n Fill full properties with template if needed for the\n unresolved values (example: sunday ETCETC)\n :return: None\n "
] |
Please provide a description of the function:def apply_inheritance(self):
self.apply_partial_inheritance('exclude')
for i in self:
self.get_customs_properties_by_inheritance(i)
# And now apply inheritance for unresolved properties
# like the dateranges in fact
... | [
"\n The only interesting property to inherit is exclude\n\n :return: None\n "
] |
Please provide a description of the function:def is_correct(self):
valid = True
# We do not want a same hg to be explode again and again
# so we tag it
for timeperiod in list(self.items.values()):
timeperiod.rec_tag = False
for timeperiod in list(self.items.... | [
"\n check if each properties of timeperiods are valid\n\n :return: True if is correct, otherwise False\n :rtype: bool\n "
] |
Please provide a description of the function:def get_override_configuration(self):
res = {}
properties = self.__class__.properties
for prop, entry in list(properties.items()):
if entry.override:
res[prop] = getattr(self, prop)
return res | [
"\n Some parameters can give as 'overridden parameters' like use_timezone\n so they will be mixed (in the scheduler) with the standard conf sent by the arbiter\n\n :return: dictionary of properties\n :rtype: dict\n "
] |
Please provide a description of the function:def check_reachable(self, forced=False, test=False):
# pylint: disable=too-many-branches
all_ok = True
self.not_configured = []
for daemon_link in self.all_daemons_links:
if daemon_link == self.arbiter_link:
... | [
"Check all daemons state (reachable or not)\n\n If test parameter is True, do not really send but simulate only for testing purpose...\n\n The update_infos function returns None when no ping has been executed\n (too early...), or True / False according to the real ping and get managed\n ... |
Please provide a description of the function:def check_status_and_get_events(self):
# pylint: disable=too-many-branches
statistics = {}
events = []
for daemon_link in self.all_daemons_links:
if daemon_link == self.arbiter_link:
# I exclude myself from... | [
"Get all the daemons status\n\n\n :return: Dictionary with all the daemons returned information\n :rtype: dict\n "
] |
Please provide a description of the function:def check_dispatch(self): # pylint: disable=too-many-branches
if not self.arbiter_link:
raise DispatcherError("Dispatcher configuration problem: no valid arbiter link!")
if not self.first_dispatch_done:
raise DispatcherError... | [
"Check that all active satellites have a configuration dispatched\n\n A DispatcherError exception is raised if no configuration is dispatched!\n\n :return: None\n "
] |
Please provide a description of the function:def get_satellites_list(self, sat_type):
satellites_list = []
if sat_type in ['arbiters', 'schedulers', 'reactionners',
'brokers', 'receivers', 'pollers']:
for satellite in getattr(self, sat_type):
... | [
"Get a sorted satellite list: master then spare\n\n :param sat_type: type of the required satellites (arbiters, schedulers, ...)\n :type sat_type: str\n :return: sorted satellites list\n :rtype: list[alignak.objects.satellitelink.SatelliteLink]\n "
] |
Please provide a description of the function:def get_scheduler_ordered_list(self, realm):
# Get the schedulers for the required realm
scheduler_links = []
for scheduler_link_uuid in realm.schedulers:
scheduler_links.append(self.schedulers[scheduler_link_uuid])
# Now... | [
"Get sorted scheduler list for a specific realm\n\n List is ordered as: alive first, then spare (if any), then dead scheduler links\n\n :param realm: realm we want scheduler from\n :type realm: alignak.objects.realm.Realm\n :return: sorted scheduler list\n :rtype: list[alignak.obj... |
Please provide a description of the function:def prepare_dispatch(self):
# pylint:disable=too-many-branches, too-many-statements, too-many-locals
if self.new_to_dispatch:
raise DispatcherError("A configuration is already prepared!")
# So we are preparing a new dispatching..... | [
"\n Prepare dispatch, so prepare for each daemon (schedulers, brokers, receivers, reactionners,\n pollers)\n\n This function will only prepare something if self.new_to_dispatch is False\n It will reset the first_dispatch_done flag\n\n A DispatcherError exception is raised if a con... |
Please provide a description of the function:def dispatch(self, test=False): # pylint: disable=too-many-branches
if not self.new_to_dispatch:
raise DispatcherError("Dispatcher cannot dispatch, "
"because no configuration is prepared!")
if self.fir... | [
"\n Send configuration to satellites\n\n :return: None\n "
] |
Please provide a description of the function:def stop_request(self, stop_now=False):
all_ok = True
for daemon_link in self.all_daemons_links:
logger.debug("Stopping: %s (%s)", daemon_link, stop_now)
if daemon_link == self.arbiter_link:
# I exclude myself ... | [
"Send a stop request to all the daemons\n\n :param stop_now: stop now or go to stop wait mode\n :type stop_now: bool\n :return: True if all daemons are reachable\n "
] |
Please provide a description of the function:def pythonize(self, val):
__boolean_states__ = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
if isinstance(val, bool):
return val
val = uni... | [
"Convert value into a boolean\n\n :param val: value to convert\n :type val: bool, int, str\n :return: boolean corresponding to value ::\n\n {'1': True, 'yes': True, 'true': True, 'on': True,\n '0': False, 'no': False, 'false': False, 'off': False}\n\n :rtype: bool\n ... |
Please provide a description of the function:def pythonize(self, val):
if isinstance(val, list):
return [s.strip() if hasattr(s, "strip") else s
for s in list_split(val, self.split_on_comma)
if hasattr(s, "strip") and s.strip() != '' or self.keep_empt... | [
"Convert value into a list::\n\n * split value (or each element if value is a list) on coma char\n * strip split values\n\n :param val: value to convert\n :type val: str\n :return: list corresponding to value\n :rtype: list\n "
] |
Please provide a description of the function:def pythonize(self, val):
val = unique_value(val)
def split(keyval):
matches = re.match(r"^\s*([^\s]+)\s*=\s*([^\s]+)\s*$", keyval)
if matches is None:
raise ValueError
return (
... | [
"Convert value into a dict::\n\n * If value is a list, try to take the last element\n * split \"key=value\" string and convert to { key:value }\n\n :param val: value to convert\n :type val:\n :return: log level corresponding to value\n :rtype: str\n ",
"Split key-v... |
Please provide a description of the function:def pythonize(self, val):
val = unique_value(val)
matches = re.match(r"^([^:]*)(?::(\d+))?$", val)
if matches is None:
raise ValueError
addr = {'address': matches.group(1)}
if matches.group(2) is not None:
... | [
"Convert value into a address ip format::\n\n * If value is a list, try to take the last element\n * match ip address and port (if available)\n\n :param val: value to convert\n :type val:\n :return: address/port corresponding to value\n :rtype: dict\n "
] |
Please provide a description of the function:def pythonize(self, val):
if isinstance(val, list) and len(set(val)) == 1:
# If we have a list with a unique value just use it
return val[0]
# Well, can't choose to remove something.
return val | [
"If value is a single list element just return the element\n does nothing otherwise\n\n :param val: value to convert\n :type val:\n :return: converted value\n :rtype:\n "
] |
Please provide a description of the function:def pythonize(self, val):
val = super(IntListProp, self).pythonize(val)
try:
return [int(e) for e in val]
except ValueError as value_except:
raise PythonizeError(str(value_except)) | [
"Convert value into a integer list::\n\n * Try to convert into a list\n * Convert each element into a int\n\n :param val: value to convert\n :type val:\n :return: integer list corresponding to value\n :rtype: list[int]\n "
] |
Please provide a description of the function:def get_response(self, method, endpoint, headers=None, json=None, params=None, data=None):
# pylint: disable=too-many-arguments
logger.debug("Parameters for get_response:")
logger.debug("\t - endpoint: %s", endpoint)
logger.debug("\t ... | [
"\n Returns the response from the requested endpoint with the requested method\n :param method: str. one of the methods accepted by Requests ('POST', 'GET', ...)\n :param endpoint: str. the relative endpoint to access\n :param params: (optional) Dictionary or bytes to be sent in the quer... |
Please provide a description of the function:def decode(response):
# Second stage. Errors are backend errors (bad login, bad url, ...)
try:
response.raise_for_status()
except requests.HTTPError as exp:
response = {"_status": "ERR",
"_erro... | [
"\n Decodes and returns the response as JSON (dict) or raise BackendException\n :param response: requests.response object\n :return: dict\n "
] |
Please provide a description of the function:def login(self, username, password):
logger.debug("login for: %s", username)
# Configured as not authenticated WS
if not username and not password:
self.set_token(token=None)
return False
if not username or n... | [
"\n Log into the WS interface and get the authentication token\n\n if login is:\n - accepted, returns True\n - refused, returns False\n\n In case of any error, raises a BackendException\n\n :param username: login name\n :type username: str\n :param password: p... |
Please provide a description of the function:def logout(self):
logger.debug("request backend logout")
if not self.authenticated:
logger.warning("Unnecessary logout ...")
return True
endpoint = 'logout'
_ = self.get_response(method='POST', endpoint=endpo... | [
"\n Logout from the backend\n\n :return: return True if logout is successfull, otherwise False\n :rtype: bool\n "
] |
Please provide a description of the function:def get(self, endpoint, params=None):
response = self.get_response(method='GET', endpoint=endpoint, params=params)
resp = self.decode(response=response)
if '_status' not in resp: # pragma: no cover - need specific backend tests
... | [
"\n Get items or item in alignak backend\n\n If an error occurs, a BackendException is raised.\n\n This method builds a response as a dictionary that always contains: _items and _status::\n\n {\n u'_items': [\n ...\n ],\n ... |
Please provide a description of the function:def post(self, endpoint, data, files=None, headers=None):
# pylint: disable=unused-argument
# We let Requests encode data to json
response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers)
resp = self.... | [
"\n Create a new item\n\n :param endpoint: endpoint (API URL)\n :type endpoint: str\n :param data: properties of item to create\n :type data: dict\n :param files: Not used. To be implemented\n :type files: None\n :param headers: headers (example: Content-Type)... |
Please provide a description of the function:def patch(self, endpoint, data):
response = self.get_response(method='PATCH', endpoint=endpoint, json=data,
headers={'Content-Type': 'application/json'})
if response.status_code == 200:
return self.de... | [
"\n Method to update an item\n\n The headers must include an If-Match containing the object _etag.\n headers = {'If-Match': contact_etag}\n\n The data dictionary contain the fields that must be modified.\n\n If the patching fails because the _etag object do not match with the ... |
Please provide a description of the function:def sanitize_name(field_name):
if not field_name:
return field_name
# Sanitize field name for TSDB (Graphite or Influx):
sanitized = field_name.strip()
if sanitized.startswith('/'):
sanitized = '_' + sanitized[1:]
# + becomes a _
... | [
"Sanitize a field name for a TSDB (Graphite or Influx)\n - remove not allowed characters from the field name\n and replace with authorized characters\n\n :param field_name: Field name to clean\n :type field_name: string\n :return: sanitized field name\n "
] |
Please provide a description of the function:def init(self, conf):
# For searching class and elements for on-demand
# we need link to types
self.my_conf = conf
self.lists_on_demand = []
self.hosts = self.my_conf.hosts
# For special void host_name handling...
... | [
"Initialize MacroResolver instance with conf.\n Must be called at least once.\n\n :param conf: configuration to load\n :type conf: alignak.objects.Config\n :return: None\n "
] |
Please provide a description of the function:def _get_macros(chain):
regex = re.compile(r'(\$)')
elts = regex.split(chain)
macros = {}
in_macro = False
for elt in elts:
if elt == '$':
in_macro = not in_macro
elif in_macro:
... | [
"Get all macros of a chain\n Cut '$' char and create a dict with the following structure::\n\n { 'MacroSTR1' : {'val': '', 'type': 'unknown'}\n 'MacroSTR2' : {'val': '', 'type': 'unknown'}\n }\n\n :param chain: chain to parse\n :type chain: str\n :return: dict with... |
Please provide a description of the function:def _get_value_from_element(self, elt, prop):
# pylint: disable=too-many-return-statements
args = None
# We have args to provide to the function
if isinstance(prop, tuple):
prop, args = prop
value = getattr(elt, pr... | [
"Get value from an element's property.\n\n the property may be a function to call.\n\n If the property is not resolved (because not implemented), this function will return 'n/a'\n\n :param elt: element\n :type elt: object\n :param prop: element property\n :type prop: str\n ... |
Please provide a description of the function:def _delete_unwanted_caracters(self, chain):
try:
chain = chain.decode('utf8', 'replace')
except UnicodeEncodeError:
# If it is still encoded correctly, ignore...
pass
except AttributeError:
# P... | [
"Remove not wanted char from chain\n unwanted char are illegal_macro_output_chars attribute\n\n :param chain: chain to remove char from\n :type chain: str\n :return: chain cleaned\n :rtype: str\n "
] |
Please provide a description of the function:def get_env_macros(self, data):
env = {}
for obj in data:
cls = obj.__class__
macros = cls.macros
for macro in macros:
if macro.startswith("USER"):
continue
pro... | [
"Get all environment macros from data\n For each object in data ::\n\n * Fetch all macros in object.__class__.macros\n * Fetch all customs macros in o.custom\n\n :param data: data to get macro\n :type data:\n :return: dict with macro name as key and macro value as value\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.