id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
21,000 | 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):
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",
".",
"proble... | 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 |
21,001 | 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):
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 |
21,002 | 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):
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 |
21,003 | 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):
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",
".",
"__da... | 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 |
21,004 | 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):
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 |
21,005 | 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):
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 |
21,006 | 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):
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\"",
"... | 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 |
21,007 | 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:
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",
":",
"... | 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 |
21,008 | 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):
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",
":",
"... | 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 |
21,009 | 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):
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 |
21,010 | 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):
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",
".",
"properti... | 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 |
21,011 | 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):
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 ... | 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 |
21,012 | 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):
# 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",
".",
... | 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 |
21,013 | 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):
# 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",
"... | 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 |
21,014 | 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):
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 rest... | 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 |
21,015 | 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):
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",
",",
"... | Stop all module instances
:return: None | [
"Stop",
"all",
"module",
"instances"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modulesmanager.py#L417-L428 |
21,016 | 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
# 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",
... | 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 |
21,017 | 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):
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",
":",
"# pyli... | 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 |
21,018 | 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):
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",
"(",... | 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 |
21,019 | 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):
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",
... | 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 |
21,020 | 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):
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... | 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 |
21,021 | 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):
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.'",
"+",
"na... | 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 |
21,022 | 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):
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"... | 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 |
21,023 | 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):
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",
... | 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 |
21,024 | 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):
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",
... | 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 |
21,025 | 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):
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",
".",
"u... | 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 |
21,026 | 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):
# 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",
"membe... | 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 |
21,027 | 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):
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",
",",
... | 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 |
21,028 | 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):
# 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",
... | 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 |
21,029 | 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):
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 i... | 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 |
21,030 | 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):
_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",
")",
":",
"... | 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 |
21,031 | 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):
# 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",
... | 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 |
21,032 | 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):
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... | 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 |
21,033 | 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):
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",
"."... | 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 |
21,034 | 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):
# 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\"",
"%",
"(... | 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 |
21,035 | 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):
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",
".",... | 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 |
21,036 | 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...
# 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_N... | 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 |
21,037 | 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):
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",
... | 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 |
21,038 | 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
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",
".",
... | 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 |
21,039 | 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):
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",
".",
... | 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 |
21,040 | 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):
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"... | 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 |
21,041 | 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):
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",
"... | 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 |
21,042 | 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):
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"... | 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 |
21,043 | 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):
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_chang... | 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 |
21,044 | 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):
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",
"... | 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 |
21,045 | 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
# 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\"",
":",
... | 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 |
21,046 | 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):
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: %... | 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 |
21,047 | 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 = "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\"",
"%",
"mess... | 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 |
21,048 | 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):
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",... | 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 |
21,049 | 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):
_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",
"=",
"mod... | 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 |
21,050 | 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):
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\"",
",",
... | 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 |
21,051 | 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=''):
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",
"[",
"'servi... | 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 |
21,052 | 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=''):
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",
"[",
"'serv... | 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 |
21,053 | 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):
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",
"(",
")",
")",
":... | 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 |
21,054 | 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):
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",
"(",
"... | 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 |
21,055 | 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
# 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",
"(",
")",
... | 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 |
21,056 | 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):
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",
... | 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 |
21,057 | Alignak-monitoring/alignak | alignak/objects/servicedependency.py | Servicedependencies.linkify_sd_by_tp | def linkify_sd_by_tp(self, timeperiods):
"""Replace dependency_period by a real object in service dependency
:param timeperiods: list of timeperiod, used to look for a specific one
:type timeperiods: alignak.objects.timeperiod.Timeperiods
:return: None
"""
for servicedep in self:
try:
tp_name = servicedep.dependency_period
timeperiod = timeperiods.find_by_name(tp_name)
if timeperiod:
servicedep.dependency_period = timeperiod.uuid
else:
servicedep.dependency_period = ''
except AttributeError as exp:
logger.error("[servicedependency] fail to linkify by timeperiods: %s", exp) | python | def linkify_sd_by_tp(self, timeperiods):
for servicedep in self:
try:
tp_name = servicedep.dependency_period
timeperiod = timeperiods.find_by_name(tp_name)
if timeperiod:
servicedep.dependency_period = timeperiod.uuid
else:
servicedep.dependency_period = ''
except AttributeError as exp:
logger.error("[servicedependency] fail to linkify by timeperiods: %s", exp) | [
"def",
"linkify_sd_by_tp",
"(",
"self",
",",
"timeperiods",
")",
":",
"for",
"servicedep",
"in",
"self",
":",
"try",
":",
"tp_name",
"=",
"servicedep",
".",
"dependency_period",
"timeperiod",
"=",
"timeperiods",
".",
"find_by_name",
"(",
"tp_name",
")",
"if",
... | Replace dependency_period by a real object in service dependency
:param timeperiods: list of timeperiod, used to look for a specific one
:type timeperiods: alignak.objects.timeperiod.Timeperiods
:return: None | [
"Replace",
"dependency_period",
"by",
"a",
"real",
"object",
"in",
"service",
"dependency"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicedependency.py#L381-L397 |
21,058 | Alignak-monitoring/alignak | alignak/objects/servicedependency.py | Servicedependencies.linkify_s_by_sd | def linkify_s_by_sd(self, services):
"""Add dependency in service objects
:return: None
"""
for servicedep in self:
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string", "undefined")
setattr(servicedep, "dependent_service_description_string", "undefined")
if getattr(servicedep, 'service_description', None) is None or\
getattr(servicedep, 'dependent_service_description', None) is None:
continue
services.add_act_dependency(servicedep.dependent_service_description,
servicedep.service_description,
servicedep.notification_failure_criteria,
getattr(servicedep, 'dependency_period', ''),
servicedep.inherits_parent)
services.add_chk_dependency(servicedep.dependent_service_description,
servicedep.service_description,
servicedep.execution_failure_criteria,
getattr(servicedep, 'dependency_period', ''),
servicedep.inherits_parent)
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string",
services[servicedep.service_description].get_name())
setattr(servicedep, "dependent_service_description_string",
services[servicedep.dependent_service_description].get_name()) | python | def linkify_s_by_sd(self, services):
for servicedep in self:
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string", "undefined")
setattr(servicedep, "dependent_service_description_string", "undefined")
if getattr(servicedep, 'service_description', None) is None or\
getattr(servicedep, 'dependent_service_description', None) is None:
continue
services.add_act_dependency(servicedep.dependent_service_description,
servicedep.service_description,
servicedep.notification_failure_criteria,
getattr(servicedep, 'dependency_period', ''),
servicedep.inherits_parent)
services.add_chk_dependency(servicedep.dependent_service_description,
servicedep.service_description,
servicedep.execution_failure_criteria,
getattr(servicedep, 'dependency_period', ''),
servicedep.inherits_parent)
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string",
services[servicedep.service_description].get_name())
setattr(servicedep, "dependent_service_description_string",
services[servicedep.dependent_service_description].get_name()) | [
"def",
"linkify_s_by_sd",
"(",
"self",
",",
"services",
")",
":",
"for",
"servicedep",
"in",
"self",
":",
"# Only used for debugging purpose when loops are detected",
"setattr",
"(",
"servicedep",
",",
"\"service_description_string\"",
",",
"\"undefined\"",
")",
"setattr"... | Add dependency in service objects
:return: None | [
"Add",
"dependency",
"in",
"service",
"objects"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicedependency.py#L399-L429 |
21,059 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.init | def init(self): # pylint: disable=too-many-branches
"""Called by the daemon broker to initialize the module"""
if not self.enabled:
logger.info(" the module is disabled.")
return True
try:
connections = self.test_connection()
except Exception as exp: # pylint: disable=broad-except
logger.error("initialization, test connection failed. Error: %s", str(exp))
if self.influxdb_enabled:
try:
# Check that configured TSDB is existing, else creates...
dbs = self.influx.get_list_database()
for db in dbs:
if db.get('name') == self.influxdb_database:
logger.info("the database %s is existing.", self.influxdb_database)
break
else:
# Create the database
logger.info("creating database %s...", self.influxdb_database)
self.influx.create_database(self.influxdb_database)
# Check that configured TSDB retention is existing, else creates...
if self.influxdb_retention_name:
rps = self.influx.get_list_retention_policies()
for rp in rps:
if rp.get('name') == self.influxdb_retention_name:
logger.info("the retention policy %s is existing.",
self.influxdb_retention_name)
break
else:
# Create a retention policy for this database
logger.info("creating database retention policy: %s - %s - %s...",
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication)
self.influx.create_retention_policy(
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication, database=self.influxdb_database)
# Check that configured TSDB user is existing, else creates...
if self.influxdb_username:
users = self.influx.get_list_users()
for user in users:
if user.get('user') == self.influxdb_username:
logger.info("the user %s is existing.",
self.influxdb_username)
break
else:
# Create a retention policy for this database
logger.info("creating user: %s...", self.influxdb_username)
self.influx.create_user(self.influxdb_username, self.influxdb_password,
admin=False)
connections = connections or True
except Exception as exp: # pylint: disable=broad-except
logger.error("InfluxDB, DB initialization failed. Error: %s", str(exp))
return connections | python | def init(self): # pylint: disable=too-many-branches
if not self.enabled:
logger.info(" the module is disabled.")
return True
try:
connections = self.test_connection()
except Exception as exp: # pylint: disable=broad-except
logger.error("initialization, test connection failed. Error: %s", str(exp))
if self.influxdb_enabled:
try:
# Check that configured TSDB is existing, else creates...
dbs = self.influx.get_list_database()
for db in dbs:
if db.get('name') == self.influxdb_database:
logger.info("the database %s is existing.", self.influxdb_database)
break
else:
# Create the database
logger.info("creating database %s...", self.influxdb_database)
self.influx.create_database(self.influxdb_database)
# Check that configured TSDB retention is existing, else creates...
if self.influxdb_retention_name:
rps = self.influx.get_list_retention_policies()
for rp in rps:
if rp.get('name') == self.influxdb_retention_name:
logger.info("the retention policy %s is existing.",
self.influxdb_retention_name)
break
else:
# Create a retention policy for this database
logger.info("creating database retention policy: %s - %s - %s...",
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication)
self.influx.create_retention_policy(
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication, database=self.influxdb_database)
# Check that configured TSDB user is existing, else creates...
if self.influxdb_username:
users = self.influx.get_list_users()
for user in users:
if user.get('user') == self.influxdb_username:
logger.info("the user %s is existing.",
self.influxdb_username)
break
else:
# Create a retention policy for this database
logger.info("creating user: %s...", self.influxdb_username)
self.influx.create_user(self.influxdb_username, self.influxdb_password,
admin=False)
connections = connections or True
except Exception as exp: # pylint: disable=broad-except
logger.error("InfluxDB, DB initialization failed. Error: %s", str(exp))
return connections | [
"def",
"init",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"enabled",
":",
"logger",
".",
"info",
"(",
"\" the module is disabled.\"",
")",
"return",
"True",
"try",
":",
"connections",
"=",
"self",
".",
"test_connectio... | Called by the daemon broker to initialize the module | [
"Called",
"by",
"the",
"daemon",
"broker",
"to",
"initialize",
"the",
"module"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L235-L294 |
21,060 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.get_metrics_from_perfdata | def get_metrics_from_perfdata(self, service, perf_data):
"""Decode the performance data to build a metrics list"""
result = []
metrics = PerfDatas(perf_data)
for metric in metrics:
logger.debug("service: %s, metric: %s (%s)", service, metric, metric.__dict__)
if metric.name in ['time']:
metric.name = "duration"
name = sanitize_name(metric.name)
name = self.multiple_values.sub(r'.\1', name)
if not name:
continue
# get metric value and its thresholds values if they exist
name_value = {
name: metric.value,
'uom_' + name: metric.uom
}
# Get or ignore extra values depending upon module configuration
if metric.warning and self.send_warning:
name_value[name + '_warn'] = metric.warning
if metric.critical and self.send_critical:
name_value[name + '_crit'] = metric.critical
if metric.min and self.send_min:
name_value[name + '_min'] = metric.min
if metric.max and self.send_max:
name_value[name + '_max'] = metric.max
for key, value in name_value.items():
result.append((key, value, metric.uom))
logger.debug("Metrics: %s - %s", service, result)
return result | python | def get_metrics_from_perfdata(self, service, perf_data):
result = []
metrics = PerfDatas(perf_data)
for metric in metrics:
logger.debug("service: %s, metric: %s (%s)", service, metric, metric.__dict__)
if metric.name in ['time']:
metric.name = "duration"
name = sanitize_name(metric.name)
name = self.multiple_values.sub(r'.\1', name)
if not name:
continue
# get metric value and its thresholds values if they exist
name_value = {
name: metric.value,
'uom_' + name: metric.uom
}
# Get or ignore extra values depending upon module configuration
if metric.warning and self.send_warning:
name_value[name + '_warn'] = metric.warning
if metric.critical and self.send_critical:
name_value[name + '_crit'] = metric.critical
if metric.min and self.send_min:
name_value[name + '_min'] = metric.min
if metric.max and self.send_max:
name_value[name + '_max'] = metric.max
for key, value in name_value.items():
result.append((key, value, metric.uom))
logger.debug("Metrics: %s - %s", service, result)
return result | [
"def",
"get_metrics_from_perfdata",
"(",
"self",
",",
"service",
",",
"perf_data",
")",
":",
"result",
"=",
"[",
"]",
"metrics",
"=",
"PerfDatas",
"(",
"perf_data",
")",
"for",
"metric",
"in",
"metrics",
":",
"logger",
".",
"debug",
"(",
"\"service: %s, metr... | Decode the performance data to build a metrics list | [
"Decode",
"the",
"performance",
"data",
"to",
"build",
"a",
"metrics",
"list"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L364-L402 |
21,061 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.send_to_tsdb | def send_to_tsdb(self, realm, host, service, metrics, ts, path):
"""Send performance data to time series database
Indeed this function stores metrics in the internal cache and checks if the flushing
is necessary and then flushes.
:param realm: concerned realm
:type: string
:param host: concerned host
:type: string
:param service: concerned service
:type: string
:param metrics: list of metrics couple (name, value)
:type: list
:param ts: timestamp
:type: int
:param path: full path (eg. Graphite) for the received metrics
:type: string
"""
if ts is None:
ts = int(time.time())
data = {
"measurement": service,
"tags": {
"host": host,
"service": service,
"realm": '.'.join(realm) if isinstance(realm, list) else realm,
"path": path
},
"time": ts,
"fields": {}
}
if path is not None:
data['tags'].update({"path": path})
for metric, value, _ in metrics:
data['fields'].update({metric: value})
# Flush if necessary
logger.debug("Data: %s", data)
self.my_metrics.append(data)
if self.metrics_count >= self.metrics_flush_count:
# self.carbon.add_data_list(self.my_metrics)
self.flush() | python | def send_to_tsdb(self, realm, host, service, metrics, ts, path):
if ts is None:
ts = int(time.time())
data = {
"measurement": service,
"tags": {
"host": host,
"service": service,
"realm": '.'.join(realm) if isinstance(realm, list) else realm,
"path": path
},
"time": ts,
"fields": {}
}
if path is not None:
data['tags'].update({"path": path})
for metric, value, _ in metrics:
data['fields'].update({metric: value})
# Flush if necessary
logger.debug("Data: %s", data)
self.my_metrics.append(data)
if self.metrics_count >= self.metrics_flush_count:
# self.carbon.add_data_list(self.my_metrics)
self.flush() | [
"def",
"send_to_tsdb",
"(",
"self",
",",
"realm",
",",
"host",
",",
"service",
",",
"metrics",
",",
"ts",
",",
"path",
")",
":",
"if",
"ts",
"is",
"None",
":",
"ts",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"data",
"=",
"{",
"\"meas... | Send performance data to time series database
Indeed this function stores metrics in the internal cache and checks if the flushing
is necessary and then flushes.
:param realm: concerned realm
:type: string
:param host: concerned host
:type: string
:param service: concerned service
:type: string
:param metrics: list of metrics couple (name, value)
:type: list
:param ts: timestamp
:type: int
:param path: full path (eg. Graphite) for the received metrics
:type: string | [
"Send",
"performance",
"data",
"to",
"time",
"series",
"database"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L546-L592 |
21,062 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.manage_initial_service_status_brok | def manage_initial_service_status_brok(self, b):
"""Prepare the known services cache"""
host_name = b.data['host_name']
service_description = b.data['service_description']
service_id = host_name+"/"+service_description
logger.debug("got initial service status: %s", service_id)
if host_name not in self.hosts_cache:
logger.error("initial service status, host is unknown: %s.", service_id)
return
self.services_cache[service_id] = {
}
if 'customs' in b.data:
self.services_cache[service_id]['_GRAPHITE_POST'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_POST', None))
logger.debug("initial service status received: %s", service_id) | python | def manage_initial_service_status_brok(self, b):
host_name = b.data['host_name']
service_description = b.data['service_description']
service_id = host_name+"/"+service_description
logger.debug("got initial service status: %s", service_id)
if host_name not in self.hosts_cache:
logger.error("initial service status, host is unknown: %s.", service_id)
return
self.services_cache[service_id] = {
}
if 'customs' in b.data:
self.services_cache[service_id]['_GRAPHITE_POST'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_POST', None))
logger.debug("initial service status received: %s", service_id) | [
"def",
"manage_initial_service_status_brok",
"(",
"self",
",",
"b",
")",
":",
"host_name",
"=",
"b",
".",
"data",
"[",
"'host_name'",
"]",
"service_description",
"=",
"b",
".",
"data",
"[",
"'service_description'",
"]",
"service_id",
"=",
"host_name",
"+",
"\"... | Prepare the known services cache | [
"Prepare",
"the",
"known",
"services",
"cache"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L594-L611 |
21,063 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.manage_initial_host_status_brok | def manage_initial_host_status_brok(self, b):
"""Prepare the known hosts cache"""
host_name = b.data['host_name']
logger.debug("got initial host status: %s", host_name)
self.hosts_cache[host_name] = {
'realm_name':
sanitize_name(b.data.get('realm_name', b.data.get('realm', 'All'))),
}
if 'customs' in b.data:
self.hosts_cache[host_name]['_GRAPHITE_PRE'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_PRE', None))
self.hosts_cache[host_name]['_GRAPHITE_GROUP'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_GROUP', None))
logger.debug("initial host status received: %s", host_name) | python | def manage_initial_host_status_brok(self, b):
host_name = b.data['host_name']
logger.debug("got initial host status: %s", host_name)
self.hosts_cache[host_name] = {
'realm_name':
sanitize_name(b.data.get('realm_name', b.data.get('realm', 'All'))),
}
if 'customs' in b.data:
self.hosts_cache[host_name]['_GRAPHITE_PRE'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_PRE', None))
self.hosts_cache[host_name]['_GRAPHITE_GROUP'] = \
sanitize_name(b.data['customs'].get('_GRAPHITE_GROUP', None))
logger.debug("initial host status received: %s", host_name) | [
"def",
"manage_initial_host_status_brok",
"(",
"self",
",",
"b",
")",
":",
"host_name",
"=",
"b",
".",
"data",
"[",
"'host_name'",
"]",
"logger",
".",
"debug",
"(",
"\"got initial host status: %s\"",
",",
"host_name",
")",
"self",
".",
"hosts_cache",
"[",
"hos... | Prepare the known hosts cache | [
"Prepare",
"the",
"known",
"hosts",
"cache"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L613-L627 |
21,064 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.manage_service_check_result_brok | def manage_service_check_result_brok(self, b): # pylint: disable=too-many-branches
"""A service check result brok has just arrived ..."""
host_name = b.data.get('host_name', None)
service_description = b.data.get('service_description', None)
if not host_name or not service_description:
return
service_id = host_name+"/"+service_description
logger.debug("service check result: %s", service_id)
# If host and service initial status broks have not been received, ignore ...
if not self.ignore_unknown and host_name not in self.hosts_cache:
logger.warning("received service check result for an unknown host: %s", service_id)
return
if service_id not in self.services_cache and not self.ignore_unknown:
logger.warning("received service check result for an unknown service: %s", service_id)
return
# Decode received metrics
metrics = self.get_metrics_from_perfdata(service_description, b.data['perf_data'])
if not metrics:
logger.debug("no metrics to send ...")
return
# If checks latency is ignored
if self.ignore_latency_limit >= b.data['latency'] > 0:
check_time = int(b.data['last_chk']) - int(b.data['latency'])
else:
check_time = int(b.data['last_chk'])
# Custom hosts variables
hname = sanitize_name(host_name)
if host_name in self.hosts_cache:
if self.hosts_cache[host_name].get('_GRAPHITE_GROUP', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_GROUP'), hname))
if self.hosts_cache[host_name].get('_GRAPHITE_PRE', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_PRE'), hname))
# Custom services variables
desc = sanitize_name(service_description)
if service_id in self.services_cache:
if self.services_cache[service_id].get('_GRAPHITE_POST', None):
desc = ".".join((desc, self.services_cache[service_id].get('_GRAPHITE_POST', None)))
# Graphite data source
if self.graphite_data_source:
path = '.'.join((hname, self.graphite_data_source, desc))
else:
path = '.'.join((hname, desc))
# Realm as a prefix
if self.realms_prefix and self.hosts_cache[host_name].get('realm_name', None):
path = '.'.join((self.hosts_cache[host_name].get('realm_name'), path))
realm_name = None
if host_name in self.hosts_cache:
realm_name = self.hosts_cache[host_name].get('realm_name', None)
# Send metrics
self.send_to_tsdb(realm_name, host_name, service_description, metrics, check_time, path) | python | def manage_service_check_result_brok(self, b): # pylint: disable=too-many-branches
host_name = b.data.get('host_name', None)
service_description = b.data.get('service_description', None)
if not host_name or not service_description:
return
service_id = host_name+"/"+service_description
logger.debug("service check result: %s", service_id)
# If host and service initial status broks have not been received, ignore ...
if not self.ignore_unknown and host_name not in self.hosts_cache:
logger.warning("received service check result for an unknown host: %s", service_id)
return
if service_id not in self.services_cache and not self.ignore_unknown:
logger.warning("received service check result for an unknown service: %s", service_id)
return
# Decode received metrics
metrics = self.get_metrics_from_perfdata(service_description, b.data['perf_data'])
if not metrics:
logger.debug("no metrics to send ...")
return
# If checks latency is ignored
if self.ignore_latency_limit >= b.data['latency'] > 0:
check_time = int(b.data['last_chk']) - int(b.data['latency'])
else:
check_time = int(b.data['last_chk'])
# Custom hosts variables
hname = sanitize_name(host_name)
if host_name in self.hosts_cache:
if self.hosts_cache[host_name].get('_GRAPHITE_GROUP', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_GROUP'), hname))
if self.hosts_cache[host_name].get('_GRAPHITE_PRE', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_PRE'), hname))
# Custom services variables
desc = sanitize_name(service_description)
if service_id in self.services_cache:
if self.services_cache[service_id].get('_GRAPHITE_POST', None):
desc = ".".join((desc, self.services_cache[service_id].get('_GRAPHITE_POST', None)))
# Graphite data source
if self.graphite_data_source:
path = '.'.join((hname, self.graphite_data_source, desc))
else:
path = '.'.join((hname, desc))
# Realm as a prefix
if self.realms_prefix and self.hosts_cache[host_name].get('realm_name', None):
path = '.'.join((self.hosts_cache[host_name].get('realm_name'), path))
realm_name = None
if host_name in self.hosts_cache:
realm_name = self.hosts_cache[host_name].get('realm_name', None)
# Send metrics
self.send_to_tsdb(realm_name, host_name, service_description, metrics, check_time, path) | [
"def",
"manage_service_check_result_brok",
"(",
"self",
",",
"b",
")",
":",
"# pylint: disable=too-many-branches",
"host_name",
"=",
"b",
".",
"data",
".",
"get",
"(",
"'host_name'",
",",
"None",
")",
"service_description",
"=",
"b",
".",
"data",
".",
"get",
"... | A service check result brok has just arrived ... | [
"A",
"service",
"check",
"result",
"brok",
"has",
"just",
"arrived",
"..."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L629-L688 |
21,065 | Alignak-monitoring/alignak | alignak/modules/inner_metrics.py | InnerMetrics.manage_host_check_result_brok | def manage_host_check_result_brok(self, b): # pylint: disable=too-many-branches
"""An host check result brok has just arrived..."""
host_name = b.data.get('host_name', None)
if not host_name:
return
logger.debug("host check result: %s", host_name)
# If host initial status brok has not been received, ignore ...
if host_name not in self.hosts_cache and not self.ignore_unknown:
logger.warning("received host check result for an unknown host: %s", host_name)
return
# Decode received metrics
metrics = self.get_metrics_from_perfdata('host_check', b.data['perf_data'])
if not metrics:
logger.debug("no metrics to send ...")
return
# If checks latency is ignored
if self.ignore_latency_limit >= b.data['latency'] > 0:
check_time = int(b.data['last_chk']) - int(b.data['latency'])
else:
check_time = int(b.data['last_chk'])
# Custom hosts variables
hname = sanitize_name(host_name)
if host_name in self.hosts_cache:
if self.hosts_cache[host_name].get('_GRAPHITE_GROUP', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_GROUP'), hname))
if self.hosts_cache[host_name].get('_GRAPHITE_PRE', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_PRE'), hname))
# Graphite data source
if self.graphite_data_source:
path = '.'.join((hname, self.graphite_data_source))
if self.hostcheck:
path = '.'.join((hname, self.graphite_data_source, self.hostcheck))
else:
path = '.'.join((hname, self.hostcheck))
# Realm as a prefix
if self.realms_prefix and self.hosts_cache[host_name].get('realm_name', None):
path = '.'.join((self.hosts_cache[host_name].get('realm_name'), path))
realm_name = None
if host_name in self.hosts_cache:
realm_name = self.hosts_cache[host_name].get('realm_name', None)
# Send metrics
self.send_to_tsdb(realm_name, host_name, self.hostcheck, metrics, check_time, path) | python | def manage_host_check_result_brok(self, b): # pylint: disable=too-many-branches
host_name = b.data.get('host_name', None)
if not host_name:
return
logger.debug("host check result: %s", host_name)
# If host initial status brok has not been received, ignore ...
if host_name not in self.hosts_cache and not self.ignore_unknown:
logger.warning("received host check result for an unknown host: %s", host_name)
return
# Decode received metrics
metrics = self.get_metrics_from_perfdata('host_check', b.data['perf_data'])
if not metrics:
logger.debug("no metrics to send ...")
return
# If checks latency is ignored
if self.ignore_latency_limit >= b.data['latency'] > 0:
check_time = int(b.data['last_chk']) - int(b.data['latency'])
else:
check_time = int(b.data['last_chk'])
# Custom hosts variables
hname = sanitize_name(host_name)
if host_name in self.hosts_cache:
if self.hosts_cache[host_name].get('_GRAPHITE_GROUP', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_GROUP'), hname))
if self.hosts_cache[host_name].get('_GRAPHITE_PRE', None):
hname = ".".join((self.hosts_cache[host_name].get('_GRAPHITE_PRE'), hname))
# Graphite data source
if self.graphite_data_source:
path = '.'.join((hname, self.graphite_data_source))
if self.hostcheck:
path = '.'.join((hname, self.graphite_data_source, self.hostcheck))
else:
path = '.'.join((hname, self.hostcheck))
# Realm as a prefix
if self.realms_prefix and self.hosts_cache[host_name].get('realm_name', None):
path = '.'.join((self.hosts_cache[host_name].get('realm_name'), path))
realm_name = None
if host_name in self.hosts_cache:
realm_name = self.hosts_cache[host_name].get('realm_name', None)
# Send metrics
self.send_to_tsdb(realm_name, host_name, self.hostcheck, metrics, check_time, path) | [
"def",
"manage_host_check_result_brok",
"(",
"self",
",",
"b",
")",
":",
"# pylint: disable=too-many-branches",
"host_name",
"=",
"b",
".",
"data",
".",
"get",
"(",
"'host_name'",
",",
"None",
")",
"if",
"not",
"host_name",
":",
"return",
"logger",
".",
"debug... | An host check result brok has just arrived... | [
"An",
"host",
"check",
"result",
"brok",
"has",
"just",
"arrived",
"..."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/modules/inner_metrics.py#L690-L740 |
21,066 | Alignak-monitoring/alignak | alignak/comment.py | Comment.get_comment_brok | def get_comment_brok(self, host_name, service_name=''):
"""Get a comment brok
:param host_name:
:param 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': 'comment', 'data': data}) | python | def get_comment_brok(self, host_name, service_name=''):
data = self.serialize()
data['host'] = host_name
if service_name:
data['service'] = service_name
return Brok({'type': 'comment', 'data': data}) | [
"def",
"get_comment_brok",
"(",
"self",
",",
"host_name",
",",
"service_name",
"=",
"''",
")",
":",
"data",
"=",
"self",
".",
"serialize",
"(",
")",
"data",
"[",
"'host'",
"]",
"=",
"host_name",
"if",
"service_name",
":",
"data",
"[",
"'service'",
"]",
... | Get a comment brok
:param host_name:
:param service_name:
:return: brok with wanted data
:rtype: alignak.brok.Brok | [
"Get",
"a",
"comment",
"brok"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/comment.py#L124-L137 |
21,067 | Alignak-monitoring/alignak | alignak/objects/notificationway.py | NotificationWays.new_inner_member | def new_inner_member(self, name, params):
"""Create new instance of NotificationWay with given name and parameters
and add it to the item list
:param name: notification way name
:type name: str
:param params: notification wat parameters
:type params: dict
:return: None
"""
params['notificationway_name'] = name
self.add_item(NotificationWay(params)) | python | def new_inner_member(self, name, params):
params['notificationway_name'] = name
self.add_item(NotificationWay(params)) | [
"def",
"new_inner_member",
"(",
"self",
",",
"name",
",",
"params",
")",
":",
"params",
"[",
"'notificationway_name'",
"]",
"=",
"name",
"self",
".",
"add_item",
"(",
"NotificationWay",
"(",
"params",
")",
")"
] | Create new instance of NotificationWay with given name and parameters
and add it to the item list
:param name: notification way name
:type name: str
:param params: notification wat parameters
:type params: dict
:return: None | [
"Create",
"new",
"instance",
"of",
"NotificationWay",
"with",
"given",
"name",
"and",
"parameters",
"and",
"add",
"it",
"to",
"the",
"item",
"list"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/notificationway.py#L389-L400 |
21,068 | Alignak-monitoring/alignak | alignak/misc/serialization.py | serialize | def serialize(obj, no_dump=False):
"""
Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if True return dict, otherwise return a json
:type no_dump: bool
:return: dict or json dumps dict with the following structure ::
{'__sys_python_module__': "%s.%s" % (o_cls.__module__, o_cls.__name__)
'content' : obj.serialize()}
:rtype: dict | str
"""
# print("Serialize (%s): %s" % (no_dump, obj))
if hasattr(obj, "serialize") and isinstance(obj.serialize, collections.Callable):
o_dict = {
'__sys_python_module__': "%s.%s" % (obj.__class__.__module__, obj.__class__.__name__),
'content': obj.serialize()
}
elif isinstance(obj, dict):
o_dict = {}
for key, value in list(obj.items()):
o_dict[key] = serialize(value, True)
elif isinstance(obj, (list, set)):
o_dict = [serialize(item, True) for item in obj]
else:
o_dict = obj
if no_dump:
return o_dict
result = None
try:
result = json.dumps(o_dict, ensure_ascii=False)
except MemoryError:
return {'_error': 'Not enough memory on this computer to correctly manage Alignak '
'objects serialization! '
'Sorry for this, please log an issue in the project repository.'}
return result | python | def serialize(obj, no_dump=False):
# print("Serialize (%s): %s" % (no_dump, obj))
if hasattr(obj, "serialize") and isinstance(obj.serialize, collections.Callable):
o_dict = {
'__sys_python_module__': "%s.%s" % (obj.__class__.__module__, obj.__class__.__name__),
'content': obj.serialize()
}
elif isinstance(obj, dict):
o_dict = {}
for key, value in list(obj.items()):
o_dict[key] = serialize(value, True)
elif isinstance(obj, (list, set)):
o_dict = [serialize(item, True) for item in obj]
else:
o_dict = obj
if no_dump:
return o_dict
result = None
try:
result = json.dumps(o_dict, ensure_ascii=False)
except MemoryError:
return {'_error': 'Not enough memory on this computer to correctly manage Alignak '
'objects serialization! '
'Sorry for this, please log an issue in the project repository.'}
return result | [
"def",
"serialize",
"(",
"obj",
",",
"no_dump",
"=",
"False",
")",
":",
"# print(\"Serialize (%s): %s\" % (no_dump, obj))",
"if",
"hasattr",
"(",
"obj",
",",
"\"serialize\"",
")",
"and",
"isinstance",
"(",
"obj",
".",
"serialize",
",",
"collections",
".",
"Calla... | Serialize an object.
Returns a dict containing an `_error` property if a MemoryError happens during the
object serialization. See #369.
:param obj: the object to serialize
:type obj: alignak.objects.item.Item | dict | list | str
:param no_dump: if True return dict, otherwise return a json
:type no_dump: bool
:return: dict or json dumps dict with the following structure ::
{'__sys_python_module__': "%s.%s" % (o_cls.__module__, o_cls.__name__)
'content' : obj.serialize()}
:rtype: dict | str | [
"Serialize",
"an",
"object",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/misc/serialization.py#L31-L78 |
21,069 | Alignak-monitoring/alignak | alignak/brok.py | Brok.get_event | def get_event(self):
"""This function returns an Event from a Brok
If the type is monitoring_log then the Brok contains a monitoring event
(alert, notification, ...) information. This function will return a tuple
with the creation time, the level and message information
:return: tuple with date, level and message
:rtype: tuple
"""
self.prepare()
return (self.creation_time, self.data['level'], self.data['message']) | python | def get_event(self):
self.prepare()
return (self.creation_time, self.data['level'], self.data['message']) | [
"def",
"get_event",
"(",
"self",
")",
":",
"self",
".",
"prepare",
"(",
")",
"return",
"(",
"self",
".",
"creation_time",
",",
"self",
".",
"data",
"[",
"'level'",
"]",
",",
"self",
".",
"data",
"[",
"'message'",
"]",
")"
] | This function returns an Event from a Brok
If the type is monitoring_log then the Brok contains a monitoring event
(alert, notification, ...) information. This function will return a tuple
with the creation time, the level and message information
:return: tuple with date, level and message
:rtype: tuple | [
"This",
"function",
"returns",
"an",
"Event",
"from",
"a",
"Brok"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/brok.py#L116-L127 |
21,070 | Alignak-monitoring/alignak | alignak/brok.py | Brok.prepare | def prepare(self):
"""Un-serialize data from data attribute and add instance_id key if necessary
:return: None
"""
# Maybe the Brok is a old daemon one or was already prepared
# if so, the data is already ok
if hasattr(self, 'prepared') and not self.prepared:
self.data = unserialize(self.data)
if self.instance_id:
self.data['instance_id'] = self.instance_id
self.prepared = True | python | def prepare(self):
# Maybe the Brok is a old daemon one or was already prepared
# if so, the data is already ok
if hasattr(self, 'prepared') and not self.prepared:
self.data = unserialize(self.data)
if self.instance_id:
self.data['instance_id'] = self.instance_id
self.prepared = True | [
"def",
"prepare",
"(",
"self",
")",
":",
"# Maybe the Brok is a old daemon one or was already prepared",
"# if so, the data is already ok",
"if",
"hasattr",
"(",
"self",
",",
"'prepared'",
")",
"and",
"not",
"self",
".",
"prepared",
":",
"self",
".",
"data",
"=",
"u... | Un-serialize data from data attribute and add instance_id key if necessary
:return: None | [
"Un",
"-",
"serialize",
"data",
"from",
"data",
"attribute",
"and",
"add",
"instance_id",
"key",
"if",
"necessary"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/brok.py#L144-L155 |
21,071 | Alignak-monitoring/alignak | alignak/complexexpression.py | ComplexExpressionNode.resolve_elements | def resolve_elements(self):
"""Get element of this node recursively
Compute rules with OR or AND rule then NOT rules.
:return: set of element
:rtype: set
"""
# If it's a leaf, we just need to dump a set with the content of the node
if self.leaf:
if not self.content:
return set()
return set(self.content)
# first got the not ones in a list, and the other in the other list
not_nodes = [s for s in self.sons if s.not_value]
positiv_nodes = [s for s in self.sons if not s.not_value] # ok a not not is hard to read..
# By default we are using a OR rule
if not self.operand:
self.operand = '|'
res = set()
# The operand will change the positiv loop only
i = 0
for node in positiv_nodes:
node_members = node.resolve_elements()
if self.operand == '|':
res = res.union(node_members)
elif self.operand == '&':
# The first elements of an AND rule should be used
if i == 0:
res = node_members
else:
res = res.intersection(node_members)
i += 1
# And we finally remove all NOT elements from the result
for node in not_nodes:
node_members = node.resolve_elements()
res = res.difference(node_members)
return res | python | def resolve_elements(self):
# If it's a leaf, we just need to dump a set with the content of the node
if self.leaf:
if not self.content:
return set()
return set(self.content)
# first got the not ones in a list, and the other in the other list
not_nodes = [s for s in self.sons if s.not_value]
positiv_nodes = [s for s in self.sons if not s.not_value] # ok a not not is hard to read..
# By default we are using a OR rule
if not self.operand:
self.operand = '|'
res = set()
# The operand will change the positiv loop only
i = 0
for node in positiv_nodes:
node_members = node.resolve_elements()
if self.operand == '|':
res = res.union(node_members)
elif self.operand == '&':
# The first elements of an AND rule should be used
if i == 0:
res = node_members
else:
res = res.intersection(node_members)
i += 1
# And we finally remove all NOT elements from the result
for node in not_nodes:
node_members = node.resolve_elements()
res = res.difference(node_members)
return res | [
"def",
"resolve_elements",
"(",
"self",
")",
":",
"# If it's a leaf, we just need to dump a set with the content of the node",
"if",
"self",
".",
"leaf",
":",
"if",
"not",
"self",
".",
"content",
":",
"return",
"set",
"(",
")",
"return",
"set",
"(",
"self",
".",
... | Get element of this node recursively
Compute rules with OR or AND rule then NOT rules.
:return: set of element
:rtype: set | [
"Get",
"element",
"of",
"this",
"node",
"recursively",
"Compute",
"rules",
"with",
"OR",
"or",
"AND",
"rule",
"then",
"NOT",
"rules",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/complexexpression.py#L72-L114 |
21,072 | Alignak-monitoring/alignak | alignak/complexexpression.py | ComplexExpressionFactory.eval_cor_pattern | def eval_cor_pattern(self, pattern): # pylint:disable=too-many-branches
"""Parse and build recursively a tree of ComplexExpressionNode from pattern
:param pattern: pattern to parse
:type pattern: str
:return: root node of parsed tree
:type: alignak.complexexpression.ComplexExpressionNode
"""
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
node = ComplexExpressionNode()
# if it's a single expression like !linux or production
# (where "linux" and "production" are hostgroup names)
# we will get the objects from it and return a leaf node
if not complex_node:
# 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:]
node.operand = self.ctx
node.leaf = True
obj, error = self.find_object(pattern)
if obj is not None:
node.content = obj
else:
node.configuration_errors.append(error)
return node
in_par = False
tmp = ''
stacked_par = 0
for char in pattern:
if char in (',', '|'):
# Maybe we are in a par, if so, just stack it
if in_par:
tmp += char
else:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
node.operand = '|'
if tmp != '':
son = self.eval_cor_pattern(tmp)
node.sons.append(son)
tmp = ''
elif char in ('&', '+'):
# Maybe we are in a par, if so, just stack it
if in_par:
tmp += char
else:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
node.operand = '&'
if tmp != '':
son = self.eval_cor_pattern(tmp)
node.sons.append(son)
tmp = ''
elif char == '(':
stacked_par += 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_par == 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_par > 1:
tmp += char
elif char == ')':
stacked_par -= 1
if stacked_par < 0:
# TODO : real error
print("Error : bad expression near", tmp, "too much ')'")
continue
if stacked_par == 0:
tmp = tmp.strip()
son = self.eval_cor_pattern(tmp)
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
# Maybe it's a classic character, 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)
node.sons.append(son)
return node | python | def eval_cor_pattern(self, pattern): # pylint:disable=too-many-branches
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
node = ComplexExpressionNode()
# if it's a single expression like !linux or production
# (where "linux" and "production" are hostgroup names)
# we will get the objects from it and return a leaf node
if not complex_node:
# 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:]
node.operand = self.ctx
node.leaf = True
obj, error = self.find_object(pattern)
if obj is not None:
node.content = obj
else:
node.configuration_errors.append(error)
return node
in_par = False
tmp = ''
stacked_par = 0
for char in pattern:
if char in (',', '|'):
# Maybe we are in a par, if so, just stack it
if in_par:
tmp += char
else:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
node.operand = '|'
if tmp != '':
son = self.eval_cor_pattern(tmp)
node.sons.append(son)
tmp = ''
elif char in ('&', '+'):
# Maybe we are in a par, if so, just stack it
if in_par:
tmp += char
else:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
node.operand = '&'
if tmp != '':
son = self.eval_cor_pattern(tmp)
node.sons.append(son)
tmp = ''
elif char == '(':
stacked_par += 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_par == 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_par > 1:
tmp += char
elif char == ')':
stacked_par -= 1
if stacked_par < 0:
# TODO : real error
print("Error : bad expression near", tmp, "too much ')'")
continue
if stacked_par == 0:
tmp = tmp.strip()
son = self.eval_cor_pattern(tmp)
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
# Maybe it's a classic character, 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)
node.sons.append(son)
return node | [
"def",
"eval_cor_pattern",
"(",
"self",
",",
"pattern",
")",
":",
"# pylint:disable=too-many-branches",
"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/ser... | Parse and build recursively a tree of ComplexExpressionNode from pattern
:param pattern: pattern to parse
:type pattern: str
:return: root node of parsed tree
:type: alignak.complexexpression.ComplexExpressionNode | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"ComplexExpressionNode",
"from",
"pattern"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/complexexpression.py#L147-L261 |
21,073 | Alignak-monitoring/alignak | alignak/complexexpression.py | ComplexExpressionFactory.find_object | def find_object(self, pattern):
"""Get a list of host corresponding to the pattern regarding the context
:param pattern: pattern to find
:type pattern: str
:return: Host list matching pattern (hostgroup name, template, all)
:rtype: list[alignak.objects.host.Host]
"""
obj = None
error = None
pattern = pattern.strip()
if pattern == '*':
obj = [h.host_name for h in list(self.all_elements.items.values())
if getattr(h, 'host_name', '') != '' and not h.is_tpl()]
return obj, error
# Ok a more classic way
if self.ctx == 'hostgroups':
# Ok try to find this hostgroup
hgr = self.grps.find_by_name(pattern)
# Maybe it's an known one?
if not hgr:
error = "Error : cannot find the %s of the expression '%s'" % (self.ctx, pattern)
return hgr, error
# Ok the group is found, get the elements!
elts = hgr.get_hosts()
elts = strip_and_uniq(elts)
# Maybe the hostgroup memebrs is '*', if so expand with all hosts
if '*' in elts:
elts.extend([h.host_name for h in list(self.all_elements.items.values())
if getattr(h, 'host_name', '') != '' and not h.is_tpl()])
# And remove this strange hostname too :)
elts.remove('*')
return elts, error
obj = self.grps.find_hosts_that_use_template(pattern)
return obj, error | python | def find_object(self, pattern):
obj = None
error = None
pattern = pattern.strip()
if pattern == '*':
obj = [h.host_name for h in list(self.all_elements.items.values())
if getattr(h, 'host_name', '') != '' and not h.is_tpl()]
return obj, error
# Ok a more classic way
if self.ctx == 'hostgroups':
# Ok try to find this hostgroup
hgr = self.grps.find_by_name(pattern)
# Maybe it's an known one?
if not hgr:
error = "Error : cannot find the %s of the expression '%s'" % (self.ctx, pattern)
return hgr, error
# Ok the group is found, get the elements!
elts = hgr.get_hosts()
elts = strip_and_uniq(elts)
# Maybe the hostgroup memebrs is '*', if so expand with all hosts
if '*' in elts:
elts.extend([h.host_name for h in list(self.all_elements.items.values())
if getattr(h, 'host_name', '') != '' and not h.is_tpl()])
# And remove this strange hostname too :)
elts.remove('*')
return elts, error
obj = self.grps.find_hosts_that_use_template(pattern)
return obj, error | [
"def",
"find_object",
"(",
"self",
",",
"pattern",
")",
":",
"obj",
"=",
"None",
"error",
"=",
"None",
"pattern",
"=",
"pattern",
".",
"strip",
"(",
")",
"if",
"pattern",
"==",
"'*'",
":",
"obj",
"=",
"[",
"h",
".",
"host_name",
"for",
"h",
"in",
... | Get a list of host corresponding to the pattern regarding the context
:param pattern: pattern to find
:type pattern: str
:return: Host list matching pattern (hostgroup name, template, all)
:rtype: list[alignak.objects.host.Host] | [
"Get",
"a",
"list",
"of",
"host",
"corresponding",
"to",
"the",
"pattern",
"regarding",
"the",
"context"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/complexexpression.py#L263-L303 |
21,074 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.all_my_hosts_and_services | def all_my_hosts_and_services(self):
"""Create an iterator for all my known hosts and services
:return: None
"""
for what in (self.hosts, self.services):
for item in what:
yield item | python | def all_my_hosts_and_services(self):
for what in (self.hosts, self.services):
for item in what:
yield item | [
"def",
"all_my_hosts_and_services",
"(",
"self",
")",
":",
"for",
"what",
"in",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
")",
":",
"for",
"item",
"in",
"what",
":",
"yield",
"item"
] | Create an iterator for all my known hosts and services
:return: None | [
"Create",
"an",
"iterator",
"for",
"all",
"my",
"known",
"hosts",
"and",
"services"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L265-L272 |
21,075 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.load_conf | def load_conf(self, instance_id, instance_name, conf):
"""Load configuration received from Arbiter and pushed by our Scheduler daemon
:param instance_name: scheduler instance name
:type instance_name: str
:param instance_id: scheduler instance id
:type instance_id: str
:param conf: configuration to load
:type conf: alignak.objects.config.Config
:return: None
"""
self.pushed_conf = conf
logger.info("loading my configuration (%s / %s):",
instance_id, self.pushed_conf.instance_id)
logger.debug("Properties:")
for key in sorted(self.pushed_conf.properties):
logger.debug("- %s: %s", key, getattr(self.pushed_conf, key, []))
logger.debug("Macros:")
for key in sorted(self.pushed_conf.macros):
logger.debug("- %s: %s", key, getattr(self.pushed_conf.macros, key, []))
logger.debug("Objects types:")
for _, _, strclss, _, _ in list(self.pushed_conf.types_creations.values()):
if strclss in ['arbiters', 'schedulers', 'brokers',
'pollers', 'reactionners', 'receivers']:
continue
setattr(self, strclss, getattr(self.pushed_conf, strclss, []))
# Internal statistics
logger.debug("- %d %s", len(getattr(self, strclss)), strclss)
statsmgr.gauge('configuration.%s' % strclss, len(getattr(self, strclss)))
# We need reversed list for searching in the retention file read
# todo: check what it is about...
self.services.optimize_service_search(self.hosts)
# Just deprecated
# # Compile the triggers
# if getattr(self, 'triggers', None):
# logger.info("compiling the triggers...")
# self.triggers.compile()
# self.triggers.load_objects(self)
# else:
# logger.info("No triggers")
# From the Arbiter configuration. Used for satellites to differentiate the schedulers
self.alignak_name = self.pushed_conf.alignak_name
self.instance_id = instance_id
self.instance_name = instance_name
self.push_flavor = getattr(self.pushed_conf, 'push_flavor', 'None')
logger.info("Set my scheduler instance: %s - %s - %s",
self.instance_id, self.instance_name, self.push_flavor)
# Tag our monitored hosts/services with our instance_id
for item in self.all_my_hosts_and_services():
item.instance_id = self.instance_id | python | def load_conf(self, instance_id, instance_name, conf):
self.pushed_conf = conf
logger.info("loading my configuration (%s / %s):",
instance_id, self.pushed_conf.instance_id)
logger.debug("Properties:")
for key in sorted(self.pushed_conf.properties):
logger.debug("- %s: %s", key, getattr(self.pushed_conf, key, []))
logger.debug("Macros:")
for key in sorted(self.pushed_conf.macros):
logger.debug("- %s: %s", key, getattr(self.pushed_conf.macros, key, []))
logger.debug("Objects types:")
for _, _, strclss, _, _ in list(self.pushed_conf.types_creations.values()):
if strclss in ['arbiters', 'schedulers', 'brokers',
'pollers', 'reactionners', 'receivers']:
continue
setattr(self, strclss, getattr(self.pushed_conf, strclss, []))
# Internal statistics
logger.debug("- %d %s", len(getattr(self, strclss)), strclss)
statsmgr.gauge('configuration.%s' % strclss, len(getattr(self, strclss)))
# We need reversed list for searching in the retention file read
# todo: check what it is about...
self.services.optimize_service_search(self.hosts)
# Just deprecated
# # Compile the triggers
# if getattr(self, 'triggers', None):
# logger.info("compiling the triggers...")
# self.triggers.compile()
# self.triggers.load_objects(self)
# else:
# logger.info("No triggers")
# From the Arbiter configuration. Used for satellites to differentiate the schedulers
self.alignak_name = self.pushed_conf.alignak_name
self.instance_id = instance_id
self.instance_name = instance_name
self.push_flavor = getattr(self.pushed_conf, 'push_flavor', 'None')
logger.info("Set my scheduler instance: %s - %s - %s",
self.instance_id, self.instance_name, self.push_flavor)
# Tag our monitored hosts/services with our instance_id
for item in self.all_my_hosts_and_services():
item.instance_id = self.instance_id | [
"def",
"load_conf",
"(",
"self",
",",
"instance_id",
",",
"instance_name",
",",
"conf",
")",
":",
"self",
".",
"pushed_conf",
"=",
"conf",
"logger",
".",
"info",
"(",
"\"loading my configuration (%s / %s):\"",
",",
"instance_id",
",",
"self",
".",
"pushed_conf",... | Load configuration received from Arbiter and pushed by our Scheduler daemon
:param instance_name: scheduler instance name
:type instance_name: str
:param instance_id: scheduler instance id
:type instance_id: str
:param conf: configuration to load
:type conf: alignak.objects.config.Config
:return: None | [
"Load",
"configuration",
"received",
"from",
"Arbiter",
"and",
"pushed",
"by",
"our",
"Scheduler",
"daemon"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L274-L329 |
21,076 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.update_recurrent_works_tick | def update_recurrent_works_tick(self, conf):
"""Modify the tick value for the scheduler recurrent work
A tick is an amount of loop of the scheduler before executing the recurrent work
The provided configuration may contain some tick-function_name keys that contain
a tick value to be updated. Those parameters are defined in the alignak environment file.
Indeed this function is called with the Scheduler daemon object. Note that the ``conf``
parameter may also be a dictionary.
:param conf: the daemon link configuration to search in
:type conf: alignak.daemons.schedulerdaemon.Alignak
:return: None
"""
for key in self.recurrent_works:
(name, fun, _) = self.recurrent_works[key]
if isinstance(conf, dict):
new_tick = conf.get('tick_%s' % name, None)
else:
new_tick = getattr(conf, 'tick_%s' % name, None)
if new_tick is not None:
logger.debug("Requesting to change the default tick to %d for the action %s",
int(new_tick), name)
else:
continue
# Update the default scheduler tick for this function
try:
new_tick = int(new_tick)
logger.info("Changing the default tick to %d for the action %s", new_tick, name)
self.recurrent_works[key] = (name, fun, new_tick)
except ValueError:
logger.warning("Changing the default tick for '%s' to '%s' failed!", new_tick, name) | python | def update_recurrent_works_tick(self, conf):
for key in self.recurrent_works:
(name, fun, _) = self.recurrent_works[key]
if isinstance(conf, dict):
new_tick = conf.get('tick_%s' % name, None)
else:
new_tick = getattr(conf, 'tick_%s' % name, None)
if new_tick is not None:
logger.debug("Requesting to change the default tick to %d for the action %s",
int(new_tick), name)
else:
continue
# Update the default scheduler tick for this function
try:
new_tick = int(new_tick)
logger.info("Changing the default tick to %d for the action %s", new_tick, name)
self.recurrent_works[key] = (name, fun, new_tick)
except ValueError:
logger.warning("Changing the default tick for '%s' to '%s' failed!", new_tick, name) | [
"def",
"update_recurrent_works_tick",
"(",
"self",
",",
"conf",
")",
":",
"for",
"key",
"in",
"self",
".",
"recurrent_works",
":",
"(",
"name",
",",
"fun",
",",
"_",
")",
"=",
"self",
".",
"recurrent_works",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"c... | Modify the tick value for the scheduler recurrent work
A tick is an amount of loop of the scheduler before executing the recurrent work
The provided configuration may contain some tick-function_name keys that contain
a tick value to be updated. Those parameters are defined in the alignak environment file.
Indeed this function is called with the Scheduler daemon object. Note that the ``conf``
parameter may also be a dictionary.
:param conf: the daemon link configuration to search in
:type conf: alignak.daemons.schedulerdaemon.Alignak
:return: None | [
"Modify",
"the",
"tick",
"value",
"for",
"the",
"scheduler",
"recurrent",
"work"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L331-L364 |
21,077 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.dump_config | def dump_config(self):
"""Dump scheduler configuration into a temporary file
The dumped content is JSON formatted
:return: None
"""
path = os.path.join(tempfile.gettempdir(),
'dump-cfg-scheduler-%s-%d.json' % (self.name, int(time.time())))
try:
self.pushed_conf.dump(path)
except (OSError, IndexError) as exp: # pragma: no cover, should never happen...
logger.critical("Error when writing the configuration dump file %s: %s",
path, str(exp)) | python | def dump_config(self):
path = os.path.join(tempfile.gettempdir(),
'dump-cfg-scheduler-%s-%d.json' % (self.name, int(time.time())))
try:
self.pushed_conf.dump(path)
except (OSError, IndexError) as exp: # pragma: no cover, should never happen...
logger.critical("Error when writing the configuration dump file %s: %s",
path, str(exp)) | [
"def",
"dump_config",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'dump-cfg-scheduler-%s-%d.json'",
"%",
"(",
"self",
".",
"name",
",",
"int",
"(",
"time",
".",
"time",
"(",
... | Dump scheduler configuration into a temporary file
The dumped content is JSON formatted
:return: None | [
"Dump",
"scheduler",
"configuration",
"into",
"a",
"temporary",
"file"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L421-L435 |
21,078 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.add_notification | def add_notification(self, notification):
"""Add a notification into actions list
:param notification: notification to add
:type notification: alignak.notification.Notification
:return: None
"""
if notification.uuid in self.actions:
logger.warning("Already existing notification: %s", notification)
return
logger.debug("Adding a notification: %s", notification)
self.actions[notification.uuid] = notification
self.nb_notifications += 1
# A notification which is not a master one asks for a brok
if notification.contact is not None:
self.add(notification.get_initial_status_brok()) | python | def add_notification(self, notification):
if notification.uuid in self.actions:
logger.warning("Already existing notification: %s", notification)
return
logger.debug("Adding a notification: %s", notification)
self.actions[notification.uuid] = notification
self.nb_notifications += 1
# A notification which is not a master one asks for a brok
if notification.contact is not None:
self.add(notification.get_initial_status_brok()) | [
"def",
"add_notification",
"(",
"self",
",",
"notification",
")",
":",
"if",
"notification",
".",
"uuid",
"in",
"self",
".",
"actions",
":",
"logger",
".",
"warning",
"(",
"\"Already existing notification: %s\"",
",",
"notification",
")",
"return",
"logger",
"."... | Add a notification into actions list
:param notification: notification to add
:type notification: alignak.notification.Notification
:return: None | [
"Add",
"a",
"notification",
"into",
"actions",
"list"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L503-L520 |
21,079 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.add_check | def add_check(self, check):
"""Add a check into the scheduler checks list
:param check: check to add
:type check: alignak.check.Check
:return: None
"""
if check is None:
return
if check.uuid in self.checks:
logger.debug("Already existing check: %s", check)
return
logger.debug("Adding a check: %s", check)
# Add a new check to the scheduler checks list
self.checks[check.uuid] = check
self.nb_checks += 1
# Raise a brok to inform about a next check is to come ...
# but only for items that are actively checked
item = self.find_item_by_id(check.ref)
if item.active_checks_enabled:
self.add(item.get_next_schedule_brok()) | python | def add_check(self, check):
if check is None:
return
if check.uuid in self.checks:
logger.debug("Already existing check: %s", check)
return
logger.debug("Adding a check: %s", check)
# Add a new check to the scheduler checks list
self.checks[check.uuid] = check
self.nb_checks += 1
# Raise a brok to inform about a next check is to come ...
# but only for items that are actively checked
item = self.find_item_by_id(check.ref)
if item.active_checks_enabled:
self.add(item.get_next_schedule_brok()) | [
"def",
"add_check",
"(",
"self",
",",
"check",
")",
":",
"if",
"check",
"is",
"None",
":",
"return",
"if",
"check",
".",
"uuid",
"in",
"self",
".",
"checks",
":",
"logger",
".",
"debug",
"(",
"\"Already existing check: %s\"",
",",
"check",
")",
"return",... | Add a check into the scheduler checks list
:param check: check to add
:type check: alignak.check.Check
:return: None | [
"Add",
"a",
"check",
"into",
"the",
"scheduler",
"checks",
"list"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L522-L544 |
21,080 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.add_event_handler | def add_event_handler(self, action):
"""Add a event handler into actions list
:param action: event handler to add
:type action: alignak.eventhandler.EventHandler
:return: None
"""
if action.uuid in self.actions:
logger.info("Already existing event handler: %s", action)
return
self.actions[action.uuid] = action
self.nb_event_handlers += 1 | python | def add_event_handler(self, action):
if action.uuid in self.actions:
logger.info("Already existing event handler: %s", action)
return
self.actions[action.uuid] = action
self.nb_event_handlers += 1 | [
"def",
"add_event_handler",
"(",
"self",
",",
"action",
")",
":",
"if",
"action",
".",
"uuid",
"in",
"self",
".",
"actions",
":",
"logger",
".",
"info",
"(",
"\"Already existing event handler: %s\"",
",",
"action",
")",
"return",
"self",
".",
"actions",
"[",... | Add a event handler into actions list
:param action: event handler to add
:type action: alignak.eventhandler.EventHandler
:return: None | [
"Add",
"a",
"event",
"handler",
"into",
"actions",
"list"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L546-L558 |
21,081 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.hook_point | def hook_point(self, hook_name):
"""Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None
"""
self.my_daemon.hook_point(hook_name=hook_name, handle=self) | python | def hook_point(self, hook_name):
self.my_daemon.hook_point(hook_name=hook_name, handle=self) | [
"def",
"hook_point",
"(",
"self",
",",
"hook_name",
")",
":",
"self",
".",
"my_daemon",
".",
"hook_point",
"(",
"hook_name",
"=",
"hook_name",
",",
"handle",
"=",
"self",
")"
] | Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None | [
"Generic",
"function",
"to",
"call",
"modules",
"methods",
"if",
"such",
"method",
"is",
"avalaible"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L600-L607 |
21,082 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.clean_queues | def clean_queues(self):
# pylint: disable=too-many-locals
"""Reduces internal list size to max allowed
* checks and broks : 5 * length of hosts + services
* actions : 5 * length of hosts + services + contacts
:return: None
"""
# If we set the interval at 0, we bail out
if getattr(self.pushed_conf, 'tick_clean_queues', 0) == 0:
logger.debug("No queues cleaning...")
return
max_checks = MULTIPLIER_MAX_CHECKS * (len(self.hosts) + len(self.services))
max_broks = MULTIPLIER_MAX_BROKS * (len(self.hosts) + len(self.services))
max_actions = MULTIPLIER_MAX_ACTIONS * len(self.contacts) * (len(self.hosts) +
len(self.services))
# For checks, it's not very simple:
# For checks, they may be referred to their host/service
# We do not just del them in the check list, but also in their service/host
# We want id of lower than max_id - 2*max_checks
self.nb_checks_dropped = 0
if max_checks and len(self.checks) > max_checks:
# keys does not ensure sorted keys. Max is slow but we have no other way.
to_del_checks = [c for c in list(self.checks.values())]
to_del_checks.sort(key=lambda x: x.creation_time)
to_del_checks = to_del_checks[:-max_checks]
self.nb_checks_dropped = len(to_del_checks)
if to_del_checks:
logger.warning("I have to drop some checks (%d)..., sorry :(",
self.nb_checks_dropped)
for chk in to_del_checks:
c_id = chk.uuid
items = getattr(self, chk.ref_type + 's')
elt = items[chk.ref]
# First remove the link in host/service
elt.remove_in_progress_check(chk)
# Then in dependent checks (I depend on, or check
# depend on me)
for dependent_checks in chk.depend_on_me:
dependent_checks.depend_on.remove(chk.uuid)
for c_temp in chk.depend_on:
c_temp.depend_on_me.remove(chk)
del self.checks[c_id] # Final Bye bye ...
# For broks and actions, it's more simple
# or broks, manage global but also all brokers
self.nb_broks_dropped = 0
for broker_link in list(self.my_daemon.brokers.values()):
if max_broks and len(broker_link.broks) > max_broks:
logger.warning("I have to drop some broks (%d > %d) for the broker %s "
"..., sorry :(", len(broker_link.broks), max_broks, broker_link)
kept_broks = sorted(broker_link.broks, key=lambda x: x.creation_time)
# Delete the oldest broks to keep the max_broks most recent...
# todo: is it a good choice !
broker_link.broks = kept_broks[0:max_broks]
self.nb_actions_dropped = 0
if max_actions and len(self.actions) > max_actions:
logger.warning("I have to del some actions (currently: %d, max: %d)..., sorry :(",
len(self.actions), max_actions)
to_del_actions = [c for c in list(self.actions.values())]
to_del_actions.sort(key=lambda x: x.creation_time)
to_del_actions = to_del_actions[:-max_actions]
self.nb_actions_dropped = len(to_del_actions)
for act in to_del_actions:
if act.is_a == 'notification':
self.find_item_by_id(act.ref).remove_in_progress_notification(act)
del self.actions[act.uuid] | python | def clean_queues(self):
# pylint: disable=too-many-locals
# If we set the interval at 0, we bail out
if getattr(self.pushed_conf, 'tick_clean_queues', 0) == 0:
logger.debug("No queues cleaning...")
return
max_checks = MULTIPLIER_MAX_CHECKS * (len(self.hosts) + len(self.services))
max_broks = MULTIPLIER_MAX_BROKS * (len(self.hosts) + len(self.services))
max_actions = MULTIPLIER_MAX_ACTIONS * len(self.contacts) * (len(self.hosts) +
len(self.services))
# For checks, it's not very simple:
# For checks, they may be referred to their host/service
# We do not just del them in the check list, but also in their service/host
# We want id of lower than max_id - 2*max_checks
self.nb_checks_dropped = 0
if max_checks and len(self.checks) > max_checks:
# keys does not ensure sorted keys. Max is slow but we have no other way.
to_del_checks = [c for c in list(self.checks.values())]
to_del_checks.sort(key=lambda x: x.creation_time)
to_del_checks = to_del_checks[:-max_checks]
self.nb_checks_dropped = len(to_del_checks)
if to_del_checks:
logger.warning("I have to drop some checks (%d)..., sorry :(",
self.nb_checks_dropped)
for chk in to_del_checks:
c_id = chk.uuid
items = getattr(self, chk.ref_type + 's')
elt = items[chk.ref]
# First remove the link in host/service
elt.remove_in_progress_check(chk)
# Then in dependent checks (I depend on, or check
# depend on me)
for dependent_checks in chk.depend_on_me:
dependent_checks.depend_on.remove(chk.uuid)
for c_temp in chk.depend_on:
c_temp.depend_on_me.remove(chk)
del self.checks[c_id] # Final Bye bye ...
# For broks and actions, it's more simple
# or broks, manage global but also all brokers
self.nb_broks_dropped = 0
for broker_link in list(self.my_daemon.brokers.values()):
if max_broks and len(broker_link.broks) > max_broks:
logger.warning("I have to drop some broks (%d > %d) for the broker %s "
"..., sorry :(", len(broker_link.broks), max_broks, broker_link)
kept_broks = sorted(broker_link.broks, key=lambda x: x.creation_time)
# Delete the oldest broks to keep the max_broks most recent...
# todo: is it a good choice !
broker_link.broks = kept_broks[0:max_broks]
self.nb_actions_dropped = 0
if max_actions and len(self.actions) > max_actions:
logger.warning("I have to del some actions (currently: %d, max: %d)..., sorry :(",
len(self.actions), max_actions)
to_del_actions = [c for c in list(self.actions.values())]
to_del_actions.sort(key=lambda x: x.creation_time)
to_del_actions = to_del_actions[:-max_actions]
self.nb_actions_dropped = len(to_del_actions)
for act in to_del_actions:
if act.is_a == 'notification':
self.find_item_by_id(act.ref).remove_in_progress_notification(act)
del self.actions[act.uuid] | [
"def",
"clean_queues",
"(",
"self",
")",
":",
"# pylint: disable=too-many-locals",
"# If we set the interval at 0, we bail out",
"if",
"getattr",
"(",
"self",
".",
"pushed_conf",
",",
"'tick_clean_queues'",
",",
"0",
")",
"==",
"0",
":",
"logger",
".",
"debug",
"(",... | Reduces internal list size to max allowed
* checks and broks : 5 * length of hosts + services
* actions : 5 * length of hosts + services + contacts
:return: None | [
"Reduces",
"internal",
"list",
"size",
"to",
"max",
"allowed"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L609-L680 |
21,083 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.update_business_values | def update_business_values(self):
"""Iter over host and service and update business_impact
:return: None
"""
for elt in self.all_my_hosts_and_services():
if not elt.is_problem:
was = elt.business_impact
elt.update_business_impact_value(self.hosts, self.services,
self.timeperiods, self.businessimpactmodulations)
new = elt.business_impact
# Ok, the business_impact change, we can update the broks
if new != was:
self.get_and_register_status_brok(elt)
# When all impacts and classic elements are updated,
# we can update problems (their value depend on impacts, so
# they must be done after)
for elt in self.all_my_hosts_and_services():
# We first update impacts and classic elements
if elt.is_problem:
was = elt.business_impact
elt.update_business_impact_value(self.hosts, self.services,
self.timeperiods, self.businessimpactmodulations)
new = elt.business_impact
# Maybe one of the impacts change it's business_impact to a high value
# and so ask for the problem to raise too
if new != was:
self.get_and_register_status_brok(elt) | python | def update_business_values(self):
for elt in self.all_my_hosts_and_services():
if not elt.is_problem:
was = elt.business_impact
elt.update_business_impact_value(self.hosts, self.services,
self.timeperiods, self.businessimpactmodulations)
new = elt.business_impact
# Ok, the business_impact change, we can update the broks
if new != was:
self.get_and_register_status_brok(elt)
# When all impacts and classic elements are updated,
# we can update problems (their value depend on impacts, so
# they must be done after)
for elt in self.all_my_hosts_and_services():
# We first update impacts and classic elements
if elt.is_problem:
was = elt.business_impact
elt.update_business_impact_value(self.hosts, self.services,
self.timeperiods, self.businessimpactmodulations)
new = elt.business_impact
# Maybe one of the impacts change it's business_impact to a high value
# and so ask for the problem to raise too
if new != was:
self.get_and_register_status_brok(elt) | [
"def",
"update_business_values",
"(",
"self",
")",
":",
"for",
"elt",
"in",
"self",
".",
"all_my_hosts_and_services",
"(",
")",
":",
"if",
"not",
"elt",
".",
"is_problem",
":",
"was",
"=",
"elt",
".",
"business_impact",
"elt",
".",
"update_business_impact_valu... | Iter over host and service and update business_impact
:return: None | [
"Iter",
"over",
"host",
"and",
"service",
"and",
"update",
"business_impact"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L716-L744 |
21,084 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.scatter_master_notifications | def scatter_master_notifications(self):
"""Generate children notifications from a master notification
Also update notification number
Master notification are raised when a notification must be sent out. They are not
launched by reactionners (only children are) but they are used to build the
children notifications.
From one master notification, several children notifications may be built,
indeed one per each contact...
:return: None
"""
now = time.time()
# We only want the master scheduled notifications that are immediately launchable
notifications = [a for a in self.actions.values()
if a.is_a == u'notification' and a.status == ACT_STATUS_SCHEDULED
and not a.contact and a.is_launchable(now)]
if notifications:
logger.debug("Scatter master notification: %d notifications",
len(notifications))
for notification in notifications:
logger.debug("Scheduler got a master notification: %s", notification)
# This is a "master" notification created by an host/service.
# We use it to create children notifications (for the contacts and
# notification_commands) which are executed in the reactionner.
item = self.find_item_by_id(notification.ref)
children = []
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
if not item.is_blocking_notifications(notification_period,
self.hosts, self.services,
notification.type, now):
# If it is possible to send notifications
# of this type at the current time, then create
# a single notification for each contact of this item.
children = item.scatter_notification(
notification, self.contacts, self.notificationways, self.timeperiods,
self.macromodulations, self.escalations,
self.find_item_by_id(getattr(item, "host", None))
)
for notif in children:
logger.debug(" - child notification: %s", notif)
notif.status = ACT_STATUS_SCHEDULED
# Add the notification to the scheduler objects
self.add(notif)
# If we have notification_interval then schedule
# the next notification (problems only)
if notification.type == u'PROBLEM':
# Update the ref notif number after raise the one of the notification
if children:
# notif_nb of the master notification
# was already current_notification_number+1.
# If notifications were sent,
# then host/service-counter will also be incremented
item.current_notification_number = notification.notif_nb
if item.notification_interval and notification.t_to_go is not None:
# We must continue to send notifications.
# Just leave it in the actions list and set it to "scheduled"
# and it will be found again later
# Ask the service/host to compute the next notif time. It can be just
# a.t_to_go + item.notification_interval*item.__class__.interval_length
# or maybe before because we have an
# escalation that need to raise up before
notification.t_to_go = item.get_next_notification_time(notification,
self.escalations,
self.timeperiods)
notification.notif_nb = item.current_notification_number + 1
logger.debug("Repeat master notification: %s", notification)
else:
# Wipe out this master notification. It is a master one
item.remove_in_progress_notification(notification)
logger.debug("Remove master notification (no repeat): %s", notification)
else:
# Wipe out this master notification.
logger.debug("Remove master notification (no more a problem): %s", notification)
# We don't repeat recover/downtime/flap/etc...
item.remove_in_progress_notification(notification) | python | def scatter_master_notifications(self):
now = time.time()
# We only want the master scheduled notifications that are immediately launchable
notifications = [a for a in self.actions.values()
if a.is_a == u'notification' and a.status == ACT_STATUS_SCHEDULED
and not a.contact and a.is_launchable(now)]
if notifications:
logger.debug("Scatter master notification: %d notifications",
len(notifications))
for notification in notifications:
logger.debug("Scheduler got a master notification: %s", notification)
# This is a "master" notification created by an host/service.
# We use it to create children notifications (for the contacts and
# notification_commands) which are executed in the reactionner.
item = self.find_item_by_id(notification.ref)
children = []
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
if not item.is_blocking_notifications(notification_period,
self.hosts, self.services,
notification.type, now):
# If it is possible to send notifications
# of this type at the current time, then create
# a single notification for each contact of this item.
children = item.scatter_notification(
notification, self.contacts, self.notificationways, self.timeperiods,
self.macromodulations, self.escalations,
self.find_item_by_id(getattr(item, "host", None))
)
for notif in children:
logger.debug(" - child notification: %s", notif)
notif.status = ACT_STATUS_SCHEDULED
# Add the notification to the scheduler objects
self.add(notif)
# If we have notification_interval then schedule
# the next notification (problems only)
if notification.type == u'PROBLEM':
# Update the ref notif number after raise the one of the notification
if children:
# notif_nb of the master notification
# was already current_notification_number+1.
# If notifications were sent,
# then host/service-counter will also be incremented
item.current_notification_number = notification.notif_nb
if item.notification_interval and notification.t_to_go is not None:
# We must continue to send notifications.
# Just leave it in the actions list and set it to "scheduled"
# and it will be found again later
# Ask the service/host to compute the next notif time. It can be just
# a.t_to_go + item.notification_interval*item.__class__.interval_length
# or maybe before because we have an
# escalation that need to raise up before
notification.t_to_go = item.get_next_notification_time(notification,
self.escalations,
self.timeperiods)
notification.notif_nb = item.current_notification_number + 1
logger.debug("Repeat master notification: %s", notification)
else:
# Wipe out this master notification. It is a master one
item.remove_in_progress_notification(notification)
logger.debug("Remove master notification (no repeat): %s", notification)
else:
# Wipe out this master notification.
logger.debug("Remove master notification (no more a problem): %s", notification)
# We don't repeat recover/downtime/flap/etc...
item.remove_in_progress_notification(notification) | [
"def",
"scatter_master_notifications",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# We only want the master scheduled notifications that are immediately launchable",
"notifications",
"=",
"[",
"a",
"for",
"a",
"in",
"self",
".",
"actions",
".",... | Generate children notifications from a master notification
Also update notification number
Master notification are raised when a notification must be sent out. They are not
launched by reactionners (only children are) but they are used to build the
children notifications.
From one master notification, several children notifications may be built,
indeed one per each contact...
:return: None | [
"Generate",
"children",
"notifications",
"from",
"a",
"master",
"notification",
"Also",
"update",
"notification",
"number"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L746-L828 |
21,085 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.manage_internal_checks | def manage_internal_checks(self):
"""Run internal checks
:return: None
"""
if os.getenv('ALIGNAK_MANAGE_INTERNAL', '1') != '1':
return
now = time.time()
for chk in list(self.checks.values()):
if not chk.internal:
# Exclude checks that are not internal ones
continue
# Exclude checks that are not yet ready to launch
if not chk.is_launchable(now) or chk.status not in [ACT_STATUS_SCHEDULED]:
continue
item = self.find_item_by_id(chk.ref)
# Only if active checks are enabled
if not item or not item.active_checks_enabled:
# Ask to remove the check
chk.status = ACT_STATUS_ZOMBIE
continue
logger.debug("Run internal check for %s", item)
self.nb_internal_checks += 1
# Execute internal check
item.manage_internal_check(self.hosts, self.services, chk, self.hostgroups,
self.servicegroups, self.macromodulations,
self.timeperiods)
# Ask to consume the check result
chk.status = ACT_STATUS_WAIT_CONSUME | python | def manage_internal_checks(self):
if os.getenv('ALIGNAK_MANAGE_INTERNAL', '1') != '1':
return
now = time.time()
for chk in list(self.checks.values()):
if not chk.internal:
# Exclude checks that are not internal ones
continue
# Exclude checks that are not yet ready to launch
if not chk.is_launchable(now) or chk.status not in [ACT_STATUS_SCHEDULED]:
continue
item = self.find_item_by_id(chk.ref)
# Only if active checks are enabled
if not item or not item.active_checks_enabled:
# Ask to remove the check
chk.status = ACT_STATUS_ZOMBIE
continue
logger.debug("Run internal check for %s", item)
self.nb_internal_checks += 1
# Execute internal check
item.manage_internal_check(self.hosts, self.services, chk, self.hostgroups,
self.servicegroups, self.macromodulations,
self.timeperiods)
# Ask to consume the check result
chk.status = ACT_STATUS_WAIT_CONSUME | [
"def",
"manage_internal_checks",
"(",
"self",
")",
":",
"if",
"os",
".",
"getenv",
"(",
"'ALIGNAK_MANAGE_INTERNAL'",
",",
"'1'",
")",
"!=",
"'1'",
":",
"return",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"chk",
"in",
"list",
"(",
"self",
".",
... | Run internal checks
:return: None | [
"Run",
"internal",
"checks"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1190-L1222 |
21,086 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.reset_topology_change_flag | def reset_topology_change_flag(self):
"""Set topology_change attribute to False in all hosts and services
:return: None
"""
for i in self.hosts:
i.topology_change = False
for i in self.services:
i.topology_change = False | python | def reset_topology_change_flag(self):
for i in self.hosts:
i.topology_change = False
for i in self.services:
i.topology_change = False | [
"def",
"reset_topology_change_flag",
"(",
"self",
")",
":",
"for",
"i",
"in",
"self",
".",
"hosts",
":",
"i",
".",
"topology_change",
"=",
"False",
"for",
"i",
"in",
"self",
".",
"services",
":",
"i",
".",
"topology_change",
"=",
"False"
] | Set topology_change attribute to False in all hosts and services
:return: None | [
"Set",
"topology_change",
"attribute",
"to",
"False",
"in",
"all",
"hosts",
"and",
"services"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1224-L1232 |
21,087 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.log_initial_states | def log_initial_states(self):
"""Raise hosts and services initial status logs
First, raise hosts status and then services. This to allow the events log
to be a little sorted.
:return: None
"""
# Raise hosts initial status broks
for elt in self.hosts:
elt.raise_initial_state()
# And then services initial status broks
for elt in self.services:
elt.raise_initial_state() | python | def log_initial_states(self):
# Raise hosts initial status broks
for elt in self.hosts:
elt.raise_initial_state()
# And then services initial status broks
for elt in self.services:
elt.raise_initial_state() | [
"def",
"log_initial_states",
"(",
"self",
")",
":",
"# Raise hosts initial status broks",
"for",
"elt",
"in",
"self",
".",
"hosts",
":",
"elt",
".",
"raise_initial_state",
"(",
")",
"# And then services initial status broks",
"for",
"elt",
"in",
"self",
".",
"servic... | Raise hosts and services initial status logs
First, raise hosts status and then services. This to allow the events log
to be a little sorted.
:return: None | [
"Raise",
"hosts",
"and",
"services",
"initial",
"status",
"logs"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1276-L1290 |
21,088 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.get_retention_data | def get_retention_data(self): # pylint: disable=too-many-branches,too-many-statements
# pylint: disable=too-many-locals
"""Get all hosts and services data to be sent to the retention storage.
This function only prepares the data because a module is in charge of making
the data survive to the scheduler restart.
todo: Alignak scheduler creates two separate dictionaries: hosts and services
It would be better to merge the services into the host dictionary!
:return: dict containing host and service data
:rtype: dict
"""
retention_data = {
'hosts': {}, 'services': {}
}
for host in self.hosts:
h_dict = {}
# Get the hosts properties and running properties
properties = host.__class__.properties
properties.update(host.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
val = getattr(host, prop)
# If a preparation function exists...
prepare_retention = entry.retention_preparation
if prepare_retention:
val = prepare_retention(host, val)
h_dict[prop] = val
retention_data['hosts'][host.host_name] = h_dict
logger.info('%d hosts sent to retention', len(retention_data['hosts']))
# Same for services
for service in self.services:
s_dict = {}
# Get the services properties and running properties
properties = service.__class__.properties
properties.update(service.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
val = getattr(service, prop)
# If a preparation function exists...
prepare_retention = entry.retention_preparation
if prepare_retention:
val = prepare_retention(service, val)
s_dict[prop] = val
retention_data['services'][(service.host_name, service.service_description)] = s_dict
logger.info('%d services sent to retention', len(retention_data['services']))
return retention_data | python | def get_retention_data(self): # pylint: disable=too-many-branches,too-many-statements
# pylint: disable=too-many-locals
retention_data = {
'hosts': {}, 'services': {}
}
for host in self.hosts:
h_dict = {}
# Get the hosts properties and running properties
properties = host.__class__.properties
properties.update(host.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
val = getattr(host, prop)
# If a preparation function exists...
prepare_retention = entry.retention_preparation
if prepare_retention:
val = prepare_retention(host, val)
h_dict[prop] = val
retention_data['hosts'][host.host_name] = h_dict
logger.info('%d hosts sent to retention', len(retention_data['hosts']))
# Same for services
for service in self.services:
s_dict = {}
# Get the services properties and running properties
properties = service.__class__.properties
properties.update(service.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
val = getattr(service, prop)
# If a preparation function exists...
prepare_retention = entry.retention_preparation
if prepare_retention:
val = prepare_retention(service, val)
s_dict[prop] = val
retention_data['services'][(service.host_name, service.service_description)] = s_dict
logger.info('%d services sent to retention', len(retention_data['services']))
return retention_data | [
"def",
"get_retention_data",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches,too-many-statements",
"# pylint: disable=too-many-locals",
"retention_data",
"=",
"{",
"'hosts'",
":",
"{",
"}",
",",
"'services'",
":",
"{",
"}",
"}",
"for",
"host",
"in",
"self"... | Get all hosts and services data to be sent to the retention storage.
This function only prepares the data because a module is in charge of making
the data survive to the scheduler restart.
todo: Alignak scheduler creates two separate dictionaries: hosts and services
It would be better to merge the services into the host dictionary!
:return: dict containing host and service data
:rtype: dict | [
"Get",
"all",
"hosts",
"and",
"services",
"data",
"to",
"be",
"sent",
"to",
"the",
"retention",
"storage",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1292-L1349 |
21,089 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.restore_retention_data | def restore_retention_data(self, data):
"""Restore retention data
Data coming from retention will override data coming from configuration
It is kinda confusing when you modify an attribute (external command) and it get saved
by retention
:param data: data from retention
:type data: dict
:return: None
"""
if 'hosts' not in data:
logger.warning("Retention data are not correct, no 'hosts' property!")
return
for host_name in data['hosts']:
# We take the dict of our value to load
host = self.hosts.find_by_name(host_name)
if host is not None:
self.restore_retention_data_item(data['hosts'][host_name], host)
statsmgr.gauge('retention.hosts', len(data['hosts']))
logger.info('%d hosts restored from retention', len(data['hosts']))
# Same for services
for (host_name, service_description) in data['services']:
# We take our dict to load
service = self.services.find_srv_by_name_and_hostname(host_name, service_description)
if service is not None:
self.restore_retention_data_item(data['services'][(host_name, service_description)],
service)
statsmgr.gauge('retention.services', len(data['services']))
logger.info('%d services restored from retention', len(data['services'])) | python | def restore_retention_data(self, data):
if 'hosts' not in data:
logger.warning("Retention data are not correct, no 'hosts' property!")
return
for host_name in data['hosts']:
# We take the dict of our value to load
host = self.hosts.find_by_name(host_name)
if host is not None:
self.restore_retention_data_item(data['hosts'][host_name], host)
statsmgr.gauge('retention.hosts', len(data['hosts']))
logger.info('%d hosts restored from retention', len(data['hosts']))
# Same for services
for (host_name, service_description) in data['services']:
# We take our dict to load
service = self.services.find_srv_by_name_and_hostname(host_name, service_description)
if service is not None:
self.restore_retention_data_item(data['services'][(host_name, service_description)],
service)
statsmgr.gauge('retention.services', len(data['services']))
logger.info('%d services restored from retention', len(data['services'])) | [
"def",
"restore_retention_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"'hosts'",
"not",
"in",
"data",
":",
"logger",
".",
"warning",
"(",
"\"Retention data are not correct, no 'hosts' property!\"",
")",
"return",
"for",
"host_name",
"in",
"data",
"[",
"'hosts... | Restore retention data
Data coming from retention will override data coming from configuration
It is kinda confusing when you modify an attribute (external command) and it get saved
by retention
:param data: data from retention
:type data: dict
:return: None | [
"Restore",
"retention",
"data"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1351-L1382 |
21,090 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.restore_retention_data_item | def restore_retention_data_item(self, data, item):
# pylint: disable=too-many-branches, too-many-locals
"""
Restore data in item
:param data: retention data of the item
:type data: dict
:param item: host or service item
:type item: alignak.objects.host.Host | alignak.objects.service.Service
:return: None
"""
# Manage the properties and running properties
properties = item.__class__.properties
properties.update(item.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
if prop not in data:
continue
# If a restoration function exists...
restore_retention = entry.retention_restoration
if restore_retention:
setattr(item, prop, restore_retention(item, data[prop]))
else:
setattr(item, prop, data[prop])
# Now manage all linked objects load from/ previous run
for notification_uuid in item.notifications_in_progress:
notification = item.notifications_in_progress[notification_uuid]
# Update the notification referenced object
notification['ref'] = item.uuid
my_notification = Notification(params=notification)
item.notifications_in_progress[notification_uuid] = my_notification
# Add a notification in the scheduler actions
self.add(my_notification)
# todo: is it useful? We do not save/restore checks in the retention data...
item.update_in_checking()
# And also add downtimes and comments
# Downtimes are in a list..
for downtime_uuid in data['downtimes']:
downtime = data['downtimes'][downtime_uuid]
# Update the downtime referenced object
downtime['ref'] = item.uuid
my_downtime = Downtime(params=downtime)
if downtime['comment_id']:
if downtime['comment_id'] not in data['comments']:
downtime['comment_id'] = ''
# case comment_id has comment dict instead uuid
# todo: This should never happen! Why this code ?
if 'uuid' in downtime['comment_id']:
data['comments'].append(downtime['comment_id'])
downtime['comment_id'] = downtime['comment_id']['uuid']
item.add_downtime(my_downtime)
# Comments are in a list..
for comment_uuid in data['comments']:
comment = data['comments'][comment_uuid]
# Update the comment referenced object
comment['ref'] = item.uuid
item.add_comment(Comment(comment))
if item.acknowledgement is not None:
# Update the comment referenced object
item.acknowledgement['ref'] = item.uuid
item.acknowledgement = Acknowledge(item.acknowledgement)
# Relink the notified_contacts as a set() of true contacts objects
# if it was loaded from the retention, it's now a list of contacts
# names
new_notified_contacts = set()
new_notified_contacts_ids = set()
for contact_name in item.notified_contacts:
contact = self.contacts.find_by_name(contact_name)
if contact is not None:
new_notified_contacts.add(contact_name)
new_notified_contacts_ids.add(contact.uuid)
item.notified_contacts = new_notified_contacts
item.notified_contacts_ids = new_notified_contacts_ids | python | def restore_retention_data_item(self, data, item):
# pylint: disable=too-many-branches, too-many-locals
# Manage the properties and running properties
properties = item.__class__.properties
properties.update(item.__class__.running_properties)
for prop, entry in list(properties.items()):
if not entry.retention:
continue
if prop not in data:
continue
# If a restoration function exists...
restore_retention = entry.retention_restoration
if restore_retention:
setattr(item, prop, restore_retention(item, data[prop]))
else:
setattr(item, prop, data[prop])
# Now manage all linked objects load from/ previous run
for notification_uuid in item.notifications_in_progress:
notification = item.notifications_in_progress[notification_uuid]
# Update the notification referenced object
notification['ref'] = item.uuid
my_notification = Notification(params=notification)
item.notifications_in_progress[notification_uuid] = my_notification
# Add a notification in the scheduler actions
self.add(my_notification)
# todo: is it useful? We do not save/restore checks in the retention data...
item.update_in_checking()
# And also add downtimes and comments
# Downtimes are in a list..
for downtime_uuid in data['downtimes']:
downtime = data['downtimes'][downtime_uuid]
# Update the downtime referenced object
downtime['ref'] = item.uuid
my_downtime = Downtime(params=downtime)
if downtime['comment_id']:
if downtime['comment_id'] not in data['comments']:
downtime['comment_id'] = ''
# case comment_id has comment dict instead uuid
# todo: This should never happen! Why this code ?
if 'uuid' in downtime['comment_id']:
data['comments'].append(downtime['comment_id'])
downtime['comment_id'] = downtime['comment_id']['uuid']
item.add_downtime(my_downtime)
# Comments are in a list..
for comment_uuid in data['comments']:
comment = data['comments'][comment_uuid]
# Update the comment referenced object
comment['ref'] = item.uuid
item.add_comment(Comment(comment))
if item.acknowledgement is not None:
# Update the comment referenced object
item.acknowledgement['ref'] = item.uuid
item.acknowledgement = Acknowledge(item.acknowledgement)
# Relink the notified_contacts as a set() of true contacts objects
# if it was loaded from the retention, it's now a list of contacts
# names
new_notified_contacts = set()
new_notified_contacts_ids = set()
for contact_name in item.notified_contacts:
contact = self.contacts.find_by_name(contact_name)
if contact is not None:
new_notified_contacts.add(contact_name)
new_notified_contacts_ids.add(contact.uuid)
item.notified_contacts = new_notified_contacts
item.notified_contacts_ids = new_notified_contacts_ids | [
"def",
"restore_retention_data_item",
"(",
"self",
",",
"data",
",",
"item",
")",
":",
"# pylint: disable=too-many-branches, too-many-locals",
"# Manage the properties and running properties",
"properties",
"=",
"item",
".",
"__class__",
".",
"properties",
"properties",
".",
... | Restore data in item
:param data: retention data of the item
:type data: dict
:param item: host or service item
:type item: alignak.objects.host.Host | alignak.objects.service.Service
:return: None | [
"Restore",
"data",
"in",
"item"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1384-L1468 |
21,091 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.fill_initial_broks | def fill_initial_broks(self, broker_name):
# pylint: disable=too-many-branches
"""Create initial broks for a specific broker
:param broker_name: broker name
:type broker_name: str
:return: number of created broks
"""
broker_uuid = None
logger.debug("My brokers: %s", self.my_daemon.brokers)
for broker_link in list(self.my_daemon.brokers.values()):
logger.debug("Searching broker: %s", broker_link)
if broker_name == broker_link.name:
broker_uuid = broker_link.uuid
logger.info("Filling initial broks for: %s (%s)", broker_name, broker_uuid)
break
else:
if self.pushed_conf:
# I am yet configured but I do not know this broker ! Something went wrong!!!
logger.error("Requested initial broks for an unknown broker: %s", broker_name)
else:
logger.info("Requested initial broks for an unknown broker: %s", broker_name)
return 0
if self.my_daemon.brokers[broker_uuid].initialized:
logger.warning("The broker %s still got its initial broks...", broker_name)
return 0
initial_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)
# First the program status
brok = self.get_program_status_brok()
self.add_brok(brok, broker_uuid)
# We can't call initial_status from all this types
# The order is important, service need host...
initial_status_types = (self.timeperiods, self.commands,
self.contacts, self.contactgroups,
self.hosts, self.hostgroups,
self.services, self.servicegroups)
self.pushed_conf.skip_initial_broks = getattr(self.pushed_conf, 'skip_initial_broks', False)
logger.debug("Skipping initial broks? %s", str(self.pushed_conf.skip_initial_broks))
if not self.pushed_conf.skip_initial_broks:
# We call initial_status from all this types
# The order is important, service need host...
initial_status_types = (self.realms, self.timeperiods, self.commands,
self.notificationways, self.contacts, self.contactgroups,
self.hosts, self.hostgroups, self.hostdependencies,
self.services, self.servicegroups, self.servicedependencies,
self.escalations)
for tab in initial_status_types:
for item in tab:
# Awful! simply to get the group members property name... :(
# todo: replace this!
member_items = None
if hasattr(item, 'members'):
member_items = getattr(self, item.my_type.replace("group", "s"))
brok = item.get_initial_status_brok(member_items)
self.add_brok(brok, broker_uuid)
# Add a brok to say that we finished all initial_pass
brok = Brok({'type': 'initial_broks_done', 'data': {'instance_id': self.instance_id}})
self.add_brok(brok, broker_uuid)
final_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)
self.my_daemon.brokers[broker_uuid].initialized = True
# Send the initial broks to our modules
self.send_broks_to_modules()
# We now have raised all the initial broks
self.raised_initial_broks = True
logger.info("Created %d initial broks for %s",
final_broks_count - initial_broks_count, broker_name)
return final_broks_count - initial_broks_count | python | def fill_initial_broks(self, broker_name):
# pylint: disable=too-many-branches
broker_uuid = None
logger.debug("My brokers: %s", self.my_daemon.brokers)
for broker_link in list(self.my_daemon.brokers.values()):
logger.debug("Searching broker: %s", broker_link)
if broker_name == broker_link.name:
broker_uuid = broker_link.uuid
logger.info("Filling initial broks for: %s (%s)", broker_name, broker_uuid)
break
else:
if self.pushed_conf:
# I am yet configured but I do not know this broker ! Something went wrong!!!
logger.error("Requested initial broks for an unknown broker: %s", broker_name)
else:
logger.info("Requested initial broks for an unknown broker: %s", broker_name)
return 0
if self.my_daemon.brokers[broker_uuid].initialized:
logger.warning("The broker %s still got its initial broks...", broker_name)
return 0
initial_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)
# First the program status
brok = self.get_program_status_brok()
self.add_brok(brok, broker_uuid)
# We can't call initial_status from all this types
# The order is important, service need host...
initial_status_types = (self.timeperiods, self.commands,
self.contacts, self.contactgroups,
self.hosts, self.hostgroups,
self.services, self.servicegroups)
self.pushed_conf.skip_initial_broks = getattr(self.pushed_conf, 'skip_initial_broks', False)
logger.debug("Skipping initial broks? %s", str(self.pushed_conf.skip_initial_broks))
if not self.pushed_conf.skip_initial_broks:
# We call initial_status from all this types
# The order is important, service need host...
initial_status_types = (self.realms, self.timeperiods, self.commands,
self.notificationways, self.contacts, self.contactgroups,
self.hosts, self.hostgroups, self.hostdependencies,
self.services, self.servicegroups, self.servicedependencies,
self.escalations)
for tab in initial_status_types:
for item in tab:
# Awful! simply to get the group members property name... :(
# todo: replace this!
member_items = None
if hasattr(item, 'members'):
member_items = getattr(self, item.my_type.replace("group", "s"))
brok = item.get_initial_status_brok(member_items)
self.add_brok(brok, broker_uuid)
# Add a brok to say that we finished all initial_pass
brok = Brok({'type': 'initial_broks_done', 'data': {'instance_id': self.instance_id}})
self.add_brok(brok, broker_uuid)
final_broks_count = len(self.my_daemon.brokers[broker_uuid].broks)
self.my_daemon.brokers[broker_uuid].initialized = True
# Send the initial broks to our modules
self.send_broks_to_modules()
# We now have raised all the initial broks
self.raised_initial_broks = True
logger.info("Created %d initial broks for %s",
final_broks_count - initial_broks_count, broker_name)
return final_broks_count - initial_broks_count | [
"def",
"fill_initial_broks",
"(",
"self",
",",
"broker_name",
")",
":",
"# pylint: disable=too-many-branches",
"broker_uuid",
"=",
"None",
"logger",
".",
"debug",
"(",
"\"My brokers: %s\"",
",",
"self",
".",
"my_daemon",
".",
"brokers",
")",
"for",
"broker_link",
... | Create initial broks for a specific broker
:param broker_name: broker name
:type broker_name: str
:return: number of created broks | [
"Create",
"initial",
"broks",
"for",
"a",
"specific",
"broker"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1470-L1547 |
21,092 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.get_program_status_brok | def get_program_status_brok(self, brok_type='program_status'):
"""Create a program status brok
Initially builds the running properties and then, if initial status brok,
get the properties from the Config class where an entry exist for the brok
'full_status'
:return: Brok with program status data
:rtype: alignak.brok.Brok
"""
# Get the running statistics
data = {
"is_running": True,
"instance_id": self.instance_id,
# "alignak_name": self.alignak_name,
"instance_name": self.name,
"last_alive": time.time(),
"pid": os.getpid(),
'_running': self.get_scheduler_stats(details=True),
'_config': {},
'_macros': {}
}
# Get configuration data from the pushed configuration
cls = self.pushed_conf.__class__
for prop, entry in list(cls.properties.items()):
# Is this property intended for broking?
if 'full_status' not in entry.fill_brok:
continue
data['_config'][prop] = self.pushed_conf.get_property_value_for_brok(
prop, cls.properties)
# data['_config'][prop] = getattr(self.pushed_conf, prop, entry.default)
# Get the macros from the pushed configuration and try to resolve
# the macros to provide the result in the status brok
macro_resolver = MacroResolver()
macro_resolver.init(self.pushed_conf)
for macro_name in sorted(self.pushed_conf.macros):
data['_macros'][macro_name] = \
macro_resolver.resolve_simple_macros_in_string("$%s$" % macro_name,
[], None, None)
logger.debug("Program status brok %s data: %s", brok_type, data)
return Brok({'type': brok_type, 'data': data}) | python | def get_program_status_brok(self, brok_type='program_status'):
# Get the running statistics
data = {
"is_running": True,
"instance_id": self.instance_id,
# "alignak_name": self.alignak_name,
"instance_name": self.name,
"last_alive": time.time(),
"pid": os.getpid(),
'_running': self.get_scheduler_stats(details=True),
'_config': {},
'_macros': {}
}
# Get configuration data from the pushed configuration
cls = self.pushed_conf.__class__
for prop, entry in list(cls.properties.items()):
# Is this property intended for broking?
if 'full_status' not in entry.fill_brok:
continue
data['_config'][prop] = self.pushed_conf.get_property_value_for_brok(
prop, cls.properties)
# data['_config'][prop] = getattr(self.pushed_conf, prop, entry.default)
# Get the macros from the pushed configuration and try to resolve
# the macros to provide the result in the status brok
macro_resolver = MacroResolver()
macro_resolver.init(self.pushed_conf)
for macro_name in sorted(self.pushed_conf.macros):
data['_macros'][macro_name] = \
macro_resolver.resolve_simple_macros_in_string("$%s$" % macro_name,
[], None, None)
logger.debug("Program status brok %s data: %s", brok_type, data)
return Brok({'type': brok_type, 'data': data}) | [
"def",
"get_program_status_brok",
"(",
"self",
",",
"brok_type",
"=",
"'program_status'",
")",
":",
"# Get the running statistics",
"data",
"=",
"{",
"\"is_running\"",
":",
"True",
",",
"\"instance_id\"",
":",
"self",
".",
"instance_id",
",",
"# \"alignak_name\": self... | Create a program status brok
Initially builds the running properties and then, if initial status brok,
get the properties from the Config class where an entry exist for the brok
'full_status'
:return: Brok with program status data
:rtype: alignak.brok.Brok | [
"Create",
"a",
"program",
"status",
"brok"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1563-L1606 |
21,093 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.consume_results | def consume_results(self): # pylint: disable=too-many-branches
"""Handle results waiting in waiting_results list.
Check ref will call consume result and update their status
:return: None
"""
# All results are in self.waiting_results
# We need to get them first
queue_size = self.waiting_results.qsize()
for _ in range(queue_size):
self.manage_results(self.waiting_results.get())
# Then we consume them
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAIT_CONSUME:
logger.debug("Consuming: %s", chk)
item = self.find_item_by_id(chk.ref)
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
dep_checks = item.consume_result(chk, notification_period, self.hosts,
self.services, self.timeperiods,
self.macromodulations, self.checkmodulations,
self.businessimpactmodulations,
self.resultmodulations, self.checks,
self.pushed_conf.log_active_checks and
not chk.passive_check)
# # Raise the log only when the check got consumed!
# # Else the item information are not up-to-date :/
# if self.pushed_conf.log_active_checks and not chk.passive_check:
# item.raise_check_result()
#
for check in dep_checks:
logger.debug("-> raised a dependency check: %s", chk)
self.add(check)
# loop to resolve dependencies
have_resolved_checks = True
while have_resolved_checks:
have_resolved_checks = False
# All 'finished' checks (no more dep) raise checks they depend on
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAITING_ME:
for dependent_checks in chk.depend_on_me:
# Ok, now dependent will no more wait
dependent_checks.depend_on.remove(chk.uuid)
have_resolved_checks = True
# REMOVE OLD DEP CHECK -> zombie
chk.status = ACT_STATUS_ZOMBIE
# Now, reinteger dep checks
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAIT_DEPEND and not chk.depend_on:
item = self.find_item_by_id(chk.ref)
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
dep_checks = item.consume_result(chk, notification_period, self.hosts,
self.services, self.timeperiods,
self.macromodulations, self.checkmodulations,
self.businessimpactmodulations,
self.resultmodulations, self.checks,
self.pushed_conf.log_active_checks and
not chk.passive_check)
for check in dep_checks:
self.add(check) | python | def consume_results(self): # pylint: disable=too-many-branches
# All results are in self.waiting_results
# We need to get them first
queue_size = self.waiting_results.qsize()
for _ in range(queue_size):
self.manage_results(self.waiting_results.get())
# Then we consume them
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAIT_CONSUME:
logger.debug("Consuming: %s", chk)
item = self.find_item_by_id(chk.ref)
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
dep_checks = item.consume_result(chk, notification_period, self.hosts,
self.services, self.timeperiods,
self.macromodulations, self.checkmodulations,
self.businessimpactmodulations,
self.resultmodulations, self.checks,
self.pushed_conf.log_active_checks and
not chk.passive_check)
# # Raise the log only when the check got consumed!
# # Else the item information are not up-to-date :/
# if self.pushed_conf.log_active_checks and not chk.passive_check:
# item.raise_check_result()
#
for check in dep_checks:
logger.debug("-> raised a dependency check: %s", chk)
self.add(check)
# loop to resolve dependencies
have_resolved_checks = True
while have_resolved_checks:
have_resolved_checks = False
# All 'finished' checks (no more dep) raise checks they depend on
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAITING_ME:
for dependent_checks in chk.depend_on_me:
# Ok, now dependent will no more wait
dependent_checks.depend_on.remove(chk.uuid)
have_resolved_checks = True
# REMOVE OLD DEP CHECK -> zombie
chk.status = ACT_STATUS_ZOMBIE
# Now, reinteger dep checks
for chk in list(self.checks.values()):
if chk.status == ACT_STATUS_WAIT_DEPEND and not chk.depend_on:
item = self.find_item_by_id(chk.ref)
notification_period = None
if getattr(item, 'notification_period', None) is not None:
notification_period = self.timeperiods[item.notification_period]
dep_checks = item.consume_result(chk, notification_period, self.hosts,
self.services, self.timeperiods,
self.macromodulations, self.checkmodulations,
self.businessimpactmodulations,
self.resultmodulations, self.checks,
self.pushed_conf.log_active_checks and
not chk.passive_check)
for check in dep_checks:
self.add(check) | [
"def",
"consume_results",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"# All results are in self.waiting_results",
"# We need to get them first",
"queue_size",
"=",
"self",
".",
"waiting_results",
".",
"qsize",
"(",
")",
"for",
"_",
"in",
"range",
"(",
... | Handle results waiting in waiting_results list.
Check ref will call consume result and update their status
:return: None | [
"Handle",
"results",
"waiting",
"in",
"waiting_results",
"list",
".",
"Check",
"ref",
"will",
"call",
"consume",
"result",
"and",
"update",
"their",
"status"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1608-L1675 |
21,094 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.get_new_actions | def get_new_actions(self):
"""Call 'get_new_actions' hook point
Iter over all hosts and services to add new actions in internal lists
:return: None
"""
_t0 = time.time()
self.hook_point('get_new_actions')
statsmgr.timer('hook.get-new-actions', time.time() - _t0)
# ask for service and hosts their next check
for elt in self.all_my_hosts_and_services():
for action in elt.actions:
logger.debug("Got a new action for %s: %s", elt, action)
self.add(action)
# We take all, we can clear it
elt.actions = [] | python | def get_new_actions(self):
_t0 = time.time()
self.hook_point('get_new_actions')
statsmgr.timer('hook.get-new-actions', time.time() - _t0)
# ask for service and hosts their next check
for elt in self.all_my_hosts_and_services():
for action in elt.actions:
logger.debug("Got a new action for %s: %s", elt, action)
self.add(action)
# We take all, we can clear it
elt.actions = [] | [
"def",
"get_new_actions",
"(",
"self",
")",
":",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"hook_point",
"(",
"'get_new_actions'",
")",
"statsmgr",
".",
"timer",
"(",
"'hook.get-new-actions'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",... | Call 'get_new_actions' hook point
Iter over all hosts and services to add new actions in internal lists
:return: None | [
"Call",
"get_new_actions",
"hook",
"point",
"Iter",
"over",
"all",
"hosts",
"and",
"services",
"to",
"add",
"new",
"actions",
"in",
"internal",
"lists"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1805-L1820 |
21,095 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.get_new_broks | def get_new_broks(self):
"""Iter over all hosts and services to add new broks in internal lists
:return: None
"""
# ask for service and hosts their broks waiting
# be eaten
for elt in self.all_my_hosts_and_services():
for brok in elt.broks:
self.add(brok)
# We got all, clear item broks list
elt.broks = []
# Also fetch broks from contact (like contactdowntime)
for contact in self.contacts:
for brok in contact.broks:
self.add(brok)
# We got all, clear contact broks list
contact.broks = [] | python | def get_new_broks(self):
# ask for service and hosts their broks waiting
# be eaten
for elt in self.all_my_hosts_and_services():
for brok in elt.broks:
self.add(brok)
# We got all, clear item broks list
elt.broks = []
# Also fetch broks from contact (like contactdowntime)
for contact in self.contacts:
for brok in contact.broks:
self.add(brok)
# We got all, clear contact broks list
contact.broks = [] | [
"def",
"get_new_broks",
"(",
"self",
")",
":",
"# ask for service and hosts their broks waiting",
"# be eaten",
"for",
"elt",
"in",
"self",
".",
"all_my_hosts_and_services",
"(",
")",
":",
"for",
"brok",
"in",
"elt",
".",
"broks",
":",
"self",
".",
"add",
"(",
... | Iter over all hosts and services to add new broks in internal lists
:return: None | [
"Iter",
"over",
"all",
"hosts",
"and",
"services",
"to",
"add",
"new",
"broks",
"in",
"internal",
"lists"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1822-L1840 |
21,096 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.send_broks_to_modules | def send_broks_to_modules(self):
"""Put broks into module queues
Only broks without sent_to_externals to True are sent
Only modules that ask for broks will get some
:return: None
"""
t00 = time.time()
nb_sent = 0
broks = []
for broker_link in list(self.my_daemon.brokers.values()):
for brok in broker_link.broks:
if not getattr(brok, 'sent_to_externals', False):
brok.to_send = True
broks.append(brok)
if not broks:
return
logger.debug("sending %d broks to modules...", len(broks))
for mod in self.my_daemon.modules_manager.get_external_instances():
logger.debug("Look for sending to module %s", mod.get_name())
module_queue = mod.to_q
if module_queue:
to_send = [b for b in broks if mod.want_brok(b)]
module_queue.put(to_send)
nb_sent += len(to_send)
# No more need to send them
for broker_link in list(self.my_daemon.brokers.values()):
for brok in broker_link.broks:
if not getattr(brok, 'sent_to_externals', False):
brok.to_send = False
brok.sent_to_externals = True
logger.debug("Time to send %d broks (after %d secs)", nb_sent, time.time() - t00) | python | def send_broks_to_modules(self):
t00 = time.time()
nb_sent = 0
broks = []
for broker_link in list(self.my_daemon.brokers.values()):
for brok in broker_link.broks:
if not getattr(brok, 'sent_to_externals', False):
brok.to_send = True
broks.append(brok)
if not broks:
return
logger.debug("sending %d broks to modules...", len(broks))
for mod in self.my_daemon.modules_manager.get_external_instances():
logger.debug("Look for sending to module %s", mod.get_name())
module_queue = mod.to_q
if module_queue:
to_send = [b for b in broks if mod.want_brok(b)]
module_queue.put(to_send)
nb_sent += len(to_send)
# No more need to send them
for broker_link in list(self.my_daemon.brokers.values()):
for brok in broker_link.broks:
if not getattr(brok, 'sent_to_externals', False):
brok.to_send = False
brok.sent_to_externals = True
logger.debug("Time to send %d broks (after %d secs)", nb_sent, time.time() - t00) | [
"def",
"send_broks_to_modules",
"(",
"self",
")",
":",
"t00",
"=",
"time",
".",
"time",
"(",
")",
"nb_sent",
"=",
"0",
"broks",
"=",
"[",
"]",
"for",
"broker_link",
"in",
"list",
"(",
"self",
".",
"my_daemon",
".",
"brokers",
".",
"values",
"(",
")",... | Put broks into module queues
Only broks without sent_to_externals to True are sent
Only modules that ask for broks will get some
:return: None | [
"Put",
"broks",
"into",
"module",
"queues",
"Only",
"broks",
"without",
"sent_to_externals",
"to",
"True",
"are",
"sent",
"Only",
"modules",
"that",
"ask",
"for",
"broks",
"will",
"get",
"some"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L1978-L2011 |
21,097 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.find_item_by_id | def find_item_by_id(self, object_id):
"""Get item based on its id or uuid
:param object_id:
:type object_id: int | str
:return:
:rtype: alignak.objects.item.Item | None
"""
# Item id may be an item
if isinstance(object_id, Item):
return object_id
# Item id should be a uuid string
if not isinstance(object_id, string_types):
logger.debug("Find an item by id, object_id is not int nor string: %s", object_id)
return object_id
for items in [self.hosts, self.services, self.actions, self.checks, self.hostgroups,
self.servicegroups, self.contacts, self.contactgroups]:
if object_id in items:
return items[object_id]
# raise AttributeError("Item with id %s not found" % object_id) # pragma: no cover,
logger.error("Item with id %s not found", str(object_id)) # pragma: no cover,
return None | python | def find_item_by_id(self, object_id):
# Item id may be an item
if isinstance(object_id, Item):
return object_id
# Item id should be a uuid string
if not isinstance(object_id, string_types):
logger.debug("Find an item by id, object_id is not int nor string: %s", object_id)
return object_id
for items in [self.hosts, self.services, self.actions, self.checks, self.hostgroups,
self.servicegroups, self.contacts, self.contactgroups]:
if object_id in items:
return items[object_id]
# raise AttributeError("Item with id %s not found" % object_id) # pragma: no cover,
logger.error("Item with id %s not found", str(object_id)) # pragma: no cover,
return None | [
"def",
"find_item_by_id",
"(",
"self",
",",
"object_id",
")",
":",
"# Item id may be an item",
"if",
"isinstance",
"(",
"object_id",
",",
"Item",
")",
":",
"return",
"object_id",
"# Item id should be a uuid string",
"if",
"not",
"isinstance",
"(",
"object_id",
",",
... | Get item based on its id or uuid
:param object_id:
:type object_id: int | str
:return:
:rtype: alignak.objects.item.Item | None | [
"Get",
"item",
"based",
"on",
"its",
"id",
"or",
"uuid"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L2203-L2227 |
21,098 | Alignak-monitoring/alignak | alignak/scheduler.py | Scheduler.before_run | def before_run(self):
"""Initialize the scheduling process"""
# Actions and checks counters
self.nb_checks = 0
self.nb_internal_checks = 0
self.nb_checks_launched = 0
self.nb_actions_launched = 0
self.nb_checks_results = 0
self.nb_checks_results_timeout = 0
self.nb_checks_results_passive = 0
self.nb_checks_results_active = 0
self.nb_actions_results = 0
self.nb_actions_results_timeout = 0
self.nb_actions_results_passive = 0
self.nb_broks_dropped = 0
self.nb_checks_dropped = 0
self.nb_actions_dropped = 0
# Broks, notifications, ... counters
self.nb_broks = 0
self.nb_notifications = 0
self.nb_event_handlers = 0
self.nb_external_commands = 0
self.ticks = 0 | python | def before_run(self):
# Actions and checks counters
self.nb_checks = 0
self.nb_internal_checks = 0
self.nb_checks_launched = 0
self.nb_actions_launched = 0
self.nb_checks_results = 0
self.nb_checks_results_timeout = 0
self.nb_checks_results_passive = 0
self.nb_checks_results_active = 0
self.nb_actions_results = 0
self.nb_actions_results_timeout = 0
self.nb_actions_results_passive = 0
self.nb_broks_dropped = 0
self.nb_checks_dropped = 0
self.nb_actions_dropped = 0
# Broks, notifications, ... counters
self.nb_broks = 0
self.nb_notifications = 0
self.nb_event_handlers = 0
self.nb_external_commands = 0
self.ticks = 0 | [
"def",
"before_run",
"(",
"self",
")",
":",
"# Actions and checks counters",
"self",
".",
"nb_checks",
"=",
"0",
"self",
".",
"nb_internal_checks",
"=",
"0",
"self",
".",
"nb_checks_launched",
"=",
"0",
"self",
".",
"nb_actions_launched",
"=",
"0",
"self",
"."... | Initialize the scheduling process | [
"Initialize",
"the",
"scheduling",
"process"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/scheduler.py#L2230-L2257 |
21,099 | Alignak-monitoring/alignak | alignak/daemons/receiverdaemon.py | Receiver.setup_new_conf | def setup_new_conf(self):
"""Receiver custom setup_new_conf method
This function calls the base satellite treatment and manages the configuration needed
for a receiver daemon:
- get and configure its satellites
- configure the modules
:return: None
"""
# Execute the base class treatment...
super(Receiver, self).setup_new_conf()
# ...then our own specific treatment!
with self.conf_lock:
# self_conf is our own configuration from the alignak environment
# self_conf = self.cur_conf['self_conf']
logger.debug("Got config: %s", self.cur_conf)
# Configure and start our modules
if not self.have_modules:
try:
self.modules = unserialize(self.cur_conf['modules'], no_load=True)
except AlignakClassLookupException as exp: # pragma: no cover, simple protection
logger.error('Cannot un-serialize modules configuration '
'received from arbiter: %s', exp)
if self.modules:
logger.info("I received some modules configuration: %s", self.modules)
self.have_modules = True
self.do_load_modules(self.modules)
# and start external modules too
self.modules_manager.start_external_instances()
else:
logger.info("I do not have modules")
# Now create the external commands manager
# We are a receiver: our role is to get and dispatch commands to the schedulers
global_conf = self.cur_conf.get('global_conf', None)
if not global_conf:
logger.error("Received a configuration without any global_conf! "
"This may hide a configuration problem with the "
"realms and the manage_sub_realms of the satellites!")
global_conf = {
'accept_passive_unknown_check_results': False,
'log_external_commands': True
}
self.external_commands_manager = \
ExternalCommandManager(None, 'receiver', self,
global_conf.get(
'accept_passive_unknown_check_results', False),
global_conf.get(
'log_external_commands', False))
# Initialize connection with all our satellites
logger.info("Initializing connection with my satellites:")
my_satellites = self.get_links_of_type(s_type='')
for satellite in list(my_satellites.values()):
logger.info("- : %s/%s", satellite.type, satellite.name)
if not self.daemon_connection_init(satellite):
logger.error("Satellite connection failed: %s", satellite)
# Now I have a configuration!
self.have_conf = True | python | def setup_new_conf(self):
# Execute the base class treatment...
super(Receiver, self).setup_new_conf()
# ...then our own specific treatment!
with self.conf_lock:
# self_conf is our own configuration from the alignak environment
# self_conf = self.cur_conf['self_conf']
logger.debug("Got config: %s", self.cur_conf)
# Configure and start our modules
if not self.have_modules:
try:
self.modules = unserialize(self.cur_conf['modules'], no_load=True)
except AlignakClassLookupException as exp: # pragma: no cover, simple protection
logger.error('Cannot un-serialize modules configuration '
'received from arbiter: %s', exp)
if self.modules:
logger.info("I received some modules configuration: %s", self.modules)
self.have_modules = True
self.do_load_modules(self.modules)
# and start external modules too
self.modules_manager.start_external_instances()
else:
logger.info("I do not have modules")
# Now create the external commands manager
# We are a receiver: our role is to get and dispatch commands to the schedulers
global_conf = self.cur_conf.get('global_conf', None)
if not global_conf:
logger.error("Received a configuration without any global_conf! "
"This may hide a configuration problem with the "
"realms and the manage_sub_realms of the satellites!")
global_conf = {
'accept_passive_unknown_check_results': False,
'log_external_commands': True
}
self.external_commands_manager = \
ExternalCommandManager(None, 'receiver', self,
global_conf.get(
'accept_passive_unknown_check_results', False),
global_conf.get(
'log_external_commands', False))
# Initialize connection with all our satellites
logger.info("Initializing connection with my satellites:")
my_satellites = self.get_links_of_type(s_type='')
for satellite in list(my_satellites.values()):
logger.info("- : %s/%s", satellite.type, satellite.name)
if not self.daemon_connection_init(satellite):
logger.error("Satellite connection failed: %s", satellite)
# Now I have a configuration!
self.have_conf = True | [
"def",
"setup_new_conf",
"(",
"self",
")",
":",
"# Execute the base class treatment...",
"super",
"(",
"Receiver",
",",
"self",
")",
".",
"setup_new_conf",
"(",
")",
"# ...then our own specific treatment!",
"with",
"self",
".",
"conf_lock",
":",
"# self_conf is our own ... | Receiver custom setup_new_conf method
This function calls the base satellite treatment and manages the configuration needed
for a receiver daemon:
- get and configure its satellites
- configure the modules
:return: None | [
"Receiver",
"custom",
"setup_new_conf",
"method"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/receiverdaemon.py#L147-L210 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.