repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.set_log_level
def set_log_level(self, log_level=None): """Set the current log level for the daemon The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL] In case of any error, this function returns an object containing some properties: '_status': 'ERR' because of the error `_message`: some more explanations about the error Else, this function returns True :param log_level: a value in one of the above :type log_level: str :return: see above :rtype: dict """ 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', '_message': u"Required log level is not allowed: %s" % log_level} alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME) alignak_logger.setLevel(log_level) return self.get_log_level()
python
def set_log_level(self, log_level=None): """Set the current log level for the daemon The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL] In case of any error, this function returns an object containing some properties: '_status': 'ERR' because of the error `_message`: some more explanations about the error Else, this function returns True :param log_level: a value in one of the above :type log_level: str :return: see above :rtype: dict """ 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', '_message': u"Required log level is not allowed: %s" % log_level} alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME) alignak_logger.setLevel(log_level) return self.get_log_level()
[ "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'", ",", "'_message'", ":", "u\"Required log level is not allowed: %s\"", "%", "log_level", "}", "alignak_logger", "=", "logging", ".", "getLogger", "(", "ALIGNAK_LOGGER_NAME", ")", "alignak_logger", ".", "setLevel", "(", "log_level", ")", "return", "self", ".", "get_log_level", "(", ")" ]
Set the current log level for the daemon The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL] In case of any error, this function returns an object containing some properties: '_status': 'ERR' because of the error `_message`: some more explanations about the error Else, this function returns True :param log_level: a value in one of the above :type log_level: str :return: see above :rtype: dict
[ "Set", "the", "current", "log", "level", "for", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L184-L209
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.stats
def stats(self, details=False): """Get statistics and information from the daemon Returns an object with the daemon identity, the daemon start_time and some extra properties depending upon the daemon type. All daemons provide these ones: - program_start: the Alignak start timestamp - spare: to indicate if the daemon is a spare one - load: the daemon load - modules: the daemon modules information - counters: the specific daemon counters :param details: Details are required (different from 0) :type details str :return: daemon stats :rtype: dict """ if details is not False: details = bool(details) res = self.identity() res.update(self.app.get_daemon_stats(details=details)) return res
python
def stats(self, details=False): """Get statistics and information from the daemon Returns an object with the daemon identity, the daemon start_time and some extra properties depending upon the daemon type. All daemons provide these ones: - program_start: the Alignak start timestamp - spare: to indicate if the daemon is a spare one - load: the daemon load - modules: the daemon modules information - counters: the specific daemon counters :param details: Details are required (different from 0) :type details str :return: daemon stats :rtype: dict """ if details is not False: details = bool(details) res = self.identity() res.update(self.app.get_daemon_stats(details=details)) return res
[ "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 Returns an object with the daemon identity, the daemon start_time and some extra properties depending upon the daemon type. All daemons provide these ones: - program_start: the Alignak start timestamp - spare: to indicate if the daemon is a spare one - load: the daemon load - modules: the daemon modules information - counters: the specific daemon counters :param details: Details are required (different from 0) :type details str :return: daemon stats :rtype: dict
[ "Get", "statistics", "and", "information", "from", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L240-L263
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface._have_conf
def _have_conf(self, magic_hash=None): """Get the daemon current configuration state If the daemon has received a configuration from its arbiter, this will return True If a `magic_hash` is provided it is compared with the one included in the daemon configuration and this function returns True only if they match! :return: boolean indicating if the daemon has a configuration :rtype: bool """ 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) # I've got a conf and a good one return self.app.have_conf and self.app.cur_conf.magic_hash == magic_hash return self.app.have_conf
python
def _have_conf(self, magic_hash=None): """Get the daemon current configuration state If the daemon has received a configuration from its arbiter, this will return True If a `magic_hash` is provided it is compared with the one included in the daemon configuration and this function returns True only if they match! :return: boolean indicating if the daemon has a configuration :rtype: bool """ 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) # I've got a conf and a good one return self.app.have_conf and self.app.cur_conf.magic_hash == magic_hash return self.app.have_conf
[ "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", ")", "# I've got a conf and a good one", "return", "self", ".", "app", ".", "have_conf", "and", "self", ".", "app", ".", "cur_conf", ".", "magic_hash", "==", "magic_hash", "return", "self", ".", "app", ".", "have_conf" ]
Get the daemon current configuration state If the daemon has received a configuration from its arbiter, this will return True If a `magic_hash` is provided it is compared with the one included in the daemon configuration and this function returns True only if they match! :return: boolean indicating if the daemon has a configuration :rtype: bool
[ "Get", "the", "daemon", "current", "configuration", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L310-L329
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface._results
def _results(self, scheduler_instance_id): """Get the results of the executed actions for the scheduler which instance id is provided Calling this method for daemons that are not configured as passive do not make sense. Indeed, this service should only be exposed on poller and reactionner daemons. :param scheduler_instance_id: instance id of the scheduler :type scheduler_instance_id: string :return: serialized list :rtype: str """ with self.app.lock: res = self.app.get_results_from_passive(scheduler_instance_id) return serialize(res, True)
python
def _results(self, scheduler_instance_id): """Get the results of the executed actions for the scheduler which instance id is provided Calling this method for daemons that are not configured as passive do not make sense. Indeed, this service should only be exposed on poller and reactionner daemons. :param scheduler_instance_id: instance id of the scheduler :type scheduler_instance_id: string :return: serialized list :rtype: str """ with self.app.lock: res = self.app.get_results_from_passive(scheduler_instance_id) return serialize(res, True)
[ "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 Calling this method for daemons that are not configured as passive do not make sense. Indeed, this service should only be exposed on poller and reactionner daemons. :param scheduler_instance_id: instance id of the scheduler :type scheduler_instance_id: string :return: serialized list :rtype: str
[ "Get", "the", "results", "of", "the", "executed", "actions", "for", "the", "scheduler", "which", "instance", "id", "is", "provided" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L367-L380
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface._broks
def _broks(self, broker_name): # pylint: disable=unused-argument """Get the broks from the daemon This is used by the brokers to get the broks list of a daemon :return: Brok list serialized :rtype: dict """ with self.app.broks_lock: res = self.app.get_broks() return serialize(res, True)
python
def _broks(self, broker_name): # pylint: disable=unused-argument """Get the broks from the daemon This is used by the brokers to get the broks list of a daemon :return: Brok list serialized :rtype: dict """ with self.app.broks_lock: res = self.app.get_broks() return serialize(res, True)
[ "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 This is used by the brokers to get the broks list of a daemon :return: Brok list serialized :rtype: dict
[ "Get", "the", "broks", "from", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L384-L394
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface._events
def _events(self): """Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list """ with self.app.events_lock: res = self.app.get_events() return serialize(res, True)
python
def _events(self): """Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list """ with self.app.events_lock: res = self.app.get_events() return serialize(res, True)
[ "def", "_events", "(", "self", ")", ":", "with", "self", ".", "app", ".", "events_lock", ":", "res", "=", "self", ".", "app", ".", "get_events", "(", ")", "return", "serialize", "(", "res", ",", "True", ")" ]
Get the monitoring events from the daemon This is used by the arbiter to get the monitoring events from all its satellites :return: Events list serialized :rtype: list
[ "Get", "the", "monitoring", "events", "from", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L398-L408
train
Alignak-monitoring/alignak
alignak/dependencynode.py
DependencyNode.get_state
def get_state(self, hosts, services): """Get node state by looking recursively over sons and applying operand :param hosts: list of available hosts to search for :param services: list of available services to search for :return: Node state :rtype: int """ # 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_state_id, host.problem_has_been_acknowledged, host.in_scheduled_downtime) if self.operand == 'service': service = services[self.sons[0]] return self.get_service_node_state(service.last_hard_state_id, service.problem_has_been_acknowledged, service.in_scheduled_downtime) if self.operand == '|': return self.get_complex_or_node_state(hosts, services) if self.operand == '&': return self.get_complex_and_node_state(hosts, services) # It's an Xof rule if self.operand == 'of:': return self.get_complex_xof_node_state(hosts, services) # We have an unknown node. Code is not reachable because we validate operands return 4
python
def get_state(self, hosts, services): """Get node state by looking recursively over sons and applying operand :param hosts: list of available hosts to search for :param services: list of available services to search for :return: Node state :rtype: int """ # 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_state_id, host.problem_has_been_acknowledged, host.in_scheduled_downtime) if self.operand == 'service': service = services[self.sons[0]] return self.get_service_node_state(service.last_hard_state_id, service.problem_has_been_acknowledged, service.in_scheduled_downtime) if self.operand == '|': return self.get_complex_or_node_state(hosts, services) if self.operand == '&': return self.get_complex_and_node_state(hosts, services) # It's an Xof rule if self.operand == 'of:': return self.get_complex_xof_node_state(hosts, services) # We have an unknown node. Code is not reachable because we validate operands return 4
[ "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_state_id", ",", "host", ".", "problem_has_been_acknowledged", ",", "host", ".", "in_scheduled_downtime", ")", "if", "self", ".", "operand", "==", "'service'", ":", "service", "=", "services", "[", "self", ".", "sons", "[", "0", "]", "]", "return", "self", ".", "get_service_node_state", "(", "service", ".", "last_hard_state_id", ",", "service", ".", "problem_has_been_acknowledged", ",", "service", ".", "in_scheduled_downtime", ")", "if", "self", ".", "operand", "==", "'|'", ":", "return", "self", ".", "get_complex_or_node_state", "(", "hosts", ",", "services", ")", "if", "self", ".", "operand", "==", "'&'", ":", "return", "self", ".", "get_complex_and_node_state", "(", "hosts", ",", "services", ")", "# It's an Xof rule", "if", "self", ".", "operand", "==", "'of:'", ":", "return", "self", ".", "get_complex_xof_node_state", "(", "hosts", ",", "services", ")", "# We have an unknown node. Code is not reachable because we validate operands", "return", "4" ]
Get node state by looking recursively over sons and applying operand :param hosts: list of available hosts to search for :param services: list of available services to search for :return: Node state :rtype: int
[ "Get", "node", "state", "by", "looking", "recursively", "over", "sons", "and", "applying", "operand" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L140-L171
train
Alignak-monitoring/alignak
alignak/dependencynode.py
DependencyNodeFactory.eval_cor_pattern
def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): """Parse and build recursively a tree of DependencyNode from pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ 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/service for char in '()&|': if char in pattern: complex_node = True # If it's a simple node, evaluate it directly if complex_node is False: return self.eval_simple_cor_pattern(pattern, hosts, services, hostgroups, servicegroups, running) return self.eval_complex_cor_pattern(pattern, hosts, services, hostgroups, servicegroups, running)
python
def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): """Parse and build recursively a tree of DependencyNode from pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ 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/service for char in '()&|': if char in pattern: complex_node = True # If it's a simple node, evaluate it directly if complex_node is False: return self.eval_simple_cor_pattern(pattern, hosts, services, hostgroups, servicegroups, running) return self.eval_complex_cor_pattern(pattern, hosts, services, hostgroups, servicegroups, running)
[ "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/service", "for", "char", "in", "'()&|'", ":", "if", "char", "in", "pattern", ":", "complex_node", "=", "True", "# If it's a simple node, evaluate it directly", "if", "complex_node", "is", "False", ":", "return", "self", ".", "eval_simple_cor_pattern", "(", "pattern", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")", "return", "self", ".", "eval_complex_cor_pattern", "(", "pattern", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")" ]
Parse and build recursively a tree of DependencyNode from pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode
[ "Parse", "and", "build", "recursively", "a", "tree", "of", "DependencyNode", "from", "pattern" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L417-L445
train
Alignak-monitoring/alignak
alignak/dependencynode.py
DependencyNodeFactory.eval_complex_cor_pattern
def eval_complex_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): # pylint: disable=too-many-branches """Parse and build recursively a tree of DependencyNode from a complex pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ node = DependencyNode() pattern = self.eval_xof_pattern(node, pattern) in_par = False tmp = '' son_is_not = False # We keep is the next son will be not or not stacked_parenthesis = 0 for char in pattern: if char == '(': stacked_parenthesis += 1 in_par = True tmp = tmp.strip() # Maybe we just start a par, but we got some things in tmp # that should not be good in fact ! if stacked_parenthesis == 1 and tmp != '': # TODO : real error print("ERROR : bad expression near", tmp) continue # If we are already in a par, add this ( # but not if it's the first one so if stacked_parenthesis > 1: tmp += char elif char == ')': stacked_parenthesis -= 1 if stacked_parenthesis < 0: # TODO : real error print("Error : bad expression near", tmp, "too much ')'") continue if stacked_parenthesis == 0: tmp = tmp.strip() son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) in_par = False # OK now clean the tmp so we start clean tmp = '' continue # ok here we are still in a huge par, we just close one sub one tmp += char # Expressions in par will be parsed in a sub node after. So just # stack pattern elif in_par: tmp += char # Until here, we're not in par # Manage the NOT for an expression. Only allow ! at the beginning # of a host or a host,service expression. elif char == '!': tmp = tmp.strip() if tmp and tmp[0] != '!': print("Error : bad expression near", tmp, "wrong position for '!'") continue # Flags next node not state son_is_not = True # DO NOT keep the c in tmp, we consumed it elif char in ['&', '|']: # Oh we got a real cut in an expression, if so, cut it tmp = tmp.strip() # Look at the rule viability if node.operand is not None and node.operand != 'of:' and char != node.operand: # Should be logged as a warning / info? :) return None if node.operand != 'of:': node.operand = char if tmp != '': son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) tmp = '' # Maybe it's a classic character or we're in par, if so, continue else: tmp += char # Be sure to manage the trainling part when the line is done tmp = tmp.strip() if tmp != '': son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) # We got our nodes, so we can update 0 values of of_values # with the number of sons node.switch_zeros_of_values() return node
python
def eval_complex_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): # pylint: disable=too-many-branches """Parse and build recursively a tree of DependencyNode from a complex pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ node = DependencyNode() pattern = self.eval_xof_pattern(node, pattern) in_par = False tmp = '' son_is_not = False # We keep is the next son will be not or not stacked_parenthesis = 0 for char in pattern: if char == '(': stacked_parenthesis += 1 in_par = True tmp = tmp.strip() # Maybe we just start a par, but we got some things in tmp # that should not be good in fact ! if stacked_parenthesis == 1 and tmp != '': # TODO : real error print("ERROR : bad expression near", tmp) continue # If we are already in a par, add this ( # but not if it's the first one so if stacked_parenthesis > 1: tmp += char elif char == ')': stacked_parenthesis -= 1 if stacked_parenthesis < 0: # TODO : real error print("Error : bad expression near", tmp, "too much ')'") continue if stacked_parenthesis == 0: tmp = tmp.strip() son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) in_par = False # OK now clean the tmp so we start clean tmp = '' continue # ok here we are still in a huge par, we just close one sub one tmp += char # Expressions in par will be parsed in a sub node after. So just # stack pattern elif in_par: tmp += char # Until here, we're not in par # Manage the NOT for an expression. Only allow ! at the beginning # of a host or a host,service expression. elif char == '!': tmp = tmp.strip() if tmp and tmp[0] != '!': print("Error : bad expression near", tmp, "wrong position for '!'") continue # Flags next node not state son_is_not = True # DO NOT keep the c in tmp, we consumed it elif char in ['&', '|']: # Oh we got a real cut in an expression, if so, cut it tmp = tmp.strip() # Look at the rule viability if node.operand is not None and node.operand != 'of:' and char != node.operand: # Should be logged as a warning / info? :) return None if node.operand != 'of:': node.operand = char if tmp != '': son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) tmp = '' # Maybe it's a classic character or we're in par, if so, continue else: tmp += char # Be sure to manage the trainling part when the line is done tmp = tmp.strip() if tmp != '': son = self.eval_cor_pattern(tmp, hosts, services, hostgroups, servicegroups, running) # Maybe our son was notted if son_is_not: son.not_value = True son_is_not = False node.sons.append(son) # We got our nodes, so we can update 0 values of of_values # with the number of sons node.switch_zeros_of_values() return node
[ "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", ")", "in_par", "=", "False", "tmp", "=", "''", "son_is_not", "=", "False", "# We keep is the next son will be not or not", "stacked_parenthesis", "=", "0", "for", "char", "in", "pattern", ":", "if", "char", "==", "'('", ":", "stacked_parenthesis", "+=", "1", "in_par", "=", "True", "tmp", "=", "tmp", ".", "strip", "(", ")", "# Maybe we just start a par, but we got some things in tmp", "# that should not be good in fact !", "if", "stacked_parenthesis", "==", "1", "and", "tmp", "!=", "''", ":", "# TODO : real error", "print", "(", "\"ERROR : bad expression near\"", ",", "tmp", ")", "continue", "# If we are already in a par, add this (", "# but not if it's the first one so", "if", "stacked_parenthesis", ">", "1", ":", "tmp", "+=", "char", "elif", "char", "==", "')'", ":", "stacked_parenthesis", "-=", "1", "if", "stacked_parenthesis", "<", "0", ":", "# TODO : real error", "print", "(", "\"Error : bad expression near\"", ",", "tmp", ",", "\"too much ')'\"", ")", "continue", "if", "stacked_parenthesis", "==", "0", ":", "tmp", "=", "tmp", ".", "strip", "(", ")", "son", "=", "self", ".", "eval_cor_pattern", "(", "tmp", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")", "# Maybe our son was notted", "if", "son_is_not", ":", "son", ".", "not_value", "=", "True", "son_is_not", "=", "False", "node", ".", "sons", ".", "append", "(", "son", ")", "in_par", "=", "False", "# OK now clean the tmp so we start clean", "tmp", "=", "''", "continue", "# ok here we are still in a huge par, we just close one sub one", "tmp", "+=", "char", "# Expressions in par will be parsed in a sub node after. So just", "# stack pattern", "elif", "in_par", ":", "tmp", "+=", "char", "# Until here, we're not in par", "# Manage the NOT for an expression. Only allow ! at the beginning", "# of a host or a host,service expression.", "elif", "char", "==", "'!'", ":", "tmp", "=", "tmp", ".", "strip", "(", ")", "if", "tmp", "and", "tmp", "[", "0", "]", "!=", "'!'", ":", "print", "(", "\"Error : bad expression near\"", ",", "tmp", ",", "\"wrong position for '!'\"", ")", "continue", "# Flags next node not state", "son_is_not", "=", "True", "# DO NOT keep the c in tmp, we consumed it", "elif", "char", "in", "[", "'&'", ",", "'|'", "]", ":", "# Oh we got a real cut in an expression, if so, cut it", "tmp", "=", "tmp", ".", "strip", "(", ")", "# Look at the rule viability", "if", "node", ".", "operand", "is", "not", "None", "and", "node", ".", "operand", "!=", "'of:'", "and", "char", "!=", "node", ".", "operand", ":", "# Should be logged as a warning / info? :)", "return", "None", "if", "node", ".", "operand", "!=", "'of:'", ":", "node", ".", "operand", "=", "char", "if", "tmp", "!=", "''", ":", "son", "=", "self", ".", "eval_cor_pattern", "(", "tmp", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")", "# Maybe our son was notted", "if", "son_is_not", ":", "son", ".", "not_value", "=", "True", "son_is_not", "=", "False", "node", ".", "sons", ".", "append", "(", "son", ")", "tmp", "=", "''", "# Maybe it's a classic character or we're in par, if so, continue", "else", ":", "tmp", "+=", "char", "# Be sure to manage the trainling part when the line is done", "tmp", "=", "tmp", ".", "strip", "(", ")", "if", "tmp", "!=", "''", ":", "son", "=", "self", ".", "eval_cor_pattern", "(", "tmp", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")", "# Maybe our son was notted", "if", "son_is_not", ":", "son", ".", "not_value", "=", "True", "son_is_not", "=", "False", "node", ".", "sons", ".", "append", "(", "son", ")", "# We got our nodes, so we can update 0 values of of_values", "# with the number of sons", "node", ".", "switch_zeros_of_values", "(", ")", "return", "node" ]
Parse and build recursively a tree of DependencyNode from a complex pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode
[ "Parse", "and", "build", "recursively", "a", "tree", "of", "DependencyNode", "from", "a", "complex", "pattern" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L477-L600
train
Alignak-monitoring/alignak
alignak/dependencynode.py
DependencyNodeFactory.eval_simple_cor_pattern
def eval_simple_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): """Parse and build recursively a tree of DependencyNode from a simple pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ node = DependencyNode() pattern = self.eval_xof_pattern(node, pattern) # If it's a not value, tag the node and find # the name without this ! operator if pattern.startswith('!'): node.not_value = True pattern = pattern[1:] # Is the pattern an expression to be expanded? if re.search(r"^([%s]+|\*):" % self.host_flags, pattern) or \ re.search(r",\s*([%s]+:.*|\*)$" % self.service_flags, pattern): # o is just extracted its attributes, then trashed. son = self.expand_expression(pattern, hosts, services, hostgroups, servicegroups, running) if node.operand != 'of:': node.operand = '&' node.sons.extend(son.sons) node.configuration_errors.extend(son.configuration_errors) node.switch_zeros_of_values() else: node.operand = 'object' obj, error = self.find_object(pattern, hosts, services) # here we have Alignak SchedulingItem object (Host/Service) if obj is not None: # Set host or service # pylint: disable=E1101 node.operand = obj.__class__.my_type node.sons.append(obj.uuid) # Only store the uuid, not the full object. else: if running is False: node.configuration_errors.append(error) else: # As business rules are re-evaluated at run time on # each scheduling loop, if the rule becomes invalid # because of a badly written macro modulation, it # should be notified upper for the error to be # displayed in the check output. raise Exception(error) return node
python
def eval_simple_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False): """Parse and build recursively a tree of DependencyNode from a simple pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode """ node = DependencyNode() pattern = self.eval_xof_pattern(node, pattern) # If it's a not value, tag the node and find # the name without this ! operator if pattern.startswith('!'): node.not_value = True pattern = pattern[1:] # Is the pattern an expression to be expanded? if re.search(r"^([%s]+|\*):" % self.host_flags, pattern) or \ re.search(r",\s*([%s]+:.*|\*)$" % self.service_flags, pattern): # o is just extracted its attributes, then trashed. son = self.expand_expression(pattern, hosts, services, hostgroups, servicegroups, running) if node.operand != 'of:': node.operand = '&' node.sons.extend(son.sons) node.configuration_errors.extend(son.configuration_errors) node.switch_zeros_of_values() else: node.operand = 'object' obj, error = self.find_object(pattern, hosts, services) # here we have Alignak SchedulingItem object (Host/Service) if obj is not None: # Set host or service # pylint: disable=E1101 node.operand = obj.__class__.my_type node.sons.append(obj.uuid) # Only store the uuid, not the full object. else: if running is False: node.configuration_errors.append(error) else: # As business rules are re-evaluated at run time on # each scheduling loop, if the rule becomes invalid # because of a badly written macro modulation, it # should be notified upper for the error to be # displayed in the check output. raise Exception(error) return node
[ "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 and find", "# the name without this ! operator", "if", "pattern", ".", "startswith", "(", "'!'", ")", ":", "node", ".", "not_value", "=", "True", "pattern", "=", "pattern", "[", "1", ":", "]", "# Is the pattern an expression to be expanded?", "if", "re", ".", "search", "(", "r\"^([%s]+|\\*):\"", "%", "self", ".", "host_flags", ",", "pattern", ")", "or", "re", ".", "search", "(", "r\",\\s*([%s]+:.*|\\*)$\"", "%", "self", ".", "service_flags", ",", "pattern", ")", ":", "# o is just extracted its attributes, then trashed.", "son", "=", "self", ".", "expand_expression", "(", "pattern", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "running", ")", "if", "node", ".", "operand", "!=", "'of:'", ":", "node", ".", "operand", "=", "'&'", "node", ".", "sons", ".", "extend", "(", "son", ".", "sons", ")", "node", ".", "configuration_errors", ".", "extend", "(", "son", ".", "configuration_errors", ")", "node", ".", "switch_zeros_of_values", "(", ")", "else", ":", "node", ".", "operand", "=", "'object'", "obj", ",", "error", "=", "self", ".", "find_object", "(", "pattern", ",", "hosts", ",", "services", ")", "# here we have Alignak SchedulingItem object (Host/Service)", "if", "obj", "is", "not", "None", ":", "# Set host or service", "# pylint: disable=E1101", "node", ".", "operand", "=", "obj", ".", "__class__", ".", "my_type", "node", ".", "sons", ".", "append", "(", "obj", ".", "uuid", ")", "# Only store the uuid, not the full object.", "else", ":", "if", "running", "is", "False", ":", "node", ".", "configuration_errors", ".", "append", "(", "error", ")", "else", ":", "# As business rules are re-evaluated at run time on", "# each scheduling loop, if the rule becomes invalid", "# because of a badly written macro modulation, it", "# should be notified upper for the error to be", "# displayed in the check output.", "raise", "Exception", "(", "error", ")", "return", "node" ]
Parse and build recursively a tree of DependencyNode from a simple pattern :param pattern: pattern to parse :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :param running: rules are evaluated at run time and parsing. True means runtime :type running: bool :return: root node of parsed tree :rtype: alignak.dependencynode.DependencyNode
[ "Parse", "and", "build", "recursively", "a", "tree", "of", "DependencyNode", "from", "a", "simple", "pattern" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L602-L655
train
Alignak-monitoring/alignak
alignak/dependencynode.py
DependencyNodeFactory.find_object
def find_object(self, pattern, hosts, services): """Find object from pattern :param pattern: text to search (host1,service1) :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :return: tuple with Host or Service object and error :rtype: tuple """ 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, use the host_name the business rule is bound to if not host_name: host_name = self.bound_item.host_name # Look if we have a service if len(elts) > 1: is_service = True service_description = elts[1].strip() if is_service: obj = services.find_srv_by_name_and_hostname(host_name, service_description) if not obj: error = "Business rule uses unknown service %s/%s"\ % (host_name, service_description) else: obj = hosts.find_by_name(host_name) if not obj: error = "Business rule uses unknown host %s" % (host_name,) return obj, error
python
def find_object(self, pattern, hosts, services): """Find object from pattern :param pattern: text to search (host1,service1) :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :return: tuple with Host or Service object and error :rtype: tuple """ 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, use the host_name the business rule is bound to if not host_name: host_name = self.bound_item.host_name # Look if we have a service if len(elts) > 1: is_service = True service_description = elts[1].strip() if is_service: obj = services.find_srv_by_name_and_hostname(host_name, service_description) if not obj: error = "Business rule uses unknown service %s/%s"\ % (host_name, service_description) else: obj = hosts.find_by_name(host_name) if not obj: error = "Business rule uses unknown host %s" % (host_name,) return obj, error
[ "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, use the host_name the business rule is bound to", "if", "not", "host_name", ":", "host_name", "=", "self", ".", "bound_item", ".", "host_name", "# Look if we have a service", "if", "len", "(", "elts", ")", ">", "1", ":", "is_service", "=", "True", "service_description", "=", "elts", "[", "1", "]", ".", "strip", "(", ")", "if", "is_service", ":", "obj", "=", "services", ".", "find_srv_by_name_and_hostname", "(", "host_name", ",", "service_description", ")", "if", "not", "obj", ":", "error", "=", "\"Business rule uses unknown service %s/%s\"", "%", "(", "host_name", ",", "service_description", ")", "else", ":", "obj", "=", "hosts", ".", "find_by_name", "(", "host_name", ")", "if", "not", "obj", ":", "error", "=", "\"Business rule uses unknown host %s\"", "%", "(", "host_name", ",", ")", "return", "obj", ",", "error" ]
Find object from pattern :param pattern: text to search (host1,service1) :type pattern: str :param hosts: hosts list, used to find a specific host :type hosts: alignak.objects.host.Host :param services: services list, used to find a specific service :type services: alignak.objects.service.Service :return: tuple with Host or Service object and error :rtype: tuple
[ "Find", "object", "from", "pattern" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L657-L691
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.is_time_valid
def is_time_valid(self, timestamp): """ Check if a time is valid or not :return: time is valid or not :rtype: bool """ if hasattr(self, 'exclude'): for daterange in self.exclude: if daterange.is_time_valid(timestamp): return False for daterange in self.dateranges: if daterange.is_time_valid(timestamp): return True return False
python
def is_time_valid(self, timestamp): """ Check if a time is valid or not :return: time is valid or not :rtype: bool """ if hasattr(self, 'exclude'): for daterange in self.exclude: if daterange.is_time_valid(timestamp): return False for daterange in self.dateranges: if daterange.is_time_valid(timestamp): return True return False
[ "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", "daterange", ".", "is_time_valid", "(", "timestamp", ")", ":", "return", "True", "return", "False" ]
Check if a time is valid or not :return: time is valid or not :rtype: bool
[ "Check", "if", "a", "time", "is", "valid", "or", "not" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L274-L288
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.get_min_from_t
def get_min_from_t(self, timestamp): """ Get the first time > timestamp which is valid :param timestamp: number of seconds :type timestamp: int :return: number of seconds :rtype: int TODO: not used, so delete it """ mins_incl = [] for daterange in self.dateranges: mins_incl.append(daterange.get_min_from_t(timestamp)) return min(mins_incl)
python
def get_min_from_t(self, timestamp): """ Get the first time > timestamp which is valid :param timestamp: number of seconds :type timestamp: int :return: number of seconds :rtype: int TODO: not used, so delete it """ mins_incl = [] for daterange in self.dateranges: mins_incl.append(daterange.get_min_from_t(timestamp)) return min(mins_incl)
[ "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", ")" ]
Get the first time > timestamp which is valid :param timestamp: number of seconds :type timestamp: int :return: number of seconds :rtype: int TODO: not used, so delete it
[ "Get", "the", "first", "time", ">", "timestamp", "which", "is", "valid" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L291-L304
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.clean_cache
def clean_cache(self): """ Clean cache with entries older than now because not used in future ;) :return: None """ 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] # same for the invalid cache t_to_del = [] for timestamp in self.invalid_cache: if timestamp < now: t_to_del.append(timestamp) for timestamp in t_to_del: del self.invalid_cache[timestamp]
python
def clean_cache(self): """ Clean cache with entries older than now because not used in future ;) :return: None """ 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] # same for the invalid cache t_to_del = [] for timestamp in self.invalid_cache: if timestamp < now: t_to_del.append(timestamp) for timestamp in t_to_del: del self.invalid_cache[timestamp]
[ "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", "]", "# same for the invalid cache", "t_to_del", "=", "[", "]", "for", "timestamp", "in", "self", ".", "invalid_cache", ":", "if", "timestamp", "<", "now", ":", "t_to_del", ".", "append", "(", "timestamp", ")", "for", "timestamp", "in", "t_to_del", ":", "del", "self", ".", "invalid_cache", "[", "timestamp", "]" ]
Clean cache with entries older than now because not used in future ;) :return: None
[ "Clean", "cache", "with", "entries", "older", "than", "now", "because", "not", "used", "in", "future", ";", ")" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L381-L401
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.get_next_valid_time_from_t
def get_next_valid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get next valid time. If it's in cache, get it, otherwise define it. The limit to find it is 1 year. :param timestamp: number of seconds :type timestamp: int or float :return: Nothing or time in seconds :rtype: None or int """ timestamp = int(timestamp) original_t = timestamp res_from_cache = self.find_next_valid_time_from_cache(timestamp) if res_from_cache is not None: return res_from_cache still_loop = True # Loop for all minutes... while still_loop: local_min = None # Ok, not in cache... dr_mins = [] for daterange in self.dateranges: dr_mins.append(daterange.get_next_valid_time_from_t(timestamp)) s_dr_mins = sorted([d for d in dr_mins if d is not None]) for t01 in s_dr_mins: if not self.exclude and still_loop: # No Exclude so we are good local_min = t01 still_loop = False else: for timeperiod in self.exclude: if not timeperiod.is_time_valid(t01) and still_loop: # OK we found a date that is not valid in any exclude timeperiod local_min = t01 still_loop = False if local_min is None: # Looking for next invalid date exc_mins = [] if s_dr_mins != []: for timeperiod in self.exclude: exc_mins.append(timeperiod.get_next_invalid_time_from_t(s_dr_mins[0])) s_exc_mins = sorted([d for d in exc_mins if d is not None]) if s_exc_mins != []: local_min = s_exc_mins[0] if local_min is None: still_loop = False else: timestamp = local_min # No loop more than one year if timestamp > original_t + 3600 * 24 * 366 + 1: still_loop = False local_min = None # Ok, we update the cache... self.cache[original_t] = local_min return local_min
python
def get_next_valid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get next valid time. If it's in cache, get it, otherwise define it. The limit to find it is 1 year. :param timestamp: number of seconds :type timestamp: int or float :return: Nothing or time in seconds :rtype: None or int """ timestamp = int(timestamp) original_t = timestamp res_from_cache = self.find_next_valid_time_from_cache(timestamp) if res_from_cache is not None: return res_from_cache still_loop = True # Loop for all minutes... while still_loop: local_min = None # Ok, not in cache... dr_mins = [] for daterange in self.dateranges: dr_mins.append(daterange.get_next_valid_time_from_t(timestamp)) s_dr_mins = sorted([d for d in dr_mins if d is not None]) for t01 in s_dr_mins: if not self.exclude and still_loop: # No Exclude so we are good local_min = t01 still_loop = False else: for timeperiod in self.exclude: if not timeperiod.is_time_valid(t01) and still_loop: # OK we found a date that is not valid in any exclude timeperiod local_min = t01 still_loop = False if local_min is None: # Looking for next invalid date exc_mins = [] if s_dr_mins != []: for timeperiod in self.exclude: exc_mins.append(timeperiod.get_next_invalid_time_from_t(s_dr_mins[0])) s_exc_mins = sorted([d for d in exc_mins if d is not None]) if s_exc_mins != []: local_min = s_exc_mins[0] if local_min is None: still_loop = False else: timestamp = local_min # No loop more than one year if timestamp > original_t + 3600 * 24 * 366 + 1: still_loop = False local_min = None # Ok, we update the cache... self.cache[original_t] = local_min return local_min
[ "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", "None", ":", "return", "res_from_cache", "still_loop", "=", "True", "# Loop for all minutes...", "while", "still_loop", ":", "local_min", "=", "None", "# Ok, not in cache...", "dr_mins", "=", "[", "]", "for", "daterange", "in", "self", ".", "dateranges", ":", "dr_mins", ".", "append", "(", "daterange", ".", "get_next_valid_time_from_t", "(", "timestamp", ")", ")", "s_dr_mins", "=", "sorted", "(", "[", "d", "for", "d", "in", "dr_mins", "if", "d", "is", "not", "None", "]", ")", "for", "t01", "in", "s_dr_mins", ":", "if", "not", "self", ".", "exclude", "and", "still_loop", ":", "# No Exclude so we are good", "local_min", "=", "t01", "still_loop", "=", "False", "else", ":", "for", "timeperiod", "in", "self", ".", "exclude", ":", "if", "not", "timeperiod", ".", "is_time_valid", "(", "t01", ")", "and", "still_loop", ":", "# OK we found a date that is not valid in any exclude timeperiod", "local_min", "=", "t01", "still_loop", "=", "False", "if", "local_min", "is", "None", ":", "# Looking for next invalid date", "exc_mins", "=", "[", "]", "if", "s_dr_mins", "!=", "[", "]", ":", "for", "timeperiod", "in", "self", ".", "exclude", ":", "exc_mins", ".", "append", "(", "timeperiod", ".", "get_next_invalid_time_from_t", "(", "s_dr_mins", "[", "0", "]", ")", ")", "s_exc_mins", "=", "sorted", "(", "[", "d", "for", "d", "in", "exc_mins", "if", "d", "is", "not", "None", "]", ")", "if", "s_exc_mins", "!=", "[", "]", ":", "local_min", "=", "s_exc_mins", "[", "0", "]", "if", "local_min", "is", "None", ":", "still_loop", "=", "False", "else", ":", "timestamp", "=", "local_min", "# No loop more than one year", "if", "timestamp", ">", "original_t", "+", "3600", "*", "24", "*", "366", "+", "1", ":", "still_loop", "=", "False", "local_min", "=", "None", "# Ok, we update the cache...", "self", ".", "cache", "[", "original_t", "]", "=", "local_min", "return", "local_min" ]
Get next valid time. If it's in cache, get it, otherwise define it. The limit to find it is 1 year. :param timestamp: number of seconds :type timestamp: int or float :return: Nothing or time in seconds :rtype: None or int
[ "Get", "next", "valid", "time", ".", "If", "it", "s", "in", "cache", "get", "it", "otherwise", "define", "it", ".", "The", "limit", "to", "find", "it", "is", "1", "year", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L403-L470
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.get_next_invalid_time_from_t
def get_next_invalid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float """ timestamp = int(timestamp) original_t = timestamp dr_mins = [] for daterange in self.dateranges: timestamp = original_t cont = True while cont: start = daterange.get_next_valid_time_from_t(timestamp) if start is not None: end = daterange.get_next_invalid_time_from_t(start) dr_mins.append((start, end)) timestamp = end else: cont = False if timestamp > original_t + (3600 * 24 * 365): cont = False periods = merge_periods(dr_mins) # manage exclude periods dr_mins = [] for exclude in self.exclude: for daterange in exclude.dateranges: timestamp = original_t cont = True while cont: start = daterange.get_next_valid_time_from_t(timestamp) if start is not None: end = daterange.get_next_invalid_time_from_t(start) dr_mins.append((start, end)) timestamp = end else: cont = False if timestamp > original_t + (3600 * 24 * 365): cont = False if not dr_mins: periods_exclude = [] else: periods_exclude = merge_periods(dr_mins) if len(periods) >= 1: # if first valid period is after original timestamp, the first invalid time # is the original timestamp if periods[0][0] > original_t: return original_t # check the first period + first period of exclude if len(periods_exclude) >= 1: if periods_exclude[0][0] < periods[0][1]: return periods_exclude[0][0] return periods[0][1] return original_t
python
def get_next_invalid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float """ timestamp = int(timestamp) original_t = timestamp dr_mins = [] for daterange in self.dateranges: timestamp = original_t cont = True while cont: start = daterange.get_next_valid_time_from_t(timestamp) if start is not None: end = daterange.get_next_invalid_time_from_t(start) dr_mins.append((start, end)) timestamp = end else: cont = False if timestamp > original_t + (3600 * 24 * 365): cont = False periods = merge_periods(dr_mins) # manage exclude periods dr_mins = [] for exclude in self.exclude: for daterange in exclude.dateranges: timestamp = original_t cont = True while cont: start = daterange.get_next_valid_time_from_t(timestamp) if start is not None: end = daterange.get_next_invalid_time_from_t(start) dr_mins.append((start, end)) timestamp = end else: cont = False if timestamp > original_t + (3600 * 24 * 365): cont = False if not dr_mins: periods_exclude = [] else: periods_exclude = merge_periods(dr_mins) if len(periods) >= 1: # if first valid period is after original timestamp, the first invalid time # is the original timestamp if periods[0][0] > original_t: return original_t # check the first period + first period of exclude if len(periods_exclude) >= 1: if periods_exclude[0][0] < periods[0][1]: return periods_exclude[0][0] return periods[0][1] return original_t
[ "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", "cont", "=", "True", "while", "cont", ":", "start", "=", "daterange", ".", "get_next_valid_time_from_t", "(", "timestamp", ")", "if", "start", "is", "not", "None", ":", "end", "=", "daterange", ".", "get_next_invalid_time_from_t", "(", "start", ")", "dr_mins", ".", "append", "(", "(", "start", ",", "end", ")", ")", "timestamp", "=", "end", "else", ":", "cont", "=", "False", "if", "timestamp", ">", "original_t", "+", "(", "3600", "*", "24", "*", "365", ")", ":", "cont", "=", "False", "periods", "=", "merge_periods", "(", "dr_mins", ")", "# manage exclude periods", "dr_mins", "=", "[", "]", "for", "exclude", "in", "self", ".", "exclude", ":", "for", "daterange", "in", "exclude", ".", "dateranges", ":", "timestamp", "=", "original_t", "cont", "=", "True", "while", "cont", ":", "start", "=", "daterange", ".", "get_next_valid_time_from_t", "(", "timestamp", ")", "if", "start", "is", "not", "None", ":", "end", "=", "daterange", ".", "get_next_invalid_time_from_t", "(", "start", ")", "dr_mins", ".", "append", "(", "(", "start", ",", "end", ")", ")", "timestamp", "=", "end", "else", ":", "cont", "=", "False", "if", "timestamp", ">", "original_t", "+", "(", "3600", "*", "24", "*", "365", ")", ":", "cont", "=", "False", "if", "not", "dr_mins", ":", "periods_exclude", "=", "[", "]", "else", ":", "periods_exclude", "=", "merge_periods", "(", "dr_mins", ")", "if", "len", "(", "periods", ")", ">=", "1", ":", "# if first valid period is after original timestamp, the first invalid time", "# is the original timestamp", "if", "periods", "[", "0", "]", "[", "0", "]", ">", "original_t", ":", "return", "original_t", "# check the first period + first period of exclude", "if", "len", "(", "periods_exclude", ")", ">=", "1", ":", "if", "periods_exclude", "[", "0", "]", "[", "0", "]", "<", "periods", "[", "0", "]", "[", "1", "]", ":", "return", "periods_exclude", "[", "0", "]", "[", "0", "]", "return", "periods", "[", "0", "]", "[", "1", "]", "return", "original_t" ]
Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float
[ "Get", "the", "next", "invalid", "time" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L472-L532
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.explode
def explode(self): """ Try to resolve all unresolved elements :return: None """ for entry in self.unresolved: self.resolve_daterange(self.dateranges, entry) self.unresolved = []
python
def explode(self): """ Try to resolve all unresolved elements :return: None """ for entry in self.unresolved: self.resolve_daterange(self.dateranges, entry) self.unresolved = []
[ "def", "explode", "(", "self", ")", ":", "for", "entry", "in", "self", ".", "unresolved", ":", "self", ".", "resolve_daterange", "(", "self", ".", "dateranges", ",", "entry", ")", "self", ".", "unresolved", "=", "[", "]" ]
Try to resolve all unresolved elements :return: None
[ "Try", "to", "resolve", "all", "unresolved", "elements" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L868-L876
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.linkify
def linkify(self, timeperiods): """ Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None """ 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 tp_name in excluded_tps: timepriod = timeperiods.find_by_name(tp_name.strip()) if timepriod is not None: new_exclude.append(timepriod.uuid) else: msg = "[timeentry::%s] unknown %s timeperiod" % (self.get_name(), tp_name) self.add_error(msg) self.exclude = new_exclude
python
def linkify(self, timeperiods): """ Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None """ 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 tp_name in excluded_tps: timepriod = timeperiods.find_by_name(tp_name.strip()) if timepriod is not None: new_exclude.append(timepriod.uuid) else: msg = "[timeentry::%s] unknown %s timeperiod" % (self.get_name(), tp_name) self.add_error(msg) self.exclude = new_exclude
[ "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", "tp_name", "in", "excluded_tps", ":", "timepriod", "=", "timeperiods", ".", "find_by_name", "(", "tp_name", ".", "strip", "(", ")", ")", "if", "timepriod", "is", "not", "None", ":", "new_exclude", ".", "append", "(", "timepriod", ".", "uuid", ")", "else", ":", "msg", "=", "\"[timeentry::%s] unknown %s timeperiod\"", "%", "(", "self", ".", "get_name", "(", ")", ",", "tp_name", ")", "self", ".", "add_error", "(", "msg", ")", "self", ".", "exclude", "=", "new_exclude" ]
Will make timeperiod in exclude with id of the timeperiods :param timeperiods: Timeperiods object :type timeperiods: :return: None
[ "Will", "make", "timeperiod", "in", "exclude", "with", "id", "of", "the", "timeperiods" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L878-L897
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiod.check_exclude_rec
def check_exclude_rec(self): # pylint: disable=access-member-before-definition """ Check if this timeperiod is tagged :return: if tagged return false, if not true :rtype: bool """ if self.rec_tag: msg = "[timeentry::%s] is in a loop in exclude parameter" % (self.get_name()) self.add_error(msg) return False self.rec_tag = True for timeperiod in self.exclude: timeperiod.check_exclude_rec() return True
python
def check_exclude_rec(self): # pylint: disable=access-member-before-definition """ Check if this timeperiod is tagged :return: if tagged return false, if not true :rtype: bool """ if self.rec_tag: msg = "[timeentry::%s] is in a loop in exclude parameter" % (self.get_name()) self.add_error(msg) return False self.rec_tag = True for timeperiod in self.exclude: timeperiod.check_exclude_rec() return True
[ "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", "self", ".", "rec_tag", "=", "True", "for", "timeperiod", "in", "self", ".", "exclude", ":", "timeperiod", ".", "check_exclude_rec", "(", ")", "return", "True" ]
Check if this timeperiod is tagged :return: if tagged return false, if not true :rtype: bool
[ "Check", "if", "this", "timeperiod", "is", "tagged" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L899-L914
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiods.explode
def explode(self): """ Try to resolve each timeperiod :return: None """ for t_id in self.items: timeperiod = self.items[t_id] timeperiod.explode()
python
def explode(self): """ Try to resolve each timeperiod :return: None """ for t_id in self.items: timeperiod = self.items[t_id] timeperiod.explode()
[ "def", "explode", "(", "self", ")", ":", "for", "t_id", "in", "self", ".", "items", ":", "timeperiod", "=", "self", ".", "items", "[", "t_id", "]", "timeperiod", ".", "explode", "(", ")" ]
Try to resolve each timeperiod :return: None
[ "Try", "to", "resolve", "each", "timeperiod" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L948-L956
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiods.linkify
def linkify(self): """ Check exclusion for each timeperiod :return: None """ for t_id in self.items: timeperiod = self.items[t_id] timeperiod.linkify(self)
python
def linkify(self): """ Check exclusion for each timeperiod :return: None """ for t_id in self.items: timeperiod = self.items[t_id] timeperiod.linkify(self)
[ "def", "linkify", "(", "self", ")", ":", "for", "t_id", "in", "self", ".", "items", ":", "timeperiod", "=", "self", ".", "items", "[", "t_id", "]", "timeperiod", ".", "linkify", "(", "self", ")" ]
Check exclusion for each timeperiod :return: None
[ "Check", "exclusion", "for", "each", "timeperiod" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L958-L966
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiods.apply_inheritance
def apply_inheritance(self): """ The only interesting property to inherit is exclude :return: None """ 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 for timeperiod in self: self.get_unresolved_properties_by_inheritance(timeperiod)
python
def apply_inheritance(self): """ The only interesting property to inherit is exclude :return: None """ 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 for timeperiod in self: self.get_unresolved_properties_by_inheritance(timeperiod)
[ "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", "for", "timeperiod", "in", "self", ":", "self", ".", "get_unresolved_properties_by_inheritance", "(", "timeperiod", ")" ]
The only interesting property to inherit is exclude :return: None
[ "The", "only", "interesting", "property", "to", "inherit", "is", "exclude" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L980-L993
train
Alignak-monitoring/alignak
alignak/objects/timeperiod.py
Timeperiods.is_correct
def is_correct(self): """ check if each properties of timeperiods are valid :return: True if is correct, otherwise False :rtype: bool """ 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.values()): for tmp_tp in list(self.items.values()): tmp_tp.rec_tag = False valid = timeperiod.check_exclude_rec() and valid # We clean the tags and collect the warning/erro messages for timeperiod in list(self.items.values()): del timeperiod.rec_tag # Now other checks if not timeperiod.is_correct(): valid = False source = getattr(timeperiod, 'imported_from', "unknown source") msg = "Configuration in %s::%s is incorrect; from: %s" % ( timeperiod.my_type, timeperiod.get_name(), source ) self.add_error(msg) self.configuration_errors += timeperiod.configuration_errors self.configuration_warnings += timeperiod.configuration_warnings # And check all timeperiods for correct (sunday is false) for timeperiod in self: valid = timeperiod.is_correct() and valid return valid
python
def is_correct(self): """ check if each properties of timeperiods are valid :return: True if is correct, otherwise False :rtype: bool """ 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.values()): for tmp_tp in list(self.items.values()): tmp_tp.rec_tag = False valid = timeperiod.check_exclude_rec() and valid # We clean the tags and collect the warning/erro messages for timeperiod in list(self.items.values()): del timeperiod.rec_tag # Now other checks if not timeperiod.is_correct(): valid = False source = getattr(timeperiod, 'imported_from', "unknown source") msg = "Configuration in %s::%s is incorrect; from: %s" % ( timeperiod.my_type, timeperiod.get_name(), source ) self.add_error(msg) self.configuration_errors += timeperiod.configuration_errors self.configuration_warnings += timeperiod.configuration_warnings # And check all timeperiods for correct (sunday is false) for timeperiod in self: valid = timeperiod.is_correct() and valid return valid
[ "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", ".", "values", "(", ")", ")", ":", "for", "tmp_tp", "in", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ":", "tmp_tp", ".", "rec_tag", "=", "False", "valid", "=", "timeperiod", ".", "check_exclude_rec", "(", ")", "and", "valid", "# We clean the tags and collect the warning/erro messages", "for", "timeperiod", "in", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ":", "del", "timeperiod", ".", "rec_tag", "# Now other checks", "if", "not", "timeperiod", ".", "is_correct", "(", ")", ":", "valid", "=", "False", "source", "=", "getattr", "(", "timeperiod", ",", "'imported_from'", ",", "\"unknown source\"", ")", "msg", "=", "\"Configuration in %s::%s is incorrect; from: %s\"", "%", "(", "timeperiod", ".", "my_type", ",", "timeperiod", ".", "get_name", "(", ")", ",", "source", ")", "self", ".", "add_error", "(", "msg", ")", "self", ".", "configuration_errors", "+=", "timeperiod", ".", "configuration_errors", "self", ".", "configuration_warnings", "+=", "timeperiod", ".", "configuration_warnings", "# And check all timeperiods for correct (sunday is false)", "for", "timeperiod", "in", "self", ":", "valid", "=", "timeperiod", ".", "is_correct", "(", ")", "and", "valid", "return", "valid" ]
check if each properties of timeperiods are valid :return: True if is correct, otherwise False :rtype: bool
[ "check", "if", "each", "properties", "of", "timeperiods", "are", "valid" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L995-L1033
train
Alignak-monitoring/alignak
alignak/dispatcher.py
Dispatcher.check_status_and_get_events
def check_status_and_get_events(self): # pylint: disable=too-many-branches """Get all the daemons status :return: Dictionary with all the daemons returned information :rtype: dict """ statistics = {} events = [] for daemon_link in self.all_daemons_links: if daemon_link == self.arbiter_link: # I exclude myself from the polling, sure I am reachable ;) continue if not daemon_link.active: # I exclude the daemons that are not active continue try: # Do not get the details to avoid overloading the communication daemon_link.statistics = daemon_link.get_daemon_stats(details=False) if daemon_link.statistics: daemon_link.statistics['_freshness'] = int(time.time()) statistics[daemon_link.name] = daemon_link.statistics logger.debug("Daemon %s statistics: %s", daemon_link.name, daemon_link.statistics) except LinkError: logger.warning("Daemon connection failed, I could not get statistics.") try: got = daemon_link.get_events() if got: events.extend(got) logger.debug("Daemon %s has %d events: %s", daemon_link.name, len(got), got) except LinkError: logger.warning("Daemon connection failed, I could not get events.") return events
python
def check_status_and_get_events(self): # pylint: disable=too-many-branches """Get all the daemons status :return: Dictionary with all the daemons returned information :rtype: dict """ statistics = {} events = [] for daemon_link in self.all_daemons_links: if daemon_link == self.arbiter_link: # I exclude myself from the polling, sure I am reachable ;) continue if not daemon_link.active: # I exclude the daemons that are not active continue try: # Do not get the details to avoid overloading the communication daemon_link.statistics = daemon_link.get_daemon_stats(details=False) if daemon_link.statistics: daemon_link.statistics['_freshness'] = int(time.time()) statistics[daemon_link.name] = daemon_link.statistics logger.debug("Daemon %s statistics: %s", daemon_link.name, daemon_link.statistics) except LinkError: logger.warning("Daemon connection failed, I could not get statistics.") try: got = daemon_link.get_events() if got: events.extend(got) logger.debug("Daemon %s has %d events: %s", daemon_link.name, len(got), got) except LinkError: logger.warning("Daemon connection failed, I could not get events.") return events
[ "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 the polling, sure I am reachable ;)", "continue", "if", "not", "daemon_link", ".", "active", ":", "# I exclude the daemons that are not active", "continue", "try", ":", "# Do not get the details to avoid overloading the communication", "daemon_link", ".", "statistics", "=", "daemon_link", ".", "get_daemon_stats", "(", "details", "=", "False", ")", "if", "daemon_link", ".", "statistics", ":", "daemon_link", ".", "statistics", "[", "'_freshness'", "]", "=", "int", "(", "time", ".", "time", "(", ")", ")", "statistics", "[", "daemon_link", ".", "name", "]", "=", "daemon_link", ".", "statistics", "logger", ".", "debug", "(", "\"Daemon %s statistics: %s\"", ",", "daemon_link", ".", "name", ",", "daemon_link", ".", "statistics", ")", "except", "LinkError", ":", "logger", ".", "warning", "(", "\"Daemon connection failed, I could not get statistics.\"", ")", "try", ":", "got", "=", "daemon_link", ".", "get_events", "(", ")", "if", "got", ":", "events", ".", "extend", "(", "got", ")", "logger", ".", "debug", "(", "\"Daemon %s has %d events: %s\"", ",", "daemon_link", ".", "name", ",", "len", "(", "got", ")", ",", "got", ")", "except", "LinkError", ":", "logger", ".", "warning", "(", "\"Daemon connection failed, I could not get events.\"", ")", "return", "events" ]
Get all the daemons status :return: Dictionary with all the daemons returned information :rtype: dict
[ "Get", "all", "the", "daemons", "status" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L299-L337
train
Alignak-monitoring/alignak
alignak/dispatcher.py
Dispatcher.get_scheduler_ordered_list
def get_scheduler_ordered_list(self, realm): """Get sorted scheduler list for a specific realm List is ordered as: alive first, then spare (if any), then dead scheduler links :param realm: realm we want scheduler from :type realm: alignak.objects.realm.Realm :return: sorted scheduler list :rtype: list[alignak.objects.schedulerlink.SchedulerLink] """ # 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 we sort the schedulers so we take alive, then spare, then dead, alive = [] spare = [] deads = [] for sdata in scheduler_links: if sdata.alive and not sdata.spare: alive.append(sdata) elif sdata.alive and sdata.spare: spare.append(sdata) else: deads.append(sdata) scheduler_links = [] scheduler_links.extend(alive) scheduler_links.extend(spare) scheduler_links.extend(deads) scheduler_links.reverse() # I need to pop the list, so reverse the list... return scheduler_links
python
def get_scheduler_ordered_list(self, realm): """Get sorted scheduler list for a specific realm List is ordered as: alive first, then spare (if any), then dead scheduler links :param realm: realm we want scheduler from :type realm: alignak.objects.realm.Realm :return: sorted scheduler list :rtype: list[alignak.objects.schedulerlink.SchedulerLink] """ # 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 we sort the schedulers so we take alive, then spare, then dead, alive = [] spare = [] deads = [] for sdata in scheduler_links: if sdata.alive and not sdata.spare: alive.append(sdata) elif sdata.alive and sdata.spare: spare.append(sdata) else: deads.append(sdata) scheduler_links = [] scheduler_links.extend(alive) scheduler_links.extend(spare) scheduler_links.extend(deads) scheduler_links.reverse() # I need to pop the list, so reverse the list... return scheduler_links
[ "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 we sort the schedulers so we take alive, then spare, then dead,", "alive", "=", "[", "]", "spare", "=", "[", "]", "deads", "=", "[", "]", "for", "sdata", "in", "scheduler_links", ":", "if", "sdata", ".", "alive", "and", "not", "sdata", ".", "spare", ":", "alive", ".", "append", "(", "sdata", ")", "elif", "sdata", ".", "alive", "and", "sdata", ".", "spare", ":", "spare", ".", "append", "(", "sdata", ")", "else", ":", "deads", ".", "append", "(", "sdata", ")", "scheduler_links", "=", "[", "]", "scheduler_links", ".", "extend", "(", "alive", ")", "scheduler_links", ".", "extend", "(", "spare", ")", "scheduler_links", ".", "extend", "(", "deads", ")", "scheduler_links", ".", "reverse", "(", ")", "# I need to pop the list, so reverse the list...", "return", "scheduler_links" ]
Get sorted scheduler list for a specific realm List is ordered as: alive first, then spare (if any), then dead scheduler links :param realm: realm we want scheduler from :type realm: alignak.objects.realm.Realm :return: sorted scheduler list :rtype: list[alignak.objects.schedulerlink.SchedulerLink]
[ "Get", "sorted", "scheduler", "list", "for", "a", "specific", "realm" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L466-L498
train
Alignak-monitoring/alignak
alignak/dispatcher.py
Dispatcher.dispatch
def dispatch(self, test=False): # pylint: disable=too-many-branches """ Send configuration to satellites :return: None """ if not self.new_to_dispatch: raise DispatcherError("Dispatcher cannot dispatch, " "because no configuration is prepared!") if self.first_dispatch_done: raise DispatcherError("Dispatcher cannot dispatch, " "because the configuration is still dispatched!") if self.dispatch_ok: logger.info("Dispatching is already done and ok...") return logger.info("Trying to send configuration to the satellites...") self.dispatch_ok = True # todo: the 3 loops hereunder may be factorized for link in self.arbiters: # If not me and a spare arbiter... if link == self.arbiter_link: # I exclude myself from the dispatching, I have my configuration ;) continue if not link.active: # I exclude the daemons that are not active continue if not link.spare: # Do not dispatch to a master arbiter! continue if link.configuration_sent: logger.debug("Arbiter %s already sent!", link.name) continue if not link.reachable: logger.debug("Arbiter %s is not reachable to receive its configuration", link.name) continue logger.info("Sending configuration to the arbiter %s", link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") # Now that the spare arbiter has a configuration, tell him it must not run, # because I'm not dead ;) link.do_not_run() for link in self.schedulers: if link.configuration_sent: logger.debug("Scheduler %s already sent!", link.name) continue if not link.active: # I exclude the daemons that are not active continue if not link.reachable: logger.debug("Scheduler %s is not reachable to receive its configuration", link.name) continue logger.info("Sending configuration to the scheduler %s", link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") for link in self.satellites: if link.configuration_sent: logger.debug("%s %s already sent!", link.type, link.name) continue if not link.active: # I exclude the daemons that are not active continue if not link.reachable: logger.warning("%s %s is not reachable to receive its configuration", link.type, link.name) continue logger.info("Sending configuration to the %s %s", link.type, link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") if self.dispatch_ok: # Newly prepared configuration got dispatched correctly self.new_to_dispatch = False self.first_dispatch_done = True
python
def dispatch(self, test=False): # pylint: disable=too-many-branches """ Send configuration to satellites :return: None """ if not self.new_to_dispatch: raise DispatcherError("Dispatcher cannot dispatch, " "because no configuration is prepared!") if self.first_dispatch_done: raise DispatcherError("Dispatcher cannot dispatch, " "because the configuration is still dispatched!") if self.dispatch_ok: logger.info("Dispatching is already done and ok...") return logger.info("Trying to send configuration to the satellites...") self.dispatch_ok = True # todo: the 3 loops hereunder may be factorized for link in self.arbiters: # If not me and a spare arbiter... if link == self.arbiter_link: # I exclude myself from the dispatching, I have my configuration ;) continue if not link.active: # I exclude the daemons that are not active continue if not link.spare: # Do not dispatch to a master arbiter! continue if link.configuration_sent: logger.debug("Arbiter %s already sent!", link.name) continue if not link.reachable: logger.debug("Arbiter %s is not reachable to receive its configuration", link.name) continue logger.info("Sending configuration to the arbiter %s", link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") # Now that the spare arbiter has a configuration, tell him it must not run, # because I'm not dead ;) link.do_not_run() for link in self.schedulers: if link.configuration_sent: logger.debug("Scheduler %s already sent!", link.name) continue if not link.active: # I exclude the daemons that are not active continue if not link.reachable: logger.debug("Scheduler %s is not reachable to receive its configuration", link.name) continue logger.info("Sending configuration to the scheduler %s", link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") for link in self.satellites: if link.configuration_sent: logger.debug("%s %s already sent!", link.type, link.name) continue if not link.active: # I exclude the daemons that are not active continue if not link.reachable: logger.warning("%s %s is not reachable to receive its configuration", link.type, link.name) continue logger.info("Sending configuration to the %s %s", link.type, link.name) logger.debug("- %s", link.cfg) link.put_conf(link.cfg, test=test) link.configuration_sent = True logger.info("- sent") if self.dispatch_ok: # Newly prepared configuration got dispatched correctly self.new_to_dispatch = False self.first_dispatch_done = True
[ "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", ".", "first_dispatch_done", ":", "raise", "DispatcherError", "(", "\"Dispatcher cannot dispatch, \"", "\"because the configuration is still dispatched!\"", ")", "if", "self", ".", "dispatch_ok", ":", "logger", ".", "info", "(", "\"Dispatching is already done and ok...\"", ")", "return", "logger", ".", "info", "(", "\"Trying to send configuration to the satellites...\"", ")", "self", ".", "dispatch_ok", "=", "True", "# todo: the 3 loops hereunder may be factorized", "for", "link", "in", "self", ".", "arbiters", ":", "# If not me and a spare arbiter...", "if", "link", "==", "self", ".", "arbiter_link", ":", "# I exclude myself from the dispatching, I have my configuration ;)", "continue", "if", "not", "link", ".", "active", ":", "# I exclude the daemons that are not active", "continue", "if", "not", "link", ".", "spare", ":", "# Do not dispatch to a master arbiter!", "continue", "if", "link", ".", "configuration_sent", ":", "logger", ".", "debug", "(", "\"Arbiter %s already sent!\"", ",", "link", ".", "name", ")", "continue", "if", "not", "link", ".", "reachable", ":", "logger", ".", "debug", "(", "\"Arbiter %s is not reachable to receive its configuration\"", ",", "link", ".", "name", ")", "continue", "logger", ".", "info", "(", "\"Sending configuration to the arbiter %s\"", ",", "link", ".", "name", ")", "logger", ".", "debug", "(", "\"- %s\"", ",", "link", ".", "cfg", ")", "link", ".", "put_conf", "(", "link", ".", "cfg", ",", "test", "=", "test", ")", "link", ".", "configuration_sent", "=", "True", "logger", ".", "info", "(", "\"- sent\"", ")", "# Now that the spare arbiter has a configuration, tell him it must not run,", "# because I'm not dead ;)", "link", ".", "do_not_run", "(", ")", "for", "link", "in", "self", ".", "schedulers", ":", "if", "link", ".", "configuration_sent", ":", "logger", ".", "debug", "(", "\"Scheduler %s already sent!\"", ",", "link", ".", "name", ")", "continue", "if", "not", "link", ".", "active", ":", "# I exclude the daemons that are not active", "continue", "if", "not", "link", ".", "reachable", ":", "logger", ".", "debug", "(", "\"Scheduler %s is not reachable to receive its configuration\"", ",", "link", ".", "name", ")", "continue", "logger", ".", "info", "(", "\"Sending configuration to the scheduler %s\"", ",", "link", ".", "name", ")", "logger", ".", "debug", "(", "\"- %s\"", ",", "link", ".", "cfg", ")", "link", ".", "put_conf", "(", "link", ".", "cfg", ",", "test", "=", "test", ")", "link", ".", "configuration_sent", "=", "True", "logger", ".", "info", "(", "\"- sent\"", ")", "for", "link", "in", "self", ".", "satellites", ":", "if", "link", ".", "configuration_sent", ":", "logger", ".", "debug", "(", "\"%s %s already sent!\"", ",", "link", ".", "type", ",", "link", ".", "name", ")", "continue", "if", "not", "link", ".", "active", ":", "# I exclude the daemons that are not active", "continue", "if", "not", "link", ".", "reachable", ":", "logger", ".", "warning", "(", "\"%s %s is not reachable to receive its configuration\"", ",", "link", ".", "type", ",", "link", ".", "name", ")", "continue", "logger", ".", "info", "(", "\"Sending configuration to the %s %s\"", ",", "link", ".", "type", ",", "link", ".", "name", ")", "logger", ".", "debug", "(", "\"- %s\"", ",", "link", ".", "cfg", ")", "link", ".", "put_conf", "(", "link", ".", "cfg", ",", "test", "=", "test", ")", "link", ".", "configuration_sent", "=", "True", "logger", ".", "info", "(", "\"- sent\"", ")", "if", "self", ".", "dispatch_ok", ":", "# Newly prepared configuration got dispatched correctly", "self", ".", "new_to_dispatch", "=", "False", "self", ".", "first_dispatch_done", "=", "True" ]
Send configuration to satellites :return: None
[ "Send", "configuration", "to", "satellites" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L839-L944
train
Alignak-monitoring/alignak
alignak/dispatcher.py
Dispatcher.stop_request
def stop_request(self, stop_now=False): """Send a stop request to all the daemons :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: True if all daemons are reachable """ 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 from the process, I know we are going to stop ;) continue if not daemon_link.active: # I exclude the daemons that are not active continue # Send a stop request to the daemon try: stop_ok = daemon_link.stop_request(stop_now=stop_now) except LinkError: stop_ok = True logger.warning("Daemon stop request failed, %s probably stopped!", daemon_link) all_ok = all_ok and stop_ok daemon_link.stopping = True self.stop_request_sent = all_ok return self.stop_request_sent
python
def stop_request(self, stop_now=False): """Send a stop request to all the daemons :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: True if all daemons are reachable """ 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 from the process, I know we are going to stop ;) continue if not daemon_link.active: # I exclude the daemons that are not active continue # Send a stop request to the daemon try: stop_ok = daemon_link.stop_request(stop_now=stop_now) except LinkError: stop_ok = True logger.warning("Daemon stop request failed, %s probably stopped!", daemon_link) all_ok = all_ok and stop_ok daemon_link.stopping = True self.stop_request_sent = all_ok return self.stop_request_sent
[ "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 from the process, I know we are going to stop ;)", "continue", "if", "not", "daemon_link", ".", "active", ":", "# I exclude the daemons that are not active", "continue", "# Send a stop request to the daemon", "try", ":", "stop_ok", "=", "daemon_link", ".", "stop_request", "(", "stop_now", "=", "stop_now", ")", "except", "LinkError", ":", "stop_ok", "=", "True", "logger", ".", "warning", "(", "\"Daemon stop request failed, %s probably stopped!\"", ",", "daemon_link", ")", "all_ok", "=", "all_ok", "and", "stop_ok", "daemon_link", ".", "stopping", "=", "True", "self", ".", "stop_request_sent", "=", "all_ok", "return", "self", ".", "stop_request_sent" ]
Send a stop request to all the daemons :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: True if all daemons are reachable
[ "Send", "a", "stop", "request", "to", "all", "the", "daemons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L946-L976
train
Alignak-monitoring/alignak
alignak/property.py
BoolProp.pythonize
def pythonize(self, val): """Convert value into a boolean :param val: value to convert :type val: bool, int, str :return: boolean corresponding to value :: {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} :rtype: bool """ __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 = unique_value(val).lower() if val in list(__boolean_states__.keys()): return __boolean_states__[val] raise PythonizeError("Cannot convert '%s' to a boolean value" % val)
python
def pythonize(self, val): """Convert value into a boolean :param val: value to convert :type val: bool, int, str :return: boolean corresponding to value :: {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} :rtype: bool """ __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 = unique_value(val).lower() if val in list(__boolean_states__.keys()): return __boolean_states__[val] raise PythonizeError("Cannot convert '%s' to a boolean value" % val)
[ "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", "=", "unique_value", "(", "val", ")", ".", "lower", "(", ")", "if", "val", "in", "list", "(", "__boolean_states__", ".", "keys", "(", ")", ")", ":", "return", "__boolean_states__", "[", "val", "]", "raise", "PythonizeError", "(", "\"Cannot convert '%s' to a boolean value\"", "%", "val", ")" ]
Convert value into a boolean :param val: value to convert :type val: bool, int, str :return: boolean corresponding to value :: {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} :rtype: bool
[ "Convert", "value", "into", "a", "boolean" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/property.py#L222-L243
train
Alignak-monitoring/alignak
alignak/property.py
ToGuessProp.pythonize
def pythonize(self, val): """If value is a single list element just return the element does nothing otherwise :param val: value to convert :type val: :return: converted value :rtype: """ 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
python
def pythonize(self, val): """If value is a single list element just return the element does nothing otherwise :param val: value to convert :type val: :return: converted value :rtype: """ 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
[ "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 does nothing otherwise :param val: value to convert :type val: :return: converted value :rtype:
[ "If", "value", "is", "a", "single", "list", "element", "just", "return", "the", "element", "does", "nothing", "otherwise" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/property.py#L471-L485
train
Alignak-monitoring/alignak
alignak/monitor.py
MonitorConnection.login
def login(self, username, password): """ Log into the WS interface and get the authentication token if login is: - accepted, returns True - refused, returns False In case of any error, raises a BackendException :param username: login name :type username: str :param password: password :type password: str :param generate: Can have these values: enabled | force | disabled :type generate: str :return: return True if authentication is successfull, otherwise False :rtype: bool """ 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 not password: logger.error("Username or password cannot be None!") self.set_token(token=None) return False endpoint = 'login' json = {'username': username, 'password': password} response = self.get_response(method='POST', endpoint=endpoint, json=json) if response.status_code == 401: logger.error("Access denied to %s", self.url_endpoint_root) self.set_token(token=None) return False resp = self.decode(response=response) if 'token' in resp: self.set_token(token=resp['token']) return True return False
python
def login(self, username, password): """ Log into the WS interface and get the authentication token if login is: - accepted, returns True - refused, returns False In case of any error, raises a BackendException :param username: login name :type username: str :param password: password :type password: str :param generate: Can have these values: enabled | force | disabled :type generate: str :return: return True if authentication is successfull, otherwise False :rtype: bool """ 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 not password: logger.error("Username or password cannot be None!") self.set_token(token=None) return False endpoint = 'login' json = {'username': username, 'password': password} response = self.get_response(method='POST', endpoint=endpoint, json=json) if response.status_code == 401: logger.error("Access denied to %s", self.url_endpoint_root) self.set_token(token=None) return False resp = self.decode(response=response) if 'token' in resp: self.set_token(token=resp['token']) return True return False
[ "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", "not", "password", ":", "logger", ".", "error", "(", "\"Username or password cannot be None!\"", ")", "self", ".", "set_token", "(", "token", "=", "None", ")", "return", "False", "endpoint", "=", "'login'", "json", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", "}", "response", "=", "self", ".", "get_response", "(", "method", "=", "'POST'", ",", "endpoint", "=", "endpoint", ",", "json", "=", "json", ")", "if", "response", ".", "status_code", "==", "401", ":", "logger", ".", "error", "(", "\"Access denied to %s\"", ",", "self", ".", "url_endpoint_root", ")", "self", ".", "set_token", "(", "token", "=", "None", ")", "return", "False", "resp", "=", "self", ".", "decode", "(", "response", "=", "response", ")", "if", "'token'", "in", "resp", ":", "self", ".", "set_token", "(", "token", "=", "resp", "[", "'token'", "]", ")", "return", "True", "return", "False" ]
Log into the WS interface and get the authentication token if login is: - accepted, returns True - refused, returns False In case of any error, raises a BackendException :param username: login name :type username: str :param password: password :type password: str :param generate: Can have these values: enabled | force | disabled :type generate: str :return: return True if authentication is successfull, otherwise False :rtype: bool
[ "Log", "into", "the", "WS", "interface", "and", "get", "the", "authentication", "token" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L153-L198
train
Alignak-monitoring/alignak
alignak/monitor.py
MonitorConnection.logout
def logout(self): """ Logout from the backend :return: return True if logout is successfull, otherwise False :rtype: bool """ logger.debug("request backend logout") if not self.authenticated: logger.warning("Unnecessary logout ...") return True endpoint = 'logout' _ = self.get_response(method='POST', endpoint=endpoint) self.session.close() self.set_token(token=None) return True
python
def logout(self): """ Logout from the backend :return: return True if logout is successfull, otherwise False :rtype: bool """ logger.debug("request backend logout") if not self.authenticated: logger.warning("Unnecessary logout ...") return True endpoint = 'logout' _ = self.get_response(method='POST', endpoint=endpoint) self.session.close() self.set_token(token=None) return True
[ "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", "=", "endpoint", ")", "self", ".", "session", ".", "close", "(", ")", "self", ".", "set_token", "(", "token", "=", "None", ")", "return", "True" ]
Logout from the backend :return: return True if logout is successfull, otherwise False :rtype: bool
[ "Logout", "from", "the", "backend" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L200-L219
train
Alignak-monitoring/alignak
alignak/monitor.py
MonitorConnection.get
def get(self, endpoint, params=None): """ Get items or item in alignak backend If an error occurs, a BackendException is raised. This method builds a response as a dictionary that always contains: _items and _status:: { u'_items': [ ... ], u'_status': u'OK' } :param endpoint: endpoint (API URL) relative from root endpoint :type endpoint: str :param params: parameters for the backend API :type params: dict :return: dictionary as specified upper :rtype: dict """ 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 resp['_status'] = u'OK' # TODO: Sure?? return resp
python
def get(self, endpoint, params=None): """ Get items or item in alignak backend If an error occurs, a BackendException is raised. This method builds a response as a dictionary that always contains: _items and _status:: { u'_items': [ ... ], u'_status': u'OK' } :param endpoint: endpoint (API URL) relative from root endpoint :type endpoint: str :param params: parameters for the backend API :type params: dict :return: dictionary as specified upper :rtype: dict """ 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 resp['_status'] = u'OK' # TODO: Sure?? return resp
[ "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", "resp", "[", "'_status'", "]", "=", "u'OK'", "# TODO: Sure??", "return", "resp" ]
Get items or item in alignak backend If an error occurs, a BackendException is raised. This method builds a response as a dictionary that always contains: _items and _status:: { u'_items': [ ... ], u'_status': u'OK' } :param endpoint: endpoint (API URL) relative from root endpoint :type endpoint: str :param params: parameters for the backend API :type params: dict :return: dictionary as specified upper :rtype: dict
[ "Get", "items", "or", "item", "in", "alignak", "backend" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L221-L249
train
Alignak-monitoring/alignak
alignak/monitor.py
MonitorConnection.post
def post(self, endpoint, data, files=None, headers=None): # pylint: disable=unused-argument """ Create a new item :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to create :type data: dict :param files: Not used. To be implemented :type files: None :param headers: headers (example: Content-Type) :type headers: dict :return: response (creation information) :rtype: dict """ # We let Requests encode data to json response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers) resp = self.decode(response=response) return resp
python
def post(self, endpoint, data, files=None, headers=None): # pylint: disable=unused-argument """ Create a new item :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to create :type data: dict :param files: Not used. To be implemented :type files: None :param headers: headers (example: Content-Type) :type headers: dict :return: response (creation information) :rtype: dict """ # We let Requests encode data to json response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers) resp = self.decode(response=response) return resp
[ "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", ".", "decode", "(", "response", "=", "response", ")", "return", "resp" ]
Create a new item :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to create :type data: dict :param files: Not used. To be implemented :type files: None :param headers: headers (example: Content-Type) :type headers: dict :return: response (creation information) :rtype: dict
[ "Create", "a", "new", "item" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L251-L272
train
Alignak-monitoring/alignak
alignak/monitor.py
MonitorConnection.patch
def patch(self, endpoint, data): """ Method to update an item The headers must include an If-Match containing the object _etag. headers = {'If-Match': contact_etag} The data dictionary contain the fields that must be modified. If the patching fails because the _etag object do not match with the provided one, a BackendException is raised with code = 412. If inception is True, this method makes e new get request on the endpoint to refresh the _etag and then a new patch is called. If an HTTP 412 error occurs, a BackendException is raised. This exception is: - code: 412 - message: response content - response: backend response All other HTTP error raises a BackendException. If some _issues are provided by the backend, this exception is: - code: HTTP error code - message: response content - response: JSON encoded backend response (including '_issues' dictionary ...) If no _issues are provided and an _error is signaled by the backend, this exception is: - code: backend error code - message: backend error message - response: JSON encoded backend response :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to update :type data: dict :param headers: headers (example: Content-Type). 'If-Match' required :type headers: dict :param inception: if True tries to get the last _etag :type inception: bool :return: dictionary containing patch response from the backend :rtype: dict """ response = self.get_response(method='PATCH', endpoint=endpoint, json=data, headers={'Content-Type': 'application/json'}) if response.status_code == 200: return self.decode(response=response) return response
python
def patch(self, endpoint, data): """ Method to update an item The headers must include an If-Match containing the object _etag. headers = {'If-Match': contact_etag} The data dictionary contain the fields that must be modified. If the patching fails because the _etag object do not match with the provided one, a BackendException is raised with code = 412. If inception is True, this method makes e new get request on the endpoint to refresh the _etag and then a new patch is called. If an HTTP 412 error occurs, a BackendException is raised. This exception is: - code: 412 - message: response content - response: backend response All other HTTP error raises a BackendException. If some _issues are provided by the backend, this exception is: - code: HTTP error code - message: response content - response: JSON encoded backend response (including '_issues' dictionary ...) If no _issues are provided and an _error is signaled by the backend, this exception is: - code: backend error code - message: backend error message - response: JSON encoded backend response :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to update :type data: dict :param headers: headers (example: Content-Type). 'If-Match' required :type headers: dict :param inception: if True tries to get the last _etag :type inception: bool :return: dictionary containing patch response from the backend :rtype: dict """ response = self.get_response(method='PATCH', endpoint=endpoint, json=data, headers={'Content-Type': 'application/json'}) if response.status_code == 200: return self.decode(response=response) return response
[ "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", ".", "decode", "(", "response", "=", "response", ")", "return", "response" ]
Method to update an item The headers must include an If-Match containing the object _etag. headers = {'If-Match': contact_etag} The data dictionary contain the fields that must be modified. If the patching fails because the _etag object do not match with the provided one, a BackendException is raised with code = 412. If inception is True, this method makes e new get request on the endpoint to refresh the _etag and then a new patch is called. If an HTTP 412 error occurs, a BackendException is raised. This exception is: - code: 412 - message: response content - response: backend response All other HTTP error raises a BackendException. If some _issues are provided by the backend, this exception is: - code: HTTP error code - message: response content - response: JSON encoded backend response (including '_issues' dictionary ...) If no _issues are provided and an _error is signaled by the backend, this exception is: - code: backend error code - message: backend error message - response: JSON encoded backend response :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to update :type data: dict :param headers: headers (example: Content-Type). 'If-Match' required :type headers: dict :param inception: if True tries to get the last _etag :type inception: bool :return: dictionary containing patch response from the backend :rtype: dict
[ "Method", "to", "update", "an", "item" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L274-L322
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver.init
def init(self, conf): """Initialize MacroResolver instance with conf. Must be called at least once. :param conf: configuration to load :type conf: alignak.objects.Config :return: None """ # 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... self.host_class = self.hosts.inner_class self.lists_on_demand.append(self.hosts) self.services = self.my_conf.services self.contacts = self.my_conf.contacts self.lists_on_demand.append(self.contacts) self.hostgroups = self.my_conf.hostgroups self.lists_on_demand.append(self.hostgroups) self.commands = self.my_conf.commands self.servicegroups = self.my_conf.servicegroups self.lists_on_demand.append(self.servicegroups) self.contactgroups = self.my_conf.contactgroups self.lists_on_demand.append(self.contactgroups) self.illegal_macro_output_chars = self.my_conf.illegal_macro_output_chars self.env_prefix = self.my_conf.env_variables_prefix
python
def init(self, conf): """Initialize MacroResolver instance with conf. Must be called at least once. :param conf: configuration to load :type conf: alignak.objects.Config :return: None """ # 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... self.host_class = self.hosts.inner_class self.lists_on_demand.append(self.hosts) self.services = self.my_conf.services self.contacts = self.my_conf.contacts self.lists_on_demand.append(self.contacts) self.hostgroups = self.my_conf.hostgroups self.lists_on_demand.append(self.hostgroups) self.commands = self.my_conf.commands self.servicegroups = self.my_conf.servicegroups self.lists_on_demand.append(self.servicegroups) self.contactgroups = self.my_conf.contactgroups self.lists_on_demand.append(self.contactgroups) self.illegal_macro_output_chars = self.my_conf.illegal_macro_output_chars self.env_prefix = self.my_conf.env_variables_prefix
[ "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...", "self", ".", "host_class", "=", "self", ".", "hosts", ".", "inner_class", "self", ".", "lists_on_demand", ".", "append", "(", "self", ".", "hosts", ")", "self", ".", "services", "=", "self", ".", "my_conf", ".", "services", "self", ".", "contacts", "=", "self", ".", "my_conf", ".", "contacts", "self", ".", "lists_on_demand", ".", "append", "(", "self", ".", "contacts", ")", "self", ".", "hostgroups", "=", "self", ".", "my_conf", ".", "hostgroups", "self", ".", "lists_on_demand", ".", "append", "(", "self", ".", "hostgroups", ")", "self", ".", "commands", "=", "self", ".", "my_conf", ".", "commands", "self", ".", "servicegroups", "=", "self", ".", "my_conf", ".", "servicegroups", "self", ".", "lists_on_demand", ".", "append", "(", "self", ".", "servicegroups", ")", "self", ".", "contactgroups", "=", "self", ".", "my_conf", ".", "contactgroups", "self", ".", "lists_on_demand", ".", "append", "(", "self", ".", "contactgroups", ")", "self", ".", "illegal_macro_output_chars", "=", "self", ".", "my_conf", ".", "illegal_macro_output_chars", "self", ".", "env_prefix", "=", "self", ".", "my_conf", ".", "env_variables_prefix" ]
Initialize MacroResolver instance with conf. Must be called at least once. :param conf: configuration to load :type conf: alignak.objects.Config :return: None
[ "Initialize", "MacroResolver", "instance", "with", "conf", ".", "Must", "be", "called", "at", "least", "once", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L146-L174
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._get_value_from_element
def _get_value_from_element(self, elt, prop): # pylint: disable=too-many-return-statements """Get value from an element's property. the property may be a function to call. If the property is not resolved (because not implemented), this function will return 'n/a' :param elt: element :type elt: object :param prop: element property :type prop: str :return: getattr(elt, prop) or getattr(elt, prop)() (call) :rtype: str """ args = None # We have args to provide to the function if isinstance(prop, tuple): prop, args = prop value = getattr(elt, prop, None) if value is None: return 'n/a' try: # If the macro is set to a list property if isinstance(value, list): # Return the list items, comma separated and bracketed return "[%s]" % ','.join(value) # If the macro is not set as a function to call if not isinstance(value, collections.Callable): return value # Case of a function call with no arguments if not args: return value() # Case where we need args to the function # ex : HOSTGROUPNAME (we need hostgroups) # ex : SHORTSTATUS (we need hosts and services if bp_rule) real_args = [] for arg in args: real_args.append(getattr(self, arg, None)) return value(*real_args) except AttributeError: # Commented because there are many unresolved macros and this log is spamming :/ # # Raise a warning and return a strange value when macro cannot be resolved # warnings.warn( # 'Error when getting the property value for a macro: %s', # MacroWarning, stacklevel=2) # Return a strange value when macro cannot be resolved return 'n/a' except UnicodeError: if isinstance(value, string_types): return str(value, 'utf8', errors='ignore') return 'n/a'
python
def _get_value_from_element(self, elt, prop): # pylint: disable=too-many-return-statements """Get value from an element's property. the property may be a function to call. If the property is not resolved (because not implemented), this function will return 'n/a' :param elt: element :type elt: object :param prop: element property :type prop: str :return: getattr(elt, prop) or getattr(elt, prop)() (call) :rtype: str """ args = None # We have args to provide to the function if isinstance(prop, tuple): prop, args = prop value = getattr(elt, prop, None) if value is None: return 'n/a' try: # If the macro is set to a list property if isinstance(value, list): # Return the list items, comma separated and bracketed return "[%s]" % ','.join(value) # If the macro is not set as a function to call if not isinstance(value, collections.Callable): return value # Case of a function call with no arguments if not args: return value() # Case where we need args to the function # ex : HOSTGROUPNAME (we need hostgroups) # ex : SHORTSTATUS (we need hosts and services if bp_rule) real_args = [] for arg in args: real_args.append(getattr(self, arg, None)) return value(*real_args) except AttributeError: # Commented because there are many unresolved macros and this log is spamming :/ # # Raise a warning and return a strange value when macro cannot be resolved # warnings.warn( # 'Error when getting the property value for a macro: %s', # MacroWarning, stacklevel=2) # Return a strange value when macro cannot be resolved return 'n/a' except UnicodeError: if isinstance(value, string_types): return str(value, 'utf8', errors='ignore') return 'n/a'
[ "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", ",", "prop", ",", "None", ")", "if", "value", "is", "None", ":", "return", "'n/a'", "try", ":", "# If the macro is set to a list property", "if", "isinstance", "(", "value", ",", "list", ")", ":", "# Return the list items, comma separated and bracketed", "return", "\"[%s]\"", "%", "','", ".", "join", "(", "value", ")", "# If the macro is not set as a function to call", "if", "not", "isinstance", "(", "value", ",", "collections", ".", "Callable", ")", ":", "return", "value", "# Case of a function call with no arguments", "if", "not", "args", ":", "return", "value", "(", ")", "# Case where we need args to the function", "# ex : HOSTGROUPNAME (we need hostgroups)", "# ex : SHORTSTATUS (we need hosts and services if bp_rule)", "real_args", "=", "[", "]", "for", "arg", "in", "args", ":", "real_args", ".", "append", "(", "getattr", "(", "self", ",", "arg", ",", "None", ")", ")", "return", "value", "(", "*", "real_args", ")", "except", "AttributeError", ":", "# Commented because there are many unresolved macros and this log is spamming :/", "# # Raise a warning and return a strange value when macro cannot be resolved", "# warnings.warn(", "# 'Error when getting the property value for a macro: %s',", "# MacroWarning, stacklevel=2)", "# Return a strange value when macro cannot be resolved", "return", "'n/a'", "except", "UnicodeError", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "str", "(", "value", ",", "'utf8'", ",", "errors", "=", "'ignore'", ")", "return", "'n/a'" ]
Get value from an element's property. the property may be a function to call. If the property is not resolved (because not implemented), this function will return 'n/a' :param elt: element :type elt: object :param prop: element property :type prop: str :return: getattr(elt, prop) or getattr(elt, prop)() (call) :rtype: str
[ "Get", "value", "from", "an", "element", "s", "property", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L202-L258
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._delete_unwanted_caracters
def _delete_unwanted_caracters(self, chain): """Remove not wanted char from chain unwanted char are illegal_macro_output_chars attribute :param chain: chain to remove char from :type chain: str :return: chain cleaned :rtype: str """ try: chain = chain.decode('utf8', 'replace') except UnicodeEncodeError: # If it is still encoded correctly, ignore... pass except AttributeError: # Python 3 will raise an exception because the line is still unicode pass for char in self.illegal_macro_output_chars: chain = chain.replace(char, '') return chain
python
def _delete_unwanted_caracters(self, chain): """Remove not wanted char from chain unwanted char are illegal_macro_output_chars attribute :param chain: chain to remove char from :type chain: str :return: chain cleaned :rtype: str """ try: chain = chain.decode('utf8', 'replace') except UnicodeEncodeError: # If it is still encoded correctly, ignore... pass except AttributeError: # Python 3 will raise an exception because the line is still unicode pass for char in self.illegal_macro_output_chars: chain = chain.replace(char, '') return chain
[ "def", "_delete_unwanted_caracters", "(", "self", ",", "chain", ")", ":", "try", ":", "chain", "=", "chain", ".", "decode", "(", "'utf8'", ",", "'replace'", ")", "except", "UnicodeEncodeError", ":", "# If it is still encoded correctly, ignore...", "pass", "except", "AttributeError", ":", "# Python 3 will raise an exception because the line is still unicode", "pass", "for", "char", "in", "self", ".", "illegal_macro_output_chars", ":", "chain", "=", "chain", ".", "replace", "(", "char", ",", "''", ")", "return", "chain" ]
Remove not wanted char from chain unwanted char are illegal_macro_output_chars attribute :param chain: chain to remove char from :type chain: str :return: chain cleaned :rtype: str
[ "Remove", "not", "wanted", "char", "from", "chain", "unwanted", "char", "are", "illegal_macro_output_chars", "attribute" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L260-L279
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver.resolve_command
def resolve_command(self, com, data, macromodulations, timeperiods): """Resolve command macros with data :param com: check / event handler or command call object :type com: object :param data: objects list, used to search for a specific macro (custom or object related) :type data: :return: command line with '$MACRO$' replaced with values :param macromodulations: the available macro modulations :type macromodulations: dict :param timeperiods: the available timeperiods :type timeperiods: dict :rtype: str """ logger.debug("Resolving: macros in: %s, arguments: %s", com.command.command_line, com.args) return self.resolve_simple_macros_in_string(com.command.command_line, data, macromodulations, timeperiods, args=com.args)
python
def resolve_command(self, com, data, macromodulations, timeperiods): """Resolve command macros with data :param com: check / event handler or command call object :type com: object :param data: objects list, used to search for a specific macro (custom or object related) :type data: :return: command line with '$MACRO$' replaced with values :param macromodulations: the available macro modulations :type macromodulations: dict :param timeperiods: the available timeperiods :type timeperiods: dict :rtype: str """ logger.debug("Resolving: macros in: %s, arguments: %s", com.command.command_line, com.args) return self.resolve_simple_macros_in_string(com.command.command_line, data, macromodulations, timeperiods, args=com.args)
[ "def", "resolve_command", "(", "self", ",", "com", ",", "data", ",", "macromodulations", ",", "timeperiods", ")", ":", "logger", ".", "debug", "(", "\"Resolving: macros in: %s, arguments: %s\"", ",", "com", ".", "command", ".", "command_line", ",", "com", ".", "args", ")", "return", "self", ".", "resolve_simple_macros_in_string", "(", "com", ".", "command", ".", "command_line", ",", "data", ",", "macromodulations", ",", "timeperiods", ",", "args", "=", "com", ".", "args", ")" ]
Resolve command macros with data :param com: check / event handler or command call object :type com: object :param data: objects list, used to search for a specific macro (custom or object related) :type data: :return: command line with '$MACRO$' replaced with values :param macromodulations: the available macro modulations :type macromodulations: dict :param timeperiods: the available timeperiods :type timeperiods: dict :rtype: str
[ "Resolve", "command", "macros", "with", "data" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L429-L447
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._get_type_of_macro
def _get_type_of_macro(macros, objs): r"""Set macros types Example:: ARG\d -> ARGN, HOSTBLABLA -> class one and set Host in class) _HOSTTOTO -> HOST CUSTOM MACRO TOTO SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1 :param macros: macros list in a dictionary :type macros: dict :param objs: objects list, used to tag object macros :type objs: list :return: None """ for macro in macros: # ARGN Macros if re.match(r'ARG\d', macro): macros[macro]['type'] = 'ARGN' continue # USERN macros # are managed in the Config class, so no # need to look that here elif re.match(r'_HOST\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'HOST' continue elif re.match(r'_SERVICE\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'SERVICE' # value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1] continue elif re.match(r'_CONTACT\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'CONTACT' continue # On demand macro elif len(macro.split(':')) > 1: macros[macro]['type'] = 'ONDEMAND' continue # OK, classical macro... for obj in objs: if macro in obj.macros: macros[macro]['type'] = 'object' macros[macro]['object'] = obj continue
python
def _get_type_of_macro(macros, objs): r"""Set macros types Example:: ARG\d -> ARGN, HOSTBLABLA -> class one and set Host in class) _HOSTTOTO -> HOST CUSTOM MACRO TOTO SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1 :param macros: macros list in a dictionary :type macros: dict :param objs: objects list, used to tag object macros :type objs: list :return: None """ for macro in macros: # ARGN Macros if re.match(r'ARG\d', macro): macros[macro]['type'] = 'ARGN' continue # USERN macros # are managed in the Config class, so no # need to look that here elif re.match(r'_HOST\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'HOST' continue elif re.match(r'_SERVICE\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'SERVICE' # value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1] continue elif re.match(r'_CONTACT\w', macro): macros[macro]['type'] = 'CUSTOM' macros[macro]['class'] = 'CONTACT' continue # On demand macro elif len(macro.split(':')) > 1: macros[macro]['type'] = 'ONDEMAND' continue # OK, classical macro... for obj in objs: if macro in obj.macros: macros[macro]['type'] = 'object' macros[macro]['object'] = obj continue
[ "def", "_get_type_of_macro", "(", "macros", ",", "objs", ")", ":", "for", "macro", "in", "macros", ":", "# ARGN Macros", "if", "re", ".", "match", "(", "r'ARG\\d'", ",", "macro", ")", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'ARGN'", "continue", "# USERN macros", "# are managed in the Config class, so no", "# need to look that here", "elif", "re", ".", "match", "(", "r'_HOST\\w'", ",", "macro", ")", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'CUSTOM'", "macros", "[", "macro", "]", "[", "'class'", "]", "=", "'HOST'", "continue", "elif", "re", ".", "match", "(", "r'_SERVICE\\w'", ",", "macro", ")", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'CUSTOM'", "macros", "[", "macro", "]", "[", "'class'", "]", "=", "'SERVICE'", "# value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1]", "continue", "elif", "re", ".", "match", "(", "r'_CONTACT\\w'", ",", "macro", ")", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'CUSTOM'", "macros", "[", "macro", "]", "[", "'class'", "]", "=", "'CONTACT'", "continue", "# On demand macro", "elif", "len", "(", "macro", ".", "split", "(", "':'", ")", ")", ">", "1", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'ONDEMAND'", "continue", "# OK, classical macro...", "for", "obj", "in", "objs", ":", "if", "macro", "in", "obj", ".", "macros", ":", "macros", "[", "macro", "]", "[", "'type'", "]", "=", "'object'", "macros", "[", "macro", "]", "[", "'object'", "]", "=", "obj", "continue" ]
r"""Set macros types Example:: ARG\d -> ARGN, HOSTBLABLA -> class one and set Host in class) _HOSTTOTO -> HOST CUSTOM MACRO TOTO SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1 :param macros: macros list in a dictionary :type macros: dict :param objs: objects list, used to tag object macros :type objs: list :return: None
[ "r", "Set", "macros", "types" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L450-L496
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._resolve_ondemand
def _resolve_ondemand(self, macro, data): # pylint: disable=too-many-locals """Get on demand macro value If the macro cannot be resolved, this function will return 'n/a' rather than an empty string, this to alert the caller of a potential problem. :param macro: macro to parse :type macro: :param data: data to get value from :type data: :return: macro value :rtype: str """ elts = macro.split(':') nb_parts = len(elts) macro_name = elts[0] # 3 parts for a service, 2 for all others types... if nb_parts == 3: val = '' (host_name, service_description) = (elts[1], elts[2]) # host_name can be void, so it's the host in data # that is important. We use our self.host_class to # find the host in the data :) if host_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: host_name = elt.host_name # Ok now we get service serv = self.services.find_srv_by_name_and_hostname(host_name, service_description) if serv is not None: cls = serv.__class__ prop = cls.macros[macro_name] val = self._get_value_from_element(serv, prop) return val # Ok, service was easy, now hard part else: val = '' elt_name = elts[1] # Special case: elt_name can be void # so it's the host where it apply if elt_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: elt_name = elt.host_name for od_list in self.lists_on_demand: cls = od_list.inner_class # We search our type by looking at the macro if macro_name in cls.macros: prop = cls.macros[macro_name] i = od_list.find_by_name(elt_name) if i is not None: val = self._get_value_from_element(i, prop) # Ok we got our value :) break return val # Return a strange value in this case rather than an empty string return 'n/a'
python
def _resolve_ondemand(self, macro, data): # pylint: disable=too-many-locals """Get on demand macro value If the macro cannot be resolved, this function will return 'n/a' rather than an empty string, this to alert the caller of a potential problem. :param macro: macro to parse :type macro: :param data: data to get value from :type data: :return: macro value :rtype: str """ elts = macro.split(':') nb_parts = len(elts) macro_name = elts[0] # 3 parts for a service, 2 for all others types... if nb_parts == 3: val = '' (host_name, service_description) = (elts[1], elts[2]) # host_name can be void, so it's the host in data # that is important. We use our self.host_class to # find the host in the data :) if host_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: host_name = elt.host_name # Ok now we get service serv = self.services.find_srv_by_name_and_hostname(host_name, service_description) if serv is not None: cls = serv.__class__ prop = cls.macros[macro_name] val = self._get_value_from_element(serv, prop) return val # Ok, service was easy, now hard part else: val = '' elt_name = elts[1] # Special case: elt_name can be void # so it's the host where it apply if elt_name == '': for elt in data: if elt is not None and elt.__class__ == self.host_class: elt_name = elt.host_name for od_list in self.lists_on_demand: cls = od_list.inner_class # We search our type by looking at the macro if macro_name in cls.macros: prop = cls.macros[macro_name] i = od_list.find_by_name(elt_name) if i is not None: val = self._get_value_from_element(i, prop) # Ok we got our value :) break return val # Return a strange value in this case rather than an empty string return 'n/a'
[ "def", "_resolve_ondemand", "(", "self", ",", "macro", ",", "data", ")", ":", "# pylint: disable=too-many-locals", "elts", "=", "macro", ".", "split", "(", "':'", ")", "nb_parts", "=", "len", "(", "elts", ")", "macro_name", "=", "elts", "[", "0", "]", "# 3 parts for a service, 2 for all others types...", "if", "nb_parts", "==", "3", ":", "val", "=", "''", "(", "host_name", ",", "service_description", ")", "=", "(", "elts", "[", "1", "]", ",", "elts", "[", "2", "]", ")", "# host_name can be void, so it's the host in data", "# that is important. We use our self.host_class to", "# find the host in the data :)", "if", "host_name", "==", "''", ":", "for", "elt", "in", "data", ":", "if", "elt", "is", "not", "None", "and", "elt", ".", "__class__", "==", "self", ".", "host_class", ":", "host_name", "=", "elt", ".", "host_name", "# Ok now we get service", "serv", "=", "self", ".", "services", ".", "find_srv_by_name_and_hostname", "(", "host_name", ",", "service_description", ")", "if", "serv", "is", "not", "None", ":", "cls", "=", "serv", ".", "__class__", "prop", "=", "cls", ".", "macros", "[", "macro_name", "]", "val", "=", "self", ".", "_get_value_from_element", "(", "serv", ",", "prop", ")", "return", "val", "# Ok, service was easy, now hard part", "else", ":", "val", "=", "''", "elt_name", "=", "elts", "[", "1", "]", "# Special case: elt_name can be void", "# so it's the host where it apply", "if", "elt_name", "==", "''", ":", "for", "elt", "in", "data", ":", "if", "elt", "is", "not", "None", "and", "elt", ".", "__class__", "==", "self", ".", "host_class", ":", "elt_name", "=", "elt", ".", "host_name", "for", "od_list", "in", "self", ".", "lists_on_demand", ":", "cls", "=", "od_list", ".", "inner_class", "# We search our type by looking at the macro", "if", "macro_name", "in", "cls", ".", "macros", ":", "prop", "=", "cls", ".", "macros", "[", "macro_name", "]", "i", "=", "od_list", ".", "find_by_name", "(", "elt_name", ")", "if", "i", "is", "not", "None", ":", "val", "=", "self", ".", "_get_value_from_element", "(", "i", ",", "prop", ")", "# Ok we got our value :)", "break", "return", "val", "# Return a strange value in this case rather than an empty string", "return", "'n/a'" ]
Get on demand macro value If the macro cannot be resolved, this function will return 'n/a' rather than an empty string, this to alert the caller of a potential problem. :param macro: macro to parse :type macro: :param data: data to get value from :type data: :return: macro value :rtype: str
[ "Get", "on", "demand", "macro", "value" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L523-L581
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._tot_hosts_by_state
def _tot_hosts_by_state(self, state=None, state_type=None): """Generic function to get the number of host in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int """ if state is None and state_type is None: return len(self.hosts) if state_type: return sum(1 for h in self.hosts if h.state == state and h.state_type == state_type) return sum(1 for h in self.hosts if h.state == state)
python
def _tot_hosts_by_state(self, state=None, state_type=None): """Generic function to get the number of host in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int """ if state is None and state_type is None: return len(self.hosts) if state_type: return sum(1 for h in self.hosts if h.state == state and h.state_type == state_type) return sum(1 for h in self.hosts if h.state == state)
[ "def", "_tot_hosts_by_state", "(", "self", ",", "state", "=", "None", ",", "state_type", "=", "None", ")", ":", "if", "state", "is", "None", "and", "state_type", "is", "None", ":", "return", "len", "(", "self", ".", "hosts", ")", "if", "state_type", ":", "return", "sum", "(", "1", "for", "h", "in", "self", ".", "hosts", "if", "h", ".", "state", "==", "state", "and", "h", ".", "state_type", "==", "state_type", ")", "return", "sum", "(", "1", "for", "h", "in", "self", ".", "hosts", "if", "h", ".", "state", "==", "state", ")" ]
Generic function to get the number of host in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int
[ "Generic", "function", "to", "get", "the", "number", "of", "host", "in", "the", "specified", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L648-L662
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._tot_unhandled_hosts_by_state
def _tot_unhandled_hosts_by_state(self, state): """Generic function to get the number of unhandled problem hosts in the specified state :param state: state to filter on :type state: :return: number of host in state *state* and which are not acknowledged problems :rtype: int """ return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and h.is_problem and not h.problem_has_been_acknowledged)
python
def _tot_unhandled_hosts_by_state(self, state): """Generic function to get the number of unhandled problem hosts in the specified state :param state: state to filter on :type state: :return: number of host in state *state* and which are not acknowledged problems :rtype: int """ return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and h.is_problem and not h.problem_has_been_acknowledged)
[ "def", "_tot_unhandled_hosts_by_state", "(", "self", ",", "state", ")", ":", "return", "sum", "(", "1", "for", "h", "in", "self", ".", "hosts", "if", "h", ".", "state", "==", "state", "and", "h", ".", "state_type", "==", "u'HARD'", "and", "h", ".", "is_problem", "and", "not", "h", ".", "problem_has_been_acknowledged", ")" ]
Generic function to get the number of unhandled problem hosts in the specified state :param state: state to filter on :type state: :return: number of host in state *state* and which are not acknowledged problems :rtype: int
[ "Generic", "function", "to", "get", "the", "number", "of", "unhandled", "problem", "hosts", "in", "the", "specified", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L664-L673
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._tot_services_by_state
def _tot_services_by_state(self, state=None, state_type=None): """Generic function to get the number of services in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int TODO: Should be moved """ if state is None and state_type is None: return len(self.services) if state_type: return sum(1 for s in self.services if s.state == state and s.state_type == state_type) return sum(1 for s in self.services if s.state == state)
python
def _tot_services_by_state(self, state=None, state_type=None): """Generic function to get the number of services in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int TODO: Should be moved """ if state is None and state_type is None: return len(self.services) if state_type: return sum(1 for s in self.services if s.state == state and s.state_type == state_type) return sum(1 for s in self.services if s.state == state)
[ "def", "_tot_services_by_state", "(", "self", ",", "state", "=", "None", ",", "state_type", "=", "None", ")", ":", "if", "state", "is", "None", "and", "state_type", "is", "None", ":", "return", "len", "(", "self", ".", "services", ")", "if", "state_type", ":", "return", "sum", "(", "1", "for", "s", "in", "self", ".", "services", "if", "s", ".", "state", "==", "state", "and", "s", ".", "state_type", "==", "state_type", ")", "return", "sum", "(", "1", "for", "s", "in", "self", ".", "services", "if", "s", ".", "state", "==", "state", ")" ]
Generic function to get the number of services in the specified state :param state: state to filter on :type state: str :param state_type: state type to filter on (HARD, SOFT) :type state_type: str :return: number of host in state *state* :rtype: int TODO: Should be moved
[ "Generic", "function", "to", "get", "the", "number", "of", "services", "in", "the", "specified", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L783-L798
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._tot_unhandled_services_by_state
def _tot_unhandled_services_by_state(self, state): """Generic function to get the number of unhandled problem services in the specified state :param state: state to filter on :type state: :return: number of service in state *state* and which are not acknowledged problems :rtype: int """ return sum(1 for s in self.services if s.state == state and s.is_problem and not s.problem_has_been_acknowledged)
python
def _tot_unhandled_services_by_state(self, state): """Generic function to get the number of unhandled problem services in the specified state :param state: state to filter on :type state: :return: number of service in state *state* and which are not acknowledged problems :rtype: int """ return sum(1 for s in self.services if s.state == state and s.is_problem and not s.problem_has_been_acknowledged)
[ "def", "_tot_unhandled_services_by_state", "(", "self", ",", "state", ")", ":", "return", "sum", "(", "1", "for", "s", "in", "self", ".", "services", "if", "s", ".", "state", "==", "state", "and", "s", ".", "is_problem", "and", "not", "s", ".", "problem_has_been_acknowledged", ")" ]
Generic function to get the number of unhandled problem services in the specified state :param state: state to filter on :type state: :return: number of service in state *state* and which are not acknowledged problems :rtype: int
[ "Generic", "function", "to", "get", "the", "number", "of", "unhandled", "problem", "services", "in", "the", "specified", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L800-L809
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._get_total_services_problems_unhandled
def _get_total_services_problems_unhandled(self): """Get the number of services that are a problem and that are not acknowledged :return: number of problem services which are not acknowledged :rtype: int """ return sum(1 for s in self.services if s.is_problem and not s.problem_has_been_acknowledged)
python
def _get_total_services_problems_unhandled(self): """Get the number of services that are a problem and that are not acknowledged :return: number of problem services which are not acknowledged :rtype: int """ return sum(1 for s in self.services if s.is_problem and not s.problem_has_been_acknowledged)
[ "def", "_get_total_services_problems_unhandled", "(", "self", ")", ":", "return", "sum", "(", "1", "for", "s", "in", "self", ".", "services", "if", "s", ".", "is_problem", "and", "not", "s", ".", "problem_has_been_acknowledged", ")" ]
Get the number of services that are a problem and that are not acknowledged :return: number of problem services which are not acknowledged :rtype: int
[ "Get", "the", "number", "of", "services", "that", "are", "a", "problem", "and", "that", "are", "not", "acknowledged" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L900-L906
train
Alignak-monitoring/alignak
alignak/macroresolver.py
MacroResolver._get_total_services_problems_handled
def _get_total_services_problems_handled(self): """ Get the number of service problems not handled :return: Number of services which are problems and not handled :rtype: int """ return sum(1 for s in self.services if s.is_problem and s.problem_has_been_acknowledged)
python
def _get_total_services_problems_handled(self): """ Get the number of service problems not handled :return: Number of services which are problems and not handled :rtype: int """ return sum(1 for s in self.services if s.is_problem and s.problem_has_been_acknowledged)
[ "def", "_get_total_services_problems_handled", "(", "self", ")", ":", "return", "sum", "(", "1", "for", "s", "in", "self", ".", "services", "if", "s", ".", "is_problem", "and", "s", ".", "problem_has_been_acknowledged", ")" ]
Get the number of service problems not handled :return: Number of services which are problems and not handled :rtype: int
[ "Get", "the", "number", "of", "service", "problems", "not", "handled" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L908-L915
train
Alignak-monitoring/alignak
alignak/misc/carboniface.py
CarbonIface.add_data
def add_data(self, metric, value, ts=None): """ Add data to queue :param metric: the metric name :type metric: str :param value: the value of data :type value: int :param ts: the timestamp :type ts: int | None :return: True if added successfully, otherwise False :rtype: bool """ if not ts: ts = time.time() if self.__data_lock.acquire(): self.__data.append((metric, (ts, value))) self.__data_lock.release() return True return False
python
def add_data(self, metric, value, ts=None): """ Add data to queue :param metric: the metric name :type metric: str :param value: the value of data :type value: int :param ts: the timestamp :type ts: int | None :return: True if added successfully, otherwise False :rtype: bool """ if not ts: ts = time.time() if self.__data_lock.acquire(): self.__data.append((metric, (ts, value))) self.__data_lock.release() return True return False
[ "def", "add_data", "(", "self", ",", "metric", ",", "value", ",", "ts", "=", "None", ")", ":", "if", "not", "ts", ":", "ts", "=", "time", ".", "time", "(", ")", "if", "self", ".", "__data_lock", ".", "acquire", "(", ")", ":", "self", ".", "__data", ".", "append", "(", "(", "metric", ",", "(", "ts", ",", "value", ")", ")", ")", "self", ".", "__data_lock", ".", "release", "(", ")", "return", "True", "return", "False" ]
Add data to queue :param metric: the metric name :type metric: str :param value: the value of data :type value: int :param ts: the timestamp :type ts: int | None :return: True if added successfully, otherwise False :rtype: bool
[ "Add", "data", "to", "queue" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/misc/carboniface.py#L40-L59
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.set_daemon_name
def set_daemon_name(self, daemon_name): """Set the daemon name of the daemon which this manager is attached to and propagate this daemon name to our managed modules :param daemon_name: :return: """ self.daemon_name = daemon_name for instance in self.instances: instance.set_loaded_into(daemon_name)
python
def set_daemon_name(self, daemon_name): """Set the daemon name of the daemon which this manager is attached to and propagate this daemon name to our managed modules :param daemon_name: :return: """ self.daemon_name = daemon_name for instance in self.instances: instance.set_loaded_into(daemon_name)
[ "def", "set_daemon_name", "(", "self", ",", "daemon_name", ")", ":", "self", ".", "daemon_name", "=", "daemon_name", "for", "instance", "in", "self", ".", "instances", ":", "instance", ".", "set_loaded_into", "(", "daemon_name", ")" ]
Set the daemon name of the daemon which this manager is attached to and propagate this daemon name to our managed modules :param daemon_name: :return:
[ "Set", "the", "daemon", "name", "of", "the", "daemon", "which", "this", "manager", "is", "attached", "to", "and", "propagate", "this", "daemon", "name", "to", "our", "managed", "modules" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L90-L99
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.load_and_init
def load_and_init(self, modules): """Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors """ self.load(modules) self.get_instances() return len(self.configuration_errors) == 0
python
def load_and_init(self, modules): """Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors """ self.load(modules) self.get_instances() return len(self.configuration_errors) == 0
[ "def", "load_and_init", "(", "self", ",", "modules", ")", ":", "self", ".", "load", "(", "modules", ")", "self", ".", "get_instances", "(", ")", "return", "len", "(", "self", ".", "configuration_errors", ")", "==", "0" ]
Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors
[ "Import", "instantiate", "&", "init", "the", "modules", "we", "manage" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L101-L110
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.load
def load(self, modules): """Load Python modules and check their usability :param modules: list of the modules that must be loaded :return: """ self.modules_assoc = [] for module in modules: if not module.enabled: logger.info("Module %s is declared but not enabled", module.name) # Store in our modules list but do not try to load # Probably someone else will load this module later... self.modules[module.uuid] = module continue logger.info("Importing Python module '%s' for %s...", module.python_name, module.name) try: python_module = importlib.import_module(module.python_name) # Check existing module properties # Todo: check all mandatory properties if not hasattr(python_module, 'properties'): # pragma: no cover self.configuration_errors.append("Module %s is missing a 'properties' " "dictionary" % module.python_name) raise AttributeError logger.info("Module properties: %s", getattr(python_module, 'properties')) # Check existing module get_instance method if not hasattr(python_module, 'get_instance') or \ not isinstance(getattr(python_module, 'get_instance'), collections.Callable): # pragma: no cover self.configuration_errors.append("Module %s is missing a 'get_instance' " "function" % module.python_name) raise AttributeError self.modules_assoc.append((module, python_module)) logger.info("Imported '%s' for %s", module.python_name, module.name) except ImportError as exp: # pragma: no cover, simple protection self.configuration_errors.append("Module %s (%s) can't be loaded, Python " "importation error: %s" % (module.python_name, module.name, str(exp))) except AttributeError: # pragma: no cover, simple protection self.configuration_errors.append("Module %s (%s) can't be loaded, " "module configuration" % (module.python_name, module.name)) else: logger.info("Loaded Python module '%s' (%s)", module.python_name, module.name)
python
def load(self, modules): """Load Python modules and check their usability :param modules: list of the modules that must be loaded :return: """ self.modules_assoc = [] for module in modules: if not module.enabled: logger.info("Module %s is declared but not enabled", module.name) # Store in our modules list but do not try to load # Probably someone else will load this module later... self.modules[module.uuid] = module continue logger.info("Importing Python module '%s' for %s...", module.python_name, module.name) try: python_module = importlib.import_module(module.python_name) # Check existing module properties # Todo: check all mandatory properties if not hasattr(python_module, 'properties'): # pragma: no cover self.configuration_errors.append("Module %s is missing a 'properties' " "dictionary" % module.python_name) raise AttributeError logger.info("Module properties: %s", getattr(python_module, 'properties')) # Check existing module get_instance method if not hasattr(python_module, 'get_instance') or \ not isinstance(getattr(python_module, 'get_instance'), collections.Callable): # pragma: no cover self.configuration_errors.append("Module %s is missing a 'get_instance' " "function" % module.python_name) raise AttributeError self.modules_assoc.append((module, python_module)) logger.info("Imported '%s' for %s", module.python_name, module.name) except ImportError as exp: # pragma: no cover, simple protection self.configuration_errors.append("Module %s (%s) can't be loaded, Python " "importation error: %s" % (module.python_name, module.name, str(exp))) except AttributeError: # pragma: no cover, simple protection self.configuration_errors.append("Module %s (%s) can't be loaded, " "module configuration" % (module.python_name, module.name)) else: logger.info("Loaded Python module '%s' (%s)", module.python_name, module.name)
[ "def", "load", "(", "self", ",", "modules", ")", ":", "self", ".", "modules_assoc", "=", "[", "]", "for", "module", "in", "modules", ":", "if", "not", "module", ".", "enabled", ":", "logger", ".", "info", "(", "\"Module %s is declared but not enabled\"", ",", "module", ".", "name", ")", "# Store in our modules list but do not try to load", "# Probably someone else will load this module later...", "self", ".", "modules", "[", "module", ".", "uuid", "]", "=", "module", "continue", "logger", ".", "info", "(", "\"Importing Python module '%s' for %s...\"", ",", "module", ".", "python_name", ",", "module", ".", "name", ")", "try", ":", "python_module", "=", "importlib", ".", "import_module", "(", "module", ".", "python_name", ")", "# Check existing module properties", "# Todo: check all mandatory properties", "if", "not", "hasattr", "(", "python_module", ",", "'properties'", ")", ":", "# pragma: no cover", "self", ".", "configuration_errors", ".", "append", "(", "\"Module %s is missing a 'properties' \"", "\"dictionary\"", "%", "module", ".", "python_name", ")", "raise", "AttributeError", "logger", ".", "info", "(", "\"Module properties: %s\"", ",", "getattr", "(", "python_module", ",", "'properties'", ")", ")", "# Check existing module get_instance method", "if", "not", "hasattr", "(", "python_module", ",", "'get_instance'", ")", "or", "not", "isinstance", "(", "getattr", "(", "python_module", ",", "'get_instance'", ")", ",", "collections", ".", "Callable", ")", ":", "# pragma: no cover", "self", ".", "configuration_errors", ".", "append", "(", "\"Module %s is missing a 'get_instance' \"", "\"function\"", "%", "module", ".", "python_name", ")", "raise", "AttributeError", "self", ".", "modules_assoc", ".", "append", "(", "(", "module", ",", "python_module", ")", ")", "logger", ".", "info", "(", "\"Imported '%s' for %s\"", ",", "module", ".", "python_name", ",", "module", ".", "name", ")", "except", "ImportError", "as", "exp", ":", "# pragma: no cover, simple protection", "self", ".", "configuration_errors", ".", "append", "(", "\"Module %s (%s) can't be loaded, Python \"", "\"importation error: %s\"", "%", "(", "module", ".", "python_name", ",", "module", ".", "name", ",", "str", "(", "exp", ")", ")", ")", "except", "AttributeError", ":", "# pragma: no cover, simple protection", "self", ".", "configuration_errors", ".", "append", "(", "\"Module %s (%s) can't be loaded, \"", "\"module configuration\"", "%", "(", "module", ".", "python_name", ",", "module", ".", "name", ")", ")", "else", ":", "logger", ".", "info", "(", "\"Loaded Python module '%s' (%s)\"", ",", "module", ".", "python_name", ",", "module", ".", "name", ")" ]
Load Python modules and check their usability :param modules: list of the modules that must be loaded :return:
[ "Load", "Python", "modules", "and", "check", "their", "usability" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L112-L158
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.try_instance_init
def try_instance_init(self, instance, late_start=False): """Try to "initialize" the given module instance. :param instance: instance to init :type instance: object :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: True on successful init. False if instance init method raised any Exception. :rtype: bool """ try: instance.init_try += 1 # Maybe it's a retry if not late_start and instance.init_try > 1: # Do not try until too frequently, or it's too loopy if instance.last_init_try > time.time() - MODULE_INIT_PERIOD: logger.info("Too early to retry initialization, retry period is %d seconds", MODULE_INIT_PERIOD) # logger.info("%s / %s", instance.last_init_try, time.time()) return False instance.last_init_try = time.time() logger.info("Trying to initialize module: %s", instance.name) # If it's an external module, create/update Queues() if instance.is_external: instance.create_queues(self.daemon.sync_manager) # The module instance init function says if initialization is ok if not instance.init(): logger.warning("Module %s initialisation failed.", instance.name) return False logger.info("Module %s is initialized.", instance.name) except Exception as exp: # pylint: disable=broad-except # pragma: no cover, simple protection msg = "The module instance %s raised an exception " \ "on initialization: %s, I remove it!" % (instance.name, str(exp)) self.configuration_errors.append(msg) logger.error(msg) logger.exception(exp) return False return True
python
def try_instance_init(self, instance, late_start=False): """Try to "initialize" the given module instance. :param instance: instance to init :type instance: object :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: True on successful init. False if instance init method raised any Exception. :rtype: bool """ try: instance.init_try += 1 # Maybe it's a retry if not late_start and instance.init_try > 1: # Do not try until too frequently, or it's too loopy if instance.last_init_try > time.time() - MODULE_INIT_PERIOD: logger.info("Too early to retry initialization, retry period is %d seconds", MODULE_INIT_PERIOD) # logger.info("%s / %s", instance.last_init_try, time.time()) return False instance.last_init_try = time.time() logger.info("Trying to initialize module: %s", instance.name) # If it's an external module, create/update Queues() if instance.is_external: instance.create_queues(self.daemon.sync_manager) # The module instance init function says if initialization is ok if not instance.init(): logger.warning("Module %s initialisation failed.", instance.name) return False logger.info("Module %s is initialized.", instance.name) except Exception as exp: # pylint: disable=broad-except # pragma: no cover, simple protection msg = "The module instance %s raised an exception " \ "on initialization: %s, I remove it!" % (instance.name, str(exp)) self.configuration_errors.append(msg) logger.error(msg) logger.exception(exp) return False return True
[ "def", "try_instance_init", "(", "self", ",", "instance", ",", "late_start", "=", "False", ")", ":", "try", ":", "instance", ".", "init_try", "+=", "1", "# Maybe it's a retry", "if", "not", "late_start", "and", "instance", ".", "init_try", ">", "1", ":", "# Do not try until too frequently, or it's too loopy", "if", "instance", ".", "last_init_try", ">", "time", ".", "time", "(", ")", "-", "MODULE_INIT_PERIOD", ":", "logger", ".", "info", "(", "\"Too early to retry initialization, retry period is %d seconds\"", ",", "MODULE_INIT_PERIOD", ")", "# logger.info(\"%s / %s\", instance.last_init_try, time.time())", "return", "False", "instance", ".", "last_init_try", "=", "time", ".", "time", "(", ")", "logger", ".", "info", "(", "\"Trying to initialize module: %s\"", ",", "instance", ".", "name", ")", "# If it's an external module, create/update Queues()", "if", "instance", ".", "is_external", ":", "instance", ".", "create_queues", "(", "self", ".", "daemon", ".", "sync_manager", ")", "# The module instance init function says if initialization is ok", "if", "not", "instance", ".", "init", "(", ")", ":", "logger", ".", "warning", "(", "\"Module %s initialisation failed.\"", ",", "instance", ".", "name", ")", "return", "False", "logger", ".", "info", "(", "\"Module %s is initialized.\"", ",", "instance", ".", "name", ")", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "# pragma: no cover, simple protection", "msg", "=", "\"The module instance %s raised an exception \"", "\"on initialization: %s, I remove it!\"", "%", "(", "instance", ".", "name", ",", "str", "(", "exp", ")", ")", "self", ".", "configuration_errors", ".", "append", "(", "msg", ")", "logger", ".", "error", "(", "msg", ")", "logger", ".", "exception", "(", "exp", ")", "return", "False", "return", "True" ]
Try to "initialize" the given module instance. :param instance: instance to init :type instance: object :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: True on successful init. False if instance init method raised any Exception. :rtype: bool
[ "Try", "to", "initialize", "the", "given", "module", "instance", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L160-L202
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.clear_instances
def clear_instances(self, instances=None): """Request to "remove" the given instances list or all if not provided :param instances: instances to remove (all instances are removed if None) :type instances: :return: None """ if instances is None: instances = self.instances[:] # have to make a copy of the list for instance in instances: self.remove_instance(instance)
python
def clear_instances(self, instances=None): """Request to "remove" the given instances list or all if not provided :param instances: instances to remove (all instances are removed if None) :type instances: :return: None """ if instances is None: instances = self.instances[:] # have to make a copy of the list for instance in instances: self.remove_instance(instance)
[ "def", "clear_instances", "(", "self", ",", "instances", "=", "None", ")", ":", "if", "instances", "is", "None", ":", "instances", "=", "self", ".", "instances", "[", ":", "]", "# have to make a copy of the list", "for", "instance", "in", "instances", ":", "self", ".", "remove_instance", "(", "instance", ")" ]
Request to "remove" the given instances list or all if not provided :param instances: instances to remove (all instances are removed if None) :type instances: :return: None
[ "Request", "to", "remove", "the", "given", "instances", "list", "or", "all", "if", "not", "provided" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L204-L214
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.set_to_restart
def set_to_restart(self, instance): """Put an instance to the restart queue :param instance: instance to restart :type instance: object :return: None """ self.to_restart.append(instance) if instance.is_external: instance.proc = None
python
def set_to_restart(self, instance): """Put an instance to the restart queue :param instance: instance to restart :type instance: object :return: None """ self.to_restart.append(instance) if instance.is_external: instance.proc = None
[ "def", "set_to_restart", "(", "self", ",", "instance", ")", ":", "self", ".", "to_restart", ".", "append", "(", "instance", ")", "if", "instance", ".", "is_external", ":", "instance", ".", "proc", "=", "None" ]
Put an instance to the restart queue :param instance: instance to restart :type instance: object :return: None
[ "Put", "an", "instance", "to", "the", "restart", "queue" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L216-L225
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.get_instances
def get_instances(self): """Create, init and then returns the list of module instances that the caller needs. This method is called once the Python modules are loaded to initialize the modules. If an instance can't be created or initialized then only log is doneand that instance is skipped. The previous modules instance(s), if any, are all cleaned. :return: module instances list :rtype: list """ self.clear_instances() for (alignak_module, python_module) in self.modules_assoc: alignak_module.properties = python_module.properties.copy() alignak_module.my_daemon = self.daemon logger.info("Alignak starting module '%s'", alignak_module.get_name()) if getattr(alignak_module, 'modules', None): modules = [] for module_uuid in alignak_module.modules: if module_uuid in self.modules: modules.append(self.modules[module_uuid]) alignak_module.modules = modules logger.debug("Module '%s', parameters: %s", alignak_module.get_name(), alignak_module.__dict__) try: instance = python_module.get_instance(alignak_module) if not isinstance(instance, BaseModule): # pragma: no cover, simple protection self.configuration_errors.append("Module %s instance is not a " "BaseModule instance: %s" % (alignak_module.get_name(), type(instance))) raise AttributeError # pragma: no cover, simple protection except Exception as exp: # pylint: disable=broad-except logger.error("The module %s raised an exception on loading, I remove it!", alignak_module.get_name()) logger.exception("Exception: %s", exp) self.configuration_errors.append("The module %s raised an exception on " "loading: %s, I remove it!" % (alignak_module.get_name(), str(exp))) else: # Give the module the data to which daemon/module it is loaded into instance.set_loaded_into(self.daemon.name) self.instances.append(instance) for instance in self.instances: # External instances are not initialized now, but only when they are started if not instance.is_external and not self.try_instance_init(instance): # If the init failed, we put in in the restart queue logger.warning("The module '%s' failed to initialize, " "I will try to restart it later", instance.name) self.set_to_restart(instance) return self.instances
python
def get_instances(self): """Create, init and then returns the list of module instances that the caller needs. This method is called once the Python modules are loaded to initialize the modules. If an instance can't be created or initialized then only log is doneand that instance is skipped. The previous modules instance(s), if any, are all cleaned. :return: module instances list :rtype: list """ self.clear_instances() for (alignak_module, python_module) in self.modules_assoc: alignak_module.properties = python_module.properties.copy() alignak_module.my_daemon = self.daemon logger.info("Alignak starting module '%s'", alignak_module.get_name()) if getattr(alignak_module, 'modules', None): modules = [] for module_uuid in alignak_module.modules: if module_uuid in self.modules: modules.append(self.modules[module_uuid]) alignak_module.modules = modules logger.debug("Module '%s', parameters: %s", alignak_module.get_name(), alignak_module.__dict__) try: instance = python_module.get_instance(alignak_module) if not isinstance(instance, BaseModule): # pragma: no cover, simple protection self.configuration_errors.append("Module %s instance is not a " "BaseModule instance: %s" % (alignak_module.get_name(), type(instance))) raise AttributeError # pragma: no cover, simple protection except Exception as exp: # pylint: disable=broad-except logger.error("The module %s raised an exception on loading, I remove it!", alignak_module.get_name()) logger.exception("Exception: %s", exp) self.configuration_errors.append("The module %s raised an exception on " "loading: %s, I remove it!" % (alignak_module.get_name(), str(exp))) else: # Give the module the data to which daemon/module it is loaded into instance.set_loaded_into(self.daemon.name) self.instances.append(instance) for instance in self.instances: # External instances are not initialized now, but only when they are started if not instance.is_external and not self.try_instance_init(instance): # If the init failed, we put in in the restart queue logger.warning("The module '%s' failed to initialize, " "I will try to restart it later", instance.name) self.set_to_restart(instance) return self.instances
[ "def", "get_instances", "(", "self", ")", ":", "self", ".", "clear_instances", "(", ")", "for", "(", "alignak_module", ",", "python_module", ")", "in", "self", ".", "modules_assoc", ":", "alignak_module", ".", "properties", "=", "python_module", ".", "properties", ".", "copy", "(", ")", "alignak_module", ".", "my_daemon", "=", "self", ".", "daemon", "logger", ".", "info", "(", "\"Alignak starting module '%s'\"", ",", "alignak_module", ".", "get_name", "(", ")", ")", "if", "getattr", "(", "alignak_module", ",", "'modules'", ",", "None", ")", ":", "modules", "=", "[", "]", "for", "module_uuid", "in", "alignak_module", ".", "modules", ":", "if", "module_uuid", "in", "self", ".", "modules", ":", "modules", ".", "append", "(", "self", ".", "modules", "[", "module_uuid", "]", ")", "alignak_module", ".", "modules", "=", "modules", "logger", ".", "debug", "(", "\"Module '%s', parameters: %s\"", ",", "alignak_module", ".", "get_name", "(", ")", ",", "alignak_module", ".", "__dict__", ")", "try", ":", "instance", "=", "python_module", ".", "get_instance", "(", "alignak_module", ")", "if", "not", "isinstance", "(", "instance", ",", "BaseModule", ")", ":", "# pragma: no cover, simple protection", "self", ".", "configuration_errors", ".", "append", "(", "\"Module %s instance is not a \"", "\"BaseModule instance: %s\"", "%", "(", "alignak_module", ".", "get_name", "(", ")", ",", "type", "(", "instance", ")", ")", ")", "raise", "AttributeError", "# pragma: no cover, simple protection", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "logger", ".", "error", "(", "\"The module %s raised an exception on loading, I remove it!\"", ",", "alignak_module", ".", "get_name", "(", ")", ")", "logger", ".", "exception", "(", "\"Exception: %s\"", ",", "exp", ")", "self", ".", "configuration_errors", ".", "append", "(", "\"The module %s raised an exception on \"", "\"loading: %s, I remove it!\"", "%", "(", "alignak_module", ".", "get_name", "(", ")", ",", "str", "(", "exp", ")", ")", ")", "else", ":", "# Give the module the data to which daemon/module it is loaded into", "instance", ".", "set_loaded_into", "(", "self", ".", "daemon", ".", "name", ")", "self", ".", "instances", ".", "append", "(", "instance", ")", "for", "instance", "in", "self", ".", "instances", ":", "# External instances are not initialized now, but only when they are started", "if", "not", "instance", ".", "is_external", "and", "not", "self", ".", "try_instance_init", "(", "instance", ")", ":", "# If the init failed, we put in in the restart queue", "logger", ".", "warning", "(", "\"The module '%s' failed to initialize, \"", "\"I will try to restart it later\"", ",", "instance", ".", "name", ")", "self", ".", "set_to_restart", "(", "instance", ")", "return", "self", ".", "instances" ]
Create, init and then returns the list of module instances that the caller needs. This method is called once the Python modules are loaded to initialize the modules. If an instance can't be created or initialized then only log is doneand that instance is skipped. The previous modules instance(s), if any, are all cleaned. :return: module instances list :rtype: list
[ "Create", "init", "and", "then", "returns", "the", "list", "of", "module", "instances", "that", "the", "caller", "needs", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L227-L281
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.start_external_instances
def start_external_instances(self, late_start=False): """Launch external instances that are load correctly :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: None """ for instance in [i for i in self.instances if i.is_external]: # But maybe the init failed a bit, so bypass this ones from now if not self.try_instance_init(instance, late_start=late_start): logger.warning("The module '%s' failed to init, I will try to restart it later", instance.name) self.set_to_restart(instance) continue # ok, init succeed logger.info("Starting external module %s", instance.name) instance.start()
python
def start_external_instances(self, late_start=False): """Launch external instances that are load correctly :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: None """ for instance in [i for i in self.instances if i.is_external]: # But maybe the init failed a bit, so bypass this ones from now if not self.try_instance_init(instance, late_start=late_start): logger.warning("The module '%s' failed to init, I will try to restart it later", instance.name) self.set_to_restart(instance) continue # ok, init succeed logger.info("Starting external module %s", instance.name) instance.start()
[ "def", "start_external_instances", "(", "self", ",", "late_start", "=", "False", ")", ":", "for", "instance", "in", "[", "i", "for", "i", "in", "self", ".", "instances", "if", "i", ".", "is_external", "]", ":", "# But maybe the init failed a bit, so bypass this ones from now", "if", "not", "self", ".", "try_instance_init", "(", "instance", ",", "late_start", "=", "late_start", ")", ":", "logger", ".", "warning", "(", "\"The module '%s' failed to init, I will try to restart it later\"", ",", "instance", ".", "name", ")", "self", ".", "set_to_restart", "(", "instance", ")", "continue", "# ok, init succeed", "logger", ".", "info", "(", "\"Starting external module %s\"", ",", "instance", ".", "name", ")", "instance", ".", "start", "(", ")" ]
Launch external instances that are load correctly :param late_start: If late_start, don't look for last_init_try :type late_start: bool :return: None
[ "Launch", "external", "instances", "that", "are", "load", "correctly" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L283-L300
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.remove_instance
def remove_instance(self, instance): """Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None """ # External instances need to be close before (process + queues) if instance.is_external: logger.info("Request external process to stop for %s", instance.name) instance.stop_process() logger.info("External process stopped.") instance.clear_queues(self.daemon.sync_manager) # Then do not listen anymore about it self.instances.remove(instance)
python
def remove_instance(self, instance): """Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None """ # External instances need to be close before (process + queues) if instance.is_external: logger.info("Request external process to stop for %s", instance.name) instance.stop_process() logger.info("External process stopped.") instance.clear_queues(self.daemon.sync_manager) # Then do not listen anymore about it self.instances.remove(instance)
[ "def", "remove_instance", "(", "self", ",", "instance", ")", ":", "# External instances need to be close before (process + queues)", "if", "instance", ".", "is_external", ":", "logger", ".", "info", "(", "\"Request external process to stop for %s\"", ",", "instance", ".", "name", ")", "instance", ".", "stop_process", "(", ")", "logger", ".", "info", "(", "\"External process stopped.\"", ")", "instance", ".", "clear_queues", "(", "self", ".", "daemon", ".", "sync_manager", ")", "# Then do not listen anymore about it", "self", ".", "instances", ".", "remove", "(", "instance", ")" ]
Request to cleanly remove the given instance. If instance is external also shutdown it cleanly :param instance: instance to remove :type instance: object :return: None
[ "Request", "to", "cleanly", "remove", "the", "given", "instance", ".", "If", "instance", "is", "external", "also", "shutdown", "it", "cleanly" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L302-L319
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.check_alive_instances
def check_alive_instances(self): """Check alive instances. If not, log error and try to restart it :return: None """ # Only for external for instance in self.instances: if instance in self.to_restart: continue if instance.is_external and instance.process and not instance.process.is_alive(): logger.error("The external module %s died unexpectedly!", instance.name) logger.info("Setting the module %s to restart", instance.name) # We clean its queues, they are no more useful instance.clear_queues(self.daemon.sync_manager) self.set_to_restart(instance) # Ok, no need to look at queue size now continue # Now look for maximum queue size. If above the defined value, the module may have # a huge problem and so bailout. It's not a perfect solution, more a watchdog # If max_queue_size is 0, don't check this if self.daemon.max_queue_size == 0: continue # Check for module queue size queue_size = 0 try: queue_size = instance.to_q.qsize() except Exception: # pylint: disable=broad-except pass if queue_size > self.daemon.max_queue_size: logger.error("The module %s has a too important queue size (%s > %s max)!", instance.name, queue_size, self.daemon.max_queue_size) logger.info("Setting the module %s to restart", instance.name) # We clean its queues, they are no more useful instance.clear_queues(self.daemon.sync_manager) self.set_to_restart(instance)
python
def check_alive_instances(self): """Check alive instances. If not, log error and try to restart it :return: None """ # Only for external for instance in self.instances: if instance in self.to_restart: continue if instance.is_external and instance.process and not instance.process.is_alive(): logger.error("The external module %s died unexpectedly!", instance.name) logger.info("Setting the module %s to restart", instance.name) # We clean its queues, they are no more useful instance.clear_queues(self.daemon.sync_manager) self.set_to_restart(instance) # Ok, no need to look at queue size now continue # Now look for maximum queue size. If above the defined value, the module may have # a huge problem and so bailout. It's not a perfect solution, more a watchdog # If max_queue_size is 0, don't check this if self.daemon.max_queue_size == 0: continue # Check for module queue size queue_size = 0 try: queue_size = instance.to_q.qsize() except Exception: # pylint: disable=broad-except pass if queue_size > self.daemon.max_queue_size: logger.error("The module %s has a too important queue size (%s > %s max)!", instance.name, queue_size, self.daemon.max_queue_size) logger.info("Setting the module %s to restart", instance.name) # We clean its queues, they are no more useful instance.clear_queues(self.daemon.sync_manager) self.set_to_restart(instance)
[ "def", "check_alive_instances", "(", "self", ")", ":", "# Only for external", "for", "instance", "in", "self", ".", "instances", ":", "if", "instance", "in", "self", ".", "to_restart", ":", "continue", "if", "instance", ".", "is_external", "and", "instance", ".", "process", "and", "not", "instance", ".", "process", ".", "is_alive", "(", ")", ":", "logger", ".", "error", "(", "\"The external module %s died unexpectedly!\"", ",", "instance", ".", "name", ")", "logger", ".", "info", "(", "\"Setting the module %s to restart\"", ",", "instance", ".", "name", ")", "# We clean its queues, they are no more useful", "instance", ".", "clear_queues", "(", "self", ".", "daemon", ".", "sync_manager", ")", "self", ".", "set_to_restart", "(", "instance", ")", "# Ok, no need to look at queue size now", "continue", "# Now look for maximum queue size. If above the defined value, the module may have", "# a huge problem and so bailout. It's not a perfect solution, more a watchdog", "# If max_queue_size is 0, don't check this", "if", "self", ".", "daemon", ".", "max_queue_size", "==", "0", ":", "continue", "# Check for module queue size", "queue_size", "=", "0", "try", ":", "queue_size", "=", "instance", ".", "to_q", ".", "qsize", "(", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "if", "queue_size", ">", "self", ".", "daemon", ".", "max_queue_size", ":", "logger", ".", "error", "(", "\"The module %s has a too important queue size (%s > %s max)!\"", ",", "instance", ".", "name", ",", "queue_size", ",", "self", ".", "daemon", ".", "max_queue_size", ")", "logger", ".", "info", "(", "\"Setting the module %s to restart\"", ",", "instance", ".", "name", ")", "# We clean its queues, they are no more useful", "instance", ".", "clear_queues", "(", "self", ".", "daemon", ".", "sync_manager", ")", "self", ".", "set_to_restart", "(", "instance", ")" ]
Check alive instances. If not, log error and try to restart it :return: None
[ "Check", "alive", "instances", ".", "If", "not", "log", "error", "and", "try", "to", "restart", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L321-L359
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.try_to_restart_deads
def try_to_restart_deads(self): """Try to reinit and restart dead instances :return: None """ to_restart = self.to_restart[:] del self.to_restart[:] for instance in to_restart: logger.warning("Trying to restart module: %s", instance.name) if self.try_instance_init(instance): logger.warning("Restarting %s...", instance.name) # Because it is a restart, clean the module inner process reference instance.process = None # If it's an external module, it will start the process instance.start() # Ok it's good now :) else: # Will retry later... self.to_restart.append(instance)
python
def try_to_restart_deads(self): """Try to reinit and restart dead instances :return: None """ to_restart = self.to_restart[:] del self.to_restart[:] for instance in to_restart: logger.warning("Trying to restart module: %s", instance.name) if self.try_instance_init(instance): logger.warning("Restarting %s...", instance.name) # Because it is a restart, clean the module inner process reference instance.process = None # If it's an external module, it will start the process instance.start() # Ok it's good now :) else: # Will retry later... self.to_restart.append(instance)
[ "def", "try_to_restart_deads", "(", "self", ")", ":", "to_restart", "=", "self", ".", "to_restart", "[", ":", "]", "del", "self", ".", "to_restart", "[", ":", "]", "for", "instance", "in", "to_restart", ":", "logger", ".", "warning", "(", "\"Trying to restart module: %s\"", ",", "instance", ".", "name", ")", "if", "self", ".", "try_instance_init", "(", "instance", ")", ":", "logger", ".", "warning", "(", "\"Restarting %s...\"", ",", "instance", ".", "name", ")", "# Because it is a restart, clean the module inner process reference", "instance", ".", "process", "=", "None", "# If it's an external module, it will start the process", "instance", ".", "start", "(", ")", "# Ok it's good now :)", "else", ":", "# Will retry later...", "self", ".", "to_restart", ".", "append", "(", "instance", ")" ]
Try to reinit and restart dead instances :return: None
[ "Try", "to", "reinit", "and", "restart", "dead", "instances" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L361-L381
train
Alignak-monitoring/alignak
alignak/modulesmanager.py
ModulesManager.stop_all
def stop_all(self): """Stop all module instances :return: None """ logger.info('Shutting down modules...') # Ask internal to quit if they can for instance in self.get_internal_instances(): if hasattr(instance, 'quit') and isinstance(instance.quit, collections.Callable): instance.quit() self.clear_instances([instance for instance in self.instances if instance.is_external])
python
def stop_all(self): """Stop all module instances :return: None """ logger.info('Shutting down modules...') # Ask internal to quit if they can for instance in self.get_internal_instances(): if hasattr(instance, 'quit') and isinstance(instance.quit, collections.Callable): instance.quit() self.clear_instances([instance for instance in self.instances if instance.is_external])
[ "def", "stop_all", "(", "self", ")", ":", "logger", ".", "info", "(", "'Shutting down modules...'", ")", "# Ask internal to quit if they can", "for", "instance", "in", "self", ".", "get_internal_instances", "(", ")", ":", "if", "hasattr", "(", "instance", ",", "'quit'", ")", "and", "isinstance", "(", "instance", ".", "quit", ",", "collections", ".", "Callable", ")", ":", "instance", ".", "quit", "(", ")", "self", ".", "clear_instances", "(", "[", "instance", "for", "instance", "in", "self", ".", "instances", "if", "instance", ".", "is_external", "]", ")" ]
Stop all module instances :return: None
[ "Stop", "all", "module", "instances" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L417-L428
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.parse
def parse(self): # pylint: disable=too-many-branches """ Check if some extra configuration files are existing in an `alignak.d` sub directory near the found configuration file. Parse the Alignak configuration file(s) Exit the script if some errors are encountered. :return: True/False """ # Search if some ini files existe in an alignak.d sub-directory sub_directory = 'alignak.d' dir_name = os.path.dirname(self.configuration_file) dir_name = os.path.join(dir_name, sub_directory) self.cfg_files = [self.configuration_file] if os.path.exists(dir_name): for root, _, walk_files in os.walk(dir_name, followlinks=True): for found_file in walk_files: if not re.search(r"\.ini$", found_file): continue self.cfg_files.append(os.path.join(root, found_file)) print("Loading configuration files: %s " % self.cfg_files) # Read and parse the found configuration files self.config = configparser.ConfigParser() try: self.config.read(self.cfg_files) if self.config._sections == {}: print("* bad formatted configuration file: %s " % self.configuration_file) if self.embedded: raise ValueError sys.exit(2) for section in self.config.sections(): if self.verbose: print("- section: %s" % section) for (key, value) in self.config.items(section): inner_property = "%s.%s" % (section, key) # Set object property setattr(self, inner_property, value) # Set environment variable os.environ[inner_property] = value if self.verbose: print(" %s = %s" % (inner_property, value)) if self.export: # Allowed shell variables may only contain: [a-zA-z0-9_] inner_property = re.sub('[^0-9a-zA-Z]+', '_', inner_property) inner_property = inner_property.upper() print("export %s=%s" % (inner_property, cmd_quote(value))) except configparser.ParsingError as exp: print("* parsing error in config file : %s\n%s" % (self.configuration_file, exp.message)) if self.embedded: return False sys.exit(3) except configparser.InterpolationMissingOptionError as exp: print("* incorrect or missing variable: %s" % str(exp)) if self.embedded: return False sys.exit(3) if self.verbose: print("Configuration file parsed correctly") return True
python
def parse(self): # pylint: disable=too-many-branches """ Check if some extra configuration files are existing in an `alignak.d` sub directory near the found configuration file. Parse the Alignak configuration file(s) Exit the script if some errors are encountered. :return: True/False """ # Search if some ini files existe in an alignak.d sub-directory sub_directory = 'alignak.d' dir_name = os.path.dirname(self.configuration_file) dir_name = os.path.join(dir_name, sub_directory) self.cfg_files = [self.configuration_file] if os.path.exists(dir_name): for root, _, walk_files in os.walk(dir_name, followlinks=True): for found_file in walk_files: if not re.search(r"\.ini$", found_file): continue self.cfg_files.append(os.path.join(root, found_file)) print("Loading configuration files: %s " % self.cfg_files) # Read and parse the found configuration files self.config = configparser.ConfigParser() try: self.config.read(self.cfg_files) if self.config._sections == {}: print("* bad formatted configuration file: %s " % self.configuration_file) if self.embedded: raise ValueError sys.exit(2) for section in self.config.sections(): if self.verbose: print("- section: %s" % section) for (key, value) in self.config.items(section): inner_property = "%s.%s" % (section, key) # Set object property setattr(self, inner_property, value) # Set environment variable os.environ[inner_property] = value if self.verbose: print(" %s = %s" % (inner_property, value)) if self.export: # Allowed shell variables may only contain: [a-zA-z0-9_] inner_property = re.sub('[^0-9a-zA-Z]+', '_', inner_property) inner_property = inner_property.upper() print("export %s=%s" % (inner_property, cmd_quote(value))) except configparser.ParsingError as exp: print("* parsing error in config file : %s\n%s" % (self.configuration_file, exp.message)) if self.embedded: return False sys.exit(3) except configparser.InterpolationMissingOptionError as exp: print("* incorrect or missing variable: %s" % str(exp)) if self.embedded: return False sys.exit(3) if self.verbose: print("Configuration file parsed correctly") return True
[ "def", "parse", "(", "self", ")", ":", "# pylint: disable=too-many-branches", "# Search if some ini files existe in an alignak.d sub-directory", "sub_directory", "=", "'alignak.d'", "dir_name", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "configuration_file", ")", "dir_name", "=", "os", ".", "path", ".", "join", "(", "dir_name", ",", "sub_directory", ")", "self", ".", "cfg_files", "=", "[", "self", ".", "configuration_file", "]", "if", "os", ".", "path", ".", "exists", "(", "dir_name", ")", ":", "for", "root", ",", "_", ",", "walk_files", "in", "os", ".", "walk", "(", "dir_name", ",", "followlinks", "=", "True", ")", ":", "for", "found_file", "in", "walk_files", ":", "if", "not", "re", ".", "search", "(", "r\"\\.ini$\"", ",", "found_file", ")", ":", "continue", "self", ".", "cfg_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "root", ",", "found_file", ")", ")", "print", "(", "\"Loading configuration files: %s \"", "%", "self", ".", "cfg_files", ")", "# Read and parse the found configuration files", "self", ".", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "try", ":", "self", ".", "config", ".", "read", "(", "self", ".", "cfg_files", ")", "if", "self", ".", "config", ".", "_sections", "==", "{", "}", ":", "print", "(", "\"* bad formatted configuration file: %s \"", "%", "self", ".", "configuration_file", ")", "if", "self", ".", "embedded", ":", "raise", "ValueError", "sys", ".", "exit", "(", "2", ")", "for", "section", "in", "self", ".", "config", ".", "sections", "(", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "\"- section: %s\"", "%", "section", ")", "for", "(", "key", ",", "value", ")", "in", "self", ".", "config", ".", "items", "(", "section", ")", ":", "inner_property", "=", "\"%s.%s\"", "%", "(", "section", ",", "key", ")", "# Set object property", "setattr", "(", "self", ",", "inner_property", ",", "value", ")", "# Set environment variable", "os", ".", "environ", "[", "inner_property", "]", "=", "value", "if", "self", ".", "verbose", ":", "print", "(", "\" %s = %s\"", "%", "(", "inner_property", ",", "value", ")", ")", "if", "self", ".", "export", ":", "# Allowed shell variables may only contain: [a-zA-z0-9_]", "inner_property", "=", "re", ".", "sub", "(", "'[^0-9a-zA-Z]+'", ",", "'_'", ",", "inner_property", ")", "inner_property", "=", "inner_property", ".", "upper", "(", ")", "print", "(", "\"export %s=%s\"", "%", "(", "inner_property", ",", "cmd_quote", "(", "value", ")", ")", ")", "except", "configparser", ".", "ParsingError", "as", "exp", ":", "print", "(", "\"* parsing error in config file : %s\\n%s\"", "%", "(", "self", ".", "configuration_file", ",", "exp", ".", "message", ")", ")", "if", "self", ".", "embedded", ":", "return", "False", "sys", ".", "exit", "(", "3", ")", "except", "configparser", ".", "InterpolationMissingOptionError", "as", "exp", ":", "print", "(", "\"* incorrect or missing variable: %s\"", "%", "str", "(", "exp", ")", ")", "if", "self", ".", "embedded", ":", "return", "False", "sys", ".", "exit", "(", "3", ")", "if", "self", ".", "verbose", ":", "print", "(", "\"Configuration file parsed correctly\"", ")", "return", "True" ]
Check if some extra configuration files are existing in an `alignak.d` sub directory near the found configuration file. Parse the Alignak configuration file(s) Exit the script if some errors are encountered. :return: True/False
[ "Check", "if", "some", "extra", "configuration", "files", "are", "existing", "in", "an", "alignak", ".", "d", "sub", "directory", "near", "the", "found", "configuration", "file", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L172-L242
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.write
def write(self, env_file): """ Write the Alignak configuration to a file :param env_file: file name to dump the configuration :type env_file: str :return: True/False """ try: with open(env_file, "w") as out_file: self.config.write(out_file) except Exception as exp: # pylint: disable=broad-except print("Dumping environment file raised an error: %s. " % exp)
python
def write(self, env_file): """ Write the Alignak configuration to a file :param env_file: file name to dump the configuration :type env_file: str :return: True/False """ try: with open(env_file, "w") as out_file: self.config.write(out_file) except Exception as exp: # pylint: disable=broad-except print("Dumping environment file raised an error: %s. " % exp)
[ "def", "write", "(", "self", ",", "env_file", ")", ":", "try", ":", "with", "open", "(", "env_file", ",", "\"w\"", ")", "as", "out_file", ":", "self", ".", "config", ".", "write", "(", "out_file", ")", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "print", "(", "\"Dumping environment file raised an error: %s. \"", "%", "exp", ")" ]
Write the Alignak configuration to a file :param env_file: file name to dump the configuration :type env_file: str :return: True/False
[ "Write", "the", "Alignak", "configuration", "to", "a", "file" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L244-L256
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.get_alignak_macros
def get_alignak_macros(self): """ Get the Alignak macros. :return: a dict containing the Alignak macros """ macros = self.get_alignak_configuration(macros=True) sections = self._search_sections('pack.') for name, _ in list(sections.items()): section_macros = self.get_alignak_configuration(section=name, macros=True) macros.update(section_macros) return macros
python
def get_alignak_macros(self): """ Get the Alignak macros. :return: a dict containing the Alignak macros """ macros = self.get_alignak_configuration(macros=True) sections = self._search_sections('pack.') for name, _ in list(sections.items()): section_macros = self.get_alignak_configuration(section=name, macros=True) macros.update(section_macros) return macros
[ "def", "get_alignak_macros", "(", "self", ")", ":", "macros", "=", "self", ".", "get_alignak_configuration", "(", "macros", "=", "True", ")", "sections", "=", "self", ".", "_search_sections", "(", "'pack.'", ")", "for", "name", ",", "_", "in", "list", "(", "sections", ".", "items", "(", ")", ")", ":", "section_macros", "=", "self", ".", "get_alignak_configuration", "(", "section", "=", "name", ",", "macros", "=", "True", ")", "macros", ".", "update", "(", "section_macros", ")", "return", "macros" ]
Get the Alignak macros. :return: a dict containing the Alignak macros
[ "Get", "the", "Alignak", "macros", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L292-L304
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.get_alignak_configuration
def get_alignak_configuration(self, section=SECTION_CONFIGURATION, legacy_cfg=False, macros=False): """ Get the Alignak configuration parameters. All the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' and the macros. If `lecagy_cfg` is True, this function only returns the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' If `macros` is True, this function only returns the variables included in the SECTION_CONFIGURATION section that are considered as macros :param section: name of the sectio nto search for :type section: str :param legacy_cfg: only get the legacy cfg declarations :type legacy_cfg: bool :param macros: only get the macros declarations :type macros: bool :return: a dict containing the Alignak configuration parameters """ configuration = self._search_sections(section) if section not in configuration: return [] for prop, _ in list(configuration[section].items()): # Only legacy configuration items if legacy_cfg: if not prop.startswith('cfg'): configuration[section].pop(prop) continue # Only macro definitions if macros: if not prop.startswith('_') and not prop.startswith('$'): configuration[section].pop(prop) continue # All values except legacy configuration and macros if prop.startswith('cfg') or prop.startswith('_') or prop.startswith('$'): configuration[section].pop(prop) return configuration[section]
python
def get_alignak_configuration(self, section=SECTION_CONFIGURATION, legacy_cfg=False, macros=False): """ Get the Alignak configuration parameters. All the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' and the macros. If `lecagy_cfg` is True, this function only returns the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' If `macros` is True, this function only returns the variables included in the SECTION_CONFIGURATION section that are considered as macros :param section: name of the sectio nto search for :type section: str :param legacy_cfg: only get the legacy cfg declarations :type legacy_cfg: bool :param macros: only get the macros declarations :type macros: bool :return: a dict containing the Alignak configuration parameters """ configuration = self._search_sections(section) if section not in configuration: return [] for prop, _ in list(configuration[section].items()): # Only legacy configuration items if legacy_cfg: if not prop.startswith('cfg'): configuration[section].pop(prop) continue # Only macro definitions if macros: if not prop.startswith('_') and not prop.startswith('$'): configuration[section].pop(prop) continue # All values except legacy configuration and macros if prop.startswith('cfg') or prop.startswith('_') or prop.startswith('$'): configuration[section].pop(prop) return configuration[section]
[ "def", "get_alignak_configuration", "(", "self", ",", "section", "=", "SECTION_CONFIGURATION", ",", "legacy_cfg", "=", "False", ",", "macros", "=", "False", ")", ":", "configuration", "=", "self", ".", "_search_sections", "(", "section", ")", "if", "section", "not", "in", "configuration", ":", "return", "[", "]", "for", "prop", ",", "_", "in", "list", "(", "configuration", "[", "section", "]", ".", "items", "(", ")", ")", ":", "# Only legacy configuration items", "if", "legacy_cfg", ":", "if", "not", "prop", ".", "startswith", "(", "'cfg'", ")", ":", "configuration", "[", "section", "]", ".", "pop", "(", "prop", ")", "continue", "# Only macro definitions", "if", "macros", ":", "if", "not", "prop", ".", "startswith", "(", "'_'", ")", "and", "not", "prop", ".", "startswith", "(", "'$'", ")", ":", "configuration", "[", "section", "]", ".", "pop", "(", "prop", ")", "continue", "# All values except legacy configuration and macros", "if", "prop", ".", "startswith", "(", "'cfg'", ")", "or", "prop", ".", "startswith", "(", "'_'", ")", "or", "prop", ".", "startswith", "(", "'$'", ")", ":", "configuration", "[", "section", "]", ".", "pop", "(", "prop", ")", "return", "configuration", "[", "section", "]" ]
Get the Alignak configuration parameters. All the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' and the macros. If `lecagy_cfg` is True, this function only returns the variables included in the SECTION_CONFIGURATION section except the variables starting with 'cfg' If `macros` is True, this function only returns the variables included in the SECTION_CONFIGURATION section that are considered as macros :param section: name of the sectio nto search for :type section: str :param legacy_cfg: only get the legacy cfg declarations :type legacy_cfg: bool :param macros: only get the macros declarations :type macros: bool :return: a dict containing the Alignak configuration parameters
[ "Get", "the", "Alignak", "configuration", "parameters", ".", "All", "the", "variables", "included", "in", "the", "SECTION_CONFIGURATION", "section", "except", "the", "variables", "starting", "with", "cfg", "and", "the", "macros", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L306-L345
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.get_daemons
def get_daemons(self, daemon_name=None, daemon_type=None): """ Get the daemons configuration parameters If name is provided, get the configuration for this daemon, else, If type is provided, get the configuration for all the daemons of this type, else get the configuration of all the daemons. :param daemon_name: the searched daemon name :param daemon_type: the searched daemon type :return: a dict containing the daemon(s) configuration parameters """ if daemon_name is not None: sections = self._search_sections('daemon.%s' % daemon_name) if 'daemon.%s' % daemon_name in sections: return sections['daemon.' + daemon_name] return {} if daemon_type is not None: sections = self._search_sections('daemon.') for name, daemon in list(sections.items()): if 'type' not in daemon or not daemon['type'] == daemon_type: sections.pop(name) return sections return self._search_sections('daemon.')
python
def get_daemons(self, daemon_name=None, daemon_type=None): """ Get the daemons configuration parameters If name is provided, get the configuration for this daemon, else, If type is provided, get the configuration for all the daemons of this type, else get the configuration of all the daemons. :param daemon_name: the searched daemon name :param daemon_type: the searched daemon type :return: a dict containing the daemon(s) configuration parameters """ if daemon_name is not None: sections = self._search_sections('daemon.%s' % daemon_name) if 'daemon.%s' % daemon_name in sections: return sections['daemon.' + daemon_name] return {} if daemon_type is not None: sections = self._search_sections('daemon.') for name, daemon in list(sections.items()): if 'type' not in daemon or not daemon['type'] == daemon_type: sections.pop(name) return sections return self._search_sections('daemon.')
[ "def", "get_daemons", "(", "self", ",", "daemon_name", "=", "None", ",", "daemon_type", "=", "None", ")", ":", "if", "daemon_name", "is", "not", "None", ":", "sections", "=", "self", ".", "_search_sections", "(", "'daemon.%s'", "%", "daemon_name", ")", "if", "'daemon.%s'", "%", "daemon_name", "in", "sections", ":", "return", "sections", "[", "'daemon.'", "+", "daemon_name", "]", "return", "{", "}", "if", "daemon_type", "is", "not", "None", ":", "sections", "=", "self", ".", "_search_sections", "(", "'daemon.'", ")", "for", "name", ",", "daemon", "in", "list", "(", "sections", ".", "items", "(", ")", ")", ":", "if", "'type'", "not", "in", "daemon", "or", "not", "daemon", "[", "'type'", "]", "==", "daemon_type", ":", "sections", ".", "pop", "(", "name", ")", "return", "sections", "return", "self", ".", "_search_sections", "(", "'daemon.'", ")" ]
Get the daemons configuration parameters If name is provided, get the configuration for this daemon, else, If type is provided, get the configuration for all the daemons of this type, else get the configuration of all the daemons. :param daemon_name: the searched daemon name :param daemon_type: the searched daemon type :return: a dict containing the daemon(s) configuration parameters
[ "Get", "the", "daemons", "configuration", "parameters" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L347-L372
train
Alignak-monitoring/alignak
alignak/bin/alignak_environment.py
AlignakConfigParser.get_modules
def get_modules(self, name=None, daemon_name=None, names_only=True): """ Get the modules configuration parameters If name is provided, get the configuration for this module, else, If daemon_name is provided, get the configuration for all the modules of this daemon, else get the configuration of all the modules. :param name: the searched module name :param daemon_name: the modules of this daemon :param names_only: if True only returns the modules names, else all the configuration data :return: a dict containing the module(s) configuration parameters """ if name is not None: sections = self._search_sections('module.' + name) if 'module.' + name in sections: return sections['module.' + name] return {} if daemon_name is not None: section = self.get_daemons(daemon_name) if 'modules' in section and section['modules']: modules = [] for module_name in section['modules'].split(','): if names_only: modules.append(module_name) else: modules.append(self.get_modules(name=module_name)) return modules return [] return self._search_sections('module.')
python
def get_modules(self, name=None, daemon_name=None, names_only=True): """ Get the modules configuration parameters If name is provided, get the configuration for this module, else, If daemon_name is provided, get the configuration for all the modules of this daemon, else get the configuration of all the modules. :param name: the searched module name :param daemon_name: the modules of this daemon :param names_only: if True only returns the modules names, else all the configuration data :return: a dict containing the module(s) configuration parameters """ if name is not None: sections = self._search_sections('module.' + name) if 'module.' + name in sections: return sections['module.' + name] return {} if daemon_name is not None: section = self.get_daemons(daemon_name) if 'modules' in section and section['modules']: modules = [] for module_name in section['modules'].split(','): if names_only: modules.append(module_name) else: modules.append(self.get_modules(name=module_name)) return modules return [] return self._search_sections('module.')
[ "def", "get_modules", "(", "self", ",", "name", "=", "None", ",", "daemon_name", "=", "None", ",", "names_only", "=", "True", ")", ":", "if", "name", "is", "not", "None", ":", "sections", "=", "self", ".", "_search_sections", "(", "'module.'", "+", "name", ")", "if", "'module.'", "+", "name", "in", "sections", ":", "return", "sections", "[", "'module.'", "+", "name", "]", "return", "{", "}", "if", "daemon_name", "is", "not", "None", ":", "section", "=", "self", ".", "get_daemons", "(", "daemon_name", ")", "if", "'modules'", "in", "section", "and", "section", "[", "'modules'", "]", ":", "modules", "=", "[", "]", "for", "module_name", "in", "section", "[", "'modules'", "]", ".", "split", "(", "','", ")", ":", "if", "names_only", ":", "modules", ".", "append", "(", "module_name", ")", "else", ":", "modules", ".", "append", "(", "self", ".", "get_modules", "(", "name", "=", "module_name", ")", ")", "return", "modules", "return", "[", "]", "return", "self", ".", "_search_sections", "(", "'module.'", ")" ]
Get the modules configuration parameters If name is provided, get the configuration for this module, else, If daemon_name is provided, get the configuration for all the modules of this daemon, else get the configuration of all the modules. :param name: the searched module name :param daemon_name: the modules of this daemon :param names_only: if True only returns the modules names, else all the configuration data :return: a dict containing the module(s) configuration parameters
[ "Get", "the", "modules", "configuration", "parameters" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/bin/alignak_environment.py#L374-L405
train
Alignak-monitoring/alignak
alignak/objects/itemgroup.py
Itemgroup.copy_shell
def copy_shell(self): """ Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None """ cls = self.__class__ new_i = cls() # create a new group new_i.uuid = self.uuid # with the same id # Copy all properties for prop in cls.properties: if hasattr(self, prop): if prop in ['members', 'unknown_members']: setattr(new_i, prop, []) else: setattr(new_i, prop, getattr(self, prop)) return new_i
python
def copy_shell(self): """ Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None """ cls = self.__class__ new_i = cls() # create a new group new_i.uuid = self.uuid # with the same id # Copy all properties for prop in cls.properties: if hasattr(self, prop): if prop in ['members', 'unknown_members']: setattr(new_i, prop, []) else: setattr(new_i, prop, getattr(self, prop)) return new_i
[ "def", "copy_shell", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "new_i", "=", "cls", "(", ")", "# create a new group", "new_i", ".", "uuid", "=", "self", ".", "uuid", "# with the same id", "# Copy all properties", "for", "prop", "in", "cls", ".", "properties", ":", "if", "hasattr", "(", "self", ",", "prop", ")", ":", "if", "prop", "in", "[", "'members'", ",", "'unknown_members'", "]", ":", "setattr", "(", "new_i", ",", "prop", ",", "[", "]", ")", "else", ":", "setattr", "(", "new_i", ",", "prop", ",", "getattr", "(", "self", ",", "prop", ")", ")", "return", "new_i" ]
Copy the group properties EXCEPT the members. Members need to be filled after manually :return: Itemgroup object :rtype: alignak.objects.itemgroup.Itemgroup :return: None
[ "Copy", "the", "group", "properties", "EXCEPT", "the", "members", ".", "Members", "need", "to", "be", "filled", "after", "manually" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/itemgroup.py#L100-L121
train
Alignak-monitoring/alignak
alignak/objects/itemgroup.py
Itemgroup.add_members
def add_members(self, members): """Add a new member to the members list :param members: member name :type members: str :return: None """ if not isinstance(members, list): members = [members] if not getattr(self, 'members', None): self.members = members else: self.members.extend(members)
python
def add_members(self, members): """Add a new member to the members list :param members: member name :type members: str :return: None """ if not isinstance(members, list): members = [members] if not getattr(self, 'members', None): self.members = members else: self.members.extend(members)
[ "def", "add_members", "(", "self", ",", "members", ")", ":", "if", "not", "isinstance", "(", "members", ",", "list", ")", ":", "members", "=", "[", "members", "]", "if", "not", "getattr", "(", "self", ",", "'members'", ",", "None", ")", ":", "self", ".", "members", "=", "members", "else", ":", "self", ".", "members", ".", "extend", "(", "members", ")" ]
Add a new member to the members list :param members: member name :type members: str :return: None
[ "Add", "a", "new", "member", "to", "the", "members", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/itemgroup.py#L144-L157
train
Alignak-monitoring/alignak
alignak/objects/itemgroup.py
Itemgroup.add_unknown_members
def add_unknown_members(self, members): """Add a new member to the unknown members list :param member: member name :type member: str :return: None """ if not isinstance(members, list): members = [members] if not hasattr(self, 'unknown_members'): self.unknown_members = members else: self.unknown_members.extend(members)
python
def add_unknown_members(self, members): """Add a new member to the unknown members list :param member: member name :type member: str :return: None """ if not isinstance(members, list): members = [members] if not hasattr(self, 'unknown_members'): self.unknown_members = members else: self.unknown_members.extend(members)
[ "def", "add_unknown_members", "(", "self", ",", "members", ")", ":", "if", "not", "isinstance", "(", "members", ",", "list", ")", ":", "members", "=", "[", "members", "]", "if", "not", "hasattr", "(", "self", ",", "'unknown_members'", ")", ":", "self", ".", "unknown_members", "=", "members", "else", ":", "self", ".", "unknown_members", ".", "extend", "(", "members", ")" ]
Add a new member to the unknown members list :param member: member name :type member: str :return: None
[ "Add", "a", "new", "member", "to", "the", "unknown", "members", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/itemgroup.py#L159-L172
train
Alignak-monitoring/alignak
alignak/objects/itemgroup.py
Itemgroup.is_correct
def is_correct(self): """ Check if a group is valid. Valid mean all members exists, so list of unknown_members is empty :return: True if group is correct, otherwise False :rtype: bool """ state = True # Make members unique, remove duplicates if self.members: self.members = list(set(self.members)) if self.unknown_members: for member in self.unknown_members: msg = "[%s::%s] as %s, got unknown member '%s'" % ( self.my_type, self.get_name(), self.__class__.my_type, member ) self.add_error(msg) state = False return super(Itemgroup, self).is_correct() and state
python
def is_correct(self): """ Check if a group is valid. Valid mean all members exists, so list of unknown_members is empty :return: True if group is correct, otherwise False :rtype: bool """ state = True # Make members unique, remove duplicates if self.members: self.members = list(set(self.members)) if self.unknown_members: for member in self.unknown_members: msg = "[%s::%s] as %s, got unknown member '%s'" % ( self.my_type, self.get_name(), self.__class__.my_type, member ) self.add_error(msg) state = False return super(Itemgroup, self).is_correct() and state
[ "def", "is_correct", "(", "self", ")", ":", "state", "=", "True", "# Make members unique, remove duplicates", "if", "self", ".", "members", ":", "self", ".", "members", "=", "list", "(", "set", "(", "self", ".", "members", ")", ")", "if", "self", ".", "unknown_members", ":", "for", "member", "in", "self", ".", "unknown_members", ":", "msg", "=", "\"[%s::%s] as %s, got unknown member '%s'\"", "%", "(", "self", ".", "my_type", ",", "self", ".", "get_name", "(", ")", ",", "self", ".", "__class__", ".", "my_type", ",", "member", ")", "self", ".", "add_error", "(", "msg", ")", "state", "=", "False", "return", "super", "(", "Itemgroup", ",", "self", ")", ".", "is_correct", "(", ")", "and", "state" ]
Check if a group is valid. Valid mean all members exists, so list of unknown_members is empty :return: True if group is correct, otherwise False :rtype: bool
[ "Check", "if", "a", "group", "is", "valid", ".", "Valid", "mean", "all", "members", "exists", "so", "list", "of", "unknown_members", "is", "empty" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/itemgroup.py#L174-L196
train
Alignak-monitoring/alignak
alignak/objects/itemgroup.py
Itemgroup.get_initial_status_brok
def get_initial_status_brok(self, extra=None): """ Get a brok with the group properties `members` contains a list of uuid which we must provide the names. Thus we will replace the default provided uuid with the members short name. The `extra` parameter, if present, is containing the Items to search for... :param extra: monitoring items, used to recover members :type extra: alignak.objects.item.Items :return:Brok object :rtype: object """ # Here members is a list of identifiers and we need their names if extra and isinstance(extra, Items): members = [] for member_id in self.members: member = extra[member_id] members.append((member.uuid, member.get_name())) extra = {'members': members} return super(Itemgroup, self).get_initial_status_brok(extra=extra)
python
def get_initial_status_brok(self, extra=None): """ Get a brok with the group properties `members` contains a list of uuid which we must provide the names. Thus we will replace the default provided uuid with the members short name. The `extra` parameter, if present, is containing the Items to search for... :param extra: monitoring items, used to recover members :type extra: alignak.objects.item.Items :return:Brok object :rtype: object """ # Here members is a list of identifiers and we need their names if extra and isinstance(extra, Items): members = [] for member_id in self.members: member = extra[member_id] members.append((member.uuid, member.get_name())) extra = {'members': members} return super(Itemgroup, self).get_initial_status_brok(extra=extra)
[ "def", "get_initial_status_brok", "(", "self", ",", "extra", "=", "None", ")", ":", "# Here members is a list of identifiers and we need their names", "if", "extra", "and", "isinstance", "(", "extra", ",", "Items", ")", ":", "members", "=", "[", "]", "for", "member_id", "in", "self", ".", "members", ":", "member", "=", "extra", "[", "member_id", "]", "members", ".", "append", "(", "(", "member", ".", "uuid", ",", "member", ".", "get_name", "(", ")", ")", ")", "extra", "=", "{", "'members'", ":", "members", "}", "return", "super", "(", "Itemgroup", ",", "self", ")", ".", "get_initial_status_brok", "(", "extra", "=", "extra", ")" ]
Get a brok with the group properties `members` contains a list of uuid which we must provide the names. Thus we will replace the default provided uuid with the members short name. The `extra` parameter, if present, is containing the Items to search for... :param extra: monitoring items, used to recover members :type extra: alignak.objects.item.Items :return:Brok object :rtype: object
[ "Get", "a", "brok", "with", "the", "group", "properties" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/itemgroup.py#L198-L219
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.check_dir
def check_dir(self, dirname): """Check and create directory :param dirname: file name :type dirname; str :return: None """ try: os.makedirs(dirname) dir_stat = os.stat(dirname) print("Created the directory: %s, stat: %s" % (dirname, dir_stat)) if not dir_stat.st_uid == self.uid: os.chown(dirname, self.uid, self.gid) os.chmod(dirname, 0o775) dir_stat = os.stat(dirname) print("Changed directory ownership and permissions: %s, stat: %s" % (dirname, dir_stat)) self.pre_log.append(("DEBUG", "Daemon '%s' directory %s checking... " "User uid: %s, directory stat: %s." % (self.name, dirname, os.getuid(), dir_stat))) self.pre_log.append(("INFO", "Daemon '%s' directory %s did not exist, I created it. " "I set ownership for this directory to %s:%s." % (self.name, dirname, self.user, self.group))) except OSError as exp: if exp.errno == errno.EEXIST and os.path.isdir(dirname): # Directory still exists... pass else: self.pre_log.append(("ERROR", "Daemon directory '%s' did not exist, " "and I could not create. Exception: %s" % (dirname, exp))) self.exit_on_error("Daemon directory '%s' did not exist, " "and I could not create.'. Exception: %s" % (dirname, exp), exit_code=3)
python
def check_dir(self, dirname): """Check and create directory :param dirname: file name :type dirname; str :return: None """ try: os.makedirs(dirname) dir_stat = os.stat(dirname) print("Created the directory: %s, stat: %s" % (dirname, dir_stat)) if not dir_stat.st_uid == self.uid: os.chown(dirname, self.uid, self.gid) os.chmod(dirname, 0o775) dir_stat = os.stat(dirname) print("Changed directory ownership and permissions: %s, stat: %s" % (dirname, dir_stat)) self.pre_log.append(("DEBUG", "Daemon '%s' directory %s checking... " "User uid: %s, directory stat: %s." % (self.name, dirname, os.getuid(), dir_stat))) self.pre_log.append(("INFO", "Daemon '%s' directory %s did not exist, I created it. " "I set ownership for this directory to %s:%s." % (self.name, dirname, self.user, self.group))) except OSError as exp: if exp.errno == errno.EEXIST and os.path.isdir(dirname): # Directory still exists... pass else: self.pre_log.append(("ERROR", "Daemon directory '%s' did not exist, " "and I could not create. Exception: %s" % (dirname, exp))) self.exit_on_error("Daemon directory '%s' did not exist, " "and I could not create.'. Exception: %s" % (dirname, exp), exit_code=3)
[ "def", "check_dir", "(", "self", ",", "dirname", ")", ":", "try", ":", "os", ".", "makedirs", "(", "dirname", ")", "dir_stat", "=", "os", ".", "stat", "(", "dirname", ")", "print", "(", "\"Created the directory: %s, stat: %s\"", "%", "(", "dirname", ",", "dir_stat", ")", ")", "if", "not", "dir_stat", ".", "st_uid", "==", "self", ".", "uid", ":", "os", ".", "chown", "(", "dirname", ",", "self", ".", "uid", ",", "self", ".", "gid", ")", "os", ".", "chmod", "(", "dirname", ",", "0o775", ")", "dir_stat", "=", "os", ".", "stat", "(", "dirname", ")", "print", "(", "\"Changed directory ownership and permissions: %s, stat: %s\"", "%", "(", "dirname", ",", "dir_stat", ")", ")", "self", ".", "pre_log", ".", "append", "(", "(", "\"DEBUG\"", ",", "\"Daemon '%s' directory %s checking... \"", "\"User uid: %s, directory stat: %s.\"", "%", "(", "self", ".", "name", ",", "dirname", ",", "os", ".", "getuid", "(", ")", ",", "dir_stat", ")", ")", ")", "self", ".", "pre_log", ".", "append", "(", "(", "\"INFO\"", ",", "\"Daemon '%s' directory %s did not exist, I created it. \"", "\"I set ownership for this directory to %s:%s.\"", "%", "(", "self", ".", "name", ",", "dirname", ",", "self", ".", "user", ",", "self", ".", "group", ")", ")", ")", "except", "OSError", "as", "exp", ":", "if", "exp", ".", "errno", "==", "errno", ".", "EEXIST", "and", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "# Directory still exists...", "pass", "else", ":", "self", ".", "pre_log", ".", "append", "(", "(", "\"ERROR\"", ",", "\"Daemon directory '%s' did not exist, \"", "\"and I could not create. Exception: %s\"", "%", "(", "dirname", ",", "exp", ")", ")", ")", "self", ".", "exit_on_error", "(", "\"Daemon directory '%s' did not exist, \"", "\"and I could not create.'. Exception: %s\"", "%", "(", "dirname", ",", "exp", ")", ",", "exit_code", "=", "3", ")" ]
Check and create directory :param dirname: file name :type dirname; str :return: None
[ "Check", "and", "create", "directory" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L789-L828
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.request_stop
def request_stop(self, message='', exit_code=0): """Remove pid and stop daemon :return: None """ # Log an error message if exit code is not 0 # Force output to stderr if exit_code: if message: logger.error(message) try: sys.stderr.write(message) except Exception: # pylint: disable=broad-except pass logger.error("Sorry, I bail out, exit code: %d", exit_code) try: sys.stderr.write("Sorry, I bail out, exit code: %d" % exit_code) except Exception: # pylint: disable=broad-except pass else: if message: logger.info(message) self.unlink() self.do_stop() logger.info("Stopped %s.", self.name) sys.exit(exit_code)
python
def request_stop(self, message='', exit_code=0): """Remove pid and stop daemon :return: None """ # Log an error message if exit code is not 0 # Force output to stderr if exit_code: if message: logger.error(message) try: sys.stderr.write(message) except Exception: # pylint: disable=broad-except pass logger.error("Sorry, I bail out, exit code: %d", exit_code) try: sys.stderr.write("Sorry, I bail out, exit code: %d" % exit_code) except Exception: # pylint: disable=broad-except pass else: if message: logger.info(message) self.unlink() self.do_stop() logger.info("Stopped %s.", self.name) sys.exit(exit_code)
[ "def", "request_stop", "(", "self", ",", "message", "=", "''", ",", "exit_code", "=", "0", ")", ":", "# Log an error message if exit code is not 0", "# Force output to stderr", "if", "exit_code", ":", "if", "message", ":", "logger", ".", "error", "(", "message", ")", "try", ":", "sys", ".", "stderr", ".", "write", "(", "message", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "logger", ".", "error", "(", "\"Sorry, I bail out, exit code: %d\"", ",", "exit_code", ")", "try", ":", "sys", ".", "stderr", ".", "write", "(", "\"Sorry, I bail out, exit code: %d\"", "%", "exit_code", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "pass", "else", ":", "if", "message", ":", "logger", ".", "info", "(", "message", ")", "self", ".", "unlink", "(", ")", "self", ".", "do_stop", "(", ")", "logger", ".", "info", "(", "\"Stopped %s.\"", ",", "self", ".", "name", ")", "sys", ".", "exit", "(", "exit_code", ")" ]
Remove pid and stop daemon :return: None
[ "Remove", "pid", "and", "stop", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L874-L901
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.daemon_connection_init
def daemon_connection_init(self, s_link, set_wait_new_conf=False): """Initialize a connection with the daemon for the provided satellite link Initialize the connection (HTTP client) to the daemon and get its running identifier. Returns True if it succeeds else if any error occur or the daemon is inactive it returns False. Assume the daemon should be reachable because we are initializing the connection... as such, force set the link reachable property If set_wait_new_conf is set, the daemon is requested to wait a new configuration if we get a running identifier. This is used by the arbiter when a new configuration must be dispatched NB: if the daemon is configured as passive, or if it is a daemon link that is inactive then it returns False without trying a connection. :param s_link: link of the daemon to connect to :type s_link: SatelliteLink :param set_wait_new_conf: if the daemon must got the wait new configuration state :type set_wait_new_conf: bool :return: True if the connection is established, else False """ logger.debug("Daemon connection initialization: %s %s", s_link.type, s_link.name) # If the link is not not active, I do not try to initialize the connection, just useless ;) if not s_link.active: logger.warning("%s '%s' is not active, do not initialize its connection!", s_link.type, s_link.name) return False # Create the daemon connection s_link.create_connection() # Get the connection running identifier - first client / server communication logger.debug("[%s] Getting running identifier for '%s'", self.name, s_link.name) # Assume the daemon should be alive and reachable # because we are initializing the connection... s_link.alive = True s_link.reachable = True got_a_running_id = None for _ in range(0, s_link.max_check_attempts): got_a_running_id = s_link.get_running_id() if got_a_running_id: s_link.last_connection = time.time() if set_wait_new_conf: s_link.wait_new_conf() break time.sleep(0.3) return got_a_running_id
python
def daemon_connection_init(self, s_link, set_wait_new_conf=False): """Initialize a connection with the daemon for the provided satellite link Initialize the connection (HTTP client) to the daemon and get its running identifier. Returns True if it succeeds else if any error occur or the daemon is inactive it returns False. Assume the daemon should be reachable because we are initializing the connection... as such, force set the link reachable property If set_wait_new_conf is set, the daemon is requested to wait a new configuration if we get a running identifier. This is used by the arbiter when a new configuration must be dispatched NB: if the daemon is configured as passive, or if it is a daemon link that is inactive then it returns False without trying a connection. :param s_link: link of the daemon to connect to :type s_link: SatelliteLink :param set_wait_new_conf: if the daemon must got the wait new configuration state :type set_wait_new_conf: bool :return: True if the connection is established, else False """ logger.debug("Daemon connection initialization: %s %s", s_link.type, s_link.name) # If the link is not not active, I do not try to initialize the connection, just useless ;) if not s_link.active: logger.warning("%s '%s' is not active, do not initialize its connection!", s_link.type, s_link.name) return False # Create the daemon connection s_link.create_connection() # Get the connection running identifier - first client / server communication logger.debug("[%s] Getting running identifier for '%s'", self.name, s_link.name) # Assume the daemon should be alive and reachable # because we are initializing the connection... s_link.alive = True s_link.reachable = True got_a_running_id = None for _ in range(0, s_link.max_check_attempts): got_a_running_id = s_link.get_running_id() if got_a_running_id: s_link.last_connection = time.time() if set_wait_new_conf: s_link.wait_new_conf() break time.sleep(0.3) return got_a_running_id
[ "def", "daemon_connection_init", "(", "self", ",", "s_link", ",", "set_wait_new_conf", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Daemon connection initialization: %s %s\"", ",", "s_link", ".", "type", ",", "s_link", ".", "name", ")", "# If the link is not not active, I do not try to initialize the connection, just useless ;)", "if", "not", "s_link", ".", "active", ":", "logger", ".", "warning", "(", "\"%s '%s' is not active, do not initialize its connection!\"", ",", "s_link", ".", "type", ",", "s_link", ".", "name", ")", "return", "False", "# Create the daemon connection", "s_link", ".", "create_connection", "(", ")", "# Get the connection running identifier - first client / server communication", "logger", ".", "debug", "(", "\"[%s] Getting running identifier for '%s'\"", ",", "self", ".", "name", ",", "s_link", ".", "name", ")", "# Assume the daemon should be alive and reachable", "# because we are initializing the connection...", "s_link", ".", "alive", "=", "True", "s_link", ".", "reachable", "=", "True", "got_a_running_id", "=", "None", "for", "_", "in", "range", "(", "0", ",", "s_link", ".", "max_check_attempts", ")", ":", "got_a_running_id", "=", "s_link", ".", "get_running_id", "(", ")", "if", "got_a_running_id", ":", "s_link", ".", "last_connection", "=", "time", ".", "time", "(", ")", "if", "set_wait_new_conf", ":", "s_link", ".", "wait_new_conf", "(", ")", "break", "time", ".", "sleep", "(", "0.3", ")", "return", "got_a_running_id" ]
Initialize a connection with the daemon for the provided satellite link Initialize the connection (HTTP client) to the daemon and get its running identifier. Returns True if it succeeds else if any error occur or the daemon is inactive it returns False. Assume the daemon should be reachable because we are initializing the connection... as such, force set the link reachable property If set_wait_new_conf is set, the daemon is requested to wait a new configuration if we get a running identifier. This is used by the arbiter when a new configuration must be dispatched NB: if the daemon is configured as passive, or if it is a daemon link that is inactive then it returns False without trying a connection. :param s_link: link of the daemon to connect to :type s_link: SatelliteLink :param set_wait_new_conf: if the daemon must got the wait new configuration state :type set_wait_new_conf: bool :return: True if the connection is established, else False
[ "Initialize", "a", "connection", "with", "the", "daemon", "for", "the", "provided", "satellite", "link" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L937-L987
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.do_load_modules
def do_load_modules(self, modules): """Wrapper for calling load_and_init method of modules_manager attribute :param modules: list of modules that should be loaded by the daemon :return: None """ _ts = time.time() logger.info("Loading modules...") if self.modules_manager.load_and_init(modules): if self.modules_manager.instances: logger.info("I correctly loaded my modules: [%s]", ','.join([inst.name for inst in self.modules_manager.instances])) else: logger.info("I do not have any module") else: # pragma: no cover, not with unit tests... logger.error("Errors were encountered when checking and loading modules:") for msg in self.modules_manager.configuration_errors: logger.error(msg) if self.modules_manager.configuration_warnings: # pragma: no cover, not tested for msg in self.modules_manager.configuration_warnings: logger.warning(msg) statsmgr.gauge('modules.count', len(modules)) statsmgr.timer('modules.load-time', time.time() - _ts)
python
def do_load_modules(self, modules): """Wrapper for calling load_and_init method of modules_manager attribute :param modules: list of modules that should be loaded by the daemon :return: None """ _ts = time.time() logger.info("Loading modules...") if self.modules_manager.load_and_init(modules): if self.modules_manager.instances: logger.info("I correctly loaded my modules: [%s]", ','.join([inst.name for inst in self.modules_manager.instances])) else: logger.info("I do not have any module") else: # pragma: no cover, not with unit tests... logger.error("Errors were encountered when checking and loading modules:") for msg in self.modules_manager.configuration_errors: logger.error(msg) if self.modules_manager.configuration_warnings: # pragma: no cover, not tested for msg in self.modules_manager.configuration_warnings: logger.warning(msg) statsmgr.gauge('modules.count', len(modules)) statsmgr.timer('modules.load-time', time.time() - _ts)
[ "def", "do_load_modules", "(", "self", ",", "modules", ")", ":", "_ts", "=", "time", ".", "time", "(", ")", "logger", ".", "info", "(", "\"Loading modules...\"", ")", "if", "self", ".", "modules_manager", ".", "load_and_init", "(", "modules", ")", ":", "if", "self", ".", "modules_manager", ".", "instances", ":", "logger", ".", "info", "(", "\"I correctly loaded my modules: [%s]\"", ",", "','", ".", "join", "(", "[", "inst", ".", "name", "for", "inst", "in", "self", ".", "modules_manager", ".", "instances", "]", ")", ")", "else", ":", "logger", ".", "info", "(", "\"I do not have any module\"", ")", "else", ":", "# pragma: no cover, not with unit tests...", "logger", ".", "error", "(", "\"Errors were encountered when checking and loading modules:\"", ")", "for", "msg", "in", "self", ".", "modules_manager", ".", "configuration_errors", ":", "logger", ".", "error", "(", "msg", ")", "if", "self", ".", "modules_manager", ".", "configuration_warnings", ":", "# pragma: no cover, not tested", "for", "msg", "in", "self", ".", "modules_manager", ".", "configuration_warnings", ":", "logger", ".", "warning", "(", "msg", ")", "statsmgr", ".", "gauge", "(", "'modules.count'", ",", "len", "(", "modules", ")", ")", "statsmgr", ".", "timer", "(", "'modules.load-time'", ",", "time", ".", "time", "(", ")", "-", "_ts", ")" ]
Wrapper for calling load_and_init method of modules_manager attribute :param modules: list of modules that should be loaded by the daemon :return: None
[ "Wrapper", "for", "calling", "load_and_init", "method", "of", "modules_manager", "attribute" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1179-L1203
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.dump_environment
def dump_environment(self): """ Try to dump memory Not currently implemented feature :return: None """ # Dump the Alignak configuration to a temporary ini file path = os.path.join(tempfile.gettempdir(), 'dump-env-%s-%s-%d.ini' % (self.type, self.name, int(time.time()))) try: with open(path, "w") as out_file: self.alignak_env.write(out_file) except Exception as exp: # pylint: disable=broad-except logger.error("Dumping daemon environment raised an error: %s. ", exp)
python
def dump_environment(self): """ Try to dump memory Not currently implemented feature :return: None """ # Dump the Alignak configuration to a temporary ini file path = os.path.join(tempfile.gettempdir(), 'dump-env-%s-%s-%d.ini' % (self.type, self.name, int(time.time()))) try: with open(path, "w") as out_file: self.alignak_env.write(out_file) except Exception as exp: # pylint: disable=broad-except logger.error("Dumping daemon environment raised an error: %s. ", exp)
[ "def", "dump_environment", "(", "self", ")", ":", "# Dump the Alignak configuration to a temporary ini file", "path", "=", "os", ".", "path", ".", "join", "(", "tempfile", ".", "gettempdir", "(", ")", ",", "'dump-env-%s-%s-%d.ini'", "%", "(", "self", ".", "type", ",", "self", ".", "name", ",", "int", "(", "time", ".", "time", "(", ")", ")", ")", ")", "try", ":", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "out_file", ":", "self", ".", "alignak_env", ".", "write", "(", "out_file", ")", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "logger", ".", "error", "(", "\"Dumping daemon environment raised an error: %s. \"", ",", "exp", ")" ]
Try to dump memory Not currently implemented feature :return: None
[ "Try", "to", "dump", "memory" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1215-L1230
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.change_to_workdir
def change_to_workdir(self): """Change working directory to working attribute :return: None """ logger.info("Changing working directory to: %s", self.workdir) self.check_dir(self.workdir) try: os.chdir(self.workdir) except OSError as exp: self.exit_on_error("Error changing to working directory: %s. Error: %s. " "Check the existence of %s and the %s/%s account " "permissions on this directory." % (self.workdir, str(exp), self.workdir, self.user, self.group), exit_code=3) self.pre_log.append(("INFO", "Using working directory: %s" % os.path.abspath(self.workdir)))
python
def change_to_workdir(self): """Change working directory to working attribute :return: None """ logger.info("Changing working directory to: %s", self.workdir) self.check_dir(self.workdir) try: os.chdir(self.workdir) except OSError as exp: self.exit_on_error("Error changing to working directory: %s. Error: %s. " "Check the existence of %s and the %s/%s account " "permissions on this directory." % (self.workdir, str(exp), self.workdir, self.user, self.group), exit_code=3) self.pre_log.append(("INFO", "Using working directory: %s" % os.path.abspath(self.workdir)))
[ "def", "change_to_workdir", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Changing working directory to: %s\"", ",", "self", ".", "workdir", ")", "self", ".", "check_dir", "(", "self", ".", "workdir", ")", "try", ":", "os", ".", "chdir", "(", "self", ".", "workdir", ")", "except", "OSError", "as", "exp", ":", "self", ".", "exit_on_error", "(", "\"Error changing to working directory: %s. Error: %s. \"", "\"Check the existence of %s and the %s/%s account \"", "\"permissions on this directory.\"", "%", "(", "self", ".", "workdir", ",", "str", "(", "exp", ")", ",", "self", ".", "workdir", ",", "self", ".", "user", ",", "self", ".", "group", ")", ",", "exit_code", "=", "3", ")", "self", ".", "pre_log", ".", "append", "(", "(", "\"INFO\"", ",", "\"Using working directory: %s\"", "%", "os", ".", "path", ".", "abspath", "(", "self", ".", "workdir", ")", ")", ")" ]
Change working directory to working attribute :return: None
[ "Change", "working", "directory", "to", "working", "attribute" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1243-L1259
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.unlink
def unlink(self): """Remove the daemon's pid file :return: None """ logger.debug("Unlinking %s", self.pid_filename) try: os.unlink(self.pid_filename) except OSError as exp: logger.debug("Got an error unlinking our pid file: %s", exp)
python
def unlink(self): """Remove the daemon's pid file :return: None """ logger.debug("Unlinking %s", self.pid_filename) try: os.unlink(self.pid_filename) except OSError as exp: logger.debug("Got an error unlinking our pid file: %s", exp)
[ "def", "unlink", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Unlinking %s\"", ",", "self", ".", "pid_filename", ")", "try", ":", "os", ".", "unlink", "(", "self", ".", "pid_filename", ")", "except", "OSError", "as", "exp", ":", "logger", ".", "debug", "(", "\"Got an error unlinking our pid file: %s\"", ",", "exp", ")" ]
Remove the daemon's pid file :return: None
[ "Remove", "the", "daemon", "s", "pid", "file" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1261-L1270
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.__open_pidfile
def __open_pidfile(self, write=False): """Open pid file in read or write mod :param write: boolean to open file in write mod (true = write) :type write: bool :return: None """ # if problem on opening or creating file it'll be raised to the caller: try: self.pre_log.append(("DEBUG", "Opening %s pid file: %s" % ('existing' if os.path.exists(self.pid_filename) else 'missing', self.pid_filename))) # Windows do not manage the rw+ mode, # so we must open in read mode first, then reopen it write mode... if not write and os.path.exists(self.pid_filename): self.fpid = open(self.pid_filename, 'r+') else: # If it doesn't exist too, we create it as void self.fpid = open(self.pid_filename, 'w+') except Exception as exp: # pylint: disable=broad-except self.exit_on_error("Error opening pid file: %s. Error: %s. " "Check the %s:%s account permissions to write this file." % (self.pid_filename, str(exp), self.user, self.group), exit_code=3)
python
def __open_pidfile(self, write=False): """Open pid file in read or write mod :param write: boolean to open file in write mod (true = write) :type write: bool :return: None """ # if problem on opening or creating file it'll be raised to the caller: try: self.pre_log.append(("DEBUG", "Opening %s pid file: %s" % ('existing' if os.path.exists(self.pid_filename) else 'missing', self.pid_filename))) # Windows do not manage the rw+ mode, # so we must open in read mode first, then reopen it write mode... if not write and os.path.exists(self.pid_filename): self.fpid = open(self.pid_filename, 'r+') else: # If it doesn't exist too, we create it as void self.fpid = open(self.pid_filename, 'w+') except Exception as exp: # pylint: disable=broad-except self.exit_on_error("Error opening pid file: %s. Error: %s. " "Check the %s:%s account permissions to write this file." % (self.pid_filename, str(exp), self.user, self.group), exit_code=3)
[ "def", "__open_pidfile", "(", "self", ",", "write", "=", "False", ")", ":", "# if problem on opening or creating file it'll be raised to the caller:", "try", ":", "self", ".", "pre_log", ".", "append", "(", "(", "\"DEBUG\"", ",", "\"Opening %s pid file: %s\"", "%", "(", "'existing'", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "pid_filename", ")", "else", "'missing'", ",", "self", ".", "pid_filename", ")", ")", ")", "# Windows do not manage the rw+ mode,", "# so we must open in read mode first, then reopen it write mode...", "if", "not", "write", "and", "os", ".", "path", ".", "exists", "(", "self", ".", "pid_filename", ")", ":", "self", ".", "fpid", "=", "open", "(", "self", ".", "pid_filename", ",", "'r+'", ")", "else", ":", "# If it doesn't exist too, we create it as void", "self", ".", "fpid", "=", "open", "(", "self", ".", "pid_filename", ",", "'w+'", ")", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "self", ".", "exit_on_error", "(", "\"Error opening pid file: %s. Error: %s. \"", "\"Check the %s:%s account permissions to write this file.\"", "%", "(", "self", ".", "pid_filename", ",", "str", "(", "exp", ")", ",", "self", ".", "user", ",", "self", ".", "group", ")", ",", "exit_code", "=", "3", ")" ]
Open pid file in read or write mod :param write: boolean to open file in write mod (true = write) :type write: bool :return: None
[ "Open", "pid", "file", "in", "read", "or", "write", "mod" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1290-L1313
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.write_pid
def write_pid(self, pid): """ Write pid to the pid file :param pid: pid of the process :type pid: None | int :return: None """ self.fpid.seek(0) self.fpid.truncate() self.fpid.write("%d" % pid) self.fpid.close() del self.fpid
python
def write_pid(self, pid): """ Write pid to the pid file :param pid: pid of the process :type pid: None | int :return: None """ self.fpid.seek(0) self.fpid.truncate() self.fpid.write("%d" % pid) self.fpid.close() del self.fpid
[ "def", "write_pid", "(", "self", ",", "pid", ")", ":", "self", ".", "fpid", ".", "seek", "(", "0", ")", "self", ".", "fpid", ".", "truncate", "(", ")", "self", ".", "fpid", ".", "write", "(", "\"%d\"", "%", "pid", ")", "self", ".", "fpid", ".", "close", "(", ")", "del", "self", ".", "fpid" ]
Write pid to the pid file :param pid: pid of the process :type pid: None | int :return: None
[ "Write", "pid", "to", "the", "pid", "file" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1378-L1389
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.close_fds
def close_fds(self, skip_close_fds): # pragma: no cover, not with unit tests... """Close all the process file descriptors. Skip the descriptors present in the skip_close_fds list :param skip_close_fds: list of file descriptor to preserve from closing :type skip_close_fds: list :return: None """ # First we manage the file descriptor, because debug file can be # relative to pwd max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: max_fds = 1024 self.pre_log.append(("DEBUG", "Maximum file descriptors: %d" % max_fds)) # Iterate through and close all file descriptors. for file_d in range(0, max_fds): if file_d in skip_close_fds: self.pre_log.append(("INFO", "Do not close fd: %s" % file_d)) continue try: os.close(file_d) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass
python
def close_fds(self, skip_close_fds): # pragma: no cover, not with unit tests... """Close all the process file descriptors. Skip the descriptors present in the skip_close_fds list :param skip_close_fds: list of file descriptor to preserve from closing :type skip_close_fds: list :return: None """ # First we manage the file descriptor, because debug file can be # relative to pwd max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == resource.RLIM_INFINITY: max_fds = 1024 self.pre_log.append(("DEBUG", "Maximum file descriptors: %d" % max_fds)) # Iterate through and close all file descriptors. for file_d in range(0, max_fds): if file_d in skip_close_fds: self.pre_log.append(("INFO", "Do not close fd: %s" % file_d)) continue try: os.close(file_d) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass
[ "def", "close_fds", "(", "self", ",", "skip_close_fds", ")", ":", "# pragma: no cover, not with unit tests...", "# First we manage the file descriptor, because debug file can be", "# relative to pwd", "max_fds", "=", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "1", "]", "if", "max_fds", "==", "resource", ".", "RLIM_INFINITY", ":", "max_fds", "=", "1024", "self", ".", "pre_log", ".", "append", "(", "(", "\"DEBUG\"", ",", "\"Maximum file descriptors: %d\"", "%", "max_fds", ")", ")", "# Iterate through and close all file descriptors.", "for", "file_d", "in", "range", "(", "0", ",", "max_fds", ")", ":", "if", "file_d", "in", "skip_close_fds", ":", "self", ".", "pre_log", ".", "append", "(", "(", "\"INFO\"", ",", "\"Do not close fd: %s\"", "%", "file_d", ")", ")", "continue", "try", ":", "os", ".", "close", "(", "file_d", ")", "except", "OSError", ":", "# ERROR, fd wasn't open to begin with (ignored)", "pass" ]
Close all the process file descriptors. Skip the descriptors present in the skip_close_fds list :param skip_close_fds: list of file descriptor to preserve from closing :type skip_close_fds: list :return: None
[ "Close", "all", "the", "process", "file", "descriptors", ".", "Skip", "the", "descriptors", "present", "in", "the", "skip_close_fds", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1391-L1414
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.do_daemon_init_and_start
def do_daemon_init_and_start(self, set_proc_title=True): """Main daemon function. Clean, allocates, initializes and starts all necessary resources to go in daemon mode. The set_proc_title parameter is mainly useful for the Alignak unit tests. This to avoid changing the test process name! :param set_proc_title: if set (default), the process title is changed to the daemon name :type set_proc_title: bool :return: False if the HTTP daemon can not be initialized, else True """ if set_proc_title: self.set_proctitle(self.name) # Change to configured user/group account self.change_to_user_group() # Change the working directory self.change_to_workdir() # Check if I am still running self.check_parallel_run() # If we must daemonize, let's do it! if self.is_daemon: if not self.daemonize(): logger.error("I could not daemonize myself :(") return False else: # Else, I set my own pid as the reference one self.write_pid(os.getpid()) # # TODO: check if really necessary! # # ------- # # Set ownership on some default log files. It may happen that these default # # files are owned by a privileged user account # try: # for log_file in ['alignak.log', 'alignak-events.log']: # if os.path.exists('/tmp/%s' % log_file): # with open('/tmp/%s' % log_file, "w") as file_log_file: # os.fchown(file_log_file.fileno(), self.uid, self.gid) # if os.path.exists('/tmp/monitoring-log/%s' % log_file): # with open('/tmp/monitoring-log/%s' % log_file, "w") as file_log_file: # os.fchown(file_log_file.fileno(), self.uid, self.gid) # except Exception as exp: # pylint: disable=broad-except # # pragma: no cover # print("Could not set default log files ownership, exception: %s" % str(exp)) # Configure the daemon logger self.setup_alignak_logger() # Setup the Web Services daemon if not self.setup_communication_daemon(): logger.error("I could not setup my communication daemon :(") return False # Creating synchonisation manager (inter-daemon queues...) self.sync_manager = self._create_manager() # Start the CherryPy server through a detached thread logger.info("Starting http_daemon thread") # pylint: disable=bad-thread-instantiation self.http_thread = threading.Thread(target=self.http_daemon_thread, name='%s-http_thread' % self.name) # Setting the thread as a daemon allows to Ctrl+C to kill the main daemon self.http_thread.daemon = True self.http_thread.start() # time.sleep(1) logger.info("HTTP daemon thread started") return True
python
def do_daemon_init_and_start(self, set_proc_title=True): """Main daemon function. Clean, allocates, initializes and starts all necessary resources to go in daemon mode. The set_proc_title parameter is mainly useful for the Alignak unit tests. This to avoid changing the test process name! :param set_proc_title: if set (default), the process title is changed to the daemon name :type set_proc_title: bool :return: False if the HTTP daemon can not be initialized, else True """ if set_proc_title: self.set_proctitle(self.name) # Change to configured user/group account self.change_to_user_group() # Change the working directory self.change_to_workdir() # Check if I am still running self.check_parallel_run() # If we must daemonize, let's do it! if self.is_daemon: if not self.daemonize(): logger.error("I could not daemonize myself :(") return False else: # Else, I set my own pid as the reference one self.write_pid(os.getpid()) # # TODO: check if really necessary! # # ------- # # Set ownership on some default log files. It may happen that these default # # files are owned by a privileged user account # try: # for log_file in ['alignak.log', 'alignak-events.log']: # if os.path.exists('/tmp/%s' % log_file): # with open('/tmp/%s' % log_file, "w") as file_log_file: # os.fchown(file_log_file.fileno(), self.uid, self.gid) # if os.path.exists('/tmp/monitoring-log/%s' % log_file): # with open('/tmp/monitoring-log/%s' % log_file, "w") as file_log_file: # os.fchown(file_log_file.fileno(), self.uid, self.gid) # except Exception as exp: # pylint: disable=broad-except # # pragma: no cover # print("Could not set default log files ownership, exception: %s" % str(exp)) # Configure the daemon logger self.setup_alignak_logger() # Setup the Web Services daemon if not self.setup_communication_daemon(): logger.error("I could not setup my communication daemon :(") return False # Creating synchonisation manager (inter-daemon queues...) self.sync_manager = self._create_manager() # Start the CherryPy server through a detached thread logger.info("Starting http_daemon thread") # pylint: disable=bad-thread-instantiation self.http_thread = threading.Thread(target=self.http_daemon_thread, name='%s-http_thread' % self.name) # Setting the thread as a daemon allows to Ctrl+C to kill the main daemon self.http_thread.daemon = True self.http_thread.start() # time.sleep(1) logger.info("HTTP daemon thread started") return True
[ "def", "do_daemon_init_and_start", "(", "self", ",", "set_proc_title", "=", "True", ")", ":", "if", "set_proc_title", ":", "self", ".", "set_proctitle", "(", "self", ".", "name", ")", "# Change to configured user/group account", "self", ".", "change_to_user_group", "(", ")", "# Change the working directory", "self", ".", "change_to_workdir", "(", ")", "# Check if I am still running", "self", ".", "check_parallel_run", "(", ")", "# If we must daemonize, let's do it!", "if", "self", ".", "is_daemon", ":", "if", "not", "self", ".", "daemonize", "(", ")", ":", "logger", ".", "error", "(", "\"I could not daemonize myself :(\"", ")", "return", "False", "else", ":", "# Else, I set my own pid as the reference one", "self", ".", "write_pid", "(", "os", ".", "getpid", "(", ")", ")", "# # TODO: check if really necessary!", "# # -------", "# # Set ownership on some default log files. It may happen that these default", "# # files are owned by a privileged user account", "# try:", "# for log_file in ['alignak.log', 'alignak-events.log']:", "# if os.path.exists('/tmp/%s' % log_file):", "# with open('/tmp/%s' % log_file, \"w\") as file_log_file:", "# os.fchown(file_log_file.fileno(), self.uid, self.gid)", "# if os.path.exists('/tmp/monitoring-log/%s' % log_file):", "# with open('/tmp/monitoring-log/%s' % log_file, \"w\") as file_log_file:", "# os.fchown(file_log_file.fileno(), self.uid, self.gid)", "# except Exception as exp: # pylint: disable=broad-except", "# # pragma: no cover", "# print(\"Could not set default log files ownership, exception: %s\" % str(exp))", "# Configure the daemon logger", "self", ".", "setup_alignak_logger", "(", ")", "# Setup the Web Services daemon", "if", "not", "self", ".", "setup_communication_daemon", "(", ")", ":", "logger", ".", "error", "(", "\"I could not setup my communication daemon :(\"", ")", "return", "False", "# Creating synchonisation manager (inter-daemon queues...)", "self", ".", "sync_manager", "=", "self", ".", "_create_manager", "(", ")", "# Start the CherryPy server through a detached thread", "logger", ".", "info", "(", "\"Starting http_daemon thread\"", ")", "# pylint: disable=bad-thread-instantiation", "self", ".", "http_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "http_daemon_thread", ",", "name", "=", "'%s-http_thread'", "%", "self", ".", "name", ")", "# Setting the thread as a daemon allows to Ctrl+C to kill the main daemon", "self", ".", "http_thread", ".", "daemon", "=", "True", "self", ".", "http_thread", ".", "start", "(", ")", "# time.sleep(1)", "logger", ".", "info", "(", "\"HTTP daemon thread started\"", ")", "return", "True" ]
Main daemon function. Clean, allocates, initializes and starts all necessary resources to go in daemon mode. The set_proc_title parameter is mainly useful for the Alignak unit tests. This to avoid changing the test process name! :param set_proc_title: if set (default), the process title is changed to the daemon name :type set_proc_title: bool :return: False if the HTTP daemon can not be initialized, else True
[ "Main", "daemon", "function", ".", "Clean", "allocates", "initializes", "and", "starts", "all", "necessary", "resources", "to", "go", "in", "daemon", "mode", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1481-L1551
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.setup_communication_daemon
def setup_communication_daemon(self): # pylint: disable=no-member """ Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False """ ca_cert = ssl_cert = ssl_key = server_dh = None # The SSL part if self.use_ssl: ssl_cert = os.path.abspath(self.server_cert) if not os.path.exists(ssl_cert): self.exit_on_error("The configured SSL server certificate file '%s' " "does not exist." % ssl_cert, exit_code=2) logger.info("Using SSL server certificate: %s", ssl_cert) ssl_key = os.path.abspath(self.server_key) if not os.path.exists(ssl_key): self.exit_on_error("The configured SSL server key file '%s' " "does not exist." % ssl_key, exit_code=2) logger.info("Using SSL server key: %s", ssl_key) if self.server_dh: server_dh = os.path.abspath(self.server_dh) logger.info("Using ssl dh cert file: %s", server_dh) self.exit_on_error("Sorry, but using a DH configuration " "is not currently supported!", exit_code=2) if self.ca_cert: ca_cert = os.path.abspath(self.ca_cert) logger.info("Using ssl ca cert file: %s", ca_cert) if self.hard_ssl_name_check: logger.info("Enabling hard SSL server name verification") # Let's create the HTTPDaemon, it will be started later # pylint: disable=E1101 try: logger.info('Setting up HTTP daemon (%s:%d), %d threads', self.host, self.port, self.thread_pool_size) self.http_daemon = HTTPDaemon(self.host, self.port, self.http_interface, self.use_ssl, ca_cert, ssl_key, ssl_cert, server_dh, self.thread_pool_size, self.log_cherrypy, self.favicon) except PortNotFree: logger.error('The HTTP daemon port (%s:%d) is not free...', self.host, self.port) return False except Exception as exp: # pylint: disable=broad-except print('Setting up HTTP daemon, exception: %s', str(exp)) logger.exception('Setting up HTTP daemon, exception: %s', str(exp)) return False return True
python
def setup_communication_daemon(self): # pylint: disable=no-member """ Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False """ ca_cert = ssl_cert = ssl_key = server_dh = None # The SSL part if self.use_ssl: ssl_cert = os.path.abspath(self.server_cert) if not os.path.exists(ssl_cert): self.exit_on_error("The configured SSL server certificate file '%s' " "does not exist." % ssl_cert, exit_code=2) logger.info("Using SSL server certificate: %s", ssl_cert) ssl_key = os.path.abspath(self.server_key) if not os.path.exists(ssl_key): self.exit_on_error("The configured SSL server key file '%s' " "does not exist." % ssl_key, exit_code=2) logger.info("Using SSL server key: %s", ssl_key) if self.server_dh: server_dh = os.path.abspath(self.server_dh) logger.info("Using ssl dh cert file: %s", server_dh) self.exit_on_error("Sorry, but using a DH configuration " "is not currently supported!", exit_code=2) if self.ca_cert: ca_cert = os.path.abspath(self.ca_cert) logger.info("Using ssl ca cert file: %s", ca_cert) if self.hard_ssl_name_check: logger.info("Enabling hard SSL server name verification") # Let's create the HTTPDaemon, it will be started later # pylint: disable=E1101 try: logger.info('Setting up HTTP daemon (%s:%d), %d threads', self.host, self.port, self.thread_pool_size) self.http_daemon = HTTPDaemon(self.host, self.port, self.http_interface, self.use_ssl, ca_cert, ssl_key, ssl_cert, server_dh, self.thread_pool_size, self.log_cherrypy, self.favicon) except PortNotFree: logger.error('The HTTP daemon port (%s:%d) is not free...', self.host, self.port) return False except Exception as exp: # pylint: disable=broad-except print('Setting up HTTP daemon, exception: %s', str(exp)) logger.exception('Setting up HTTP daemon, exception: %s', str(exp)) return False return True
[ "def", "setup_communication_daemon", "(", "self", ")", ":", "# pylint: disable=no-member", "ca_cert", "=", "ssl_cert", "=", "ssl_key", "=", "server_dh", "=", "None", "# The SSL part", "if", "self", ".", "use_ssl", ":", "ssl_cert", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "server_cert", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ssl_cert", ")", ":", "self", ".", "exit_on_error", "(", "\"The configured SSL server certificate file '%s' \"", "\"does not exist.\"", "%", "ssl_cert", ",", "exit_code", "=", "2", ")", "logger", ".", "info", "(", "\"Using SSL server certificate: %s\"", ",", "ssl_cert", ")", "ssl_key", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "server_key", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "ssl_key", ")", ":", "self", ".", "exit_on_error", "(", "\"The configured SSL server key file '%s' \"", "\"does not exist.\"", "%", "ssl_key", ",", "exit_code", "=", "2", ")", "logger", ".", "info", "(", "\"Using SSL server key: %s\"", ",", "ssl_key", ")", "if", "self", ".", "server_dh", ":", "server_dh", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "server_dh", ")", "logger", ".", "info", "(", "\"Using ssl dh cert file: %s\"", ",", "server_dh", ")", "self", ".", "exit_on_error", "(", "\"Sorry, but using a DH configuration \"", "\"is not currently supported!\"", ",", "exit_code", "=", "2", ")", "if", "self", ".", "ca_cert", ":", "ca_cert", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "ca_cert", ")", "logger", ".", "info", "(", "\"Using ssl ca cert file: %s\"", ",", "ca_cert", ")", "if", "self", ".", "hard_ssl_name_check", ":", "logger", ".", "info", "(", "\"Enabling hard SSL server name verification\"", ")", "# Let's create the HTTPDaemon, it will be started later", "# pylint: disable=E1101", "try", ":", "logger", ".", "info", "(", "'Setting up HTTP daemon (%s:%d), %d threads'", ",", "self", ".", "host", ",", "self", ".", "port", ",", "self", ".", "thread_pool_size", ")", "self", ".", "http_daemon", "=", "HTTPDaemon", "(", "self", ".", "host", ",", "self", ".", "port", ",", "self", ".", "http_interface", ",", "self", ".", "use_ssl", ",", "ca_cert", ",", "ssl_key", ",", "ssl_cert", ",", "server_dh", ",", "self", ".", "thread_pool_size", ",", "self", ".", "log_cherrypy", ",", "self", ".", "favicon", ")", "except", "PortNotFree", ":", "logger", ".", "error", "(", "'The HTTP daemon port (%s:%d) is not free...'", ",", "self", ".", "host", ",", "self", ".", "port", ")", "return", "False", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "print", "(", "'Setting up HTTP daemon, exception: %s'", ",", "str", "(", "exp", ")", ")", "logger", ".", "exception", "(", "'Setting up HTTP daemon, exception: %s'", ",", "str", "(", "exp", ")", ")", "return", "False", "return", "True" ]
Setup HTTP server daemon to listen for incoming HTTP requests from other Alignak daemons :return: True if initialization is ok, else False
[ "Setup", "HTTP", "server", "daemon", "to", "listen", "for", "incoming", "HTTP", "requests", "from", "other", "Alignak", "daemons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1553-L1607
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.set_proctitle
def set_proctitle(self, daemon_name=None): """Set the proctitle of the daemon :param daemon_name: daemon instance name (eg. arbiter-master). If not provided, only the daemon type (eg. arbiter) will be used for the process title :type daemon_name: str :return: None """ logger.debug("Setting my process name: %s", daemon_name) if daemon_name: setproctitle("alignak-%s %s" % (self.type, daemon_name)) if self.modules_manager: self.modules_manager.set_daemon_name(daemon_name) else: setproctitle("alignak-%s" % self.type)
python
def set_proctitle(self, daemon_name=None): """Set the proctitle of the daemon :param daemon_name: daemon instance name (eg. arbiter-master). If not provided, only the daemon type (eg. arbiter) will be used for the process title :type daemon_name: str :return: None """ logger.debug("Setting my process name: %s", daemon_name) if daemon_name: setproctitle("alignak-%s %s" % (self.type, daemon_name)) if self.modules_manager: self.modules_manager.set_daemon_name(daemon_name) else: setproctitle("alignak-%s" % self.type)
[ "def", "set_proctitle", "(", "self", ",", "daemon_name", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Setting my process name: %s\"", ",", "daemon_name", ")", "if", "daemon_name", ":", "setproctitle", "(", "\"alignak-%s %s\"", "%", "(", "self", ".", "type", ",", "daemon_name", ")", ")", "if", "self", ".", "modules_manager", ":", "self", ".", "modules_manager", ".", "set_daemon_name", "(", "daemon_name", ")", "else", ":", "setproctitle", "(", "\"alignak-%s\"", "%", "self", ".", "type", ")" ]
Set the proctitle of the daemon :param daemon_name: daemon instance name (eg. arbiter-master). If not provided, only the daemon type (eg. arbiter) will be used for the process title :type daemon_name: str :return: None
[ "Set", "the", "proctitle", "of", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1734-L1748
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.http_daemon_thread
def http_daemon_thread(self): """Main function of the http daemon thread will loop forever unless we stop the root daemon The main thing is to have a pool of X concurrent requests for the http_daemon, so "no_lock" calls can always be directly answer without having a "locked" version to finish. This is achieved thanks to the CherryPy thread pool. This function is threaded to be detached from the main process as such it will not block the process main loop.. :return: None """ logger.debug("HTTP thread running") try: # This function is a blocking function serving HTTP protocol self.http_daemon.run() except PortNotFree as exp: logger.exception('The HTTP daemon port is not free: %s', exp) raise except Exception as exp: # pylint: disable=broad-except self.exit_on_exception(exp) logger.debug("HTTP thread exiting")
python
def http_daemon_thread(self): """Main function of the http daemon thread will loop forever unless we stop the root daemon The main thing is to have a pool of X concurrent requests for the http_daemon, so "no_lock" calls can always be directly answer without having a "locked" version to finish. This is achieved thanks to the CherryPy thread pool. This function is threaded to be detached from the main process as such it will not block the process main loop.. :return: None """ logger.debug("HTTP thread running") try: # This function is a blocking function serving HTTP protocol self.http_daemon.run() except PortNotFree as exp: logger.exception('The HTTP daemon port is not free: %s', exp) raise except Exception as exp: # pylint: disable=broad-except self.exit_on_exception(exp) logger.debug("HTTP thread exiting")
[ "def", "http_daemon_thread", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"HTTP thread running\"", ")", "try", ":", "# This function is a blocking function serving HTTP protocol", "self", ".", "http_daemon", ".", "run", "(", ")", "except", "PortNotFree", "as", "exp", ":", "logger", ".", "exception", "(", "'The HTTP daemon port is not free: %s'", ",", "exp", ")", "raise", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "self", ".", "exit_on_exception", "(", "exp", ")", "logger", ".", "debug", "(", "\"HTTP thread exiting\"", ")" ]
Main function of the http daemon thread will loop forever unless we stop the root daemon The main thing is to have a pool of X concurrent requests for the http_daemon, so "no_lock" calls can always be directly answer without having a "locked" version to finish. This is achieved thanks to the CherryPy thread pool. This function is threaded to be detached from the main process as such it will not block the process main loop.. :return: None
[ "Main", "function", "of", "the", "http", "daemon", "thread", "will", "loop", "forever", "unless", "we", "stop", "the", "root", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1781-L1801
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.make_a_pause
def make_a_pause(self, timeout=0.0001, check_time_change=True): """ Wait up to timeout and check for system time change. This function checks if the system time changed since the last call. If so, the difference is returned to the caller. The duration of this call is removed from the timeout. If this duration is greater than the required timeout, no sleep is executed and the extra time is returned to the caller If the required timeout was overlapped, then the first return value will be greater than the required timeout. If the required timeout is null, then the timeout value is set as a very short time to keep a nice behavior to the system CPU ;) :param timeout: timeout to wait for activity :type timeout: float :param check_time_change: True (default) to check if the system time changed :type check_time_change: bool :return:Returns a 2-tuple: * first value is the time spent for the time change check * second value is the time change difference :rtype: tuple """ if timeout == 0: timeout = 0.0001 if not check_time_change: # Time to sleep time.sleep(timeout) self.sleep_time += timeout return 0, 0 # Check is system time changed before = time.time() time_changed = self.check_for_system_time_change() after = time.time() elapsed = after - before if elapsed > timeout: return elapsed, time_changed # Time to sleep time.sleep(timeout - elapsed) # Increase our sleep time for the time we slept before += time_changed self.sleep_time += time.time() - before return elapsed, time_changed
python
def make_a_pause(self, timeout=0.0001, check_time_change=True): """ Wait up to timeout and check for system time change. This function checks if the system time changed since the last call. If so, the difference is returned to the caller. The duration of this call is removed from the timeout. If this duration is greater than the required timeout, no sleep is executed and the extra time is returned to the caller If the required timeout was overlapped, then the first return value will be greater than the required timeout. If the required timeout is null, then the timeout value is set as a very short time to keep a nice behavior to the system CPU ;) :param timeout: timeout to wait for activity :type timeout: float :param check_time_change: True (default) to check if the system time changed :type check_time_change: bool :return:Returns a 2-tuple: * first value is the time spent for the time change check * second value is the time change difference :rtype: tuple """ if timeout == 0: timeout = 0.0001 if not check_time_change: # Time to sleep time.sleep(timeout) self.sleep_time += timeout return 0, 0 # Check is system time changed before = time.time() time_changed = self.check_for_system_time_change() after = time.time() elapsed = after - before if elapsed > timeout: return elapsed, time_changed # Time to sleep time.sleep(timeout - elapsed) # Increase our sleep time for the time we slept before += time_changed self.sleep_time += time.time() - before return elapsed, time_changed
[ "def", "make_a_pause", "(", "self", ",", "timeout", "=", "0.0001", ",", "check_time_change", "=", "True", ")", ":", "if", "timeout", "==", "0", ":", "timeout", "=", "0.0001", "if", "not", "check_time_change", ":", "# Time to sleep", "time", ".", "sleep", "(", "timeout", ")", "self", ".", "sleep_time", "+=", "timeout", "return", "0", ",", "0", "# Check is system time changed", "before", "=", "time", ".", "time", "(", ")", "time_changed", "=", "self", ".", "check_for_system_time_change", "(", ")", "after", "=", "time", ".", "time", "(", ")", "elapsed", "=", "after", "-", "before", "if", "elapsed", ">", "timeout", ":", "return", "elapsed", ",", "time_changed", "# Time to sleep", "time", ".", "sleep", "(", "timeout", "-", "elapsed", ")", "# Increase our sleep time for the time we slept", "before", "+=", "time_changed", "self", ".", "sleep_time", "+=", "time", ".", "time", "(", ")", "-", "before", "return", "elapsed", ",", "time_changed" ]
Wait up to timeout and check for system time change. This function checks if the system time changed since the last call. If so, the difference is returned to the caller. The duration of this call is removed from the timeout. If this duration is greater than the required timeout, no sleep is executed and the extra time is returned to the caller If the required timeout was overlapped, then the first return value will be greater than the required timeout. If the required timeout is null, then the timeout value is set as a very short time to keep a nice behavior to the system CPU ;) :param timeout: timeout to wait for activity :type timeout: float :param check_time_change: True (default) to check if the system time changed :type check_time_change: bool :return:Returns a 2-tuple: * first value is the time spent for the time change check * second value is the time change difference :rtype: tuple
[ "Wait", "up", "to", "timeout", "and", "check", "for", "system", "time", "change", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1803-L1851
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.wait_for_initial_conf
def wait_for_initial_conf(self, timeout=1.0): """Wait initial configuration from the arbiter. Basically sleep 1.0 and check if new_conf is here :param timeout: timeout to wait :type timeout: int :return: None """ logger.info("Waiting for initial configuration") # Arbiter do not already set our have_conf param _ts = time.time() while not self.new_conf and not self.interrupted: # Make a pause and check if the system time changed _, _ = self.make_a_pause(timeout, check_time_change=True) if not self.interrupted: logger.info("Got initial configuration, waited for: %.2f seconds", time.time() - _ts) statsmgr.timer('configuration.initial', time.time() - _ts) else: logger.info("Interrupted before getting the initial configuration")
python
def wait_for_initial_conf(self, timeout=1.0): """Wait initial configuration from the arbiter. Basically sleep 1.0 and check if new_conf is here :param timeout: timeout to wait :type timeout: int :return: None """ logger.info("Waiting for initial configuration") # Arbiter do not already set our have_conf param _ts = time.time() while not self.new_conf and not self.interrupted: # Make a pause and check if the system time changed _, _ = self.make_a_pause(timeout, check_time_change=True) if not self.interrupted: logger.info("Got initial configuration, waited for: %.2f seconds", time.time() - _ts) statsmgr.timer('configuration.initial', time.time() - _ts) else: logger.info("Interrupted before getting the initial configuration")
[ "def", "wait_for_initial_conf", "(", "self", ",", "timeout", "=", "1.0", ")", ":", "logger", ".", "info", "(", "\"Waiting for initial configuration\"", ")", "# Arbiter do not already set our have_conf param", "_ts", "=", "time", ".", "time", "(", ")", "while", "not", "self", ".", "new_conf", "and", "not", "self", ".", "interrupted", ":", "# Make a pause and check if the system time changed", "_", ",", "_", "=", "self", ".", "make_a_pause", "(", "timeout", ",", "check_time_change", "=", "True", ")", "if", "not", "self", ".", "interrupted", ":", "logger", ".", "info", "(", "\"Got initial configuration, waited for: %.2f seconds\"", ",", "time", ".", "time", "(", ")", "-", "_ts", ")", "statsmgr", ".", "timer", "(", "'configuration.initial'", ",", "time", ".", "time", "(", ")", "-", "_ts", ")", "else", ":", "logger", ".", "info", "(", "\"Interrupted before getting the initial configuration\"", ")" ]
Wait initial configuration from the arbiter. Basically sleep 1.0 and check if new_conf is here :param timeout: timeout to wait :type timeout: int :return: None
[ "Wait", "initial", "configuration", "from", "the", "arbiter", ".", "Basically", "sleep", "1", ".", "0", "and", "check", "if", "new_conf", "is", "here" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1885-L1904
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.watch_for_new_conf
def watch_for_new_conf(self, timeout=0): """Check if a new configuration was sent to the daemon This function is called on each daemon loop turn. Basically it is a sleep... If a new configuration was posted, this function returns True :param timeout: timeout to wait. Default is no wait time. :type timeout: float :return: None """ logger.debug("Watching for a new configuration, timeout: %s", timeout) self.make_a_pause(timeout=timeout, check_time_change=False) return any(self.new_conf)
python
def watch_for_new_conf(self, timeout=0): """Check if a new configuration was sent to the daemon This function is called on each daemon loop turn. Basically it is a sleep... If a new configuration was posted, this function returns True :param timeout: timeout to wait. Default is no wait time. :type timeout: float :return: None """ logger.debug("Watching for a new configuration, timeout: %s", timeout) self.make_a_pause(timeout=timeout, check_time_change=False) return any(self.new_conf)
[ "def", "watch_for_new_conf", "(", "self", ",", "timeout", "=", "0", ")", ":", "logger", ".", "debug", "(", "\"Watching for a new configuration, timeout: %s\"", ",", "timeout", ")", "self", ".", "make_a_pause", "(", "timeout", "=", "timeout", ",", "check_time_change", "=", "False", ")", "return", "any", "(", "self", ".", "new_conf", ")" ]
Check if a new configuration was sent to the daemon This function is called on each daemon loop turn. Basically it is a sleep... If a new configuration was posted, this function returns True :param timeout: timeout to wait. Default is no wait time. :type timeout: float :return: None
[ "Check", "if", "a", "new", "configuration", "was", "sent", "to", "the", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1927-L1940
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.hook_point
def hook_point(self, hook_name, handle=None): """Used to call module function that may define a hook function for hook_name Available hook points: - `tick`, called on each daemon loop turn - `save_retention`; called by the scheduler when live state saving is to be done - `load_retention`; called by the scheduler when live state restoring is necessary (on restart) - `get_new_actions`; called by the scheduler before adding the actions to be executed - `early_configuration`; called by the arbiter when it begins parsing the configuration - `read_configuration`; called by the arbiter when it read the configuration - `late_configuration`; called by the arbiter when it finishes parsing the configuration As a default, the `handle` parameter provided to the hooked function is the caller Daemon object. The scheduler will provide its own instance when it call this function. :param hook_name: function name we may hook in module :type hook_name: str :param handle: parameter to provide to the hook function :type: handle: alignak.Satellite :return: None """ full_hook_name = 'hook_' + hook_name for module in self.modules_manager.instances: _ts = time.time() if not hasattr(module, full_hook_name): continue fun = getattr(module, full_hook_name) try: fun(handle if handle is not None else self) # pylint: disable=broad-except except Exception as exp: # pragma: no cover, never happen during unit tests... logger.warning('The instance %s raised an exception %s. I disabled it,' ' and set it to restart later', module.name, str(exp)) logger.exception('Exception %s', exp) self.modules_manager.set_to_restart(module) else: statsmgr.timer('hook.%s.%s' % (hook_name, module.name), time.time() - _ts)
python
def hook_point(self, hook_name, handle=None): """Used to call module function that may define a hook function for hook_name Available hook points: - `tick`, called on each daemon loop turn - `save_retention`; called by the scheduler when live state saving is to be done - `load_retention`; called by the scheduler when live state restoring is necessary (on restart) - `get_new_actions`; called by the scheduler before adding the actions to be executed - `early_configuration`; called by the arbiter when it begins parsing the configuration - `read_configuration`; called by the arbiter when it read the configuration - `late_configuration`; called by the arbiter when it finishes parsing the configuration As a default, the `handle` parameter provided to the hooked function is the caller Daemon object. The scheduler will provide its own instance when it call this function. :param hook_name: function name we may hook in module :type hook_name: str :param handle: parameter to provide to the hook function :type: handle: alignak.Satellite :return: None """ full_hook_name = 'hook_' + hook_name for module in self.modules_manager.instances: _ts = time.time() if not hasattr(module, full_hook_name): continue fun = getattr(module, full_hook_name) try: fun(handle if handle is not None else self) # pylint: disable=broad-except except Exception as exp: # pragma: no cover, never happen during unit tests... logger.warning('The instance %s raised an exception %s. I disabled it,' ' and set it to restart later', module.name, str(exp)) logger.exception('Exception %s', exp) self.modules_manager.set_to_restart(module) else: statsmgr.timer('hook.%s.%s' % (hook_name, module.name), time.time() - _ts)
[ "def", "hook_point", "(", "self", ",", "hook_name", ",", "handle", "=", "None", ")", ":", "full_hook_name", "=", "'hook_'", "+", "hook_name", "for", "module", "in", "self", ".", "modules_manager", ".", "instances", ":", "_ts", "=", "time", ".", "time", "(", ")", "if", "not", "hasattr", "(", "module", ",", "full_hook_name", ")", ":", "continue", "fun", "=", "getattr", "(", "module", ",", "full_hook_name", ")", "try", ":", "fun", "(", "handle", "if", "handle", "is", "not", "None", "else", "self", ")", "# pylint: disable=broad-except", "except", "Exception", "as", "exp", ":", "# pragma: no cover, never happen during unit tests...", "logger", ".", "warning", "(", "'The instance %s raised an exception %s. I disabled it,'", "' and set it to restart later'", ",", "module", ".", "name", ",", "str", "(", "exp", ")", ")", "logger", ".", "exception", "(", "'Exception %s'", ",", "exp", ")", "self", ".", "modules_manager", ".", "set_to_restart", "(", "module", ")", "else", ":", "statsmgr", ".", "timer", "(", "'hook.%s.%s'", "%", "(", "hook_name", ",", "module", ".", "name", ")", ",", "time", ".", "time", "(", ")", "-", "_ts", ")" ]
Used to call module function that may define a hook function for hook_name Available hook points: - `tick`, called on each daemon loop turn - `save_retention`; called by the scheduler when live state saving is to be done - `load_retention`; called by the scheduler when live state restoring is necessary (on restart) - `get_new_actions`; called by the scheduler before adding the actions to be executed - `early_configuration`; called by the arbiter when it begins parsing the configuration - `read_configuration`; called by the arbiter when it read the configuration - `late_configuration`; called by the arbiter when it finishes parsing the configuration As a default, the `handle` parameter provided to the hooked function is the caller Daemon object. The scheduler will provide its own instance when it call this function. :param hook_name: function name we may hook in module :type hook_name: str :param handle: parameter to provide to the hook function :type: handle: alignak.Satellite :return: None
[ "Used", "to", "call", "module", "function", "that", "may", "define", "a", "hook", "function", "for", "hook_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1942-L1982
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.get_id
def get_id(self, details=False): # pylint: disable=unused-argument """Get daemon identification information :return: A dict with the following structure :: { "alignak": selfAlignak instance name "type": daemon type "name": daemon name "version": Alignak version } :rtype: dict """ # Modules information res = { "alignak": getattr(self, 'alignak_name', 'unknown'), "type": getattr(self, 'type', 'unknown'), "name": getattr(self, 'name', 'unknown'), "version": VERSION } return res
python
def get_id(self, details=False): # pylint: disable=unused-argument """Get daemon identification information :return: A dict with the following structure :: { "alignak": selfAlignak instance name "type": daemon type "name": daemon name "version": Alignak version } :rtype: dict """ # Modules information res = { "alignak": getattr(self, 'alignak_name', 'unknown'), "type": getattr(self, 'type', 'unknown'), "name": getattr(self, 'name', 'unknown'), "version": VERSION } return res
[ "def", "get_id", "(", "self", ",", "details", "=", "False", ")", ":", "# pylint: disable=unused-argument", "# Modules information", "res", "=", "{", "\"alignak\"", ":", "getattr", "(", "self", ",", "'alignak_name'", ",", "'unknown'", ")", ",", "\"type\"", ":", "getattr", "(", "self", ",", "'type'", ",", "'unknown'", ")", ",", "\"name\"", ":", "getattr", "(", "self", ",", "'name'", ",", "'unknown'", ")", ",", "\"version\"", ":", "VERSION", "}", "return", "res" ]
Get daemon identification information :return: A dict with the following structure :: { "alignak": selfAlignak instance name "type": daemon type "name": daemon name "version": Alignak version } :rtype: dict
[ "Get", "daemon", "identification", "information" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L2005-L2026
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.exit_ok
def exit_ok(self, message, exit_code=None): """Log a message and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None """ logger.info("Exiting...") if message: logger.info("-----") logger.error("Exit message: %s", message) logger.info("-----") self.request_stop() if exit_code is not None: exit(exit_code)
python
def exit_ok(self, message, exit_code=None): """Log a message and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None """ logger.info("Exiting...") if message: logger.info("-----") logger.error("Exit message: %s", message) logger.info("-----") self.request_stop() if exit_code is not None: exit(exit_code)
[ "def", "exit_ok", "(", "self", ",", "message", ",", "exit_code", "=", "None", ")", ":", "logger", ".", "info", "(", "\"Exiting...\"", ")", "if", "message", ":", "logger", ".", "info", "(", "\"-----\"", ")", "logger", ".", "error", "(", "\"Exit message: %s\"", ",", "message", ")", "logger", ".", "info", "(", "\"-----\"", ")", "self", ".", "request_stop", "(", ")", "if", "exit_code", "is", "not", "None", ":", "exit", "(", "exit_code", ")" ]
Log a message and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None
[ "Log", "a", "message", "and", "exit" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L2075-L2093
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.exit_on_error
def exit_on_error(self, message, exit_code=1): # pylint: disable=no-self-use """Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None """ log = "I got an unrecoverable error. I have to exit." if message: log += "\n-----\nError message: %s" % message print("Error message: %s" % message) log += "-----\n" log += "You can get help at https://github.com/Alignak-monitoring/alignak\n" log += "If you think this is a bug, create a new issue including as much " \ "details as possible (version, configuration,...)" if exit_code is not None: exit(exit_code)
python
def exit_on_error(self, message, exit_code=1): # pylint: disable=no-self-use """Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None """ log = "I got an unrecoverable error. I have to exit." if message: log += "\n-----\nError message: %s" % message print("Error message: %s" % message) log += "-----\n" log += "You can get help at https://github.com/Alignak-monitoring/alignak\n" log += "If you think this is a bug, create a new issue including as much " \ "details as possible (version, configuration,...)" if exit_code is not None: exit(exit_code)
[ "def", "exit_on_error", "(", "self", ",", "message", ",", "exit_code", "=", "1", ")", ":", "# pylint: disable=no-self-use", "log", "=", "\"I got an unrecoverable error. I have to exit.\"", "if", "message", ":", "log", "+=", "\"\\n-----\\nError message: %s\"", "%", "message", "print", "(", "\"Error message: %s\"", "%", "message", ")", "log", "+=", "\"-----\\n\"", "log", "+=", "\"You can get help at https://github.com/Alignak-monitoring/alignak\\n\"", "log", "+=", "\"If you think this is a bug, create a new issue including as much \"", "\"details as possible (version, configuration,...)\"", "if", "exit_code", "is", "not", "None", ":", "exit", "(", "exit_code", ")" ]
Log generic message when getting an error and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None
[ "Log", "generic", "message", "when", "getting", "an", "error", "and", "exit" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L2095-L2114
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.exit_on_exception
def exit_on_exception(self, raised_exception, message='', exit_code=99): """Log generic message when getting an unrecoverable error :param raised_exception: raised Exception :type raised_exception: Exception :param message: message for the exit reason :type message: str :param exit_code: exit with the provided value as exit code :type exit_code: int :return: None """ self.exit_on_error(message=message, exit_code=None) logger.critical("-----\nException: %s\nBack trace of the error:\n%s", str(raised_exception), traceback.format_exc()) exit(exit_code)
python
def exit_on_exception(self, raised_exception, message='', exit_code=99): """Log generic message when getting an unrecoverable error :param raised_exception: raised Exception :type raised_exception: Exception :param message: message for the exit reason :type message: str :param exit_code: exit with the provided value as exit code :type exit_code: int :return: None """ self.exit_on_error(message=message, exit_code=None) logger.critical("-----\nException: %s\nBack trace of the error:\n%s", str(raised_exception), traceback.format_exc()) exit(exit_code)
[ "def", "exit_on_exception", "(", "self", ",", "raised_exception", ",", "message", "=", "''", ",", "exit_code", "=", "99", ")", ":", "self", ".", "exit_on_error", "(", "message", "=", "message", ",", "exit_code", "=", "None", ")", "logger", ".", "critical", "(", "\"-----\\nException: %s\\nBack trace of the error:\\n%s\"", ",", "str", "(", "raised_exception", ")", ",", "traceback", ".", "format_exc", "(", ")", ")", "exit", "(", "exit_code", ")" ]
Log generic message when getting an unrecoverable error :param raised_exception: raised Exception :type raised_exception: Exception :param message: message for the exit reason :type message: str :param exit_code: exit with the provided value as exit code :type exit_code: int :return: None
[ "Log", "generic", "message", "when", "getting", "an", "unrecoverable", "error" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L2116-L2132
train
Alignak-monitoring/alignak
alignak/daemon.py
Daemon.get_objects_from_from_queues
def get_objects_from_from_queues(self): """ Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool """ _t0 = time.time() had_some_objects = False for module in self.modules_manager.get_external_instances(): queue = module.from_q if not queue: continue while True: queue_size = queue.qsize() if queue_size: statsmgr.gauge('queues.from.%s.count' % module.get_name(), queue_size) try: obj = queue.get_nowait() except Full: logger.warning("Module %s from queue is full", module.get_name()) except Empty: break except (IOError, EOFError) as exp: logger.warning("Module %s from queue is no more available: %s", module.get_name(), str(exp)) except Exception as exp: # pylint: disable=broad-except logger.error("An external module queue got a problem '%s'", str(exp)) else: had_some_objects = True self.add(obj) statsmgr.timer('queues.time', time.time() - _t0) return had_some_objects
python
def get_objects_from_from_queues(self): """ Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool """ _t0 = time.time() had_some_objects = False for module in self.modules_manager.get_external_instances(): queue = module.from_q if not queue: continue while True: queue_size = queue.qsize() if queue_size: statsmgr.gauge('queues.from.%s.count' % module.get_name(), queue_size) try: obj = queue.get_nowait() except Full: logger.warning("Module %s from queue is full", module.get_name()) except Empty: break except (IOError, EOFError) as exp: logger.warning("Module %s from queue is no more available: %s", module.get_name(), str(exp)) except Exception as exp: # pylint: disable=broad-except logger.error("An external module queue got a problem '%s'", str(exp)) else: had_some_objects = True self.add(obj) statsmgr.timer('queues.time', time.time() - _t0) return had_some_objects
[ "def", "get_objects_from_from_queues", "(", "self", ")", ":", "_t0", "=", "time", ".", "time", "(", ")", "had_some_objects", "=", "False", "for", "module", "in", "self", ".", "modules_manager", ".", "get_external_instances", "(", ")", ":", "queue", "=", "module", ".", "from_q", "if", "not", "queue", ":", "continue", "while", "True", ":", "queue_size", "=", "queue", ".", "qsize", "(", ")", "if", "queue_size", ":", "statsmgr", ".", "gauge", "(", "'queues.from.%s.count'", "%", "module", ".", "get_name", "(", ")", ",", "queue_size", ")", "try", ":", "obj", "=", "queue", ".", "get_nowait", "(", ")", "except", "Full", ":", "logger", ".", "warning", "(", "\"Module %s from queue is full\"", ",", "module", ".", "get_name", "(", ")", ")", "except", "Empty", ":", "break", "except", "(", "IOError", ",", "EOFError", ")", "as", "exp", ":", "logger", ".", "warning", "(", "\"Module %s from queue is no more available: %s\"", ",", "module", ".", "get_name", "(", ")", ",", "str", "(", "exp", ")", ")", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "logger", ".", "error", "(", "\"An external module queue got a problem '%s'\"", ",", "str", "(", "exp", ")", ")", "else", ":", "had_some_objects", "=", "True", "self", ".", "add", "(", "obj", ")", "statsmgr", ".", "timer", "(", "'queues.time'", ",", "time", ".", "time", "(", ")", "-", "_t0", ")", "return", "had_some_objects" ]
Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool
[ "Get", "objects", "from", "from", "queues", "and", "add", "them", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L2134-L2166
train
Alignak-monitoring/alignak
alignak/downtime.py
Downtime.add_automatic_comment
def add_automatic_comment(self, ref): """Add comment on ref for downtime :param ref: the host/service we want to link a comment to :type ref: alignak.objects.schedulingitem.SchedulingItem :return: None """ if self.fixed is True: text = (DOWNTIME_FIXED_MESSAGE % (ref.my_type, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)), ref.my_type)) else: hours, remainder = divmod(self.duration, 3600) minutes, _ = divmod(remainder, 60) text = (DOWNTIME_FLEXIBLE_MESSAGE % (ref.my_type, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)), hours, minutes, ref.my_type)) data = { 'comment': text, 'comment_type': 1 if ref.my_type == 'host' else 2, 'entry_type': 2, 'source': 0, 'expires': False, 'ref': ref.uuid } comment = Comment(data) self.comment_id = comment.uuid ref.comments[comment.uuid] = comment return comment
python
def add_automatic_comment(self, ref): """Add comment on ref for downtime :param ref: the host/service we want to link a comment to :type ref: alignak.objects.schedulingitem.SchedulingItem :return: None """ if self.fixed is True: text = (DOWNTIME_FIXED_MESSAGE % (ref.my_type, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)), ref.my_type)) else: hours, remainder = divmod(self.duration, 3600) minutes, _ = divmod(remainder, 60) text = (DOWNTIME_FLEXIBLE_MESSAGE % (ref.my_type, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time)), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time)), hours, minutes, ref.my_type)) data = { 'comment': text, 'comment_type': 1 if ref.my_type == 'host' else 2, 'entry_type': 2, 'source': 0, 'expires': False, 'ref': ref.uuid } comment = Comment(data) self.comment_id = comment.uuid ref.comments[comment.uuid] = comment return comment
[ "def", "add_automatic_comment", "(", "self", ",", "ref", ")", ":", "if", "self", ".", "fixed", "is", "True", ":", "text", "=", "(", "DOWNTIME_FIXED_MESSAGE", "%", "(", "ref", ".", "my_type", ",", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "time", ".", "localtime", "(", "self", ".", "start_time", ")", ")", ",", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "time", ".", "localtime", "(", "self", ".", "end_time", ")", ")", ",", "ref", ".", "my_type", ")", ")", "else", ":", "hours", ",", "remainder", "=", "divmod", "(", "self", ".", "duration", ",", "3600", ")", "minutes", ",", "_", "=", "divmod", "(", "remainder", ",", "60", ")", "text", "=", "(", "DOWNTIME_FLEXIBLE_MESSAGE", "%", "(", "ref", ".", "my_type", ",", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "time", ".", "localtime", "(", "self", ".", "start_time", ")", ")", ",", "time", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ",", "time", ".", "localtime", "(", "self", ".", "end_time", ")", ")", ",", "hours", ",", "minutes", ",", "ref", ".", "my_type", ")", ")", "data", "=", "{", "'comment'", ":", "text", ",", "'comment_type'", ":", "1", "if", "ref", ".", "my_type", "==", "'host'", "else", "2", ",", "'entry_type'", ":", "2", ",", "'source'", ":", "0", ",", "'expires'", ":", "False", ",", "'ref'", ":", "ref", ".", "uuid", "}", "comment", "=", "Comment", "(", "data", ")", "self", ".", "comment_id", "=", "comment", ".", "uuid", "ref", ".", "comments", "[", "comment", ".", "uuid", "]", "=", "comment", "return", "comment" ]
Add comment on ref for downtime :param ref: the host/service we want to link a comment to :type ref: alignak.objects.schedulingitem.SchedulingItem :return: None
[ "Add", "comment", "on", "ref", "for", "downtime" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/downtime.py#L313-L349
train
Alignak-monitoring/alignak
alignak/downtime.py
Downtime.get_raise_brok
def get_raise_brok(self, host_name, service_name=''): """Get a start downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok """ data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_raise', 'data': data})
python
def get_raise_brok(self, host_name, service_name=''): """Get a start downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok """ data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_raise', 'data': data})
[ "def", "get_raise_brok", "(", "self", ",", "host_name", ",", "service_name", "=", "''", ")", ":", "data", "=", "self", ".", "serialize", "(", ")", "data", "[", "'host'", "]", "=", "host_name", "if", "service_name", "!=", "''", ":", "data", "[", "'service'", "]", "=", "service_name", "return", "Brok", "(", "{", "'type'", ":", "'downtime_raise'", ",", "'data'", ":", "data", "}", ")" ]
Get a start downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok
[ "Get", "a", "start", "downtime", "brok" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/downtime.py#L379-L394
train
Alignak-monitoring/alignak
alignak/downtime.py
Downtime.get_expire_brok
def get_expire_brok(self, host_name, service_name=''): """Get an expire downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok """ data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_expire', 'data': data})
python
def get_expire_brok(self, host_name, service_name=''): """Get an expire downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok """ data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_expire', 'data': data})
[ "def", "get_expire_brok", "(", "self", ",", "host_name", ",", "service_name", "=", "''", ")", ":", "data", "=", "self", ".", "serialize", "(", ")", "data", "[", "'host'", "]", "=", "host_name", "if", "service_name", "!=", "''", ":", "data", "[", "'service'", "]", "=", "service_name", "return", "Brok", "(", "{", "'type'", ":", "'downtime_expire'", ",", "'data'", ":", "data", "}", ")" ]
Get an expire downtime brok :param host_name: host concerned by the downtime :type host_name :param service_name: service concerned by the downtime :type service_name :return: brok with wanted data :rtype: alignak.brok.Brok
[ "Get", "an", "expire", "downtime", "brok" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/downtime.py#L396-L411
train
Alignak-monitoring/alignak
alignak/objects/command.py
Command.fill_data_brok_from
def fill_data_brok_from(self, data, brok_type): """ Add properties to data if fill_brok of these class properties is same as brok_type :param data: dictionnary of this command :type data: dict :param brok_type: type of brok :type brok_type: str :return: None """ cls = self.__class__ # Now config properties for prop, entry in list(cls.properties.items()): # Is this property intended for broking? # if 'fill_brok' in entry[prop]: if brok_type in entry.fill_brok: if hasattr(self, prop): data[prop] = getattr(self, prop)
python
def fill_data_brok_from(self, data, brok_type): """ Add properties to data if fill_brok of these class properties is same as brok_type :param data: dictionnary of this command :type data: dict :param brok_type: type of brok :type brok_type: str :return: None """ cls = self.__class__ # Now config properties for prop, entry in list(cls.properties.items()): # Is this property intended for broking? # if 'fill_brok' in entry[prop]: if brok_type in entry.fill_brok: if hasattr(self, prop): data[prop] = getattr(self, prop)
[ "def", "fill_data_brok_from", "(", "self", ",", "data", ",", "brok_type", ")", ":", "cls", "=", "self", ".", "__class__", "# Now config properties", "for", "prop", ",", "entry", "in", "list", "(", "cls", ".", "properties", ".", "items", "(", ")", ")", ":", "# Is this property intended for broking?", "# if 'fill_brok' in entry[prop]:", "if", "brok_type", "in", "entry", ".", "fill_brok", ":", "if", "hasattr", "(", "self", ",", "prop", ")", ":", "data", "[", "prop", "]", "=", "getattr", "(", "self", ",", "prop", ")" ]
Add properties to data if fill_brok of these class properties is same as brok_type :param data: dictionnary of this command :type data: dict :param brok_type: type of brok :type brok_type: str :return: None
[ "Add", "properties", "to", "data", "if", "fill_brok", "of", "these", "class", "properties", "is", "same", "as", "brok_type" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/command.py#L126-L144
train
Alignak-monitoring/alignak
alignak/objects/servicedependency.py
Servicedependency.get_name
def get_name(self): """Get name based on 4 class attributes Each attribute is substituted by '' if attribute does not exist :return: dependent_host_name/dependent_service_description..host_name/service_description :rtype: str TODO: Clean this function (use format for string) """ return getattr(self, 'dependent_host_name', '') + '/'\ + getattr(self, 'dependent_service_description', '') \ + '..' + getattr(self, 'host_name', '') + '/' \ + getattr(self, 'service_description', '')
python
def get_name(self): """Get name based on 4 class attributes Each attribute is substituted by '' if attribute does not exist :return: dependent_host_name/dependent_service_description..host_name/service_description :rtype: str TODO: Clean this function (use format for string) """ return getattr(self, 'dependent_host_name', '') + '/'\ + getattr(self, 'dependent_service_description', '') \ + '..' + getattr(self, 'host_name', '') + '/' \ + getattr(self, 'service_description', '')
[ "def", "get_name", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "'dependent_host_name'", ",", "''", ")", "+", "'/'", "+", "getattr", "(", "self", ",", "'dependent_service_description'", ",", "''", ")", "+", "'..'", "+", "getattr", "(", "self", ",", "'host_name'", ",", "''", ")", "+", "'/'", "+", "getattr", "(", "self", ",", "'service_description'", ",", "''", ")" ]
Get name based on 4 class attributes Each attribute is substituted by '' if attribute does not exist :return: dependent_host_name/dependent_service_description..host_name/service_description :rtype: str TODO: Clean this function (use format for string)
[ "Get", "name", "based", "on", "4", "class", "attributes", "Each", "attribute", "is", "substituted", "by", "if", "attribute", "does", "not", "exist" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicedependency.py#L108-L119
train
Alignak-monitoring/alignak
alignak/objects/servicedependency.py
Servicedependencies.explode_hostgroup
def explode_hostgroup(self, svc_dep, hostgroups): # pylint: disable=too-many-locals """Explode a service dependency for each member of hostgroup :param svc_dep: service dependency to explode :type svc_dep: alignak.objects.servicedependency.Servicedependency :param hostgroups: used to find hostgroup objects :type hostgroups: alignak.objects.hostgroup.Hostgroups :return:None """ # We will create a service dependency for each host part of the host group # First get services snames = [d.strip() for d in svc_dep.service_description.split(',')] # And dep services dep_snames = [d.strip() for d in svc_dep.dependent_service_description.split(',')] # Now for each host into hostgroup we will create a service dependency object hg_names = [n.strip() for n in svc_dep.hostgroup_name.split(',')] for hg_name in hg_names: hostgroup = hostgroups.find_by_name(hg_name) if hostgroup is None: err = "ERROR: the servicedependecy got an unknown hostgroup_name '%s'" % hg_name self.add_error(err) continue hnames = [] hnames.extend([m.strip() for m in hostgroup.get_hosts()]) for hname in hnames: for dep_sname in dep_snames: for sname in snames: new_sd = svc_dep.copy() new_sd.host_name = hname new_sd.service_description = sname new_sd.dependent_host_name = hname new_sd.dependent_service_description = dep_sname self.add_item(new_sd)
python
def explode_hostgroup(self, svc_dep, hostgroups): # pylint: disable=too-many-locals """Explode a service dependency for each member of hostgroup :param svc_dep: service dependency to explode :type svc_dep: alignak.objects.servicedependency.Servicedependency :param hostgroups: used to find hostgroup objects :type hostgroups: alignak.objects.hostgroup.Hostgroups :return:None """ # We will create a service dependency for each host part of the host group # First get services snames = [d.strip() for d in svc_dep.service_description.split(',')] # And dep services dep_snames = [d.strip() for d in svc_dep.dependent_service_description.split(',')] # Now for each host into hostgroup we will create a service dependency object hg_names = [n.strip() for n in svc_dep.hostgroup_name.split(',')] for hg_name in hg_names: hostgroup = hostgroups.find_by_name(hg_name) if hostgroup is None: err = "ERROR: the servicedependecy got an unknown hostgroup_name '%s'" % hg_name self.add_error(err) continue hnames = [] hnames.extend([m.strip() for m in hostgroup.get_hosts()]) for hname in hnames: for dep_sname in dep_snames: for sname in snames: new_sd = svc_dep.copy() new_sd.host_name = hname new_sd.service_description = sname new_sd.dependent_host_name = hname new_sd.dependent_service_description = dep_sname self.add_item(new_sd)
[ "def", "explode_hostgroup", "(", "self", ",", "svc_dep", ",", "hostgroups", ")", ":", "# pylint: disable=too-many-locals", "# We will create a service dependency for each host part of the host group", "# First get services", "snames", "=", "[", "d", ".", "strip", "(", ")", "for", "d", "in", "svc_dep", ".", "service_description", ".", "split", "(", "','", ")", "]", "# And dep services", "dep_snames", "=", "[", "d", ".", "strip", "(", ")", "for", "d", "in", "svc_dep", ".", "dependent_service_description", ".", "split", "(", "','", ")", "]", "# Now for each host into hostgroup we will create a service dependency object", "hg_names", "=", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "svc_dep", ".", "hostgroup_name", ".", "split", "(", "','", ")", "]", "for", "hg_name", "in", "hg_names", ":", "hostgroup", "=", "hostgroups", ".", "find_by_name", "(", "hg_name", ")", "if", "hostgroup", "is", "None", ":", "err", "=", "\"ERROR: the servicedependecy got an unknown hostgroup_name '%s'\"", "%", "hg_name", "self", ".", "add_error", "(", "err", ")", "continue", "hnames", "=", "[", "]", "hnames", ".", "extend", "(", "[", "m", ".", "strip", "(", ")", "for", "m", "in", "hostgroup", ".", "get_hosts", "(", ")", "]", ")", "for", "hname", "in", "hnames", ":", "for", "dep_sname", "in", "dep_snames", ":", "for", "sname", "in", "snames", ":", "new_sd", "=", "svc_dep", ".", "copy", "(", ")", "new_sd", ".", "host_name", "=", "hname", "new_sd", ".", "service_description", "=", "sname", "new_sd", ".", "dependent_host_name", "=", "hname", "new_sd", ".", "dependent_service_description", "=", "dep_sname", "self", ".", "add_item", "(", "new_sd", ")" ]
Explode a service dependency for each member of hostgroup :param svc_dep: service dependency to explode :type svc_dep: alignak.objects.servicedependency.Servicedependency :param hostgroups: used to find hostgroup objects :type hostgroups: alignak.objects.hostgroup.Hostgroups :return:None
[ "Explode", "a", "service", "dependency", "for", "each", "member", "of", "hostgroup" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicedependency.py#L168-L204
train
Alignak-monitoring/alignak
alignak/objects/servicedependency.py
Servicedependencies.linkify_sd_by_s
def linkify_sd_by_s(self, hosts, services): """Replace dependent_service_description and service_description in service dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :param services: service list to look for a specific one :type services: alignak.objects.service.Services :return: None """ to_del = [] errors = self.configuration_errors warns = self.configuration_warnings for servicedep in self: try: s_name = servicedep.dependent_service_description hst_name = servicedep.dependent_host_name # The new member list, in id serv = services.find_srv_by_name_and_hostname(hst_name, s_name) if serv is None: host = hosts.find_by_name(hst_name) if not (host and host.is_excluded_for_sdesc(s_name)): errors.append("Service %s not found for host %s" % (s_name, hst_name)) elif host: warns.append("Service %s is excluded from host %s ; " "removing this servicedependency as it's unusuable." % (s_name, hst_name)) to_del.append(servicedep) continue servicedep.dependent_service_description = serv.uuid s_name = servicedep.service_description hst_name = servicedep.host_name # The new member list, in id serv = services.find_srv_by_name_and_hostname(hst_name, s_name) if serv is None: host = hosts.find_by_name(hst_name) if not (host and host.is_excluded_for_sdesc(s_name)): errors.append("Service %s not found for host %s" % (s_name, hst_name)) elif host: warns.append("Service %s is excluded from host %s ; " "removing this servicedependency as it's unusuable." % (s_name, hst_name)) to_del.append(servicedep) continue servicedep.service_description = serv.uuid except AttributeError as err: logger.error("[servicedependency] fail to linkify by service %s: %s", servicedep, err) to_del.append(servicedep) for servicedep in to_del: self.remove_item(servicedep)
python
def linkify_sd_by_s(self, hosts, services): """Replace dependent_service_description and service_description in service dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :param services: service list to look for a specific one :type services: alignak.objects.service.Services :return: None """ to_del = [] errors = self.configuration_errors warns = self.configuration_warnings for servicedep in self: try: s_name = servicedep.dependent_service_description hst_name = servicedep.dependent_host_name # The new member list, in id serv = services.find_srv_by_name_and_hostname(hst_name, s_name) if serv is None: host = hosts.find_by_name(hst_name) if not (host and host.is_excluded_for_sdesc(s_name)): errors.append("Service %s not found for host %s" % (s_name, hst_name)) elif host: warns.append("Service %s is excluded from host %s ; " "removing this servicedependency as it's unusuable." % (s_name, hst_name)) to_del.append(servicedep) continue servicedep.dependent_service_description = serv.uuid s_name = servicedep.service_description hst_name = servicedep.host_name # The new member list, in id serv = services.find_srv_by_name_and_hostname(hst_name, s_name) if serv is None: host = hosts.find_by_name(hst_name) if not (host and host.is_excluded_for_sdesc(s_name)): errors.append("Service %s not found for host %s" % (s_name, hst_name)) elif host: warns.append("Service %s is excluded from host %s ; " "removing this servicedependency as it's unusuable." % (s_name, hst_name)) to_del.append(servicedep) continue servicedep.service_description = serv.uuid except AttributeError as err: logger.error("[servicedependency] fail to linkify by service %s: %s", servicedep, err) to_del.append(servicedep) for servicedep in to_del: self.remove_item(servicedep)
[ "def", "linkify_sd_by_s", "(", "self", ",", "hosts", ",", "services", ")", ":", "to_del", "=", "[", "]", "errors", "=", "self", ".", "configuration_errors", "warns", "=", "self", ".", "configuration_warnings", "for", "servicedep", "in", "self", ":", "try", ":", "s_name", "=", "servicedep", ".", "dependent_service_description", "hst_name", "=", "servicedep", ".", "dependent_host_name", "# The new member list, in id", "serv", "=", "services", ".", "find_srv_by_name_and_hostname", "(", "hst_name", ",", "s_name", ")", "if", "serv", "is", "None", ":", "host", "=", "hosts", ".", "find_by_name", "(", "hst_name", ")", "if", "not", "(", "host", "and", "host", ".", "is_excluded_for_sdesc", "(", "s_name", ")", ")", ":", "errors", ".", "append", "(", "\"Service %s not found for host %s\"", "%", "(", "s_name", ",", "hst_name", ")", ")", "elif", "host", ":", "warns", ".", "append", "(", "\"Service %s is excluded from host %s ; \"", "\"removing this servicedependency as it's unusuable.\"", "%", "(", "s_name", ",", "hst_name", ")", ")", "to_del", ".", "append", "(", "servicedep", ")", "continue", "servicedep", ".", "dependent_service_description", "=", "serv", ".", "uuid", "s_name", "=", "servicedep", ".", "service_description", "hst_name", "=", "servicedep", ".", "host_name", "# The new member list, in id", "serv", "=", "services", ".", "find_srv_by_name_and_hostname", "(", "hst_name", ",", "s_name", ")", "if", "serv", "is", "None", ":", "host", "=", "hosts", ".", "find_by_name", "(", "hst_name", ")", "if", "not", "(", "host", "and", "host", ".", "is_excluded_for_sdesc", "(", "s_name", ")", ")", ":", "errors", ".", "append", "(", "\"Service %s not found for host %s\"", "%", "(", "s_name", ",", "hst_name", ")", ")", "elif", "host", ":", "warns", ".", "append", "(", "\"Service %s is excluded from host %s ; \"", "\"removing this servicedependency as it's unusuable.\"", "%", "(", "s_name", ",", "hst_name", ")", ")", "to_del", ".", "append", "(", "servicedep", ")", "continue", "servicedep", ".", "service_description", "=", "serv", ".", "uuid", "except", "AttributeError", "as", "err", ":", "logger", ".", "error", "(", "\"[servicedependency] fail to linkify by service %s: %s\"", ",", "servicedep", ",", "err", ")", "to_del", ".", "append", "(", "servicedep", ")", "for", "servicedep", "in", "to_del", ":", "self", ".", "remove_item", "(", "servicedep", ")" ]
Replace dependent_service_description and service_description in service dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :param services: service list to look for a specific one :type services: alignak.objects.service.Services :return: None
[ "Replace", "dependent_service_description", "and", "service_description", "in", "service", "dependency", "by", "the", "real", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicedependency.py#L324-L379
train