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,200
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.get_broks_from_satellites
def get_broks_from_satellites(self): # pragma: no cover - not used! """Get broks from my all internal satellite links The arbiter get the broks from ALL the known satellites :return: None """ for satellites in [self.conf.brokers, self.conf.schedulers, self.conf.pollers, self.conf.reactionners, self.conf.receivers]: for satellite in satellites: # Get only if reachable... if not satellite.reachable: continue logger.debug("Getting broks from: %s", satellite.name) new_broks = satellite.get_and_clear_broks() if new_broks: logger.debug("Got %d broks from: %s", len(new_broks), satellite.name) for brok in new_broks: self.add(brok)
python
def get_broks_from_satellites(self): # pragma: no cover - not used! for satellites in [self.conf.brokers, self.conf.schedulers, self.conf.pollers, self.conf.reactionners, self.conf.receivers]: for satellite in satellites: # Get only if reachable... if not satellite.reachable: continue logger.debug("Getting broks from: %s", satellite.name) new_broks = satellite.get_and_clear_broks() if new_broks: logger.debug("Got %d broks from: %s", len(new_broks), satellite.name) for brok in new_broks: self.add(brok)
[ "def", "get_broks_from_satellites", "(", "self", ")", ":", "# pragma: no cover - not used!", "for", "satellites", "in", "[", "self", ".", "conf", ".", "brokers", ",", "self", ".", "conf", ".", "schedulers", ",", "self", ".", "conf", ".", "pollers", ",", "sel...
Get broks from my all internal satellite links The arbiter get the broks from ALL the known satellites :return: None
[ "Get", "broks", "from", "my", "all", "internal", "satellite", "links" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L327-L345
21,201
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.get_initial_broks_from_satellites
def get_initial_broks_from_satellites(self): """Get initial broks from my internal satellite links :return: None """ for satellites in [self.conf.brokers, self.conf.schedulers, self.conf.pollers, self.conf.reactionners, self.conf.receivers]: for satellite in satellites: # Get only if reachable... if not satellite.reachable: continue logger.debug("Getting initial brok from: %s", satellite.name) brok = satellite.get_initial_status_brok() logger.debug("Satellite '%s' initial brok: %s", satellite.name, brok) self.add(brok)
python
def get_initial_broks_from_satellites(self): for satellites in [self.conf.brokers, self.conf.schedulers, self.conf.pollers, self.conf.reactionners, self.conf.receivers]: for satellite in satellites: # Get only if reachable... if not satellite.reachable: continue logger.debug("Getting initial brok from: %s", satellite.name) brok = satellite.get_initial_status_brok() logger.debug("Satellite '%s' initial brok: %s", satellite.name, brok) self.add(brok)
[ "def", "get_initial_broks_from_satellites", "(", "self", ")", ":", "for", "satellites", "in", "[", "self", ".", "conf", ".", "brokers", ",", "self", ".", "conf", ".", "schedulers", ",", "self", ".", "conf", ".", "pollers", ",", "self", ".", "conf", ".", ...
Get initial broks from my internal satellite links :return: None
[ "Get", "initial", "broks", "from", "my", "internal", "satellite", "links" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L347-L361
21,202
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.load_modules_configuration_objects
def load_modules_configuration_objects(self, raw_objects): # pragma: no cover, # not yet with unit tests. """Load configuration objects from arbiter modules If module implements get_objects arbiter will call it and add create objects :param raw_objects: raw objects we got from reading config files :type raw_objects: dict :return: None """ # Now we ask for configuration modules if they # got items for us for instance in self.modules_manager.instances: logger.debug("Getting objects from the module: %s", instance.name) if not hasattr(instance, 'get_objects'): logger.debug("The module '%s' do not provide any objects.", instance.name) return try: logger.info("Getting Alignak monitored configuration objects from module '%s'", instance.name) got_objects = instance.get_objects() except Exception as exp: # pylint: disable=broad-except logger.exception("Module %s get_objects raised an exception %s. " "Log and continue to run.", instance.name, exp) continue if not got_objects: logger.warning("The module '%s' did not provided any objects.", instance.name) return types_creations = self.conf.types_creations for o_type in types_creations: (_, _, prop, _, _) = types_creations[o_type] if prop in ['arbiters', 'brokers', 'schedulers', 'pollers', 'reactionners', 'receivers', 'modules']: continue if prop not in got_objects: logger.warning("Did not get any '%s' objects from %s", prop, instance.name) continue for obj in got_objects[prop]: # test if raw_objects[k] are already set - if not, add empty array if o_type not in raw_objects: raw_objects[o_type] = [] # Update the imported_from property if the module did not set if 'imported_from' not in obj: obj['imported_from'] = 'module:%s' % instance.name # Append to the raw objects raw_objects[o_type].append(obj) logger.debug("Added %i %s objects from %s", len(got_objects[prop]), o_type, instance.name)
python
def load_modules_configuration_objects(self, raw_objects): # pragma: no cover, # not yet with unit tests. # Now we ask for configuration modules if they # got items for us for instance in self.modules_manager.instances: logger.debug("Getting objects from the module: %s", instance.name) if not hasattr(instance, 'get_objects'): logger.debug("The module '%s' do not provide any objects.", instance.name) return try: logger.info("Getting Alignak monitored configuration objects from module '%s'", instance.name) got_objects = instance.get_objects() except Exception as exp: # pylint: disable=broad-except logger.exception("Module %s get_objects raised an exception %s. " "Log and continue to run.", instance.name, exp) continue if not got_objects: logger.warning("The module '%s' did not provided any objects.", instance.name) return types_creations = self.conf.types_creations for o_type in types_creations: (_, _, prop, _, _) = types_creations[o_type] if prop in ['arbiters', 'brokers', 'schedulers', 'pollers', 'reactionners', 'receivers', 'modules']: continue if prop not in got_objects: logger.warning("Did not get any '%s' objects from %s", prop, instance.name) continue for obj in got_objects[prop]: # test if raw_objects[k] are already set - if not, add empty array if o_type not in raw_objects: raw_objects[o_type] = [] # Update the imported_from property if the module did not set if 'imported_from' not in obj: obj['imported_from'] = 'module:%s' % instance.name # Append to the raw objects raw_objects[o_type].append(obj) logger.debug("Added %i %s objects from %s", len(got_objects[prop]), o_type, instance.name)
[ "def", "load_modules_configuration_objects", "(", "self", ",", "raw_objects", ")", ":", "# pragma: no cover,", "# not yet with unit tests.", "# Now we ask for configuration modules if they", "# got items for us", "for", "instance", "in", "self", ".", "modules_manager", ".", "in...
Load configuration objects from arbiter modules If module implements get_objects arbiter will call it and add create objects :param raw_objects: raw objects we got from reading config files :type raw_objects: dict :return: None
[ "Load", "configuration", "objects", "from", "arbiter", "modules", "If", "module", "implements", "get_objects", "arbiter", "will", "call", "it", "and", "add", "create", "objects" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L821-L871
21,203
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.load_modules_alignak_configuration
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests. """Load Alignak configuration from the arbiter modules If module implements get_alignak_configuration, call this function :param raw_objects: raw objects we got from reading config files :type raw_objects: dict :return: None """ alignak_cfg = {} # Ask configured modules if they got configuration for us for instance in self.modules_manager.instances: if not hasattr(instance, 'get_alignak_configuration'): return try: logger.info("Getting Alignak global configuration from module '%s'", instance.name) cfg = instance.get_alignak_configuration() alignak_cfg.update(cfg) except Exception as exp: # pylint: disable=broad-except logger.error("Module %s get_alignak_configuration raised an exception %s. " "Log and continue to run", instance.name, str(exp)) output = io.StringIO() traceback.print_exc(file=output) logger.error("Back trace of this remove: %s", output.getvalue()) output.close() continue params = [] if alignak_cfg: logger.info("Got Alignak global configuration:") for key, value in sorted(alignak_cfg.items()): logger.info("- %s = %s", key, value) # properties starting with an _ character are "transformed" to macro variables if key.startswith('_'): key = '$' + key[1:].upper() + '$' # properties valued as None are filtered if value is None: continue # properties valued as None string are filtered if value == 'None': continue # properties valued as empty strings are filtered if value == '': continue # set properties as legacy Shinken configuration files params.append("%s=%s" % (key, value)) self.conf.load_params(params)
python
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests. alignak_cfg = {} # Ask configured modules if they got configuration for us for instance in self.modules_manager.instances: if not hasattr(instance, 'get_alignak_configuration'): return try: logger.info("Getting Alignak global configuration from module '%s'", instance.name) cfg = instance.get_alignak_configuration() alignak_cfg.update(cfg) except Exception as exp: # pylint: disable=broad-except logger.error("Module %s get_alignak_configuration raised an exception %s. " "Log and continue to run", instance.name, str(exp)) output = io.StringIO() traceback.print_exc(file=output) logger.error("Back trace of this remove: %s", output.getvalue()) output.close() continue params = [] if alignak_cfg: logger.info("Got Alignak global configuration:") for key, value in sorted(alignak_cfg.items()): logger.info("- %s = %s", key, value) # properties starting with an _ character are "transformed" to macro variables if key.startswith('_'): key = '$' + key[1:].upper() + '$' # properties valued as None are filtered if value is None: continue # properties valued as None string are filtered if value == 'None': continue # properties valued as empty strings are filtered if value == '': continue # set properties as legacy Shinken configuration files params.append("%s=%s" % (key, value)) self.conf.load_params(params)
[ "def", "load_modules_alignak_configuration", "(", "self", ")", ":", "# pragma: no cover, not yet with unit tests.", "alignak_cfg", "=", "{", "}", "# Ask configured modules if they got configuration for us", "for", "instance", "in", "self", ".", "modules_manager", ".", "instance...
Load Alignak configuration from the arbiter modules If module implements get_alignak_configuration, call this function :param raw_objects: raw objects we got from reading config files :type raw_objects: dict :return: None
[ "Load", "Alignak", "configuration", "from", "the", "arbiter", "modules", "If", "module", "implements", "get_alignak_configuration", "call", "this", "function" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L873-L919
21,204
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.request_stop
def request_stop(self, message='', exit_code=0): """Stop the Arbiter daemon :return: None """ # Only a master arbiter can stop the daemons if self.is_master: # Stop the daemons self.daemons_stop(timeout=self.conf.daemons_stop_timeout) # Request the daemon stop super(Arbiter, self).request_stop(message, exit_code)
python
def request_stop(self, message='', exit_code=0): # Only a master arbiter can stop the daemons if self.is_master: # Stop the daemons self.daemons_stop(timeout=self.conf.daemons_stop_timeout) # Request the daemon stop super(Arbiter, self).request_stop(message, exit_code)
[ "def", "request_stop", "(", "self", ",", "message", "=", "''", ",", "exit_code", "=", "0", ")", ":", "# Only a master arbiter can stop the daemons", "if", "self", ".", "is_master", ":", "# Stop the daemons", "self", ".", "daemons_stop", "(", "timeout", "=", "sel...
Stop the Arbiter daemon :return: None
[ "Stop", "the", "Arbiter", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L921-L932
21,205
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.start_daemon
def start_daemon(self, satellite): """Manage the list of detected missing daemons If the daemon does not in exist `my_daemons`, then: - prepare daemon start arguments (port, name and log file) - start the daemon - make sure it started correctly :param satellite: the satellite for which a daemon is to be started :type satellite: SatelliteLink :return: True if the daemon started correctly """ logger.info(" launching a daemon for: %s/%s...", satellite.type, satellite.name) # The daemon startup script location may be defined in the configuration daemon_script_location = getattr(self.conf, 'daemons_script_location', self.bindir) if not daemon_script_location: daemon_script_location = "alignak-%s" % satellite.type else: daemon_script_location = "%s/alignak-%s" % (daemon_script_location, satellite.type) # Some extra arguments may be defined in the Alignak configuration daemon_arguments = getattr(self.conf, 'daemons_arguments', '') args = [daemon_script_location, "--name", satellite.name, "--environment", self.env_filename, "--host", str(satellite.host), "--port", str(satellite.port)] if daemon_arguments: args.append(daemon_arguments) logger.info(" ... with some arguments: %s", args) try: process = psutil.Popen(args, stdin=None, stdout=None, stderr=None) # A brief pause... time.sleep(0.1) except Exception as exp: # pylint: disable=broad-except logger.error("Error when launching %s: %s", satellite.name, exp) logger.error("Command: %s", args) return False logger.info(" %s launched (pid=%d, gids=%s)", satellite.name, process.pid, process.gids()) # My satellites/daemons map self.my_daemons[satellite.name] = { 'satellite': satellite, 'process': process } return True
python
def start_daemon(self, satellite): logger.info(" launching a daemon for: %s/%s...", satellite.type, satellite.name) # The daemon startup script location may be defined in the configuration daemon_script_location = getattr(self.conf, 'daemons_script_location', self.bindir) if not daemon_script_location: daemon_script_location = "alignak-%s" % satellite.type else: daemon_script_location = "%s/alignak-%s" % (daemon_script_location, satellite.type) # Some extra arguments may be defined in the Alignak configuration daemon_arguments = getattr(self.conf, 'daemons_arguments', '') args = [daemon_script_location, "--name", satellite.name, "--environment", self.env_filename, "--host", str(satellite.host), "--port", str(satellite.port)] if daemon_arguments: args.append(daemon_arguments) logger.info(" ... with some arguments: %s", args) try: process = psutil.Popen(args, stdin=None, stdout=None, stderr=None) # A brief pause... time.sleep(0.1) except Exception as exp: # pylint: disable=broad-except logger.error("Error when launching %s: %s", satellite.name, exp) logger.error("Command: %s", args) return False logger.info(" %s launched (pid=%d, gids=%s)", satellite.name, process.pid, process.gids()) # My satellites/daemons map self.my_daemons[satellite.name] = { 'satellite': satellite, 'process': process } return True
[ "def", "start_daemon", "(", "self", ",", "satellite", ")", ":", "logger", ".", "info", "(", "\" launching a daemon for: %s/%s...\"", ",", "satellite", ".", "type", ",", "satellite", ".", "name", ")", "# The daemon startup script location may be defined in the configurati...
Manage the list of detected missing daemons If the daemon does not in exist `my_daemons`, then: - prepare daemon start arguments (port, name and log file) - start the daemon - make sure it started correctly :param satellite: the satellite for which a daemon is to be started :type satellite: SatelliteLink :return: True if the daemon started correctly
[ "Manage", "the", "list", "of", "detected", "missing", "daemons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L934-L984
21,206
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.daemons_start
def daemons_start(self, run_daemons=True): """Manage the list of the daemons in the configuration Check if the daemon needs to be started by the Arbiter. If so, starts the daemon if `run_daemons` is True :param run_daemons: run the daemons or make a simple check :type run_daemons: bool :return: True if all daemons are running, else False. always True for a simple check """ result = True if run_daemons: logger.info("Alignak configured daemons start:") else: logger.info("Alignak configured daemons check:") # Parse the list of the missing daemons and try to run the corresponding processes for satellites_list in [self.conf.arbiters, self.conf.receivers, self.conf.reactionners, self.conf.pollers, self.conf.brokers, self.conf.schedulers]: for satellite in satellites_list: logger.info("- found %s, to be launched: %s, address: %s", satellite.name, satellite.alignak_launched, satellite.uri) if satellite == self.link_to_myself: # Ignore myself ;) continue if satellite.alignak_launched and \ satellite.address not in ['127.0.0.1', 'localhost']: logger.error("Alignak is required to launch a daemon for %s %s " "but the satelitte is defined on an external address: %s", satellite.type, satellite.name, satellite.address) result = False continue if not run_daemons: # When checking, ignore the daemon launch part... continue if not satellite.alignak_launched: logger.debug("Alignak will not launch '%s'") continue if not satellite.active: logger.warning("- daemon '%s' is declared but not set as active, " "do not start...", satellite.name) continue if satellite.name in self.my_daemons: logger.warning("- daemon '%s' is already running", satellite.name) continue started = self.start_daemon(satellite) result = result and started return result
python
def daemons_start(self, run_daemons=True): result = True if run_daemons: logger.info("Alignak configured daemons start:") else: logger.info("Alignak configured daemons check:") # Parse the list of the missing daemons and try to run the corresponding processes for satellites_list in [self.conf.arbiters, self.conf.receivers, self.conf.reactionners, self.conf.pollers, self.conf.brokers, self.conf.schedulers]: for satellite in satellites_list: logger.info("- found %s, to be launched: %s, address: %s", satellite.name, satellite.alignak_launched, satellite.uri) if satellite == self.link_to_myself: # Ignore myself ;) continue if satellite.alignak_launched and \ satellite.address not in ['127.0.0.1', 'localhost']: logger.error("Alignak is required to launch a daemon for %s %s " "but the satelitte is defined on an external address: %s", satellite.type, satellite.name, satellite.address) result = False continue if not run_daemons: # When checking, ignore the daemon launch part... continue if not satellite.alignak_launched: logger.debug("Alignak will not launch '%s'") continue if not satellite.active: logger.warning("- daemon '%s' is declared but not set as active, " "do not start...", satellite.name) continue if satellite.name in self.my_daemons: logger.warning("- daemon '%s' is already running", satellite.name) continue started = self.start_daemon(satellite) result = result and started return result
[ "def", "daemons_start", "(", "self", ",", "run_daemons", "=", "True", ")", ":", "result", "=", "True", "if", "run_daemons", ":", "logger", ".", "info", "(", "\"Alignak configured daemons start:\"", ")", "else", ":", "logger", ".", "info", "(", "\"Alignak confi...
Manage the list of the daemons in the configuration Check if the daemon needs to be started by the Arbiter. If so, starts the daemon if `run_daemons` is True :param run_daemons: run the daemons or make a simple check :type run_daemons: bool :return: True if all daemons are running, else False. always True for a simple check
[ "Manage", "the", "list", "of", "the", "daemons", "in", "the", "configuration" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L986-L1043
21,207
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.daemons_stop
def daemons_stop(self, timeout=30, kill_children=False): """Stop the Alignak daemons Iterate over the self-launched daemons and their children list to send a TERM Wait for daemons to terminate and then send a KILL for those that are not yet stopped As a default behavior, only the launched daemons are killed, not their children. Each daemon will manage its children killing :param timeout: delay to wait before killing a daemon :type timeout: int :param kill_children: also kill the children (defaults to False) :type kill_children: bool :return: True if all daemons stopped """ def on_terminate(proc): """Process termination callback function""" logger.debug("process %s terminated with exit code %s", proc.pid, proc.returncode) result = True if self.my_daemons: logger.info("Alignak self-launched daemons stop:") start = time.time() for daemon in list(self.my_daemons.values()): # Terminate the daemon and its children process procs = [] if kill_children: procs = daemon['process'].children() procs.append(daemon['process']) for process in procs: try: logger.info("- terminating process %s", process.name()) process.terminate() except psutil.AccessDenied: logger.warning("Process %s is %s", process.name(), process.status()) procs = [] for daemon in list(self.my_daemons.values()): # Stop the daemon and its children process if kill_children: procs = daemon['process'].children() procs.append(daemon['process']) _, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate) if alive: # Kill processes for process in alive: logger.warning("Process %s did not stopped, trying to kill", process.name()) process.kill() _, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate) if alive: # give up for process in alive: logger.warning("process %s survived SIGKILL; giving up", process.name()) result = False logger.debug("Stopping daemons duration: %.2f seconds", time.time() - start) return result
python
def daemons_stop(self, timeout=30, kill_children=False): def on_terminate(proc): """Process termination callback function""" logger.debug("process %s terminated with exit code %s", proc.pid, proc.returncode) result = True if self.my_daemons: logger.info("Alignak self-launched daemons stop:") start = time.time() for daemon in list(self.my_daemons.values()): # Terminate the daemon and its children process procs = [] if kill_children: procs = daemon['process'].children() procs.append(daemon['process']) for process in procs: try: logger.info("- terminating process %s", process.name()) process.terminate() except psutil.AccessDenied: logger.warning("Process %s is %s", process.name(), process.status()) procs = [] for daemon in list(self.my_daemons.values()): # Stop the daemon and its children process if kill_children: procs = daemon['process'].children() procs.append(daemon['process']) _, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate) if alive: # Kill processes for process in alive: logger.warning("Process %s did not stopped, trying to kill", process.name()) process.kill() _, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate) if alive: # give up for process in alive: logger.warning("process %s survived SIGKILL; giving up", process.name()) result = False logger.debug("Stopping daemons duration: %.2f seconds", time.time() - start) return result
[ "def", "daemons_stop", "(", "self", ",", "timeout", "=", "30", ",", "kill_children", "=", "False", ")", ":", "def", "on_terminate", "(", "proc", ")", ":", "\"\"\"Process termination callback function\"\"\"", "logger", ".", "debug", "(", "\"process %s terminated with...
Stop the Alignak daemons Iterate over the self-launched daemons and their children list to send a TERM Wait for daemons to terminate and then send a KILL for those that are not yet stopped As a default behavior, only the launched daemons are killed, not their children. Each daemon will manage its children killing :param timeout: delay to wait before killing a daemon :type timeout: int :param kill_children: also kill the children (defaults to False) :type kill_children: bool :return: True if all daemons stopped
[ "Stop", "the", "Alignak", "daemons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1109-L1170
21,208
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.setup_new_conf
def setup_new_conf(self): # pylint: disable=too-many-locals """ Setup a new configuration received from a Master arbiter. TODO: perharps we should not accept the configuration or raise an error if we do not find our own configuration data in the data. Thus this should never happen... :return: None """ # Execute the base class treatment... super(Arbiter, self).setup_new_conf() with self.conf_lock: logger.info("I received a new configuration from my master") # Get the new configuration self.cur_conf = self.new_conf # self_conf is our own configuration from the alignak environment # Arbiters do not have this property in the received configuration because # they already loaded a configuration on daemon load self_conf = self.cur_conf.get('self_conf', None) if not self_conf: self_conf = self.conf # whole_conf contains the full configuration load by my master whole_conf = self.cur_conf['whole_conf'] logger.debug("Received a new configuration, containing:") for key in self.cur_conf: logger.debug("- %s: %s", key, self.cur_conf[key]) logger.debug("satellite self configuration part: %s", self_conf) # Update Alignak name self.alignak_name = self.cur_conf['alignak_name'] logger.info("My Alignak instance: %s", self.alignak_name) # This to indicate that the new configuration got managed... self.new_conf = {} # Get the whole monitored objects configuration t00 = time.time() try: received_conf_part = unserialize(whole_conf) except AlignakClassLookupException as exp: # pragma: no cover, simple protection # This to indicate that the new configuration is not managed... self.new_conf = { "_status": "Cannot un-serialize configuration received from arbiter" } logger.error(self.new_conf['_status']) logger.error("Back trace of the error:\n%s", traceback.format_exc()) return except Exception as exp: # pylint: disable=broad-except # This to indicate that the new configuration is not managed... self.new_conf = { "_status": "Cannot un-serialize configuration received from arbiter" } logger.error(self.new_conf['_status']) logger.error(self.new_conf) self.exit_on_exception(exp, self.new_conf) logger.info("Monitored configuration %s received at %d. Un-serialized in %d secs", received_conf_part, t00, time.time() - t00) # Now we create our arbiters and schedulers links my_satellites = getattr(self, 'arbiters', {}) received_satellites = self.cur_conf['arbiters'] for link_uuid in received_satellites: rs_conf = received_satellites[link_uuid] logger.debug("- received %s - %s: %s", rs_conf['instance_id'], rs_conf['type'], rs_conf['name']) # Must look if we already had a configuration and save our broks already_got = rs_conf['instance_id'] in my_satellites broks = [] actions = {} wait_homerun = {} external_commands = {} running_id = 0 if already_got: logger.warning("I already got: %s", rs_conf['instance_id']) # Save some information running_id = my_satellites[link_uuid].running_id (broks, actions, wait_homerun, external_commands) = \ my_satellites[link_uuid].get_and_clear_context() # Delete the former link del my_satellites[link_uuid] # My new satellite link... new_link = SatelliteLink.get_a_satellite_link('arbiter', rs_conf) my_satellites[new_link.uuid] = new_link logger.info("I got a new arbiter satellite: %s", new_link) new_link.running_id = running_id new_link.external_commands = external_commands new_link.broks = broks new_link.wait_homerun = wait_homerun new_link.actions = actions # # replacing satellite address and port by those defined in satellite_map # if new_link.name in self_conf.satellite_map: # overriding = self_conf.satellite_map[new_link.name] # # satellite = dict(satellite) # make a copy # # new_link.update(self_conf.get('satellite_map', {})[new_link.name]) # logger.warning("Do not override the configuration for: %s, with: %s. " # "Please check whether this is necessary!", # new_link.name, overriding) # for arbiter_link in received_conf_part.arbiters: # logger.info("I have arbiter links in my configuration: %s", arbiter_link.name) # if arbiter_link.name != self.name and not arbiter_link.spare: # # Arbiter is not me! # logger.info("I found my master arbiter in the configuration: %s", # arbiter_link.name) # continue # # logger.info("I found myself in the received configuration: %s", arbiter_link.name) # self.link_to_myself = arbiter_link # # We received a configuration s we are not a master ! # self.is_master = False # self.link_to_myself.spare = True # # Set myself as alive ;) # self.link_to_myself.set_alive() # Now I have a configuration! self.have_conf = True
python
def setup_new_conf(self): # pylint: disable=too-many-locals # Execute the base class treatment... super(Arbiter, self).setup_new_conf() with self.conf_lock: logger.info("I received a new configuration from my master") # Get the new configuration self.cur_conf = self.new_conf # self_conf is our own configuration from the alignak environment # Arbiters do not have this property in the received configuration because # they already loaded a configuration on daemon load self_conf = self.cur_conf.get('self_conf', None) if not self_conf: self_conf = self.conf # whole_conf contains the full configuration load by my master whole_conf = self.cur_conf['whole_conf'] logger.debug("Received a new configuration, containing:") for key in self.cur_conf: logger.debug("- %s: %s", key, self.cur_conf[key]) logger.debug("satellite self configuration part: %s", self_conf) # Update Alignak name self.alignak_name = self.cur_conf['alignak_name'] logger.info("My Alignak instance: %s", self.alignak_name) # This to indicate that the new configuration got managed... self.new_conf = {} # Get the whole monitored objects configuration t00 = time.time() try: received_conf_part = unserialize(whole_conf) except AlignakClassLookupException as exp: # pragma: no cover, simple protection # This to indicate that the new configuration is not managed... self.new_conf = { "_status": "Cannot un-serialize configuration received from arbiter" } logger.error(self.new_conf['_status']) logger.error("Back trace of the error:\n%s", traceback.format_exc()) return except Exception as exp: # pylint: disable=broad-except # This to indicate that the new configuration is not managed... self.new_conf = { "_status": "Cannot un-serialize configuration received from arbiter" } logger.error(self.new_conf['_status']) logger.error(self.new_conf) self.exit_on_exception(exp, self.new_conf) logger.info("Monitored configuration %s received at %d. Un-serialized in %d secs", received_conf_part, t00, time.time() - t00) # Now we create our arbiters and schedulers links my_satellites = getattr(self, 'arbiters', {}) received_satellites = self.cur_conf['arbiters'] for link_uuid in received_satellites: rs_conf = received_satellites[link_uuid] logger.debug("- received %s - %s: %s", rs_conf['instance_id'], rs_conf['type'], rs_conf['name']) # Must look if we already had a configuration and save our broks already_got = rs_conf['instance_id'] in my_satellites broks = [] actions = {} wait_homerun = {} external_commands = {} running_id = 0 if already_got: logger.warning("I already got: %s", rs_conf['instance_id']) # Save some information running_id = my_satellites[link_uuid].running_id (broks, actions, wait_homerun, external_commands) = \ my_satellites[link_uuid].get_and_clear_context() # Delete the former link del my_satellites[link_uuid] # My new satellite link... new_link = SatelliteLink.get_a_satellite_link('arbiter', rs_conf) my_satellites[new_link.uuid] = new_link logger.info("I got a new arbiter satellite: %s", new_link) new_link.running_id = running_id new_link.external_commands = external_commands new_link.broks = broks new_link.wait_homerun = wait_homerun new_link.actions = actions # # replacing satellite address and port by those defined in satellite_map # if new_link.name in self_conf.satellite_map: # overriding = self_conf.satellite_map[new_link.name] # # satellite = dict(satellite) # make a copy # # new_link.update(self_conf.get('satellite_map', {})[new_link.name]) # logger.warning("Do not override the configuration for: %s, with: %s. " # "Please check whether this is necessary!", # new_link.name, overriding) # for arbiter_link in received_conf_part.arbiters: # logger.info("I have arbiter links in my configuration: %s", arbiter_link.name) # if arbiter_link.name != self.name and not arbiter_link.spare: # # Arbiter is not me! # logger.info("I found my master arbiter in the configuration: %s", # arbiter_link.name) # continue # # logger.info("I found myself in the received configuration: %s", arbiter_link.name) # self.link_to_myself = arbiter_link # # We received a configuration s we are not a master ! # self.is_master = False # self.link_to_myself.spare = True # # Set myself as alive ;) # self.link_to_myself.set_alive() # Now I have a configuration! self.have_conf = True
[ "def", "setup_new_conf", "(", "self", ")", ":", "# pylint: disable=too-many-locals", "# Execute the base class treatment...", "super", "(", "Arbiter", ",", "self", ")", ".", "setup_new_conf", "(", ")", "with", "self", ".", "conf_lock", ":", "logger", ".", "info", ...
Setup a new configuration received from a Master arbiter. TODO: perharps we should not accept the configuration or raise an error if we do not find our own configuration data in the data. Thus this should never happen... :return: None
[ "Setup", "a", "new", "configuration", "received", "from", "a", "Master", "arbiter", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1219-L1342
21,209
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.wait_for_master_death
def wait_for_master_death(self): """Wait for a master timeout and take the lead if necessary :return: None """ logger.info("Waiting for master death") timeout = 1.0 self.last_master_ping = time.time() master_timeout = 300 for arbiter_link in self.conf.arbiters: if not arbiter_link.spare: master_timeout = \ arbiter_link.spare_check_interval * arbiter_link.spare_max_check_attempts logger.info("I'll wait master death for %d seconds", master_timeout) while not self.interrupted: # Make a pause and check if the system time changed _, tcdiff = self.make_a_pause(timeout) # If there was a system time change then we have to adapt last_master_ping: if tcdiff: self.last_master_ping += tcdiff if self.new_conf: self.setup_new_conf() sys.stdout.write(".") sys.stdout.flush() # Now check if master is dead or not now = time.time() if now - self.last_master_ping > master_timeout: logger.info("Arbiter Master is dead. The arbiter %s takes the lead!", self.link_to_myself.name) for arbiter_link in self.conf.arbiters: if not arbiter_link.spare: arbiter_link.alive = False self.must_run = True break
python
def wait_for_master_death(self): logger.info("Waiting for master death") timeout = 1.0 self.last_master_ping = time.time() master_timeout = 300 for arbiter_link in self.conf.arbiters: if not arbiter_link.spare: master_timeout = \ arbiter_link.spare_check_interval * arbiter_link.spare_max_check_attempts logger.info("I'll wait master death for %d seconds", master_timeout) while not self.interrupted: # Make a pause and check if the system time changed _, tcdiff = self.make_a_pause(timeout) # If there was a system time change then we have to adapt last_master_ping: if tcdiff: self.last_master_ping += tcdiff if self.new_conf: self.setup_new_conf() sys.stdout.write(".") sys.stdout.flush() # Now check if master is dead or not now = time.time() if now - self.last_master_ping > master_timeout: logger.info("Arbiter Master is dead. The arbiter %s takes the lead!", self.link_to_myself.name) for arbiter_link in self.conf.arbiters: if not arbiter_link.spare: arbiter_link.alive = False self.must_run = True break
[ "def", "wait_for_master_death", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Waiting for master death\"", ")", "timeout", "=", "1.0", "self", ".", "last_master_ping", "=", "time", ".", "time", "(", ")", "master_timeout", "=", "300", "for", "arbiter_li...
Wait for a master timeout and take the lead if necessary :return: None
[ "Wait", "for", "a", "master", "timeout", "and", "take", "the", "lead", "if", "necessary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1344-L1382
21,210
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.manage_signal
def manage_signal(self, sig, frame): """Manage signals caught by the process Specific behavior for the arbiter when it receives a sigkill or sigterm :param sig: signal caught by the process :type sig: str :param frame: current stack frame :type frame: :return: None """ # Request the arbiter to stop if sig in [signal.SIGINT, signal.SIGTERM]: logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) self.kill_request = True self.kill_timestamp = time.time() logger.info("request to stop in progress") else: Daemon.manage_signal(self, sig, frame)
python
def manage_signal(self, sig, frame): # Request the arbiter to stop if sig in [signal.SIGINT, signal.SIGTERM]: logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) self.kill_request = True self.kill_timestamp = time.time() logger.info("request to stop in progress") else: Daemon.manage_signal(self, sig, frame)
[ "def", "manage_signal", "(", "self", ",", "sig", ",", "frame", ")", ":", "# Request the arbiter to stop", "if", "sig", "in", "[", "signal", ".", "SIGINT", ",", "signal", ".", "SIGTERM", "]", ":", "logger", ".", "info", "(", "\"received a signal: %s\"", ",", ...
Manage signals caught by the process Specific behavior for the arbiter when it receives a sigkill or sigterm :param sig: signal caught by the process :type sig: str :param frame: current stack frame :type frame: :return: None
[ "Manage", "signals", "caught", "by", "the", "process", "Specific", "behavior", "for", "the", "arbiter", "when", "it", "receives", "a", "sigkill", "or", "sigterm" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1394-L1411
21,211
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.configuration_dispatch
def configuration_dispatch(self, not_configured=None): """Monitored configuration preparation and dispatch :return: None """ if not not_configured: self.dispatcher = Dispatcher(self.conf, self.link_to_myself) # I set my own dispatched configuration as the provided one... # because I will not push a configuration to myself :) self.cur_conf = self.conf # Loop for the first configuration dispatching, if the first dispatch fails, bail out! # Without a correct configuration, Alignak daemons will not run correctly first_connection_try_count = 0 logger.info("Connecting to my satellites...") while True: first_connection_try_count += 1 # Initialize connection with all our satellites self.all_connected = True for satellite in self.dispatcher.all_daemons_links: if satellite == self.link_to_myself: continue if not satellite.active: continue connected = self.daemon_connection_init(satellite, set_wait_new_conf=True) logger.debug(" %s is %s", satellite, connected) self.all_connected = self.all_connected and connected if self.all_connected: logger.info("- satellites connection #%s is ok", first_connection_try_count) break else: logger.warning("- satellites connection #%s is not correct; " "let's give another chance after %d seconds...", first_connection_try_count, self.link_to_myself.polling_interval) if first_connection_try_count >= 3: self.request_stop("All the daemons connections could not be established " "despite %d tries! " "Sorry, I bail out!" % first_connection_try_count, exit_code=4) time.sleep(self.link_to_myself.polling_interval) # Now I have a connection with all the daemons I need to contact them, # check they are alive and ready to run _t0 = time.time() self.all_connected = self.dispatcher.check_reachable() statsmgr.timer('dispatcher.check-alive', time.time() - _t0) _t0 = time.time() # Preparing the configuration for dispatching logger.info("Preparing the configuration for dispatching...") self.dispatcher.prepare_dispatch() statsmgr.timer('dispatcher.prepare-dispatch', time.time() - _t0) logger.info("- configuration is ready to dispatch") # Loop for the first configuration dispatching, if the first dispatch fails, bail out! # Without a correct configuration, Alignak daemons will not run correctly first_dispatch_try_count = 0 logger.info("Dispatching the configuration to my satellites...") while True: first_dispatch_try_count += 1 # Check reachable - if a configuration is prepared, this will force the # daemons communication, and the dispatching will be launched _t0 = time.time() logger.info("- configuration dispatching #%s...", first_dispatch_try_count) self.dispatcher.check_reachable(forced=True) statsmgr.timer('dispatcher.dispatch', time.time() - _t0) # Make a pause to let our satellites get ready... pause = max(1, max(self.conf.daemons_dispatch_timeout, len(self.my_daemons) * 0.5)) # pause = len(self.my_daemons) * 0.2 logger.info("- pausing %d seconds...", pause) time.sleep(pause) _t0 = time.time() logger.info("- checking configuration dispatch...") # Checking the dispatch is accepted self.dispatcher.check_dispatch() statsmgr.timer('dispatcher.check-dispatch', time.time() - _t0) if self.dispatcher.dispatch_ok: logger.info("- configuration dispatching #%s is ok", first_dispatch_try_count) break else: logger.warning("- configuration dispatching #%s is not correct; " "let's give another chance...", first_dispatch_try_count) if first_dispatch_try_count >= 3: self.request_stop("The configuration could not be dispatched despite %d tries! " "Sorry, I bail out!" % first_connection_try_count, exit_code=4)
python
def configuration_dispatch(self, not_configured=None): if not not_configured: self.dispatcher = Dispatcher(self.conf, self.link_to_myself) # I set my own dispatched configuration as the provided one... # because I will not push a configuration to myself :) self.cur_conf = self.conf # Loop for the first configuration dispatching, if the first dispatch fails, bail out! # Without a correct configuration, Alignak daemons will not run correctly first_connection_try_count = 0 logger.info("Connecting to my satellites...") while True: first_connection_try_count += 1 # Initialize connection with all our satellites self.all_connected = True for satellite in self.dispatcher.all_daemons_links: if satellite == self.link_to_myself: continue if not satellite.active: continue connected = self.daemon_connection_init(satellite, set_wait_new_conf=True) logger.debug(" %s is %s", satellite, connected) self.all_connected = self.all_connected and connected if self.all_connected: logger.info("- satellites connection #%s is ok", first_connection_try_count) break else: logger.warning("- satellites connection #%s is not correct; " "let's give another chance after %d seconds...", first_connection_try_count, self.link_to_myself.polling_interval) if first_connection_try_count >= 3: self.request_stop("All the daemons connections could not be established " "despite %d tries! " "Sorry, I bail out!" % first_connection_try_count, exit_code=4) time.sleep(self.link_to_myself.polling_interval) # Now I have a connection with all the daemons I need to contact them, # check they are alive and ready to run _t0 = time.time() self.all_connected = self.dispatcher.check_reachable() statsmgr.timer('dispatcher.check-alive', time.time() - _t0) _t0 = time.time() # Preparing the configuration for dispatching logger.info("Preparing the configuration for dispatching...") self.dispatcher.prepare_dispatch() statsmgr.timer('dispatcher.prepare-dispatch', time.time() - _t0) logger.info("- configuration is ready to dispatch") # Loop for the first configuration dispatching, if the first dispatch fails, bail out! # Without a correct configuration, Alignak daemons will not run correctly first_dispatch_try_count = 0 logger.info("Dispatching the configuration to my satellites...") while True: first_dispatch_try_count += 1 # Check reachable - if a configuration is prepared, this will force the # daemons communication, and the dispatching will be launched _t0 = time.time() logger.info("- configuration dispatching #%s...", first_dispatch_try_count) self.dispatcher.check_reachable(forced=True) statsmgr.timer('dispatcher.dispatch', time.time() - _t0) # Make a pause to let our satellites get ready... pause = max(1, max(self.conf.daemons_dispatch_timeout, len(self.my_daemons) * 0.5)) # pause = len(self.my_daemons) * 0.2 logger.info("- pausing %d seconds...", pause) time.sleep(pause) _t0 = time.time() logger.info("- checking configuration dispatch...") # Checking the dispatch is accepted self.dispatcher.check_dispatch() statsmgr.timer('dispatcher.check-dispatch', time.time() - _t0) if self.dispatcher.dispatch_ok: logger.info("- configuration dispatching #%s is ok", first_dispatch_try_count) break else: logger.warning("- configuration dispatching #%s is not correct; " "let's give another chance...", first_dispatch_try_count) if first_dispatch_try_count >= 3: self.request_stop("The configuration could not be dispatched despite %d tries! " "Sorry, I bail out!" % first_connection_try_count, exit_code=4)
[ "def", "configuration_dispatch", "(", "self", ",", "not_configured", "=", "None", ")", ":", "if", "not", "not_configured", ":", "self", ".", "dispatcher", "=", "Dispatcher", "(", "self", ".", "conf", ",", "self", ".", "link_to_myself", ")", "# I set my own dis...
Monitored configuration preparation and dispatch :return: None
[ "Monitored", "configuration", "preparation", "and", "dispatch" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1413-L1504
21,212
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.do_before_loop
def do_before_loop(self): """Called before the main daemon loop. :return: None """ logger.info("I am the arbiter: %s", self.link_to_myself.name) # If I am a spare, I do not have anything to do here... if not self.is_master: logger.debug("Waiting for my master death...") return # Arbiter check if some daemons need to be started if not self.daemons_start(run_daemons=True): self.request_stop(message="Some Alignak daemons did not started correctly.", exit_code=4) if not self.daemons_check(): self.request_stop(message="Some Alignak daemons cannot be checked.", exit_code=4) # Make a pause to let our started daemons get ready... pause = max(1, max(self.conf.daemons_start_timeout, len(self.my_daemons) * 0.5)) if pause: logger.info("Pausing %.2f seconds...", pause) time.sleep(pause) # Prepare and dispatch the monitored configuration self.configuration_dispatch() # Now we can get all initial broks for our satellites _t0 = time.time() self.get_initial_broks_from_satellites() statsmgr.timer('broks.get-initial', time.time() - _t0) # Now create the external commands manager # We are a dispatcher: our role is to dispatch commands to the schedulers self.external_commands_manager = ExternalCommandManager( self.conf, 'dispatcher', self, self.conf.accept_passive_unknown_check_results, self.conf.log_external_commands)
python
def do_before_loop(self): logger.info("I am the arbiter: %s", self.link_to_myself.name) # If I am a spare, I do not have anything to do here... if not self.is_master: logger.debug("Waiting for my master death...") return # Arbiter check if some daemons need to be started if not self.daemons_start(run_daemons=True): self.request_stop(message="Some Alignak daemons did not started correctly.", exit_code=4) if not self.daemons_check(): self.request_stop(message="Some Alignak daemons cannot be checked.", exit_code=4) # Make a pause to let our started daemons get ready... pause = max(1, max(self.conf.daemons_start_timeout, len(self.my_daemons) * 0.5)) if pause: logger.info("Pausing %.2f seconds...", pause) time.sleep(pause) # Prepare and dispatch the monitored configuration self.configuration_dispatch() # Now we can get all initial broks for our satellites _t0 = time.time() self.get_initial_broks_from_satellites() statsmgr.timer('broks.get-initial', time.time() - _t0) # Now create the external commands manager # We are a dispatcher: our role is to dispatch commands to the schedulers self.external_commands_manager = ExternalCommandManager( self.conf, 'dispatcher', self, self.conf.accept_passive_unknown_check_results, self.conf.log_external_commands)
[ "def", "do_before_loop", "(", "self", ")", ":", "logger", ".", "info", "(", "\"I am the arbiter: %s\"", ",", "self", ".", "link_to_myself", ".", "name", ")", "# If I am a spare, I do not have anything to do here...", "if", "not", "self", ".", "is_master", ":", "logg...
Called before the main daemon loop. :return: None
[ "Called", "before", "the", "main", "daemon", "loop", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1506-L1545
21,213
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.get_monitoring_problems
def get_monitoring_problems(self): """Get the schedulers satellites problems list :return: problems dictionary :rtype: dict """ res = self.get_id() res['problems'] = {} # Report our schedulers information, but only if a dispatcher exists if getattr(self, 'dispatcher', None) is None: return res for satellite in self.dispatcher.all_daemons_links: if satellite.type not in ['scheduler']: continue if not satellite.active: continue if satellite.statistics and 'problems' in satellite.statistics: res['problems'][satellite.name] = { '_freshness': satellite.statistics['_freshness'], 'problems': satellite.statistics['problems'] } return res
python
def get_monitoring_problems(self): res = self.get_id() res['problems'] = {} # Report our schedulers information, but only if a dispatcher exists if getattr(self, 'dispatcher', None) is None: return res for satellite in self.dispatcher.all_daemons_links: if satellite.type not in ['scheduler']: continue if not satellite.active: continue if satellite.statistics and 'problems' in satellite.statistics: res['problems'][satellite.name] = { '_freshness': satellite.statistics['_freshness'], 'problems': satellite.statistics['problems'] } return res
[ "def", "get_monitoring_problems", "(", "self", ")", ":", "res", "=", "self", ".", "get_id", "(", ")", "res", "[", "'problems'", "]", "=", "{", "}", "# Report our schedulers information, but only if a dispatcher exists", "if", "getattr", "(", "self", ",", "'dispatc...
Get the schedulers satellites problems list :return: problems dictionary :rtype: dict
[ "Get", "the", "schedulers", "satellites", "problems", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1801-L1826
21,214
Alignak-monitoring/alignak
alignak/daemons/arbiterdaemon.py
Arbiter.get_livesynthesis
def get_livesynthesis(self): """Get the schedulers satellites live synthesis :return: compiled livesynthesis dictionary :rtype: dict """ res = self.get_id() res['livesynthesis'] = { '_overall': { '_freshness': int(time.time()), 'livesynthesis': { 'hosts_total': 0, 'hosts_not_monitored': 0, 'hosts_up_hard': 0, 'hosts_up_soft': 0, 'hosts_down_hard': 0, 'hosts_down_soft': 0, 'hosts_unreachable_hard': 0, 'hosts_unreachable_soft': 0, 'hosts_problems': 0, 'hosts_acknowledged': 0, 'hosts_in_downtime': 0, 'hosts_flapping': 0, 'services_total': 0, 'services_not_monitored': 0, 'services_ok_hard': 0, 'services_ok_soft': 0, 'services_warning_hard': 0, 'services_warning_soft': 0, 'services_critical_hard': 0, 'services_critical_soft': 0, 'services_unknown_hard': 0, 'services_unknown_soft': 0, 'services_unreachable_hard': 0, 'services_unreachable_soft': 0, 'services_problems': 0, 'services_acknowledged': 0, 'services_in_downtime': 0, 'services_flapping': 0, } } } # Report our schedulers information, but only if a dispatcher exists if getattr(self, 'dispatcher', None) is None: return res for satellite in self.dispatcher.all_daemons_links: if satellite.type not in ['scheduler']: continue if not satellite.active: continue if 'livesynthesis' in satellite.statistics: # Scheduler detailed live synthesis res['livesynthesis'][satellite.name] = { '_freshness': satellite.statistics['_freshness'], 'livesynthesis': satellite.statistics['livesynthesis'] } # Cumulated live synthesis for prop in res['livesynthesis']['_overall']['livesynthesis']: if prop in satellite.statistics['livesynthesis']: res['livesynthesis']['_overall']['livesynthesis'][prop] += \ satellite.statistics['livesynthesis'][prop] return res
python
def get_livesynthesis(self): res = self.get_id() res['livesynthesis'] = { '_overall': { '_freshness': int(time.time()), 'livesynthesis': { 'hosts_total': 0, 'hosts_not_monitored': 0, 'hosts_up_hard': 0, 'hosts_up_soft': 0, 'hosts_down_hard': 0, 'hosts_down_soft': 0, 'hosts_unreachable_hard': 0, 'hosts_unreachable_soft': 0, 'hosts_problems': 0, 'hosts_acknowledged': 0, 'hosts_in_downtime': 0, 'hosts_flapping': 0, 'services_total': 0, 'services_not_monitored': 0, 'services_ok_hard': 0, 'services_ok_soft': 0, 'services_warning_hard': 0, 'services_warning_soft': 0, 'services_critical_hard': 0, 'services_critical_soft': 0, 'services_unknown_hard': 0, 'services_unknown_soft': 0, 'services_unreachable_hard': 0, 'services_unreachable_soft': 0, 'services_problems': 0, 'services_acknowledged': 0, 'services_in_downtime': 0, 'services_flapping': 0, } } } # Report our schedulers information, but only if a dispatcher exists if getattr(self, 'dispatcher', None) is None: return res for satellite in self.dispatcher.all_daemons_links: if satellite.type not in ['scheduler']: continue if not satellite.active: continue if 'livesynthesis' in satellite.statistics: # Scheduler detailed live synthesis res['livesynthesis'][satellite.name] = { '_freshness': satellite.statistics['_freshness'], 'livesynthesis': satellite.statistics['livesynthesis'] } # Cumulated live synthesis for prop in res['livesynthesis']['_overall']['livesynthesis']: if prop in satellite.statistics['livesynthesis']: res['livesynthesis']['_overall']['livesynthesis'][prop] += \ satellite.statistics['livesynthesis'][prop] return res
[ "def", "get_livesynthesis", "(", "self", ")", ":", "res", "=", "self", ".", "get_id", "(", ")", "res", "[", "'livesynthesis'", "]", "=", "{", "'_overall'", ":", "{", "'_freshness'", ":", "int", "(", "time", ".", "time", "(", ")", ")", ",", "'livesynt...
Get the schedulers satellites live synthesis :return: compiled livesynthesis dictionary :rtype: dict
[ "Get", "the", "schedulers", "satellites", "live", "synthesis" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1828-L1893
21,215
Alignak-monitoring/alignak
alignak/objects/service.py
Service.overall_state_id
def overall_state_id(self): """Get the service overall state. The service overall state identifier is the service status including: - the monitored state - the acknowledged state - the downtime state The overall state is (prioritized): - a service is not monitored (5) - a service critical or unreachable (4) - a service warning or unknown (3) - a service downtimed (2) - a service acknowledged (1) - a service ok (0) *Note* that services in unknown state are considered as warning, and unreachable ones are considered as critical! Also note that the service state is considered only for HARD state type! """ overall_state = 0 if not self.monitored: overall_state = 5 elif self.acknowledged: overall_state = 1 elif self.downtimed: overall_state = 2 elif self.state_type == 'HARD': if self.state == 'WARNING': overall_state = 3 elif self.state == 'CRITICAL': overall_state = 4 elif self.state == 'UNKNOWN': overall_state = 3 elif self.state == 'UNREACHABLE': overall_state = 4 return overall_state
python
def overall_state_id(self): overall_state = 0 if not self.monitored: overall_state = 5 elif self.acknowledged: overall_state = 1 elif self.downtimed: overall_state = 2 elif self.state_type == 'HARD': if self.state == 'WARNING': overall_state = 3 elif self.state == 'CRITICAL': overall_state = 4 elif self.state == 'UNKNOWN': overall_state = 3 elif self.state == 'UNREACHABLE': overall_state = 4 return overall_state
[ "def", "overall_state_id", "(", "self", ")", ":", "overall_state", "=", "0", "if", "not", "self", ".", "monitored", ":", "overall_state", "=", "5", "elif", "self", ".", "acknowledged", ":", "overall_state", "=", "1", "elif", "self", ".", "downtimed", ":", ...
Get the service overall state. The service overall state identifier is the service status including: - the monitored state - the acknowledged state - the downtime state The overall state is (prioritized): - a service is not monitored (5) - a service critical or unreachable (4) - a service warning or unknown (3) - a service downtimed (2) - a service acknowledged (1) - a service ok (0) *Note* that services in unknown state are considered as warning, and unreachable ones are considered as critical! Also note that the service state is considered only for HARD state type!
[ "Get", "the", "service", "overall", "state", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L255-L294
21,216
Alignak-monitoring/alignak
alignak/objects/service.py
Service.fill_predictive_missing_parameters
def fill_predictive_missing_parameters(self): """define state with initial_state :return: None """ if self.initial_state == 'w': self.state = u'WARNING' elif self.initial_state == 'u': self.state = u'UNKNOWN' elif self.initial_state == 'c': self.state = u'CRITICAL' elif self.initial_state == 'x': self.state = u'UNREACHABLE'
python
def fill_predictive_missing_parameters(self): if self.initial_state == 'w': self.state = u'WARNING' elif self.initial_state == 'u': self.state = u'UNKNOWN' elif self.initial_state == 'c': self.state = u'CRITICAL' elif self.initial_state == 'x': self.state = u'UNREACHABLE'
[ "def", "fill_predictive_missing_parameters", "(", "self", ")", ":", "if", "self", ".", "initial_state", "==", "'w'", ":", "self", ".", "state", "=", "u'WARNING'", "elif", "self", ".", "initial_state", "==", "'u'", ":", "self", ".", "state", "=", "u'UNKNOWN'"...
define state with initial_state :return: None
[ "define", "state", "with", "initial_state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L307-L319
21,217
Alignak-monitoring/alignak
alignak/objects/service.py
Service.get_name
def get_name(self): """Accessor to service_description attribute or name if first not defined :return: service name :rtype: str """ if hasattr(self, 'service_description'): return self.service_description if hasattr(self, 'name'): return self.name return 'SERVICE-DESCRIPTION-MISSING'
python
def get_name(self): if hasattr(self, 'service_description'): return self.service_description if hasattr(self, 'name'): return self.name return 'SERVICE-DESCRIPTION-MISSING'
[ "def", "get_name", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'service_description'", ")", ":", "return", "self", ".", "service_description", "if", "hasattr", "(", "self", ",", "'name'", ")", ":", "return", "self", ".", "name", "return", ...
Accessor to service_description attribute or name if first not defined :return: service name :rtype: str
[ "Accessor", "to", "service_description", "attribute", "or", "name", "if", "first", "not", "defined" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L351-L361
21,218
Alignak-monitoring/alignak
alignak/objects/service.py
Service.get_groupnames
def get_groupnames(self, sgs): """Get servicegroups list :return: comma separated list of servicegroups :rtype: str """ return ','.join([sgs[sg].get_name() for sg in self.servicegroups])
python
def get_groupnames(self, sgs): return ','.join([sgs[sg].get_name() for sg in self.servicegroups])
[ "def", "get_groupnames", "(", "self", ",", "sgs", ")", ":", "return", "','", ".", "join", "(", "[", "sgs", "[", "sg", "]", ".", "get_name", "(", ")", "for", "sg", "in", "self", ".", "servicegroups", "]", ")" ]
Get servicegroups list :return: comma separated list of servicegroups :rtype: str
[ "Get", "servicegroups", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L383-L389
21,219
Alignak-monitoring/alignak
alignak/objects/service.py
Service.duplicate
def duplicate(self, host): # pylint: disable=too-many-locals """For a given host, look for all copy we must create for for_each property :param host: alignak host object :type host: alignak.objects.host.Host :return: list :rtype: list """ duplicates = [] # In macro, it's all in UPPER case prop = self.duplicate_foreach.strip().upper() if prop not in host.customs: # If I do not have the property, we bail out return duplicates # Get the list entry, and the not one if there is one entry = host.customs[prop] # Look at the list of the key we do NOT want maybe, # for _disks it will be _!disks not_entry = host.customs.get('_' + '!' + prop[1:], '').split(',') not_keys = strip_and_uniq(not_entry) default_value = getattr(self, 'default_value', '') # Transform the generator string to a list # Missing values are filled with the default value try: key_values = tuple(generate_key_value_sequences(entry, default_value)) except KeyValueSyntaxError as exc: fmt_dict = { 'prop': self.duplicate_foreach, 'host': host.get_name(), 'svc': self.service_description, 'entry': entry, 'exc': exc, } err = ( "The custom property %(prop)r of the " "host %(host)r is not a valid entry for a service generator: %(exc)s, " "with entry=%(entry)r") % fmt_dict logger.warning(err) host.add_error(err) return duplicates for key_value in key_values: key = key_value['KEY'] # Maybe this key is in the NOT list, if so, skip it if key in not_keys: continue new_s = self.copy() new_s.host_name = host.get_name() if self.is_tpl(): # if template, the new one is not new_s.register = 1 for key in key_value: if key == 'KEY': if hasattr(self, 'service_description'): # We want to change all illegal chars to a _ sign. # We can't use class.illegal_obj_char # because in the "explode" phase, we do not have access to this data! :( safe_key_value = re.sub(r'[' + "`~!$%^&*\"|'<>?,()=" + ']+', '_', key_value[key]) new_s.service_description = self.service_description.replace( '$' + key + '$', safe_key_value ) # Here is a list of property where we will expand the $KEY$ by the value _the_expandables = ['check_command', 'aggregation', 'event_handler'] for prop in _the_expandables: if hasattr(self, prop): # here we can replace VALUE, VALUE1, VALUE2,... setattr(new_s, prop, getattr(new_s, prop).replace('$' + key + '$', key_value[key])) if hasattr(self, 'service_dependencies'): for i, servicedep in enumerate(new_s.service_dependencies): new_s.service_dependencies[i] = servicedep.replace( '$' + key + '$', key_value[key] ) # And then add in our list this new service duplicates.append(new_s) return duplicates
python
def duplicate(self, host): # pylint: disable=too-many-locals duplicates = [] # In macro, it's all in UPPER case prop = self.duplicate_foreach.strip().upper() if prop not in host.customs: # If I do not have the property, we bail out return duplicates # Get the list entry, and the not one if there is one entry = host.customs[prop] # Look at the list of the key we do NOT want maybe, # for _disks it will be _!disks not_entry = host.customs.get('_' + '!' + prop[1:], '').split(',') not_keys = strip_and_uniq(not_entry) default_value = getattr(self, 'default_value', '') # Transform the generator string to a list # Missing values are filled with the default value try: key_values = tuple(generate_key_value_sequences(entry, default_value)) except KeyValueSyntaxError as exc: fmt_dict = { 'prop': self.duplicate_foreach, 'host': host.get_name(), 'svc': self.service_description, 'entry': entry, 'exc': exc, } err = ( "The custom property %(prop)r of the " "host %(host)r is not a valid entry for a service generator: %(exc)s, " "with entry=%(entry)r") % fmt_dict logger.warning(err) host.add_error(err) return duplicates for key_value in key_values: key = key_value['KEY'] # Maybe this key is in the NOT list, if so, skip it if key in not_keys: continue new_s = self.copy() new_s.host_name = host.get_name() if self.is_tpl(): # if template, the new one is not new_s.register = 1 for key in key_value: if key == 'KEY': if hasattr(self, 'service_description'): # We want to change all illegal chars to a _ sign. # We can't use class.illegal_obj_char # because in the "explode" phase, we do not have access to this data! :( safe_key_value = re.sub(r'[' + "`~!$%^&*\"|'<>?,()=" + ']+', '_', key_value[key]) new_s.service_description = self.service_description.replace( '$' + key + '$', safe_key_value ) # Here is a list of property where we will expand the $KEY$ by the value _the_expandables = ['check_command', 'aggregation', 'event_handler'] for prop in _the_expandables: if hasattr(self, prop): # here we can replace VALUE, VALUE1, VALUE2,... setattr(new_s, prop, getattr(new_s, prop).replace('$' + key + '$', key_value[key])) if hasattr(self, 'service_dependencies'): for i, servicedep in enumerate(new_s.service_dependencies): new_s.service_dependencies[i] = servicedep.replace( '$' + key + '$', key_value[key] ) # And then add in our list this new service duplicates.append(new_s) return duplicates
[ "def", "duplicate", "(", "self", ",", "host", ")", ":", "# pylint: disable=too-many-locals", "duplicates", "=", "[", "]", "# In macro, it's all in UPPER case", "prop", "=", "self", ".", "duplicate_foreach", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", ...
For a given host, look for all copy we must create for for_each property :param host: alignak host object :type host: alignak.objects.host.Host :return: list :rtype: list
[ "For", "a", "given", "host", "look", "for", "all", "copy", "we", "must", "create", "for", "for_each", "property" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L457-L537
21,220
Alignak-monitoring/alignak
alignak/objects/service.py
Service.set_state_from_exit_status
def set_state_from_exit_status(self, status, notif_period, hosts, services): """Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE according to the status of a check result. :param status: integer between 0 and 4 :type status: int :return: None """ now = time.time() # we should put in last_state the good last state: # if not just change the state by an problem/impact # we can take current state. But if it's the case, the # real old state is self.state_before_impact (it's the TRUE # state in fact) # but only if the global conf have enable the impact state change cls = self.__class__ if cls.enable_problem_impacts_states_change \ and self.is_impact \ and not self.state_changed_since_impact: self.last_state = self.state_before_impact else: # standard case self.last_state = self.state # The last times are kept as integer values rather than float... no need for ms! if status == 0: self.state = u'OK' self.state_id = 0 self.last_time_ok = int(self.last_state_update) # self.last_time_ok = self.last_state_update state_code = 'o' elif status == 1: self.state = u'WARNING' self.state_id = 1 self.last_time_warning = int(self.last_state_update) # self.last_time_warning = self.last_state_update state_code = 'w' elif status == 2: self.state = u'CRITICAL' self.state_id = 2 self.last_time_critical = int(self.last_state_update) # self.last_time_critical = self.last_state_update state_code = 'c' elif status == 3: self.state = u'UNKNOWN' self.state_id = 3 self.last_time_unknown = int(self.last_state_update) # self.last_time_unknown = self.last_state_update state_code = 'u' elif status == 4: self.state = u'UNREACHABLE' self.state_id = 4 self.last_time_unreachable = int(self.last_state_update) # self.last_time_unreachable = self.last_state_update state_code = 'x' else: self.state = u'CRITICAL' # exit code UNDETERMINED self.state_id = 2 self.last_time_critical = int(self.last_state_update) # self.last_time_critical = self.last_state_update state_code = 'c' if state_code in self.flap_detection_options: self.add_flapping_change(self.state != self.last_state) # Now we add a value, we update the is_flapping prop self.update_flapping(notif_period, hosts, services) if self.state != self.last_state: self.last_state_change = self.last_state_update self.duration_sec = now - self.last_state_change
python
def set_state_from_exit_status(self, status, notif_period, hosts, services): now = time.time() # we should put in last_state the good last state: # if not just change the state by an problem/impact # we can take current state. But if it's the case, the # real old state is self.state_before_impact (it's the TRUE # state in fact) # but only if the global conf have enable the impact state change cls = self.__class__ if cls.enable_problem_impacts_states_change \ and self.is_impact \ and not self.state_changed_since_impact: self.last_state = self.state_before_impact else: # standard case self.last_state = self.state # The last times are kept as integer values rather than float... no need for ms! if status == 0: self.state = u'OK' self.state_id = 0 self.last_time_ok = int(self.last_state_update) # self.last_time_ok = self.last_state_update state_code = 'o' elif status == 1: self.state = u'WARNING' self.state_id = 1 self.last_time_warning = int(self.last_state_update) # self.last_time_warning = self.last_state_update state_code = 'w' elif status == 2: self.state = u'CRITICAL' self.state_id = 2 self.last_time_critical = int(self.last_state_update) # self.last_time_critical = self.last_state_update state_code = 'c' elif status == 3: self.state = u'UNKNOWN' self.state_id = 3 self.last_time_unknown = int(self.last_state_update) # self.last_time_unknown = self.last_state_update state_code = 'u' elif status == 4: self.state = u'UNREACHABLE' self.state_id = 4 self.last_time_unreachable = int(self.last_state_update) # self.last_time_unreachable = self.last_state_update state_code = 'x' else: self.state = u'CRITICAL' # exit code UNDETERMINED self.state_id = 2 self.last_time_critical = int(self.last_state_update) # self.last_time_critical = self.last_state_update state_code = 'c' if state_code in self.flap_detection_options: self.add_flapping_change(self.state != self.last_state) # Now we add a value, we update the is_flapping prop self.update_flapping(notif_period, hosts, services) if self.state != self.last_state: self.last_state_change = self.last_state_update self.duration_sec = now - self.last_state_change
[ "def", "set_state_from_exit_status", "(", "self", ",", "status", ",", "notif_period", ",", "hosts", ",", "services", ")", ":", "now", "=", "time", ".", "time", "(", ")", "# we should put in last_state the good last state:", "# if not just change the state by an problem/im...
Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE according to the status of a check result. :param status: integer between 0 and 4 :type status: int :return: None
[ "Set", "the", "state", "in", "UP", "WARNING", "CRITICAL", "UNKNOWN", "or", "UNREACHABLE", "according", "to", "the", "status", "of", "a", "check", "result", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L550-L619
21,221
Alignak-monitoring/alignak
alignak/objects/service.py
Service.is_state
def is_state(self, status): # pylint: disable=too-many-return-statements """Return True if status match the current service status :param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files :type status: str :return: True if status <=> self.status, otherwise False :rtype: bool """ if status == self.state: return True # Now low status if status == 'o' and self.state == u'OK': return True if status == 'c' and self.state == u'CRITICAL': return True if status == 'w' and self.state == u'WARNING': return True if status == 'u' and self.state == u'UNKNOWN': return True if status == 'x' and self.state == u'UNREACHABLE': return True return False
python
def is_state(self, status): # pylint: disable=too-many-return-statements if status == self.state: return True # Now low status if status == 'o' and self.state == u'OK': return True if status == 'c' and self.state == u'CRITICAL': return True if status == 'w' and self.state == u'WARNING': return True if status == 'u' and self.state == u'UNKNOWN': return True if status == 'x' and self.state == u'UNREACHABLE': return True return False
[ "def", "is_state", "(", "self", ",", "status", ")", ":", "# pylint: disable=too-many-return-statements", "if", "status", "==", "self", ".", "state", ":", "return", "True", "# Now low status", "if", "status", "==", "'o'", "and", "self", ".", "state", "==", "u'O...
Return True if status match the current service status :param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files :type status: str :return: True if status <=> self.status, otherwise False :rtype: bool
[ "Return", "True", "if", "status", "match", "the", "current", "service", "status" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L621-L643
21,222
Alignak-monitoring/alignak
alignak/objects/service.py
Service.last_time_non_ok_or_up
def last_time_non_ok_or_up(self): """Get the last time the service was in a non-OK state :return: the nearest last time the service was not ok :rtype: int """ non_ok_times = [x for x in [self.last_time_warning, self.last_time_critical, self.last_time_unknown] if x > self.last_time_ok] if not non_ok_times: last_time_non_ok = 0 # todo: program_start would be better? else: last_time_non_ok = min(non_ok_times) return last_time_non_ok
python
def last_time_non_ok_or_up(self): non_ok_times = [x for x in [self.last_time_warning, self.last_time_critical, self.last_time_unknown] if x > self.last_time_ok] if not non_ok_times: last_time_non_ok = 0 # todo: program_start would be better? else: last_time_non_ok = min(non_ok_times) return last_time_non_ok
[ "def", "last_time_non_ok_or_up", "(", "self", ")", ":", "non_ok_times", "=", "[", "x", "for", "x", "in", "[", "self", ".", "last_time_warning", ",", "self", ".", "last_time_critical", ",", "self", ".", "last_time_unknown", "]", "if", "x", ">", "self", ".",...
Get the last time the service was in a non-OK state :return: the nearest last time the service was not ok :rtype: int
[ "Get", "the", "last", "time", "the", "service", "was", "in", "a", "non", "-", "OK", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L645-L659
21,223
Alignak-monitoring/alignak
alignak/objects/service.py
Service.get_data_for_notifications
def get_data_for_notifications(self, contact, notif, host_ref): """Get data for a notification :param contact: The contact to return :type contact: :param notif: the notification to return :type notif: :return: list containing the service, the host and the given parameters :rtype: list """ if not host_ref: return [self, contact, notif] return [host_ref, self, contact, notif]
python
def get_data_for_notifications(self, contact, notif, host_ref): if not host_ref: return [self, contact, notif] return [host_ref, self, contact, notif]
[ "def", "get_data_for_notifications", "(", "self", ",", "contact", ",", "notif", ",", "host_ref", ")", ":", "if", "not", "host_ref", ":", "return", "[", "self", ",", "contact", ",", "notif", "]", "return", "[", "host_ref", ",", "self", ",", "contact", ","...
Get data for a notification :param contact: The contact to return :type contact: :param notif: the notification to return :type notif: :return: list containing the service, the host and the given parameters :rtype: list
[ "Get", "data", "for", "a", "notification" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1028-L1040
21,224
Alignak-monitoring/alignak
alignak/objects/service.py
Service.get_short_status
def get_short_status(self, hosts, services): """Get the short status of this host :return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state :rtype: str """ mapping = { 0: "O", 1: "W", 2: "C", 3: "U", 4: "N", } if self.got_business_rule: return mapping.get(self.business_rule.get_state(hosts, services), "n/a") return mapping.get(self.state_id, "n/a")
python
def get_short_status(self, hosts, services): mapping = { 0: "O", 1: "W", 2: "C", 3: "U", 4: "N", } if self.got_business_rule: return mapping.get(self.business_rule.get_state(hosts, services), "n/a") return mapping.get(self.state_id, "n/a")
[ "def", "get_short_status", "(", "self", ",", "hosts", ",", "services", ")", ":", "mapping", "=", "{", "0", ":", "\"O\"", ",", "1", ":", "\"W\"", ",", "2", ":", "\"C\"", ",", "3", ":", "\"U\"", ",", "4", ":", "\"N\"", ",", "}", "if", "self", "."...
Get the short status of this host :return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state :rtype: str
[ "Get", "the", "short", "status", "of", "this", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1257-L1273
21,225
Alignak-monitoring/alignak
alignak/objects/service.py
Services.add_template
def add_template(self, tpl): """ Adds and index a template into the `templates` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param tpl: The template to add :type tpl: :return: None """ objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') sdesc = getattr(tpl, 'service_description', '') hname = getattr(tpl, 'host_name', '') logger.debug("Adding a %s template: host_name: %s, name: %s, service_description: %s", objcls, hname, name, sdesc) if not name and not hname: msg = "a %s template has been defined without name nor host_name. from: %s" \ % (objcls, tpl.imported_from) tpl.add_error(msg) elif not name and not sdesc: msg = "a %s template has been defined without name nor service_description. from: %s" \ % (objcls, tpl.imported_from) tpl.add_error(msg) elif not name: # If name is not defined, use the host_name_service_description as name (fix #791) setattr(tpl, 'name', "%s_%s" % (hname, sdesc)) tpl = self.index_template(tpl) elif name: tpl = self.index_template(tpl) self.templates[tpl.uuid] = tpl logger.debug('\tAdded service template #%d %s', len(self.templates), tpl)
python
def add_template(self, tpl): objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') sdesc = getattr(tpl, 'service_description', '') hname = getattr(tpl, 'host_name', '') logger.debug("Adding a %s template: host_name: %s, name: %s, service_description: %s", objcls, hname, name, sdesc) if not name and not hname: msg = "a %s template has been defined without name nor host_name. from: %s" \ % (objcls, tpl.imported_from) tpl.add_error(msg) elif not name and not sdesc: msg = "a %s template has been defined without name nor service_description. from: %s" \ % (objcls, tpl.imported_from) tpl.add_error(msg) elif not name: # If name is not defined, use the host_name_service_description as name (fix #791) setattr(tpl, 'name', "%s_%s" % (hname, sdesc)) tpl = self.index_template(tpl) elif name: tpl = self.index_template(tpl) self.templates[tpl.uuid] = tpl logger.debug('\tAdded service template #%d %s', len(self.templates), tpl)
[ "def", "add_template", "(", "self", ",", "tpl", ")", ":", "objcls", "=", "self", ".", "inner_class", ".", "my_type", "name", "=", "getattr", "(", "tpl", ",", "'name'", ",", "''", ")", "sdesc", "=", "getattr", "(", "tpl", ",", "'service_description'", "...
Adds and index a template into the `templates` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param tpl: The template to add :type tpl: :return: None
[ "Adds", "and", "index", "a", "template", "into", "the", "templates", "container", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1312-L1344
21,226
Alignak-monitoring/alignak
alignak/objects/service.py
Services.find_srvs_by_hostname
def find_srvs_by_hostname(self, host_name): """Get all services from a host based on a host_name :param host_name: the host name we want services :type host_name: str :return: list of services :rtype: list[alignak.objects.service.Service] """ if hasattr(self, 'hosts'): host = self.hosts.find_by_name(host_name) if host is None: return None return host.get_services() return None
python
def find_srvs_by_hostname(self, host_name): if hasattr(self, 'hosts'): host = self.hosts.find_by_name(host_name) if host is None: return None return host.get_services() return None
[ "def", "find_srvs_by_hostname", "(", "self", ",", "host_name", ")", ":", "if", "hasattr", "(", "self", ",", "'hosts'", ")", ":", "host", "=", "self", ".", "hosts", ".", "find_by_name", "(", "host_name", ")", "if", "host", "is", "None", ":", "return", "...
Get all services from a host based on a host_name :param host_name: the host name we want services :type host_name: str :return: list of services :rtype: list[alignak.objects.service.Service]
[ "Get", "all", "services", "from", "a", "host", "based", "on", "a", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1358-L1371
21,227
Alignak-monitoring/alignak
alignak/objects/service.py
Services.find_srv_by_name_and_hostname
def find_srv_by_name_and_hostname(self, host_name, sdescr): """Get a specific service based on a host_name and service_description :param host_name: host name linked to needed service :type host_name: str :param sdescr: service name we need :type sdescr: str :return: the service found or None :rtype: alignak.objects.service.Service """ key = (host_name, sdescr) return self.name_to_item.get(key, None)
python
def find_srv_by_name_and_hostname(self, host_name, sdescr): key = (host_name, sdescr) return self.name_to_item.get(key, None)
[ "def", "find_srv_by_name_and_hostname", "(", "self", ",", "host_name", ",", "sdescr", ")", ":", "key", "=", "(", "host_name", ",", "sdescr", ")", "return", "self", ".", "name_to_item", ".", "get", "(", "key", ",", "None", ")" ]
Get a specific service based on a host_name and service_description :param host_name: host name linked to needed service :type host_name: str :param sdescr: service name we need :type sdescr: str :return: the service found or None :rtype: alignak.objects.service.Service
[ "Get", "a", "specific", "service", "based", "on", "a", "host_name", "and", "service_description" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1373-L1384
21,228
Alignak-monitoring/alignak
alignak/objects/service.py
Services.linkify_s_by_hst
def linkify_s_by_hst(self, hosts): """Link services with their parent host :param hosts: Hosts to look for simple host :type hosts: alignak.objects.host.Hosts :return: None """ for serv in self: # If we do not have a host_name, we set it as # a template element to delete. (like Nagios) if not hasattr(serv, 'host_name'): serv.host = None continue try: hst_name = serv.host_name # The new member list, in id hst = hosts.find_by_name(hst_name) # Let the host know we are his service if hst is not None: serv.host = hst.uuid hst.add_service_link(serv.uuid) else: # Ok, the host do not exists! err = "Warning: the service '%s' got an invalid host_name '%s'" % \ (serv.get_name(), hst_name) serv.configuration_warnings.append(err) continue except AttributeError: pass
python
def linkify_s_by_hst(self, hosts): for serv in self: # If we do not have a host_name, we set it as # a template element to delete. (like Nagios) if not hasattr(serv, 'host_name'): serv.host = None continue try: hst_name = serv.host_name # The new member list, in id hst = hosts.find_by_name(hst_name) # Let the host know we are his service if hst is not None: serv.host = hst.uuid hst.add_service_link(serv.uuid) else: # Ok, the host do not exists! err = "Warning: the service '%s' got an invalid host_name '%s'" % \ (serv.get_name(), hst_name) serv.configuration_warnings.append(err) continue except AttributeError: pass
[ "def", "linkify_s_by_hst", "(", "self", ",", "hosts", ")", ":", "for", "serv", "in", "self", ":", "# If we do not have a host_name, we set it as", "# a template element to delete. (like Nagios)", "if", "not", "hasattr", "(", "serv", ",", "'host_name'", ")", ":", "serv...
Link services with their parent host :param hosts: Hosts to look for simple host :type hosts: alignak.objects.host.Hosts :return: None
[ "Link", "services", "with", "their", "parent", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1487-L1514
21,229
Alignak-monitoring/alignak
alignak/objects/service.py
Services.linkify_s_by_sg
def linkify_s_by_sg(self, servicegroups): """Link services with servicegroups :param servicegroups: Servicegroups :type servicegroups: alignak.objects.servicegroup.Servicegroups :return: None """ for serv in self: new_servicegroups = [] if hasattr(serv, 'servicegroups') and serv.servicegroups != '': for sg_name in serv.servicegroups: sg_name = sg_name.strip() servicegroup = servicegroups.find_by_name(sg_name) if servicegroup is not None: new_servicegroups.append(servicegroup.uuid) else: err = "Error: the servicegroup '%s' of the service '%s' is unknown" %\ (sg_name, serv.get_dbg_name()) serv.add_error(err) serv.servicegroups = new_servicegroups
python
def linkify_s_by_sg(self, servicegroups): for serv in self: new_servicegroups = [] if hasattr(serv, 'servicegroups') and serv.servicegroups != '': for sg_name in serv.servicegroups: sg_name = sg_name.strip() servicegroup = servicegroups.find_by_name(sg_name) if servicegroup is not None: new_servicegroups.append(servicegroup.uuid) else: err = "Error: the servicegroup '%s' of the service '%s' is unknown" %\ (sg_name, serv.get_dbg_name()) serv.add_error(err) serv.servicegroups = new_servicegroups
[ "def", "linkify_s_by_sg", "(", "self", ",", "servicegroups", ")", ":", "for", "serv", "in", "self", ":", "new_servicegroups", "=", "[", "]", "if", "hasattr", "(", "serv", ",", "'servicegroups'", ")", "and", "serv", ".", "servicegroups", "!=", "''", ":", ...
Link services with servicegroups :param servicegroups: Servicegroups :type servicegroups: alignak.objects.servicegroup.Servicegroups :return: None
[ "Link", "services", "with", "servicegroups" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1516-L1535
21,230
Alignak-monitoring/alignak
alignak/objects/service.py
Services.clean
def clean(self): """Remove services without host object linked to Note that this should not happen! :return: None """ to_del = [] for serv in self: if not serv.host: to_del.append(serv.uuid) for service_uuid in to_del: del self.items[service_uuid]
python
def clean(self): to_del = [] for serv in self: if not serv.host: to_del.append(serv.uuid) for service_uuid in to_del: del self.items[service_uuid]
[ "def", "clean", "(", "self", ")", ":", "to_del", "=", "[", "]", "for", "serv", "in", "self", ":", "if", "not", "serv", ".", "host", ":", "to_del", ".", "append", "(", "serv", ".", "uuid", ")", "for", "service_uuid", "in", "to_del", ":", "del", "s...
Remove services without host object linked to Note that this should not happen! :return: None
[ "Remove", "services", "without", "host", "object", "linked", "to" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1586-L1598
21,231
Alignak-monitoring/alignak
alignak/objects/service.py
Services.explode_services_from_hosts
def explode_services_from_hosts(self, hosts, service, hnames): """ Explodes a service based on a list of hosts. :param hosts: The hosts container :type hosts: :param service: The base service to explode :type service: :param hnames: The host_name list to explode service on :type hnames: str :return: None """ duplicate_for_hosts = [] # get the list of our host_names if more than 1 not_hosts = [] # the list of !host_name so we remove them after for hname in hnames: hname = hname.strip() # If the name begin with a !, we put it in # the not list if hname.startswith('!'): not_hosts.append(hname[1:]) else: # the standard list duplicate_for_hosts.append(hname) # remove duplicate items from duplicate_for_hosts: duplicate_for_hosts = list(set(duplicate_for_hosts)) # Ok now we clean the duplicate_for_hosts with all hosts # of the not for hname in not_hosts: try: duplicate_for_hosts.remove(hname) except IndexError: pass # Now we duplicate the service for all host_names for hname in duplicate_for_hosts: host = hosts.find_by_name(hname) if host is None: service.add_error("Error: The hostname %s is unknown for the service %s!" % (hname, service.get_name())) continue if host.is_excluded_for(service): continue new_s = service.copy() new_s.host_name = hname self.add_item(new_s)
python
def explode_services_from_hosts(self, hosts, service, hnames): duplicate_for_hosts = [] # get the list of our host_names if more than 1 not_hosts = [] # the list of !host_name so we remove them after for hname in hnames: hname = hname.strip() # If the name begin with a !, we put it in # the not list if hname.startswith('!'): not_hosts.append(hname[1:]) else: # the standard list duplicate_for_hosts.append(hname) # remove duplicate items from duplicate_for_hosts: duplicate_for_hosts = list(set(duplicate_for_hosts)) # Ok now we clean the duplicate_for_hosts with all hosts # of the not for hname in not_hosts: try: duplicate_for_hosts.remove(hname) except IndexError: pass # Now we duplicate the service for all host_names for hname in duplicate_for_hosts: host = hosts.find_by_name(hname) if host is None: service.add_error("Error: The hostname %s is unknown for the service %s!" % (hname, service.get_name())) continue if host.is_excluded_for(service): continue new_s = service.copy() new_s.host_name = hname self.add_item(new_s)
[ "def", "explode_services_from_hosts", "(", "self", ",", "hosts", ",", "service", ",", "hnames", ")", ":", "duplicate_for_hosts", "=", "[", "]", "# get the list of our host_names if more than 1", "not_hosts", "=", "[", "]", "# the list of !host_name so we remove them after",...
Explodes a service based on a list of hosts. :param hosts: The hosts container :type hosts: :param service: The base service to explode :type service: :param hnames: The host_name list to explode service on :type hnames: str :return: None
[ "Explodes", "a", "service", "based", "on", "a", "list", "of", "hosts", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1600-L1646
21,232
Alignak-monitoring/alignak
alignak/objects/service.py
Services._local_create_service
def _local_create_service(self, hosts, host_name, service): """Create a new service based on a host_name and service instance. :param hosts: The hosts items instance. :type hosts: alignak.objects.host.Hosts :param host_name: The host_name to create a new service. :type host_name: str :param service: The service to be used as template. :type service: Service :return: The new service created. :rtype: alignak.objects.service.Service """ host = hosts.find_by_name(host_name.strip()) if host.is_excluded_for(service): return None # Creates a real service instance from the template new_s = service.copy() new_s.host_name = host_name new_s.register = 1 self.add_item(new_s) return new_s
python
def _local_create_service(self, hosts, host_name, service): host = hosts.find_by_name(host_name.strip()) if host.is_excluded_for(service): return None # Creates a real service instance from the template new_s = service.copy() new_s.host_name = host_name new_s.register = 1 self.add_item(new_s) return new_s
[ "def", "_local_create_service", "(", "self", ",", "hosts", ",", "host_name", ",", "service", ")", ":", "host", "=", "hosts", ".", "find_by_name", "(", "host_name", ".", "strip", "(", ")", ")", "if", "host", ".", "is_excluded_for", "(", "service", ")", ":...
Create a new service based on a host_name and service instance. :param hosts: The hosts items instance. :type hosts: alignak.objects.host.Hosts :param host_name: The host_name to create a new service. :type host_name: str :param service: The service to be used as template. :type service: Service :return: The new service created. :rtype: alignak.objects.service.Service
[ "Create", "a", "new", "service", "based", "on", "a", "host_name", "and", "service", "instance", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1649-L1670
21,233
Alignak-monitoring/alignak
alignak/objects/service.py
Services.explode_services_from_templates
def explode_services_from_templates(self, hosts, service_template): """ Explodes services from templates. All hosts holding the specified templates are bound with the service. :param hosts: The hosts container. :type hosts: alignak.objects.host.Hosts :param service_template: The service to explode. :type service_template: alignak.objects.service.Service :return: None """ hname = getattr(service_template, "host_name", None) if not hname: logger.debug("Service template %s is declared without an host_name", service_template.get_name()) return logger.debug("Explode services %s for the host: %s", service_template.get_name(), hname) # Now really create the services if is_complex_expr(hname): hnames = self.evaluate_hostgroup_expression( hname.strip(), hosts, hosts.templates, look_in='templates') for name in hnames: self._local_create_service(hosts, name, service_template) else: hnames = [n.strip() for n in hname.split(',') if n.strip()] for hname in hnames: for name in hosts.find_hosts_that_use_template(hname): self._local_create_service(hosts, name, service_template)
python
def explode_services_from_templates(self, hosts, service_template): hname = getattr(service_template, "host_name", None) if not hname: logger.debug("Service template %s is declared without an host_name", service_template.get_name()) return logger.debug("Explode services %s for the host: %s", service_template.get_name(), hname) # Now really create the services if is_complex_expr(hname): hnames = self.evaluate_hostgroup_expression( hname.strip(), hosts, hosts.templates, look_in='templates') for name in hnames: self._local_create_service(hosts, name, service_template) else: hnames = [n.strip() for n in hname.split(',') if n.strip()] for hname in hnames: for name in hosts.find_hosts_that_use_template(hname): self._local_create_service(hosts, name, service_template)
[ "def", "explode_services_from_templates", "(", "self", ",", "hosts", ",", "service_template", ")", ":", "hname", "=", "getattr", "(", "service_template", ",", "\"host_name\"", ",", "None", ")", "if", "not", "hname", ":", "logger", ".", "debug", "(", "\"Service...
Explodes services from templates. All hosts holding the specified templates are bound with the service. :param hosts: The hosts container. :type hosts: alignak.objects.host.Hosts :param service_template: The service to explode. :type service_template: alignak.objects.service.Service :return: None
[ "Explodes", "services", "from", "templates", ".", "All", "hosts", "holding", "the", "specified", "templates", "are", "bound", "with", "the", "service", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1672-L1701
21,234
Alignak-monitoring/alignak
alignak/objects/service.py
Services.explode_services_duplicates
def explode_services_duplicates(self, hosts, service): """ Explodes services holding a `duplicate_foreach` clause. :param hosts: The hosts container :type hosts: alignak.objects.host.Hosts :param service: The service to explode :type service: alignak.objects.service.Service """ hname = getattr(service, "host_name", None) if hname is None: return # the generator case, we must create several new services # we must find our host, and get all key:value we need host = hosts.find_by_name(hname.strip()) if host is None: service.add_error('Error: The hostname %s is unknown for the service %s!' % (hname, service.get_name())) return # Duplicate services for new_s in service.duplicate(host): if host.is_excluded_for(new_s): continue # Adds concrete instance self.add_item(new_s)
python
def explode_services_duplicates(self, hosts, service): hname = getattr(service, "host_name", None) if hname is None: return # the generator case, we must create several new services # we must find our host, and get all key:value we need host = hosts.find_by_name(hname.strip()) if host is None: service.add_error('Error: The hostname %s is unknown for the service %s!' % (hname, service.get_name())) return # Duplicate services for new_s in service.duplicate(host): if host.is_excluded_for(new_s): continue # Adds concrete instance self.add_item(new_s)
[ "def", "explode_services_duplicates", "(", "self", ",", "hosts", ",", "service", ")", ":", "hname", "=", "getattr", "(", "service", ",", "\"host_name\"", ",", "None", ")", "if", "hname", "is", "None", ":", "return", "# the generator case, we must create several ne...
Explodes services holding a `duplicate_foreach` clause. :param hosts: The hosts container :type hosts: alignak.objects.host.Hosts :param service: The service to explode :type service: alignak.objects.service.Service
[ "Explodes", "services", "holding", "a", "duplicate_foreach", "clause", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1703-L1729
21,235
Alignak-monitoring/alignak
alignak/objects/service.py
Services.register_service_into_servicegroups
def register_service_into_servicegroups(service, servicegroups): """ Registers a service into the service groups declared in its `servicegroups` attribute. :param service: The service to register :type service: :param servicegroups: The servicegroups container :type servicegroups: :return: None """ if hasattr(service, 'service_description'): sname = service.service_description shname = getattr(service, 'host_name', '') if hasattr(service, 'servicegroups'): # Todo: See if we can remove this if if isinstance(service.servicegroups, list): sgs = service.servicegroups else: sgs = service.servicegroups.split(',') for servicegroup in sgs: servicegroups.add_member([shname, sname], servicegroup.strip())
python
def register_service_into_servicegroups(service, servicegroups): if hasattr(service, 'service_description'): sname = service.service_description shname = getattr(service, 'host_name', '') if hasattr(service, 'servicegroups'): # Todo: See if we can remove this if if isinstance(service.servicegroups, list): sgs = service.servicegroups else: sgs = service.servicegroups.split(',') for servicegroup in sgs: servicegroups.add_member([shname, sname], servicegroup.strip())
[ "def", "register_service_into_servicegroups", "(", "service", ",", "servicegroups", ")", ":", "if", "hasattr", "(", "service", ",", "'service_description'", ")", ":", "sname", "=", "service", ".", "service_description", "shname", "=", "getattr", "(", "service", ",...
Registers a service into the service groups declared in its `servicegroups` attribute. :param service: The service to register :type service: :param servicegroups: The servicegroups container :type servicegroups: :return: None
[ "Registers", "a", "service", "into", "the", "service", "groups", "declared", "in", "its", "servicegroups", "attribute", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1732-L1753
21,236
Alignak-monitoring/alignak
alignak/objects/service.py
Services.register_service_dependencies
def register_service_dependencies(service, servicedependencies): """ Registers a service dependencies. :param service: The service to register :type service: :param servicedependencies: The servicedependencies container :type servicedependencies: :return: None """ # We explode service_dependencies into Servicedependency # We just create serviceDep with goods values (as STRING!), # the link pass will be done after sdeps = [d.strip() for d in getattr(service, "service_dependencies", [])] # %2=0 are for hosts, !=0 are for service_description i = 0 hname = '' for elt in sdeps: if i % 2 == 0: # host hname = elt else: # description desc = elt # we can register it (service) (depend on) -> (hname, desc) # If we do not have enough data for service, it'service no use if hasattr(service, 'service_description') and hasattr(service, 'host_name'): if hname == '': hname = service.host_name servicedependencies.add_service_dependency( service.host_name, service.service_description, hname, desc) i += 1
python
def register_service_dependencies(service, servicedependencies): # We explode service_dependencies into Servicedependency # We just create serviceDep with goods values (as STRING!), # the link pass will be done after sdeps = [d.strip() for d in getattr(service, "service_dependencies", [])] # %2=0 are for hosts, !=0 are for service_description i = 0 hname = '' for elt in sdeps: if i % 2 == 0: # host hname = elt else: # description desc = elt # we can register it (service) (depend on) -> (hname, desc) # If we do not have enough data for service, it'service no use if hasattr(service, 'service_description') and hasattr(service, 'host_name'): if hname == '': hname = service.host_name servicedependencies.add_service_dependency( service.host_name, service.service_description, hname, desc) i += 1
[ "def", "register_service_dependencies", "(", "service", ",", "servicedependencies", ")", ":", "# We explode service_dependencies into Servicedependency", "# We just create serviceDep with goods values (as STRING!),", "# the link pass will be done after", "sdeps", "=", "[", "d", ".", ...
Registers a service dependencies. :param service: The service to register :type service: :param servicedependencies: The servicedependencies container :type servicedependencies: :return: None
[ "Registers", "a", "service", "dependencies", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1756-L1785
21,237
Alignak-monitoring/alignak
alignak/objects/service.py
Services.explode
def explode(self, hosts, hostgroups, contactgroups, servicegroups, servicedependencies): # pylint: disable=too-many-locals """ Explodes services, from host, hostgroups, contactgroups, servicegroups and dependencies. :param hosts: The hosts container :type hosts: [alignak.object.host.Host] :param hostgroups: The hosts goups container :type hostgroups: [alignak.object.hostgroup.Hostgroup] :param contactgroups: The contacts goups container :type contactgroups: [alignak.object.contactgroup.Contactgroup] :param servicegroups: The services goups container :type servicegroups: [alignak.object.servicegroup.Servicegroup] :param servicedependencies: The services dependencies container :type servicedependencies: [alignak.object.servicedependency.Servicedependency] :return: None """ # Then for every service create a copy of the service with just the host # because we are adding services, we can't just loop in it itemkeys = list(self.items.keys()) for s_id in itemkeys: serv = self.items[s_id] # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self.explode_host_groups_into_hosts(serv, hosts, hostgroups) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self.explode_contact_groups_into_contacts(serv, contactgroups) hnames = getattr(serv, "host_name", '') hnames = list(set([n.strip() for n in hnames.split(',') if n.strip()])) # hnames = strip_and_uniq(hnames) # We will duplicate if we have multiple host_name # or if we are a template (so a clean service) if len(hnames) == 1: self.index_item(serv) else: if len(hnames) >= 2: self.explode_services_from_hosts(hosts, serv, hnames) # Delete expanded source service, even if some errors exist self.remove_item(serv) for s_id in self.templates: template = self.templates[s_id] self.explode_contact_groups_into_contacts(template, contactgroups) self.explode_services_from_templates(hosts, template) # Explode services that have a duplicate_foreach clause duplicates = [serv.uuid for serv in self if getattr(serv, 'duplicate_foreach', '')] for s_id in duplicates: serv = self.items[s_id] self.explode_services_duplicates(hosts, serv) if not serv.configuration_errors: self.remove_item(serv) to_remove = [] for service in self: host = hosts.find_by_name(service.host_name) if host and host.is_excluded_for(service): to_remove.append(service) for service in to_remove: self.remove_item(service) # Servicegroups property need to be fulfill for got the information # And then just register to this service_group for serv in self: self.register_service_into_servicegroups(serv, servicegroups) self.register_service_dependencies(serv, servicedependencies)
python
def explode(self, hosts, hostgroups, contactgroups, servicegroups, servicedependencies): # pylint: disable=too-many-locals # Then for every service create a copy of the service with just the host # because we are adding services, we can't just loop in it itemkeys = list(self.items.keys()) for s_id in itemkeys: serv = self.items[s_id] # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self.explode_host_groups_into_hosts(serv, hosts, hostgroups) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self.explode_contact_groups_into_contacts(serv, contactgroups) hnames = getattr(serv, "host_name", '') hnames = list(set([n.strip() for n in hnames.split(',') if n.strip()])) # hnames = strip_and_uniq(hnames) # We will duplicate if we have multiple host_name # or if we are a template (so a clean service) if len(hnames) == 1: self.index_item(serv) else: if len(hnames) >= 2: self.explode_services_from_hosts(hosts, serv, hnames) # Delete expanded source service, even if some errors exist self.remove_item(serv) for s_id in self.templates: template = self.templates[s_id] self.explode_contact_groups_into_contacts(template, contactgroups) self.explode_services_from_templates(hosts, template) # Explode services that have a duplicate_foreach clause duplicates = [serv.uuid for serv in self if getattr(serv, 'duplicate_foreach', '')] for s_id in duplicates: serv = self.items[s_id] self.explode_services_duplicates(hosts, serv) if not serv.configuration_errors: self.remove_item(serv) to_remove = [] for service in self: host = hosts.find_by_name(service.host_name) if host and host.is_excluded_for(service): to_remove.append(service) for service in to_remove: self.remove_item(service) # Servicegroups property need to be fulfill for got the information # And then just register to this service_group for serv in self: self.register_service_into_servicegroups(serv, servicegroups) self.register_service_dependencies(serv, servicedependencies)
[ "def", "explode", "(", "self", ",", "hosts", ",", "hostgroups", ",", "contactgroups", ",", "servicegroups", ",", "servicedependencies", ")", ":", "# pylint: disable=too-many-locals", "# Then for every service create a copy of the service with just the host", "# because we are add...
Explodes services, from host, hostgroups, contactgroups, servicegroups and dependencies. :param hosts: The hosts container :type hosts: [alignak.object.host.Host] :param hostgroups: The hosts goups container :type hostgroups: [alignak.object.hostgroup.Hostgroup] :param contactgroups: The contacts goups container :type contactgroups: [alignak.object.contactgroup.Contactgroup] :param servicegroups: The services goups container :type servicegroups: [alignak.object.servicegroup.Servicegroup] :param servicedependencies: The services dependencies container :type servicedependencies: [alignak.object.servicedependency.Servicedependency] :return: None
[ "Explodes", "services", "from", "host", "hostgroups", "contactgroups", "servicegroups", "and", "dependencies", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1788-L1856
21,238
Alignak-monitoring/alignak
alignak/objects/escalation.py
Escalation.get_next_notif_time
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period): """Get the next notification time for the escalation Only legit for time based escalation :param t_wished: time we would like to send a new notification (usually now) :type t_wished: :param status: status of the host or service :type status: :param creation_time: time the notification was created :type creation_time: :param interval: time interval length :type interval: int :return: timestamp for next notification or None :rtype: int | None """ short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c', u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's', u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'} # If we are not time based, we bail out! if not self.time_based: return None # Check if we are valid if status in short_states and short_states[status] not in self.escalation_options: return None # Look for the min of our future validity start = self.first_notification_time * interval + creation_time # If we are after the classic next time, we are not asking for a smaller interval if start > t_wished: return None # Maybe the time we found is not a valid one.... if escal_period is not None and not escal_period.is_time_valid(start): return None # Ok so I ask for my start as a possibility for the next notification time return start
python
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period): short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c', u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's', u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'} # If we are not time based, we bail out! if not self.time_based: return None # Check if we are valid if status in short_states and short_states[status] not in self.escalation_options: return None # Look for the min of our future validity start = self.first_notification_time * interval + creation_time # If we are after the classic next time, we are not asking for a smaller interval if start > t_wished: return None # Maybe the time we found is not a valid one.... if escal_period is not None and not escal_period.is_time_valid(start): return None # Ok so I ask for my start as a possibility for the next notification time return start
[ "def", "get_next_notif_time", "(", "self", ",", "t_wished", ",", "status", ",", "creation_time", ",", "interval", ",", "escal_period", ")", ":", "short_states", "=", "{", "u'WARNING'", ":", "'w'", ",", "u'UNKNOWN'", ":", "'u'", ",", "u'CRITICAL'", ":", "'c'"...
Get the next notification time for the escalation Only legit for time based escalation :param t_wished: time we would like to send a new notification (usually now) :type t_wished: :param status: status of the host or service :type status: :param creation_time: time the notification was created :type creation_time: :param interval: time interval length :type interval: int :return: timestamp for next notification or None :rtype: int | None
[ "Get", "the", "next", "notification", "time", "for", "the", "escalation", "Only", "legit", "for", "time", "based", "escalation" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L189-L228
21,239
Alignak-monitoring/alignak
alignak/objects/escalation.py
Escalations.linkify_es_by_s
def linkify_es_by_s(self, services): """Add each escalation object into service.escalation attribute :param services: service list, used to look for a specific service :type services: alignak.objects.service.Services :return: None """ for escalation in self: # If no host, no hope of having a service if not hasattr(escalation, 'host_name'): continue es_hname, sdesc = escalation.host_name, escalation.service_description if not es_hname.strip() or not sdesc.strip(): continue for hname in strip_and_uniq(es_hname.split(',')): if sdesc.strip() == '*': slist = services.find_srvs_by_hostname(hname) if slist is not None: slist = [services[serv] for serv in slist] for serv in slist: serv.escalations.append(escalation.uuid) else: for sname in strip_and_uniq(sdesc.split(',')): serv = services.find_srv_by_name_and_hostname(hname, sname) if serv is not None: serv.escalations.append(escalation.uuid)
python
def linkify_es_by_s(self, services): for escalation in self: # If no host, no hope of having a service if not hasattr(escalation, 'host_name'): continue es_hname, sdesc = escalation.host_name, escalation.service_description if not es_hname.strip() or not sdesc.strip(): continue for hname in strip_and_uniq(es_hname.split(',')): if sdesc.strip() == '*': slist = services.find_srvs_by_hostname(hname) if slist is not None: slist = [services[serv] for serv in slist] for serv in slist: serv.escalations.append(escalation.uuid) else: for sname in strip_and_uniq(sdesc.split(',')): serv = services.find_srv_by_name_and_hostname(hname, sname) if serv is not None: serv.escalations.append(escalation.uuid)
[ "def", "linkify_es_by_s", "(", "self", ",", "services", ")", ":", "for", "escalation", "in", "self", ":", "# If no host, no hope of having a service", "if", "not", "hasattr", "(", "escalation", ",", "'host_name'", ")", ":", "continue", "es_hname", ",", "sdesc", ...
Add each escalation object into service.escalation attribute :param services: service list, used to look for a specific service :type services: alignak.objects.service.Services :return: None
[ "Add", "each", "escalation", "object", "into", "service", ".", "escalation", "attribute" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L320-L347
21,240
Alignak-monitoring/alignak
alignak/objects/escalation.py
Escalations.linkify_es_by_h
def linkify_es_by_h(self, hosts): """Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None """ for escal in self: # If no host, no hope of having a service if (not hasattr(escal, 'host_name') or escal.host_name.strip() == '' or (hasattr(escal, 'service_description') and escal.service_description.strip() != '')): continue # I must be NOT a escalation on for service for hname in strip_and_uniq(escal.host_name.split(',')): host = hosts.find_by_name(hname) if host is not None: host.escalations.append(escal.uuid)
python
def linkify_es_by_h(self, hosts): for escal in self: # If no host, no hope of having a service if (not hasattr(escal, 'host_name') or escal.host_name.strip() == '' or (hasattr(escal, 'service_description') and escal.service_description.strip() != '')): continue # I must be NOT a escalation on for service for hname in strip_and_uniq(escal.host_name.split(',')): host = hosts.find_by_name(hname) if host is not None: host.escalations.append(escal.uuid)
[ "def", "linkify_es_by_h", "(", "self", ",", "hosts", ")", ":", "for", "escal", "in", "self", ":", "# If no host, no hope of having a service", "if", "(", "not", "hasattr", "(", "escal", ",", "'host_name'", ")", "or", "escal", ".", "host_name", ".", "strip", ...
Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None
[ "Add", "each", "escalation", "object", "into", "host", ".", "escalation", "attribute" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L349-L366
21,241
Alignak-monitoring/alignak
alignak/objects/escalation.py
Escalations.explode
def explode(self, hosts, hostgroups, contactgroups): """Loop over all escalation and explode hostsgroups in host and contactgroups in contacts Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts :param hosts: host list to explode :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroup list to explode :type hostgroups: alignak.objects.hostgroup.Hostgroups :param contactgroups: contactgroup list to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: None """ for i in self: # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self.explode_host_groups_into_hosts(i, hosts, hostgroups) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self.explode_contact_groups_into_contacts(i, contactgroups)
python
def explode(self, hosts, hostgroups, contactgroups): for i in self: # items::explode_host_groups_into_hosts # take all hosts from our hostgroup_name into our host_name property self.explode_host_groups_into_hosts(i, hosts, hostgroups) # items::explode_contact_groups_into_contacts # take all contacts from our contact_groups into our contact property self.explode_contact_groups_into_contacts(i, contactgroups)
[ "def", "explode", "(", "self", ",", "hosts", ",", "hostgroups", ",", "contactgroups", ")", ":", "for", "i", "in", "self", ":", "# items::explode_host_groups_into_hosts", "# take all hosts from our hostgroup_name into our host_name property", "self", ".", "explode_host_group...
Loop over all escalation and explode hostsgroups in host and contactgroups in contacts Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts :param hosts: host list to explode :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroup list to explode :type hostgroups: alignak.objects.hostgroup.Hostgroups :param contactgroups: contactgroup list to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: None
[ "Loop", "over", "all", "escalation", "and", "explode", "hostsgroups", "in", "host", "and", "contactgroups", "in", "contacts" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L368-L389
21,242
Alignak-monitoring/alignak
alignak/objects/hostgroup.py
Hostgroup.get_hosts_by_explosion
def get_hosts_by_explosion(self, hostgroups): # pylint: disable=access-member-before-definition """ Get hosts of this group :param hostgroups: Hostgroup object :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: list of hosts of this group :rtype: list """ # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every HG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[hostgroup::%s] got a loop in hostgroup definition", self.get_name()) return self.get_hosts() # Ok, not a loop, we tag it and continue self.rec_tag = True hg_mbrs = self.get_hostgroup_members() for hg_mbr in hg_mbrs: hostgroup = hostgroups.find_by_name(hg_mbr.strip()) if hostgroup is not None: value = hostgroup.get_hosts_by_explosion(hostgroups) if value is not None: self.add_members(value) return self.get_hosts()
python
def get_hosts_by_explosion(self, hostgroups): # pylint: disable=access-member-before-definition # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every HG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[hostgroup::%s] got a loop in hostgroup definition", self.get_name()) return self.get_hosts() # Ok, not a loop, we tag it and continue self.rec_tag = True hg_mbrs = self.get_hostgroup_members() for hg_mbr in hg_mbrs: hostgroup = hostgroups.find_by_name(hg_mbr.strip()) if hostgroup is not None: value = hostgroup.get_hosts_by_explosion(hostgroups) if value is not None: self.add_members(value) return self.get_hosts()
[ "def", "get_hosts_by_explosion", "(", "self", ",", "hostgroups", ")", ":", "# pylint: disable=access-member-before-definition", "# First we tag the hg so it will not be explode", "# if a son of it already call it", "self", ".", "already_exploded", "=", "True", "# Now the recursive pa...
Get hosts of this group :param hostgroups: Hostgroup object :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: list of hosts of this group :rtype: list
[ "Get", "hosts", "of", "this", "group" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L134-L167
21,243
Alignak-monitoring/alignak
alignak/objects/hostgroup.py
Hostgroups.add_member
def add_member(self, host_name, hostgroup_name): """Add a host string to a hostgroup member if the host group do not exist, create it :param host_name: host name :type host_name: str :param hostgroup_name:hostgroup name :type hostgroup_name: str :return: None """ hostgroup = self.find_by_name(hostgroup_name) if not hostgroup: hostgroup = Hostgroup({'hostgroup_name': hostgroup_name, 'alias': hostgroup_name, 'members': host_name}) self.add(hostgroup) else: hostgroup.add_members(host_name)
python
def add_member(self, host_name, hostgroup_name): hostgroup = self.find_by_name(hostgroup_name) if not hostgroup: hostgroup = Hostgroup({'hostgroup_name': hostgroup_name, 'alias': hostgroup_name, 'members': host_name}) self.add(hostgroup) else: hostgroup.add_members(host_name)
[ "def", "add_member", "(", "self", ",", "host_name", ",", "hostgroup_name", ")", ":", "hostgroup", "=", "self", ".", "find_by_name", "(", "hostgroup_name", ")", "if", "not", "hostgroup", ":", "hostgroup", "=", "Hostgroup", "(", "{", "'hostgroup_name'", ":", "...
Add a host string to a hostgroup member if the host group do not exist, create it :param host_name: host name :type host_name: str :param hostgroup_name:hostgroup name :type hostgroup_name: str :return: None
[ "Add", "a", "host", "string", "to", "a", "hostgroup", "member", "if", "the", "host", "group", "do", "not", "exist", "create", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L178-L195
21,244
Alignak-monitoring/alignak
alignak/objects/hostgroup.py
Hostgroups.linkify
def linkify(self, hosts=None, realms=None, forced_realms_hostgroups=True): """Link hostgroups with hosts and realms :param hosts: all Hosts :type hosts: alignak.objects.host.Hosts :param realms: all Realms :type realms: alignak.objects.realm.Realms :return: None """ self.linkify_hostgroups_hosts(hosts) self.linkify_hostgroups_realms_hosts(realms, hosts, forced_realms_hostgroups)
python
def linkify(self, hosts=None, realms=None, forced_realms_hostgroups=True): self.linkify_hostgroups_hosts(hosts) self.linkify_hostgroups_realms_hosts(realms, hosts, forced_realms_hostgroups)
[ "def", "linkify", "(", "self", ",", "hosts", "=", "None", ",", "realms", "=", "None", ",", "forced_realms_hostgroups", "=", "True", ")", ":", "self", ".", "linkify_hostgroups_hosts", "(", "hosts", ")", "self", ".", "linkify_hostgroups_realms_hosts", "(", "real...
Link hostgroups with hosts and realms :param hosts: all Hosts :type hosts: alignak.objects.host.Hosts :param realms: all Realms :type realms: alignak.objects.realm.Realms :return: None
[ "Link", "hostgroups", "with", "hosts", "and", "realms" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L210-L220
21,245
Alignak-monitoring/alignak
alignak/objects/hostgroup.py
Hostgroups.linkify_hostgroups_hosts
def linkify_hostgroups_hosts(self, hosts): """We just search for each hostgroup the id of the hosts and replace the names by the found identifiers :param hosts: object Hosts :type hosts: alignak.objects.host.Hosts :return: None """ for hostgroup in self: members = hostgroup.get_hosts() # The new members identifiers list new_members = [] for member in members: # member is an host name member = member.strip() if not member: # void entry, skip this continue if member == '*': # All the hosts identifiers list new_members.extend(list(hosts.items.keys())) else: host = hosts.find_by_name(member) if host is not None: new_members.append(host.uuid) if hostgroup.uuid not in host.hostgroups: host.hostgroups.append(hostgroup.uuid) else: hostgroup.add_unknown_members(member) # Make members unique new_members = list(set(new_members)) # We find the id, we replace the names hostgroup.replace_members(new_members)
python
def linkify_hostgroups_hosts(self, hosts): for hostgroup in self: members = hostgroup.get_hosts() # The new members identifiers list new_members = [] for member in members: # member is an host name member = member.strip() if not member: # void entry, skip this continue if member == '*': # All the hosts identifiers list new_members.extend(list(hosts.items.keys())) else: host = hosts.find_by_name(member) if host is not None: new_members.append(host.uuid) if hostgroup.uuid not in host.hostgroups: host.hostgroups.append(hostgroup.uuid) else: hostgroup.add_unknown_members(member) # Make members unique new_members = list(set(new_members)) # We find the id, we replace the names hostgroup.replace_members(new_members)
[ "def", "linkify_hostgroups_hosts", "(", "self", ",", "hosts", ")", ":", "for", "hostgroup", "in", "self", ":", "members", "=", "hostgroup", ".", "get_hosts", "(", ")", "# The new members identifiers list", "new_members", "=", "[", "]", "for", "member", "in", "...
We just search for each hostgroup the id of the hosts and replace the names by the found identifiers :param hosts: object Hosts :type hosts: alignak.objects.host.Hosts :return: None
[ "We", "just", "search", "for", "each", "hostgroup", "the", "id", "of", "the", "hosts", "and", "replace", "the", "names", "by", "the", "found", "identifiers" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L222-L256
21,246
Alignak-monitoring/alignak
alignak/objects/hostgroup.py
Hostgroups.explode
def explode(self): """ Fill members with hostgroup_members :return: None """ # We do not want a same hostgroup to be exploded again and again # so we tag it for tmp_hg in list(self.items.values()): tmp_hg.already_exploded = False for hostgroup in list(self.items.values()): if hostgroup.already_exploded: continue # get_hosts_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_hg in list(self.items.values()): tmp_hg.rec_tag = False hostgroup.get_hosts_by_explosion(self) # We clean the tags for tmp_hg in list(self.items.values()): if hasattr(tmp_hg, 'rec_tag'): del tmp_hg.rec_tag del tmp_hg.already_exploded
python
def explode(self): # We do not want a same hostgroup to be exploded again and again # so we tag it for tmp_hg in list(self.items.values()): tmp_hg.already_exploded = False for hostgroup in list(self.items.values()): if hostgroup.already_exploded: continue # get_hosts_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_hg in list(self.items.values()): tmp_hg.rec_tag = False hostgroup.get_hosts_by_explosion(self) # We clean the tags for tmp_hg in list(self.items.values()): if hasattr(tmp_hg, 'rec_tag'): del tmp_hg.rec_tag del tmp_hg.already_exploded
[ "def", "explode", "(", "self", ")", ":", "# We do not want a same hostgroup to be exploded again and again", "# so we tag it", "for", "tmp_hg", "in", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ":", "tmp_hg", ".", "already_exploded", "=", "Fal...
Fill members with hostgroup_members :return: None
[ "Fill", "members", "with", "hostgroup_members" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L380-L405
21,247
Alignak-monitoring/alignak
alignak/http/daemon.py
HTTPDaemon.run
def run(self): """Wrapper to start the CherryPy server This function throws a PortNotFree exception if any socket error is raised. :return: None """ def _started_callback(): """Callback function when Cherrypy Engine is started""" cherrypy.log("CherryPy engine started and listening...") self.cherrypy_thread = None try: cherrypy.log("Starting CherryPy engine on %s" % (self.uri)) self.cherrypy_thread = cherrypy.engine.start_with_callback(_started_callback) cherrypy.engine.block() cherrypy.log("Exited from the engine block") except socket.error as exp: raise PortNotFree("Error: Sorry, the HTTP server did not started correctly: error: %s" % (str(exp)))
python
def run(self): def _started_callback(): """Callback function when Cherrypy Engine is started""" cherrypy.log("CherryPy engine started and listening...") self.cherrypy_thread = None try: cherrypy.log("Starting CherryPy engine on %s" % (self.uri)) self.cherrypy_thread = cherrypy.engine.start_with_callback(_started_callback) cherrypy.engine.block() cherrypy.log("Exited from the engine block") except socket.error as exp: raise PortNotFree("Error: Sorry, the HTTP server did not started correctly: error: %s" % (str(exp)))
[ "def", "run", "(", "self", ")", ":", "def", "_started_callback", "(", ")", ":", "\"\"\"Callback function when Cherrypy Engine is started\"\"\"", "cherrypy", ".", "log", "(", "\"CherryPy engine started and listening...\"", ")", "self", ".", "cherrypy_thread", "=", "None", ...
Wrapper to start the CherryPy server This function throws a PortNotFree exception if any socket error is raised. :return: None
[ "Wrapper", "to", "start", "the", "CherryPy", "server" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/daemon.py#L163-L182
21,248
Alignak-monitoring/alignak
alignak/http/daemon.py
HTTPDaemon.stop
def stop(self): # pylint: disable=no-self-use """Wrapper to stop the CherryPy server :return: None """ cherrypy.log("Stopping CherryPy engine (current state: %s)..." % cherrypy.engine.state) try: cherrypy.engine.exit() except RuntimeWarning: pass except SystemExit: cherrypy.log('SystemExit raised: shutting down bus') cherrypy.log("Stopped")
python
def stop(self): # pylint: disable=no-self-use cherrypy.log("Stopping CherryPy engine (current state: %s)..." % cherrypy.engine.state) try: cherrypy.engine.exit() except RuntimeWarning: pass except SystemExit: cherrypy.log('SystemExit raised: shutting down bus') cherrypy.log("Stopped")
[ "def", "stop", "(", "self", ")", ":", "# pylint: disable=no-self-use", "cherrypy", ".", "log", "(", "\"Stopping CherryPy engine (current state: %s)...\"", "%", "cherrypy", ".", "engine", ".", "state", ")", "try", ":", "cherrypy", ".", "engine", ".", "exit", "(", ...
Wrapper to stop the CherryPy server :return: None
[ "Wrapper", "to", "stop", "the", "CherryPy", "server" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/daemon.py#L184-L196
21,249
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.create_queues
def create_queues(self, manager=None): """ Create the shared queues that will be used by alignak daemon process and this module process. But clear queues if they were already set before recreating new one. Note: If manager is None, then we are running the unit tests for the modules and we must create some queues for the external modules without a SyncManager :param manager: Manager() object :type manager: None | object :return: None """ self.clear_queues(manager) # If no Manager() object, go with classic Queue() if not manager: self.from_q = Queue() self.to_q = Queue() else: self.from_q = manager.Queue() self.to_q = manager.Queue()
python
def create_queues(self, manager=None): self.clear_queues(manager) # If no Manager() object, go with classic Queue() if not manager: self.from_q = Queue() self.to_q = Queue() else: self.from_q = manager.Queue() self.to_q = manager.Queue()
[ "def", "create_queues", "(", "self", ",", "manager", "=", "None", ")", ":", "self", ".", "clear_queues", "(", "manager", ")", "# If no Manager() object, go with classic Queue()", "if", "not", "manager", ":", "self", ".", "from_q", "=", "Queue", "(", ")", "self...
Create the shared queues that will be used by alignak daemon process and this module process. But clear queues if they were already set before recreating new one. Note: If manager is None, then we are running the unit tests for the modules and we must create some queues for the external modules without a SyncManager :param manager: Manager() object :type manager: None | object :return: None
[ "Create", "the", "shared", "queues", "that", "will", "be", "used", "by", "alignak", "daemon", "process", "and", "this", "module", "process", ".", "But", "clear", "queues", "if", "they", "were", "already", "set", "before", "recreating", "new", "one", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L189-L210
21,250
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.clear_queues
def clear_queues(self, manager): """Release the resources associated to the queues of this instance :param manager: Manager() object :type manager: None | object :return: None """ for queue in (self.to_q, self.from_q): if queue is None: continue # If we got no manager, we directly call the clean if not manager: try: queue.close() queue.join_thread() except AttributeError: pass # else: # q._callmethod('close') # q._callmethod('join_thread') self.to_q = self.from_q = None
python
def clear_queues(self, manager): for queue in (self.to_q, self.from_q): if queue is None: continue # If we got no manager, we directly call the clean if not manager: try: queue.close() queue.join_thread() except AttributeError: pass # else: # q._callmethod('close') # q._callmethod('join_thread') self.to_q = self.from_q = None
[ "def", "clear_queues", "(", "self", ",", "manager", ")", ":", "for", "queue", "in", "(", "self", ".", "to_q", ",", "self", ".", "from_q", ")", ":", "if", "queue", "is", "None", ":", "continue", "# If we got no manager, we directly call the clean", "if", "not...
Release the resources associated to the queues of this instance :param manager: Manager() object :type manager: None | object :return: None
[ "Release", "the", "resources", "associated", "to", "the", "queues", "of", "this", "instance" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L212-L232
21,251
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.start_module
def start_module(self): """Wrapper for _main function. Catch and raise any exception occurring in the main function :return: None """ try: self._main() except Exception as exp: logger.exception('%s', traceback.format_exc()) raise Exception(exp)
python
def start_module(self): try: self._main() except Exception as exp: logger.exception('%s', traceback.format_exc()) raise Exception(exp)
[ "def", "start_module", "(", "self", ")", ":", "try", ":", "self", ".", "_main", "(", ")", "except", "Exception", "as", "exp", ":", "logger", ".", "exception", "(", "'%s'", ",", "traceback", ".", "format_exc", "(", ")", ")", "raise", "Exception", "(", ...
Wrapper for _main function. Catch and raise any exception occurring in the main function :return: None
[ "Wrapper", "for", "_main", "function", ".", "Catch", "and", "raise", "any", "exception", "occurring", "in", "the", "main", "function" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L234-L244
21,252
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.start
def start(self, http_daemon=None): # pylint: disable=unused-argument """Actually restart the process if the module is external Try first to stop the process and create a new Process instance with target start_module. Finally start process. :param http_daemon: Not used here but can be used in other modules :type http_daemon: None | object :return: None """ if not self.is_external: return if self.process: self.stop_process() logger.info("Starting external process for module %s...", self.name) proc = Process(target=self.start_module, args=(), group=None) # Under windows we should not call start() on an object that got its process # as an object, so we remove it and we set it in a earlier start try: del self.properties['process'] except KeyError: pass proc.start() # We save the process data AFTER the fork() self.process = proc self.properties['process'] = proc logger.info("%s is now started (pid=%d)", self.name, proc.pid)
python
def start(self, http_daemon=None): # pylint: disable=unused-argument if not self.is_external: return if self.process: self.stop_process() logger.info("Starting external process for module %s...", self.name) proc = Process(target=self.start_module, args=(), group=None) # Under windows we should not call start() on an object that got its process # as an object, so we remove it and we set it in a earlier start try: del self.properties['process'] except KeyError: pass proc.start() # We save the process data AFTER the fork() self.process = proc self.properties['process'] = proc logger.info("%s is now started (pid=%d)", self.name, proc.pid)
[ "def", "start", "(", "self", ",", "http_daemon", "=", "None", ")", ":", "# pylint: disable=unused-argument", "if", "not", "self", ".", "is_external", ":", "return", "if", "self", ".", "process", ":", "self", ".", "stop_process", "(", ")", "logger", ".", "i...
Actually restart the process if the module is external Try first to stop the process and create a new Process instance with target start_module. Finally start process. :param http_daemon: Not used here but can be used in other modules :type http_daemon: None | object :return: None
[ "Actually", "restart", "the", "process", "if", "the", "module", "is", "external", "Try", "first", "to", "stop", "the", "process", "and", "create", "a", "new", "Process", "instance", "with", "target", "start_module", ".", "Finally", "start", "process", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L246-L276
21,253
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.stop_process
def stop_process(self): """Request the module process to stop and release it :return: None """ if not self.process: return logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid) self.kill() # Clean inner process reference self.process = None
python
def stop_process(self): if not self.process: return logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid) self.kill() # Clean inner process reference self.process = None
[ "def", "stop_process", "(", "self", ")", ":", "if", "not", "self", ".", "process", ":", "return", "logger", ".", "info", "(", "\"I'm stopping module %r (pid=%d)\"", ",", "self", ".", "name", ",", "self", ".", "process", ".", "pid", ")", "self", ".", "kil...
Request the module process to stop and release it :return: None
[ "Request", "the", "module", "process", "to", "stop", "and", "release", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L303-L314
21,254
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.manage_brok
def manage_brok(self, brok): """Request the module to manage the given brok. There are a lot of different possible broks to manage. The list is defined in the Brok class. An internal module may redefine this function or, easier, define only the function for the brok it is interested with. Hence a module interested in the `service_check_result` broks will only need to define a function named as `manage_service_check_result_brok` :param brok: :type brok: :return: :rtype: """ manage = getattr(self, 'manage_' + brok.type + '_brok', None) if not manage: return False # Be sure the brok is prepared before calling the function brok.prepare() return manage(brok)
python
def manage_brok(self, brok): manage = getattr(self, 'manage_' + brok.type + '_brok', None) if not manage: return False # Be sure the brok is prepared before calling the function brok.prepare() return manage(brok)
[ "def", "manage_brok", "(", "self", ",", "brok", ")", ":", "manage", "=", "getattr", "(", "self", ",", "'manage_'", "+", "brok", ".", "type", "+", "'_brok'", ",", "None", ")", "if", "not", "manage", ":", "return", "False", "# Be sure the brok is prepared be...
Request the module to manage the given brok. There are a lot of different possible broks to manage. The list is defined in the Brok class. An internal module may redefine this function or, easier, define only the function for the brok it is interested with. Hence a module interested in the `service_check_result` broks will only need to define a function named as `manage_service_check_result_brok` :param brok: :type brok: :return: :rtype:
[ "Request", "the", "module", "to", "manage", "the", "given", "brok", ".", "There", "are", "a", "lot", "of", "different", "possible", "broks", "to", "manage", ".", "The", "list", "is", "defined", "in", "the", "Brok", "class", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L327-L348
21,255
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule.manage_signal
def manage_signal(self, sig, frame): # pylint: disable=unused-argument """Generic function to handle signals Only called when the module process received SIGINT or SIGKILL. Set interrupted attribute to True, self.process to None and returns :param sig: signal sent :type sig: :param frame: frame before catching signal :type frame: :return: None """ logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) if sig == signal.SIGHUP: # if SIGHUP, reload configuration in arbiter logger.info("Modules are not able to reload their configuration. " "Stopping the module...") logger.info("Request to stop the module") self.interrupted = True
python
def manage_signal(self, sig, frame): # pylint: disable=unused-argument logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) if sig == signal.SIGHUP: # if SIGHUP, reload configuration in arbiter logger.info("Modules are not able to reload their configuration. " "Stopping the module...") logger.info("Request to stop the module") self.interrupted = True
[ "def", "manage_signal", "(", "self", ",", "sig", ",", "frame", ")", ":", "# pylint: disable=unused-argument", "logger", ".", "info", "(", "\"received a signal: %s\"", ",", "SIGNALS_TO_NAMES_DICT", "[", "sig", "]", ")", "if", "sig", "==", "signal", ".", "SIGHUP",...
Generic function to handle signals Only called when the module process received SIGINT or SIGKILL. Set interrupted attribute to True, self.process to None and returns :param sig: signal sent :type sig: :param frame: frame before catching signal :type frame: :return: None
[ "Generic", "function", "to", "handle", "signals" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L350-L371
21,256
Alignak-monitoring/alignak
alignak/basemodule.py
BaseModule._main
def _main(self): """module "main" method. Only used by external modules. :return: None """ self.set_proctitle(self.name) self.set_signal_handler() logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid()) # Will block here! try: self.main() except (IOError, EOFError): pass # logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc()) except Exception as exp: # pylint: disable=broad-except logger.exception('main function exception: %s', exp) self.do_stop() logger.info("process for module %s is now exiting (pid=%d)", self.name, os.getpid()) exit()
python
def _main(self): self.set_proctitle(self.name) self.set_signal_handler() logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid()) # Will block here! try: self.main() except (IOError, EOFError): pass # logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc()) except Exception as exp: # pylint: disable=broad-except logger.exception('main function exception: %s', exp) self.do_stop() logger.info("process for module %s is now exiting (pid=%d)", self.name, os.getpid()) exit()
[ "def", "_main", "(", "self", ")", ":", "self", ".", "set_proctitle", "(", "self", ".", "name", ")", "self", ".", "set_signal_handler", "(", ")", "logger", ".", "info", "(", "\"process for module %s is now running (pid=%d)\"", ",", "self", ".", "name", ",", "...
module "main" method. Only used by external modules. :return: None
[ "module", "main", "method", ".", "Only", "used", "by", "external", "modules", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L435-L457
21,257
Alignak-monitoring/alignak
alignak/action.py
no_block_read
def no_block_read(output): """Try to read a file descriptor in a non blocking mode If the fcntl is available (unix only) we try to read in a asynchronous mode, so we won't block the PIPE at 64K buffer (deadlock...) :param output: file or socket to read from :type output: file :return: data read from fd :rtype: str """ _buffer = "" if not fcntl: return _buffer o_fd = output.fileno() o_fl = fcntl.fcntl(o_fd, fcntl.F_GETFL) fcntl.fcntl(o_fd, fcntl.F_SETFL, o_fl | os.O_NONBLOCK) try: _buffer = output.read() except Exception: # pylint: disable=broad-except pass return _buffer
python
def no_block_read(output): _buffer = "" if not fcntl: return _buffer o_fd = output.fileno() o_fl = fcntl.fcntl(o_fd, fcntl.F_GETFL) fcntl.fcntl(o_fd, fcntl.F_SETFL, o_fl | os.O_NONBLOCK) try: _buffer = output.read() except Exception: # pylint: disable=broad-except pass return _buffer
[ "def", "no_block_read", "(", "output", ")", ":", "_buffer", "=", "\"\"", "if", "not", "fcntl", ":", "return", "_buffer", "o_fd", "=", "output", ".", "fileno", "(", ")", "o_fl", "=", "fcntl", ".", "fcntl", "(", "o_fd", ",", "fcntl", ".", "F_GETFL", ")...
Try to read a file descriptor in a non blocking mode If the fcntl is available (unix only) we try to read in a asynchronous mode, so we won't block the PIPE at 64K buffer (deadlock...) :param output: file or socket to read from :type output: file :return: data read from fd :rtype: str
[ "Try", "to", "read", "a", "file", "descriptor", "in", "a", "non", "blocking", "mode" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/action.py#L106-L130
21,258
Alignak-monitoring/alignak
alignak/action.py
ActionBase.get_local_environnement
def get_local_environnement(self): """ Mix the environment and the environment variables into a new local environment dictionary Note: We cannot just update the global os.environ because this would effect all other checks. :return: local environment variables :rtype: dict """ # Do not use copy.copy() here, as the resulting copy still # changes the real environment (it is still a os._Environment # instance). local_env = os.environ.copy() for local_var in self.env: local_env[local_var] = self.env[local_var] return local_env
python
def get_local_environnement(self): # Do not use copy.copy() here, as the resulting copy still # changes the real environment (it is still a os._Environment # instance). local_env = os.environ.copy() for local_var in self.env: local_env[local_var] = self.env[local_var] return local_env
[ "def", "get_local_environnement", "(", "self", ")", ":", "# Do not use copy.copy() here, as the resulting copy still", "# changes the real environment (it is still a os._Environment", "# instance).", "local_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "for", "local_v...
Mix the environment and the environment variables into a new local environment dictionary Note: We cannot just update the global os.environ because this would effect all other checks. :return: local environment variables :rtype: dict
[ "Mix", "the", "environment", "and", "the", "environment", "variables", "into", "a", "new", "local", "environment", "dictionary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/action.py#L245-L262
21,259
Alignak-monitoring/alignak
alignak/action.py
ActionBase.execute
def execute(self): """Start this action command in a subprocess. :raise: ActionError 'toomanyopenfiles' if too many opened files on the system 'no_process_launched' if arguments parsing failed 'process_launch_failed': if the process launch failed :return: reference to the started process :rtype: psutil.Process """ self.status = ACT_STATUS_LAUNCHED self.check_time = time.time() self.wait_time = 0.0001 self.last_poll = self.check_time # Get a local env variables with our additional values self.local_env = self.get_local_environnement() # Initialize stdout and stderr. self.stdoutdata = '' self.stderrdata = '' logger.debug("Launch command: '%s', ref: %s, timeout: %s", self.command, self.ref, self.timeout) if self.log_actions: if os.environ['ALIGNAK_LOG_ACTIONS'] == 'WARNING': logger.warning("Launch command: '%s'", self.command) else: logger.info("Launch command: '%s'", self.command) return self._execute()
python
def execute(self): self.status = ACT_STATUS_LAUNCHED self.check_time = time.time() self.wait_time = 0.0001 self.last_poll = self.check_time # Get a local env variables with our additional values self.local_env = self.get_local_environnement() # Initialize stdout and stderr. self.stdoutdata = '' self.stderrdata = '' logger.debug("Launch command: '%s', ref: %s, timeout: %s", self.command, self.ref, self.timeout) if self.log_actions: if os.environ['ALIGNAK_LOG_ACTIONS'] == 'WARNING': logger.warning("Launch command: '%s'", self.command) else: logger.info("Launch command: '%s'", self.command) return self._execute()
[ "def", "execute", "(", "self", ")", ":", "self", ".", "status", "=", "ACT_STATUS_LAUNCHED", "self", ".", "check_time", "=", "time", ".", "time", "(", ")", "self", ".", "wait_time", "=", "0.0001", "self", ".", "last_poll", "=", "self", ".", "check_time", ...
Start this action command in a subprocess. :raise: ActionError 'toomanyopenfiles' if too many opened files on the system 'no_process_launched' if arguments parsing failed 'process_launch_failed': if the process launch failed :return: reference to the started process :rtype: psutil.Process
[ "Start", "this", "action", "command", "in", "a", "subprocess", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/action.py#L264-L295
21,260
Alignak-monitoring/alignak
alignak/action.py
ActionBase.copy_shell__
def copy_shell__(self, new_i): """Create all attributes listed in 'ONLY_COPY_PROP' and return `self` with these attributes. :param new_i: object to :type new_i: object :return: object with new properties added :rtype: object """ for prop in ONLY_COPY_PROP: setattr(new_i, prop, getattr(self, prop)) return new_i
python
def copy_shell__(self, new_i): for prop in ONLY_COPY_PROP: setattr(new_i, prop, getattr(self, prop)) return new_i
[ "def", "copy_shell__", "(", "self", ",", "new_i", ")", ":", "for", "prop", "in", "ONLY_COPY_PROP", ":", "setattr", "(", "new_i", ",", "prop", ",", "getattr", "(", "self", ",", "prop", ")", ")", "return", "new_i" ]
Create all attributes listed in 'ONLY_COPY_PROP' and return `self` with these attributes. :param new_i: object to :type new_i: object :return: object with new properties added :rtype: object
[ "Create", "all", "attributes", "listed", "in", "ONLY_COPY_PROP", "and", "return", "self", "with", "these", "attributes", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/action.py#L507-L517
21,261
Alignak-monitoring/alignak
alignak/objects/contactgroup.py
Contactgroup.get_contacts_by_explosion
def get_contacts_by_explosion(self, contactgroups): # pylint: disable=access-member-before-definition """ Get contacts of this group :param contactgroups: Contactgroups object, use to look for a specific one :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: list of contact of this group :rtype: list[alignak.objects.contact.Contact] """ # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every CG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[contactgroup::%s] got a loop in contactgroup definition", self.get_name()) if hasattr(self, 'members'): return self.members return '' # Ok, not a loop, we tag it and continue self.rec_tag = True cg_mbrs = self.get_contactgroup_members() for cg_mbr in cg_mbrs: contactgroup = contactgroups.find_by_name(cg_mbr.strip()) if contactgroup is not None: value = contactgroup.get_contacts_by_explosion(contactgroups) if value is not None: self.add_members(value) if hasattr(self, 'members'): return self.members return ''
python
def get_contacts_by_explosion(self, contactgroups): # pylint: disable=access-member-before-definition # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every CG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[contactgroup::%s] got a loop in contactgroup definition", self.get_name()) if hasattr(self, 'members'): return self.members return '' # Ok, not a loop, we tag it and continue self.rec_tag = True cg_mbrs = self.get_contactgroup_members() for cg_mbr in cg_mbrs: contactgroup = contactgroups.find_by_name(cg_mbr.strip()) if contactgroup is not None: value = contactgroup.get_contacts_by_explosion(contactgroups) if value is not None: self.add_members(value) if hasattr(self, 'members'): return self.members return ''
[ "def", "get_contacts_by_explosion", "(", "self", ",", "contactgroups", ")", ":", "# pylint: disable=access-member-before-definition", "# First we tag the hg so it will not be explode", "# if a son of it already call it", "self", ".", "already_exploded", "=", "True", "# Now the recurs...
Get contacts of this group :param contactgroups: Contactgroups object, use to look for a specific one :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: list of contact of this group :rtype: list[alignak.objects.contact.Contact]
[ "Get", "contacts", "of", "this", "group" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contactgroup.py#L110-L148
21,262
Alignak-monitoring/alignak
alignak/objects/contactgroup.py
Contactgroups.add_member
def add_member(self, contact_name, contactgroup_name): """Add a contact string to a contact member if the contact group do not exist, create it :param contact_name: contact name :type contact_name: str :param contactgroup_name: contact group name :type contactgroup_name: str :return: None """ contactgroup = self.find_by_name(contactgroup_name) if not contactgroup: contactgroup = Contactgroup({'contactgroup_name': contactgroup_name, 'alias': contactgroup_name, 'members': contact_name}) self.add_contactgroup(contactgroup) else: contactgroup.add_members(contact_name)
python
def add_member(self, contact_name, contactgroup_name): contactgroup = self.find_by_name(contactgroup_name) if not contactgroup: contactgroup = Contactgroup({'contactgroup_name': contactgroup_name, 'alias': contactgroup_name, 'members': contact_name}) self.add_contactgroup(contactgroup) else: contactgroup.add_members(contact_name)
[ "def", "add_member", "(", "self", ",", "contact_name", ",", "contactgroup_name", ")", ":", "contactgroup", "=", "self", ".", "find_by_name", "(", "contactgroup_name", ")", "if", "not", "contactgroup", ":", "contactgroup", "=", "Contactgroup", "(", "{", "'contact...
Add a contact string to a contact member if the contact group do not exist, create it :param contact_name: contact name :type contact_name: str :param contactgroup_name: contact group name :type contactgroup_name: str :return: None
[ "Add", "a", "contact", "string", "to", "a", "contact", "member", "if", "the", "contact", "group", "do", "not", "exist", "create", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contactgroup.py#L159-L176
21,263
Alignak-monitoring/alignak
alignak/objects/contactgroup.py
Contactgroups.linkify_contactgroups_contacts
def linkify_contactgroups_contacts(self, contacts): """Link the contacts with contactgroups :param contacts: realms object to link with :type contacts: alignak.objects.contact.Contacts :return: None """ for contactgroup in self: mbrs = contactgroup.get_contacts() # The new member list, in id new_mbrs = [] for mbr in mbrs: mbr = mbr.strip() # protect with strip at the beginning so don't care about spaces if mbr == '': # void entry, skip this continue member = contacts.find_by_name(mbr) # Maybe the contact is missing, if so, must be put in unknown_members if member is not None: new_mbrs.append(member.uuid) else: contactgroup.add_unknown_members(mbr) # Make members uniq new_mbrs = list(set(new_mbrs)) # We find the id, we replace the names contactgroup.replace_members(new_mbrs)
python
def linkify_contactgroups_contacts(self, contacts): for contactgroup in self: mbrs = contactgroup.get_contacts() # The new member list, in id new_mbrs = [] for mbr in mbrs: mbr = mbr.strip() # protect with strip at the beginning so don't care about spaces if mbr == '': # void entry, skip this continue member = contacts.find_by_name(mbr) # Maybe the contact is missing, if so, must be put in unknown_members if member is not None: new_mbrs.append(member.uuid) else: contactgroup.add_unknown_members(mbr) # Make members uniq new_mbrs = list(set(new_mbrs)) # We find the id, we replace the names contactgroup.replace_members(new_mbrs)
[ "def", "linkify_contactgroups_contacts", "(", "self", ",", "contacts", ")", ":", "for", "contactgroup", "in", "self", ":", "mbrs", "=", "contactgroup", ".", "get_contacts", "(", ")", "# The new member list, in id", "new_mbrs", "=", "[", "]", "for", "mbr", "in", ...
Link the contacts with contactgroups :param contacts: realms object to link with :type contacts: alignak.objects.contact.Contacts :return: None
[ "Link", "the", "contacts", "with", "contactgroups" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contactgroup.py#L212-L239
21,264
Alignak-monitoring/alignak
alignak/objects/contactgroup.py
Contactgroups.explode
def explode(self): """ Fill members with contactgroup_members :return:None """ # We do not want a same hg to be explode again and again # so we tag it for tmp_cg in list(self.items.values()): tmp_cg.already_exploded = False for contactgroup in list(self.items.values()): if contactgroup.already_exploded: continue # get_contacts_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_cg in list(self.items.values()): tmp_cg.rec_tag = False contactgroup.get_contacts_by_explosion(self) # We clean the tags for tmp_cg in list(self.items.values()): if hasattr(tmp_cg, 'rec_tag'): del tmp_cg.rec_tag del tmp_cg.already_exploded
python
def explode(self): # We do not want a same hg to be explode again and again # so we tag it for tmp_cg in list(self.items.values()): tmp_cg.already_exploded = False for contactgroup in list(self.items.values()): if contactgroup.already_exploded: continue # get_contacts_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_cg in list(self.items.values()): tmp_cg.rec_tag = False contactgroup.get_contacts_by_explosion(self) # We clean the tags for tmp_cg in list(self.items.values()): if hasattr(tmp_cg, 'rec_tag'): del tmp_cg.rec_tag del tmp_cg.already_exploded
[ "def", "explode", "(", "self", ")", ":", "# We do not want a same hg to be explode again and again", "# so we tag it", "for", "tmp_cg", "in", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ":", "tmp_cg", ".", "already_exploded", "=", "False", "...
Fill members with contactgroup_members :return:None
[ "Fill", "members", "with", "contactgroup_members" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/contactgroup.py#L241-L266
21,265
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.add_flapping_change
def add_flapping_change(self, sample): """Add a flapping sample and keep cls.flap_history samples :param sample: Sample to add :type sample: bool :return: None """ cls = self.__class__ # If this element is not in flapping check, or # the flapping is globally disable, bailout if not self.flap_detection_enabled or not cls.enable_flap_detection: return self.flapping_changes.append(sample) # Keep just 20 changes (global flap_history value) flap_history = cls.flap_history if len(self.flapping_changes) > flap_history: self.flapping_changes.pop(0)
python
def add_flapping_change(self, sample): cls = self.__class__ # If this element is not in flapping check, or # the flapping is globally disable, bailout if not self.flap_detection_enabled or not cls.enable_flap_detection: return self.flapping_changes.append(sample) # Keep just 20 changes (global flap_history value) flap_history = cls.flap_history if len(self.flapping_changes) > flap_history: self.flapping_changes.pop(0)
[ "def", "add_flapping_change", "(", "self", ",", "sample", ")", ":", "cls", "=", "self", ".", "__class__", "# If this element is not in flapping check, or", "# the flapping is globally disable, bailout", "if", "not", "self", ".", "flap_detection_enabled", "or", "not", "cls...
Add a flapping sample and keep cls.flap_history samples :param sample: Sample to add :type sample: bool :return: None
[ "Add", "a", "flapping", "sample", "and", "keep", "cls", ".", "flap_history", "samples" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L550-L570
21,266
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.add_attempt
def add_attempt(self): """Add an attempt when a object is a non-ok state :return: None """ self.attempt += 1 self.attempt = min(self.attempt, self.max_check_attempts)
python
def add_attempt(self): self.attempt += 1 self.attempt = min(self.attempt, self.max_check_attempts)
[ "def", "add_attempt", "(", "self", ")", ":", "self", ".", "attempt", "+=", "1", "self", ".", "attempt", "=", "min", "(", "self", ".", "attempt", ",", "self", ".", "max_check_attempts", ")" ]
Add an attempt when a object is a non-ok state :return: None
[ "Add", "an", "attempt", "when", "a", "object", "is", "a", "non", "-", "ok", "state" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L637-L643
21,267
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.do_check_freshness
def do_check_freshness(self, hosts, services, timeperiods, macromodulations, checkmodulations, checks, when): # pylint: disable=too-many-nested-blocks, too-many-branches """Check freshness and schedule a check now if necessary. This function is called by the scheduler if Alignak is configured to check the freshness. It is called for hosts that have the freshness check enabled if they are only passively checked. It is called for services that have the freshness check enabled if they are only passively checked and if their depending host is not in a freshness expired state (freshness_expiry = True). A log is raised when the freshess expiry is detected and the item is set as freshness_expiry. :param hosts: hosts objects, used to launch checks :type hosts: alignak.objects.host.Hosts :param services: services objects, used launch checks :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used to get check_period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param macromodulations: Macro modulations objects, used in commands (notif, check) :type macromodulations: alignak.objects.macromodulation.Macromodulations :param checkmodulations: Checkmodulations objects, used to change check command if necessary :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations :param checks: checks dict, used to get checks_in_progress for the object :type checks: dict :return: A check or None :rtype: None | object """ now = when # Before, check if class (host or service) have check_freshness OK # Then check if item want freshness, then check freshness cls = self.__class__ if not self.in_checking and self.freshness_threshold and not self.freshness_expired: # logger.debug("Checking freshness for %s, last state update: %s, now: %s.", # self.get_full_name(), self.last_state_update, now) if os.getenv('ALIGNAK_LOG_CHECKS', None): logger.info("--ALC-- -> checking freshness for: %s", self.get_full_name()) # If we never checked this item, we begin the freshness period if not self.last_state_update: self.last_state_update = int(now) if self.last_state_update < now - \ (self.freshness_threshold + cls.additional_freshness_latency): timeperiod = timeperiods[self.check_period] if timeperiod is None or timeperiod.is_time_valid(now): # Create a new check for the scheduler chk = self.launch_check(now, hosts, services, timeperiods, macromodulations, checkmodulations, checks) if not chk: logger.warning("No raised freshness check for: %s", self) return None chk.freshness_expiry_check = True chk.check_time = time.time() chk.output = "Freshness period expired: %s" % ( datetime.utcfromtimestamp(int(chk.check_time)).strftime( "%Y-%m-%d %H:%M:%S %Z")) if self.my_type == 'host': if self.freshness_state == 'o': chk.exit_status = 0 elif self.freshness_state == 'd': chk.exit_status = 2 elif self.freshness_state in ['u', 'x']: chk.exit_status = 4 else: chk.exit_status = 3 else: if self.freshness_state == 'o': chk.exit_status = 0 elif self.freshness_state == 'w': chk.exit_status = 1 elif self.freshness_state == 'c': chk.exit_status = 2 elif self.freshness_state == 'u': chk.exit_status = 3 elif self.freshness_state == 'x': chk.exit_status = 4 else: chk.exit_status = 3 return chk else: logger.debug("Ignored freshness check for %s, because " "we are not in the check period.", self.get_full_name()) return None
python
def do_check_freshness(self, hosts, services, timeperiods, macromodulations, checkmodulations, checks, when): # pylint: disable=too-many-nested-blocks, too-many-branches now = when # Before, check if class (host or service) have check_freshness OK # Then check if item want freshness, then check freshness cls = self.__class__ if not self.in_checking and self.freshness_threshold and not self.freshness_expired: # logger.debug("Checking freshness for %s, last state update: %s, now: %s.", # self.get_full_name(), self.last_state_update, now) if os.getenv('ALIGNAK_LOG_CHECKS', None): logger.info("--ALC-- -> checking freshness for: %s", self.get_full_name()) # If we never checked this item, we begin the freshness period if not self.last_state_update: self.last_state_update = int(now) if self.last_state_update < now - \ (self.freshness_threshold + cls.additional_freshness_latency): timeperiod = timeperiods[self.check_period] if timeperiod is None or timeperiod.is_time_valid(now): # Create a new check for the scheduler chk = self.launch_check(now, hosts, services, timeperiods, macromodulations, checkmodulations, checks) if not chk: logger.warning("No raised freshness check for: %s", self) return None chk.freshness_expiry_check = True chk.check_time = time.time() chk.output = "Freshness period expired: %s" % ( datetime.utcfromtimestamp(int(chk.check_time)).strftime( "%Y-%m-%d %H:%M:%S %Z")) if self.my_type == 'host': if self.freshness_state == 'o': chk.exit_status = 0 elif self.freshness_state == 'd': chk.exit_status = 2 elif self.freshness_state in ['u', 'x']: chk.exit_status = 4 else: chk.exit_status = 3 else: if self.freshness_state == 'o': chk.exit_status = 0 elif self.freshness_state == 'w': chk.exit_status = 1 elif self.freshness_state == 'c': chk.exit_status = 2 elif self.freshness_state == 'u': chk.exit_status = 3 elif self.freshness_state == 'x': chk.exit_status = 4 else: chk.exit_status = 3 return chk else: logger.debug("Ignored freshness check for %s, because " "we are not in the check period.", self.get_full_name()) return None
[ "def", "do_check_freshness", "(", "self", ",", "hosts", ",", "services", ",", "timeperiods", ",", "macromodulations", ",", "checkmodulations", ",", "checks", ",", "when", ")", ":", "# pylint: disable=too-many-nested-blocks, too-many-branches", "now", "=", "when", "# B...
Check freshness and schedule a check now if necessary. This function is called by the scheduler if Alignak is configured to check the freshness. It is called for hosts that have the freshness check enabled if they are only passively checked. It is called for services that have the freshness check enabled if they are only passively checked and if their depending host is not in a freshness expired state (freshness_expiry = True). A log is raised when the freshess expiry is detected and the item is set as freshness_expiry. :param hosts: hosts objects, used to launch checks :type hosts: alignak.objects.host.Hosts :param services: services objects, used launch checks :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used to get check_period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param macromodulations: Macro modulations objects, used in commands (notif, check) :type macromodulations: alignak.objects.macromodulation.Macromodulations :param checkmodulations: Checkmodulations objects, used to change check command if necessary :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations :param checks: checks dict, used to get checks_in_progress for the object :type checks: dict :return: A check or None :rtype: None | object
[ "Check", "freshness", "and", "schedule", "a", "check", "now", "if", "necessary", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L653-L740
21,268
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.update_business_impact_value
def update_business_impact_value(self, hosts, services, timeperiods, bi_modulations): """We update our 'business_impact' value with the max of the impacts business_impact if we got impacts. And save our 'configuration' business_impact if we do not have do it before If we do not have impacts, we revert our value :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used to get modulation_period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulations objects :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: None TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style """ # First save our business_impact if not already do if self.my_own_business_impact == -1: self.my_own_business_impact = self.business_impact # We look at our crit modulations. If one apply, we take apply it # and it's done in_modulation = False for bi_modulation_id in self.business_impact_modulations: bi_modulation = bi_modulations[bi_modulation_id] now = time.time() period = timeperiods[bi_modulation.modulation_period] if period is None or period.is_time_valid(now): self.business_impact = bi_modulation.business_impact in_modulation = True # We apply the first available, that's all break # If we truly have impacts, we get the max business_impact # if it's huge than ourselves if self.impacts: bp_impacts = [hosts[elem].business_impact for elem in self.impacts if elem in hosts] bp_impacts.extend([services[elem].business_impact for elem in self.impacts if elem in services]) self.business_impact = max(self.business_impact, max(bp_impacts)) return # If we are not a problem, we setup our own_crit if we are not in a # modulation period if self.my_own_business_impact != -1 and not in_modulation: self.business_impact = self.my_own_business_impact
python
def update_business_impact_value(self, hosts, services, timeperiods, bi_modulations): # First save our business_impact if not already do if self.my_own_business_impact == -1: self.my_own_business_impact = self.business_impact # We look at our crit modulations. If one apply, we take apply it # and it's done in_modulation = False for bi_modulation_id in self.business_impact_modulations: bi_modulation = bi_modulations[bi_modulation_id] now = time.time() period = timeperiods[bi_modulation.modulation_period] if period is None or period.is_time_valid(now): self.business_impact = bi_modulation.business_impact in_modulation = True # We apply the first available, that's all break # If we truly have impacts, we get the max business_impact # if it's huge than ourselves if self.impacts: bp_impacts = [hosts[elem].business_impact for elem in self.impacts if elem in hosts] bp_impacts.extend([services[elem].business_impact for elem in self.impacts if elem in services]) self.business_impact = max(self.business_impact, max(bp_impacts)) return # If we are not a problem, we setup our own_crit if we are not in a # modulation period if self.my_own_business_impact != -1 and not in_modulation: self.business_impact = self.my_own_business_impact
[ "def", "update_business_impact_value", "(", "self", ",", "hosts", ",", "services", ",", "timeperiods", ",", "bi_modulations", ")", ":", "# First save our business_impact if not already do", "if", "self", ".", "my_own_business_impact", "==", "-", "1", ":", "self", ".",...
We update our 'business_impact' value with the max of the impacts business_impact if we got impacts. And save our 'configuration' business_impact if we do not have do it before If we do not have impacts, we revert our value :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used to get modulation_period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulations objects :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: None TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style
[ "We", "update", "our", "business_impact", "value", "with", "the", "max", "of", "the", "impacts", "business_impact", "if", "we", "got", "impacts", ".", "And", "save", "our", "configuration", "business_impact", "if", "we", "do", "not", "have", "do", "it", "bef...
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L796-L844
21,269
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.no_more_a_problem
def no_more_a_problem(self, hosts, services, timeperiods, bi_modulations): """Remove this objects as an impact for other schedulingitem. :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used for update_business_impact_value :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulation are used when setting myself as problem :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: None TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style """ was_pb = self.is_problem if self.is_problem: self.is_problem = False # we warn impacts that we are no more a problem for impact_id in self.impacts: if impact_id in hosts: impact = hosts[impact_id] else: impact = services[impact_id] impact.unregister_a_problem(self) # we can just drop our impacts list self.impacts = [] # We update our business_impact value, it's not a huge thing :) self.update_business_impact_value(hosts, services, timeperiods, bi_modulations) # If we were a problem, we say to everyone # our new status, with good business_impact value if was_pb: # And we register a new broks for update status self.broks.append(self.get_update_status_brok())
python
def no_more_a_problem(self, hosts, services, timeperiods, bi_modulations): was_pb = self.is_problem if self.is_problem: self.is_problem = False # we warn impacts that we are no more a problem for impact_id in self.impacts: if impact_id in hosts: impact = hosts[impact_id] else: impact = services[impact_id] impact.unregister_a_problem(self) # we can just drop our impacts list self.impacts = [] # We update our business_impact value, it's not a huge thing :) self.update_business_impact_value(hosts, services, timeperiods, bi_modulations) # If we were a problem, we say to everyone # our new status, with good business_impact value if was_pb: # And we register a new broks for update status self.broks.append(self.get_update_status_brok())
[ "def", "no_more_a_problem", "(", "self", ",", "hosts", ",", "services", ",", "timeperiods", ",", "bi_modulations", ")", ":", "was_pb", "=", "self", ".", "is_problem", "if", "self", ".", "is_problem", ":", "self", ".", "is_problem", "=", "False", "# we warn i...
Remove this objects as an impact for other schedulingitem. :param hosts: hosts objects, used to get impacts :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get impacts :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used for update_business_impact_value :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulation are used when setting myself as problem :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: None TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style
[ "Remove", "this", "objects", "as", "an", "impact", "for", "other", "schedulingitem", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L846-L884
21,270
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.register_a_problem
def register_a_problem(self, prob, hosts, services, timeperiods, bi_modulations): # pylint: disable=too-many-locals """Call recursively by potentials impacts so they update their source_problems list. But do not go below if the problem is not a real one for me like If I've got multiple parents for examples :param prob: problem to register :type prob: alignak.objects.schedulingitem.SchedulingItem :param hosts: hosts objects, used to get object in act_depend_of_me :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of_me :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used for all kind of timeperiod (notif, check) :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulation are used when setting myself as problem :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: list of host/service that are impacts :rtype: list[alignak.objects.schedulingitem.SchedulingItem] TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style """ # Maybe we already have this problem? If so, bailout too if prob.uuid in self.source_problems: return [] now = time.time() was_an_impact = self.is_impact # Our father already look if he impacts us. So if we are here, # it's that we really are impacted self.is_impact = True impacts = [] # Ok, if we are impacted, we can add it in our # problem list # TODO: remove this unused check if self.is_impact: logger.debug("I am impacted: %s", self) # Maybe I was a problem myself, now I can say: not my fault! if self.is_problem: self.no_more_a_problem(hosts, services, timeperiods, bi_modulations) # Ok, we are now impacted, we should take the good state # but only when we just go to the impacted state if not was_an_impact: self.set_impact_state() # Ok now we can be a simple impact impacts.append(self.uuid) if prob.uuid not in self.source_problems: self.source_problems.append(prob.uuid) # we should send this problem to all potential impacted that # depend on us for (impacted_item_id, status, timeperiod_id, _) in self.act_depend_of_me: # Check if the status is ok for impact if impacted_item_id in hosts: impact = hosts[impacted_item_id] else: impact = services[impacted_item_id] timeperiod = timeperiods[timeperiod_id] for stat in status: if self.is_state(stat): # now check if we should bailout because of a # not good timeperiod for dep if timeperiod is None or timeperiod.is_time_valid(now): new_impacts = impact.register_a_problem(prob, hosts, services, timeperiods, bi_modulations) impacts.extend(new_impacts) # And we register a new broks for update status self.broks.append(self.get_update_status_brok()) # now we return all impacts (can be void of course) return impacts
python
def register_a_problem(self, prob, hosts, services, timeperiods, bi_modulations): # pylint: disable=too-many-locals # Maybe we already have this problem? If so, bailout too if prob.uuid in self.source_problems: return [] now = time.time() was_an_impact = self.is_impact # Our father already look if he impacts us. So if we are here, # it's that we really are impacted self.is_impact = True impacts = [] # Ok, if we are impacted, we can add it in our # problem list # TODO: remove this unused check if self.is_impact: logger.debug("I am impacted: %s", self) # Maybe I was a problem myself, now I can say: not my fault! if self.is_problem: self.no_more_a_problem(hosts, services, timeperiods, bi_modulations) # Ok, we are now impacted, we should take the good state # but only when we just go to the impacted state if not was_an_impact: self.set_impact_state() # Ok now we can be a simple impact impacts.append(self.uuid) if prob.uuid not in self.source_problems: self.source_problems.append(prob.uuid) # we should send this problem to all potential impacted that # depend on us for (impacted_item_id, status, timeperiod_id, _) in self.act_depend_of_me: # Check if the status is ok for impact if impacted_item_id in hosts: impact = hosts[impacted_item_id] else: impact = services[impacted_item_id] timeperiod = timeperiods[timeperiod_id] for stat in status: if self.is_state(stat): # now check if we should bailout because of a # not good timeperiod for dep if timeperiod is None or timeperiod.is_time_valid(now): new_impacts = impact.register_a_problem(prob, hosts, services, timeperiods, bi_modulations) impacts.extend(new_impacts) # And we register a new broks for update status self.broks.append(self.get_update_status_brok()) # now we return all impacts (can be void of course) return impacts
[ "def", "register_a_problem", "(", "self", ",", "prob", ",", "hosts", ",", "services", ",", "timeperiods", ",", "bi_modulations", ")", ":", "# pylint: disable=too-many-locals", "# Maybe we already have this problem? If so, bailout too", "if", "prob", ".", "uuid", "in", "...
Call recursively by potentials impacts so they update their source_problems list. But do not go below if the problem is not a real one for me like If I've got multiple parents for examples :param prob: problem to register :type prob: alignak.objects.schedulingitem.SchedulingItem :param hosts: hosts objects, used to get object in act_depend_of_me :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of_me :type services: alignak.objects.service.Services :param timeperiods: Timeperiods objects, used for all kind of timeperiod (notif, check) :type timeperiods: alignak.objects.timeperiod.Timeperiods :param bi_modulations: business impact modulation are used when setting myself as problem :type bi_modulations: alignak.object.businessimpactmodulation.Businessimpactmodulations :return: list of host/service that are impacts :rtype: list[alignak.objects.schedulingitem.SchedulingItem] TODO: SchedulingItem object should not handle other schedulingitem obj. We should call obj.register* on both obj. This is 'Java' style
[ "Call", "recursively", "by", "potentials", "impacts", "so", "they", "update", "their", "source_problems", "list", ".", "But", "do", "not", "go", "below", "if", "the", "problem", "is", "not", "a", "real", "one", "for", "me", "like", "If", "I", "ve", "got"...
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L886-L961
21,271
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.unregister_a_problem
def unregister_a_problem(self, prob): """Remove the problem from our problems list and check if we are still 'impacted' :param prob: problem to remove :type prob: alignak.objects.schedulingitem.SchedulingItem :return: None """ self.source_problems.remove(prob.uuid) # For know if we are still an impact, maybe our dependencies # are not aware of the remove of the impact state because it's not ordered # so we can just look at if we still have some problem in our list if not self.source_problems: self.is_impact = False # No more an impact, we can unset the impact state self.unset_impact_state() # And we register a new broks for update status self.broks.append(self.get_update_status_brok())
python
def unregister_a_problem(self, prob): self.source_problems.remove(prob.uuid) # For know if we are still an impact, maybe our dependencies # are not aware of the remove of the impact state because it's not ordered # so we can just look at if we still have some problem in our list if not self.source_problems: self.is_impact = False # No more an impact, we can unset the impact state self.unset_impact_state() # And we register a new broks for update status self.broks.append(self.get_update_status_brok())
[ "def", "unregister_a_problem", "(", "self", ",", "prob", ")", ":", "self", ".", "source_problems", ".", "remove", "(", "prob", ".", "uuid", ")", "# For know if we are still an impact, maybe our dependencies", "# are not aware of the remove of the impact state because it's not o...
Remove the problem from our problems list and check if we are still 'impacted' :param prob: problem to remove :type prob: alignak.objects.schedulingitem.SchedulingItem :return: None
[ "Remove", "the", "problem", "from", "our", "problems", "list", "and", "check", "if", "we", "are", "still", "impacted" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L963-L982
21,272
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.is_enable_action_dependent
def is_enable_action_dependent(self, hosts, services): """ Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state. :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of :type services: alignak.objects.service.Services :return: True if all dependencies matches the status, false otherwise :rtype: bool """ # Use to know if notification is raise or not enable_action = False for (dep_id, status, _, _) in self.act_depend_of: if 'n' in status: enable_action = True else: if dep_id in hosts: dep = hosts[dep_id] else: dep = services[dep_id] p_is_down = False dep_match = [dep.is_state(stat) for stat in status] # check if the parent match a case, so he is down if True in dep_match: p_is_down = True if not p_is_down: enable_action = True return enable_action
python
def is_enable_action_dependent(self, hosts, services): # Use to know if notification is raise or not enable_action = False for (dep_id, status, _, _) in self.act_depend_of: if 'n' in status: enable_action = True else: if dep_id in hosts: dep = hosts[dep_id] else: dep = services[dep_id] p_is_down = False dep_match = [dep.is_state(stat) for stat in status] # check if the parent match a case, so he is down if True in dep_match: p_is_down = True if not p_is_down: enable_action = True return enable_action
[ "def", "is_enable_action_dependent", "(", "self", ",", "hosts", ",", "services", ")", ":", "# Use to know if notification is raise or not", "enable_action", "=", "False", "for", "(", "dep_id", ",", "status", ",", "_", ",", "_", ")", "in", "self", ".", "act_depen...
Check if dependencies states match dependencies statuses This basically means that a dependency is in a bad state and it can explain this object state. :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of :type services: alignak.objects.service.Services :return: True if all dependencies matches the status, false otherwise :rtype: bool
[ "Check", "if", "dependencies", "states", "match", "dependencies", "statuses", "This", "basically", "means", "that", "a", "dependency", "is", "in", "a", "bad", "state", "and", "it", "can", "explain", "this", "object", "state", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L984-L1014
21,273
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.check_and_set_unreachability
def check_and_set_unreachability(self, hosts, services): """ Check if all dependencies are down, if yes set this object as unreachable. todo: this function do not care about execution_failure_criteria! :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of :type services: alignak.objects.service.Services :return: None """ parent_is_down = [] for (dep_id, _, _, _) in self.act_depend_of: if dep_id in hosts: dep = hosts[dep_id] else: dep = services[dep_id] if dep.state in ['d', 'DOWN', 'c', 'CRITICAL', 'u', 'UNKNOWN', 'x', 'UNREACHABLE']: parent_is_down.append(True) else: parent_is_down.append(False) if False in parent_is_down: return # all parents down self.set_unreachable()
python
def check_and_set_unreachability(self, hosts, services): parent_is_down = [] for (dep_id, _, _, _) in self.act_depend_of: if dep_id in hosts: dep = hosts[dep_id] else: dep = services[dep_id] if dep.state in ['d', 'DOWN', 'c', 'CRITICAL', 'u', 'UNKNOWN', 'x', 'UNREACHABLE']: parent_is_down.append(True) else: parent_is_down.append(False) if False in parent_is_down: return # all parents down self.set_unreachable()
[ "def", "check_and_set_unreachability", "(", "self", ",", "hosts", ",", "services", ")", ":", "parent_is_down", "=", "[", "]", "for", "(", "dep_id", ",", "_", ",", "_", ",", "_", ")", "in", "self", ".", "act_depend_of", ":", "if", "dep_id", "in", "hosts...
Check if all dependencies are down, if yes set this object as unreachable. todo: this function do not care about execution_failure_criteria! :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services objects, used to get object in act_depend_of :type services: alignak.objects.service.Services :return: None
[ "Check", "if", "all", "dependencies", "are", "down", "if", "yes", "set", "this", "object", "as", "unreachable", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1016-L1042
21,274
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.compensate_system_time_change
def compensate_system_time_change(self, difference): # pragma: no cover, # not with unit tests """If a system time change occurs we have to update properties time related to reflect change :param difference: difference between new time and old time :type difference: :return: None """ # We only need to change some value for prop in ('last_notification', 'last_state_change', 'last_hard_state_change'): val = getattr(self, prop) # current value # Do not go below 1970 :) val = max(0, val + difference) # diff may be negative setattr(self, prop, val)
python
def compensate_system_time_change(self, difference): # pragma: no cover, # not with unit tests # We only need to change some value for prop in ('last_notification', 'last_state_change', 'last_hard_state_change'): val = getattr(self, prop) # current value # Do not go below 1970 :) val = max(0, val + difference) # diff may be negative setattr(self, prop, val)
[ "def", "compensate_system_time_change", "(", "self", ",", "difference", ")", ":", "# pragma: no cover,", "# not with unit tests", "# We only need to change some value", "for", "prop", "in", "(", "'last_notification'", ",", "'last_state_change'", ",", "'last_hard_state_change'",...
If a system time change occurs we have to update properties time related to reflect change :param difference: difference between new time and old time :type difference: :return: None
[ "If", "a", "system", "time", "change", "occurs", "we", "have", "to", "update", "properties", "time", "related", "to", "reflect", "change" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1300-L1314
21,275
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.remove_in_progress_check
def remove_in_progress_check(self, check): """Remove check from check in progress :param check: Check to remove :type check: alignak.objects.check.Check :return: None """ # The check is consumed, update the in_checking properties if check in self.checks_in_progress: self.checks_in_progress.remove(check) self.update_in_checking()
python
def remove_in_progress_check(self, check): # The check is consumed, update the in_checking properties if check in self.checks_in_progress: self.checks_in_progress.remove(check) self.update_in_checking()
[ "def", "remove_in_progress_check", "(", "self", ",", "check", ")", ":", "# The check is consumed, update the in_checking properties", "if", "check", "in", "self", ".", "checks_in_progress", ":", "self", ".", "checks_in_progress", ".", "remove", "(", "check", ")", "sel...
Remove check from check in progress :param check: Check to remove :type check: alignak.objects.check.Check :return: None
[ "Remove", "check", "from", "check", "in", "progress" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1334-L1344
21,276
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.remove_in_progress_notification
def remove_in_progress_notification(self, notification): """ Remove a notification and mark them as zombie :param notification: the notification to remove :type notification: alignak.notification.Notification :return: None """ if notification.uuid in self.notifications_in_progress: notification.status = ACT_STATUS_ZOMBIE del self.notifications_in_progress[notification.uuid]
python
def remove_in_progress_notification(self, notification): if notification.uuid in self.notifications_in_progress: notification.status = ACT_STATUS_ZOMBIE del self.notifications_in_progress[notification.uuid]
[ "def", "remove_in_progress_notification", "(", "self", ",", "notification", ")", ":", "if", "notification", ".", "uuid", "in", "self", ".", "notifications_in_progress", ":", "notification", ".", "status", "=", "ACT_STATUS_ZOMBIE", "del", "self", ".", "notifications_...
Remove a notification and mark them as zombie :param notification: the notification to remove :type notification: alignak.notification.Notification :return: None
[ "Remove", "a", "notification", "and", "mark", "them", "as", "zombie" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1354-L1364
21,277
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.remove_in_progress_notifications
def remove_in_progress_notifications(self, master=True): """Remove all notifications from notifications_in_progress Preserves some specific notifications (downtime, ...) :param master: remove master notifications only if True (default value) :type master: bool :param force: force remove all notifications except if False :type force: bool :return:None """ for notification in list(self.notifications_in_progress.values()): if master and notification.contact: continue # Do not remove some specific notifications if notification.type in [u'DOWNTIMESTART', u'DOWNTIMEEND', u'DOWNTIMECANCELLED', u'CUSTOM', u'ACKNOWLEDGEMENT']: continue self.remove_in_progress_notification(notification)
python
def remove_in_progress_notifications(self, master=True): for notification in list(self.notifications_in_progress.values()): if master and notification.contact: continue # Do not remove some specific notifications if notification.type in [u'DOWNTIMESTART', u'DOWNTIMEEND', u'DOWNTIMECANCELLED', u'CUSTOM', u'ACKNOWLEDGEMENT']: continue self.remove_in_progress_notification(notification)
[ "def", "remove_in_progress_notifications", "(", "self", ",", "master", "=", "True", ")", ":", "for", "notification", "in", "list", "(", "self", ".", "notifications_in_progress", ".", "values", "(", ")", ")", ":", "if", "master", "and", "notification", ".", "...
Remove all notifications from notifications_in_progress Preserves some specific notifications (downtime, ...) :param master: remove master notifications only if True (default value) :type master: bool :param force: force remove all notifications except if False :type force: bool :return:None
[ "Remove", "all", "notifications", "from", "notifications_in_progress" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1366-L1384
21,278
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.check_for_flexible_downtime
def check_for_flexible_downtime(self, timeperiods, hosts, services): """Enter in a downtime if necessary and raise start notification When a non Ok state occurs we try to raise a flexible downtime. :param timeperiods: Timeperiods objects, used for downtime period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param hosts: hosts objects, used to enter downtime :type hosts: alignak.objects.host.Hosts :param services: services objects, used to enter downtime :type services: alignak.objects.service.Services :return: None """ status_updated = False for downtime_id in self.downtimes: downtime = self.downtimes[downtime_id] # Activate flexible downtimes (do not activate triggered downtimes) # Note: only activate if we are between downtime start and end time! if downtime.fixed or downtime.is_in_effect: continue if downtime.start_time <= self.last_chk and downtime.end_time >= self.last_chk \ and self.state_id != 0 and downtime.trigger_id in ['', '0']: # returns downtimestart notifications self.broks.extend(downtime.enter(timeperiods, hosts, services)) status_updated = True if status_updated is True: self.broks.append(self.get_update_status_brok())
python
def check_for_flexible_downtime(self, timeperiods, hosts, services): status_updated = False for downtime_id in self.downtimes: downtime = self.downtimes[downtime_id] # Activate flexible downtimes (do not activate triggered downtimes) # Note: only activate if we are between downtime start and end time! if downtime.fixed or downtime.is_in_effect: continue if downtime.start_time <= self.last_chk and downtime.end_time >= self.last_chk \ and self.state_id != 0 and downtime.trigger_id in ['', '0']: # returns downtimestart notifications self.broks.extend(downtime.enter(timeperiods, hosts, services)) status_updated = True if status_updated is True: self.broks.append(self.get_update_status_brok())
[ "def", "check_for_flexible_downtime", "(", "self", ",", "timeperiods", ",", "hosts", ",", "services", ")", ":", "status_updated", "=", "False", "for", "downtime_id", "in", "self", ".", "downtimes", ":", "downtime", "=", "self", ".", "downtimes", "[", "downtime...
Enter in a downtime if necessary and raise start notification When a non Ok state occurs we try to raise a flexible downtime. :param timeperiods: Timeperiods objects, used for downtime period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param hosts: hosts objects, used to enter downtime :type hosts: alignak.objects.host.Hosts :param services: services objects, used to enter downtime :type services: alignak.objects.service.Services :return: None
[ "Enter", "in", "a", "downtime", "if", "necessary", "and", "raise", "start", "notification", "When", "a", "non", "Ok", "state", "occurs", "we", "try", "to", "raise", "a", "flexible", "downtime", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1505-L1530
21,279
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.update_hard_unknown_phase_state
def update_hard_unknown_phase_state(self): """Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None """ self.was_in_hard_unknown_reach_phase = self.in_hard_unknown_reach_phase # We do not care about SOFT state at all # and we are sure we are no more in such a phase if self.state_type != 'HARD' or self.last_state_type != 'HARD': self.in_hard_unknown_reach_phase = False # So if we are not in already in such a phase, we check for # a start or not. So here we are sure to be in a HARD/HARD following # state if not self.in_hard_unknown_reach_phase: if self.state == 'UNKNOWN' and self.last_state != 'UNKNOWN' \ or self.state == 'UNREACHABLE' and self.last_state != 'UNREACHABLE': self.in_hard_unknown_reach_phase = True # We also backup with which state we was before enter this phase self.state_before_hard_unknown_reach_phase = self.last_state return else: # if we were already in such a phase, look for its end if self.state != 'UNKNOWN' and self.state != 'UNREACHABLE': self.in_hard_unknown_reach_phase = False # If we just exit the phase, look if we exit with a different state # than we enter or not. If so, lie and say we were not in such phase # because we need so to raise a new notif if not self.in_hard_unknown_reach_phase and self.was_in_hard_unknown_reach_phase: if self.state != self.state_before_hard_unknown_reach_phase: self.was_in_hard_unknown_reach_phase = False
python
def update_hard_unknown_phase_state(self): self.was_in_hard_unknown_reach_phase = self.in_hard_unknown_reach_phase # We do not care about SOFT state at all # and we are sure we are no more in such a phase if self.state_type != 'HARD' or self.last_state_type != 'HARD': self.in_hard_unknown_reach_phase = False # So if we are not in already in such a phase, we check for # a start or not. So here we are sure to be in a HARD/HARD following # state if not self.in_hard_unknown_reach_phase: if self.state == 'UNKNOWN' and self.last_state != 'UNKNOWN' \ or self.state == 'UNREACHABLE' and self.last_state != 'UNREACHABLE': self.in_hard_unknown_reach_phase = True # We also backup with which state we was before enter this phase self.state_before_hard_unknown_reach_phase = self.last_state return else: # if we were already in such a phase, look for its end if self.state != 'UNKNOWN' and self.state != 'UNREACHABLE': self.in_hard_unknown_reach_phase = False # If we just exit the phase, look if we exit with a different state # than we enter or not. If so, lie and say we were not in such phase # because we need so to raise a new notif if not self.in_hard_unknown_reach_phase and self.was_in_hard_unknown_reach_phase: if self.state != self.state_before_hard_unknown_reach_phase: self.was_in_hard_unknown_reach_phase = False
[ "def", "update_hard_unknown_phase_state", "(", "self", ")", ":", "self", ".", "was_in_hard_unknown_reach_phase", "=", "self", ".", "in_hard_unknown_reach_phase", "# We do not care about SOFT state at all", "# and we are sure we are no more in such a phase", "if", "self", ".", "st...
Update in_hard_unknown_reach_phase attribute and was_in_hard_unknown_reach_phase UNKNOWN during a HARD state are not so important, and they should not raise notif about it :return: None
[ "Update", "in_hard_unknown_reach_phase", "attribute", "and", "was_in_hard_unknown_reach_phase", "UNKNOWN", "during", "a", "HARD", "state", "are", "not", "so", "important", "and", "they", "should", "not", "raise", "notif", "about", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1532-L1567
21,280
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.update_notification_command
def update_notification_command(self, notif, contact, macromodulations, timeperiods, host_ref=None): """Update the notification command by resolving Macros And because we are just launching the notification, we can say that this contact has been notified :param notif: notification to send :type notif: alignak.objects.notification.Notification :param contact: contact for this host/service :type contact: alignak.object.contact.Contact :param macromodulations: Macro modulations objects, used in the notification command :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: Timeperiods objects, used to get modulation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param host_ref: reference host (used for a service) :type host_ref: alignak.object.host.Host :return: None """ cls = self.__class__ macrosolver = MacroResolver() data = self.get_data_for_notifications(contact, notif, host_ref) notif.command = macrosolver.resolve_command(notif.command_call, data, macromodulations, timeperiods) if cls.enable_environment_macros or notif.enable_environment_macros: notif.env = macrosolver.get_env_macros(data)
python
def update_notification_command(self, notif, contact, macromodulations, timeperiods, host_ref=None): cls = self.__class__ macrosolver = MacroResolver() data = self.get_data_for_notifications(contact, notif, host_ref) notif.command = macrosolver.resolve_command(notif.command_call, data, macromodulations, timeperiods) if cls.enable_environment_macros or notif.enable_environment_macros: notif.env = macrosolver.get_env_macros(data)
[ "def", "update_notification_command", "(", "self", ",", "notif", ",", "contact", ",", "macromodulations", ",", "timeperiods", ",", "host_ref", "=", "None", ")", ":", "cls", "=", "self", ".", "__class__", "macrosolver", "=", "MacroResolver", "(", ")", "data", ...
Update the notification command by resolving Macros And because we are just launching the notification, we can say that this contact has been notified :param notif: notification to send :type notif: alignak.objects.notification.Notification :param contact: contact for this host/service :type contact: alignak.object.contact.Contact :param macromodulations: Macro modulations objects, used in the notification command :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: Timeperiods objects, used to get modulation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :param host_ref: reference host (used for a service) :type host_ref: alignak.object.host.Host :return: None
[ "Update", "the", "notification", "command", "by", "resolving", "Macros", "And", "because", "we", "are", "just", "launching", "the", "notification", "we", "can", "say", "that", "this", "contact", "has", "been", "notified" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L1997-L2021
21,281
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.is_escalable
def is_escalable(self, notification, escalations, timeperiods): """Check if a notification can be escalated. Basically call is_eligible for each escalation :param notification: notification we would like to escalate :type notification: alignak.objects.notification.Notification :param escalations: Esclations objects, used to get escalation objects (period) :type escalations: alignak.objects.escalation.Escalations :param timeperiods: Timeperiods objects, used to get escalation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: True if notification can be escalated, otherwise False :rtype: bool """ cls = self.__class__ # We search since when we are in notification for escalations # that are based on time in_notif_time = time.time() - notification.creation_time # Check is an escalation match the current_notification_number for escalation_id in self.escalations: escalation = escalations[escalation_id] escalation_period = timeperiods[escalation.escalation_period] if escalation.is_eligible(notification.t_to_go, self.state, notification.notif_nb, in_notif_time, cls.interval_length, escalation_period): return True return False
python
def is_escalable(self, notification, escalations, timeperiods): cls = self.__class__ # We search since when we are in notification for escalations # that are based on time in_notif_time = time.time() - notification.creation_time # Check is an escalation match the current_notification_number for escalation_id in self.escalations: escalation = escalations[escalation_id] escalation_period = timeperiods[escalation.escalation_period] if escalation.is_eligible(notification.t_to_go, self.state, notification.notif_nb, in_notif_time, cls.interval_length, escalation_period): return True return False
[ "def", "is_escalable", "(", "self", ",", "notification", ",", "escalations", ",", "timeperiods", ")", ":", "cls", "=", "self", ".", "__class__", "# We search since when we are in notification for escalations", "# that are based on time", "in_notif_time", "=", "time", ".",...
Check if a notification can be escalated. Basically call is_eligible for each escalation :param notification: notification we would like to escalate :type notification: alignak.objects.notification.Notification :param escalations: Esclations objects, used to get escalation objects (period) :type escalations: alignak.objects.escalation.Escalations :param timeperiods: Timeperiods objects, used to get escalation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: True if notification can be escalated, otherwise False :rtype: bool
[ "Check", "if", "a", "notification", "can", "be", "escalated", ".", "Basically", "call", "is_eligible", "for", "each", "escalation" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2023-L2050
21,282
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.get_next_notification_time
def get_next_notification_time(self, notif, escalations, timeperiods): # pylint: disable=too-many-locals """Get the next notification time for a notification Take the standard notification_interval or ask for our escalation if one of them need a smaller value to escalade :param notif: Notification we need time :type notif: alignak.objects.notification.Notification :param escalations: Esclations objects, used to get escalation objects (interval, period) :type escalations: alignak.objects.escalation.Escalations :param timeperiods: Timeperiods objects, used to get escalation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: Timestamp of next notification :rtype: int """ res = None now = time.time() cls = self.__class__ # Look at the minimum notification interval notification_interval = self.notification_interval # and then look for currently active notifications, and take notification_interval # if filled and less than the self value in_notif_time = time.time() - notif.creation_time for escalation_id in self.escalations: escalation = escalations[escalation_id] escalation_period = timeperiods[escalation.escalation_period] if escalation.is_eligible(notif.t_to_go, self.state, notif.notif_nb, in_notif_time, cls.interval_length, escalation_period): if escalation.notification_interval != -1 and \ escalation.notification_interval < notification_interval: notification_interval = escalation.notification_interval # So take the by default time std_time = notif.t_to_go + notification_interval * cls.interval_length # Maybe the notification comes from retention data and # next notification alert is in the past # if so let use the now value instead if std_time < now: std_time = now + notification_interval * cls.interval_length # standard time is a good one res = std_time creation_time = notif.creation_time in_notif_time = now - notif.creation_time for escalation_id in self.escalations: escalation = escalations[escalation_id] # If the escalation was already raised, we do not look for a new "early start" if escalation.get_name() not in notif.already_start_escalations: escalation_period = timeperiods[escalation.escalation_period] next_t = escalation.get_next_notif_time(std_time, self.state, creation_time, cls.interval_length, escalation_period) # If we got a real result (time base escalation), we add it if next_t is not None and now < next_t < res: res = next_t # And we take the minimum of this result. Can be standard or escalation asked return res
python
def get_next_notification_time(self, notif, escalations, timeperiods): # pylint: disable=too-many-locals res = None now = time.time() cls = self.__class__ # Look at the minimum notification interval notification_interval = self.notification_interval # and then look for currently active notifications, and take notification_interval # if filled and less than the self value in_notif_time = time.time() - notif.creation_time for escalation_id in self.escalations: escalation = escalations[escalation_id] escalation_period = timeperiods[escalation.escalation_period] if escalation.is_eligible(notif.t_to_go, self.state, notif.notif_nb, in_notif_time, cls.interval_length, escalation_period): if escalation.notification_interval != -1 and \ escalation.notification_interval < notification_interval: notification_interval = escalation.notification_interval # So take the by default time std_time = notif.t_to_go + notification_interval * cls.interval_length # Maybe the notification comes from retention data and # next notification alert is in the past # if so let use the now value instead if std_time < now: std_time = now + notification_interval * cls.interval_length # standard time is a good one res = std_time creation_time = notif.creation_time in_notif_time = now - notif.creation_time for escalation_id in self.escalations: escalation = escalations[escalation_id] # If the escalation was already raised, we do not look for a new "early start" if escalation.get_name() not in notif.already_start_escalations: escalation_period = timeperiods[escalation.escalation_period] next_t = escalation.get_next_notif_time(std_time, self.state, creation_time, cls.interval_length, escalation_period) # If we got a real result (time base escalation), we add it if next_t is not None and now < next_t < res: res = next_t # And we take the minimum of this result. Can be standard or escalation asked return res
[ "def", "get_next_notification_time", "(", "self", ",", "notif", ",", "escalations", ",", "timeperiods", ")", ":", "# pylint: disable=too-many-locals", "res", "=", "None", "now", "=", "time", ".", "time", "(", ")", "cls", "=", "self", ".", "__class__", "# Look ...
Get the next notification time for a notification Take the standard notification_interval or ask for our escalation if one of them need a smaller value to escalade :param notif: Notification we need time :type notif: alignak.objects.notification.Notification :param escalations: Esclations objects, used to get escalation objects (interval, period) :type escalations: alignak.objects.escalation.Escalations :param timeperiods: Timeperiods objects, used to get escalation period :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: Timestamp of next notification :rtype: int
[ "Get", "the", "next", "notification", "time", "for", "a", "notification", "Take", "the", "standard", "notification_interval", "or", "ask", "for", "our", "escalation", "if", "one", "of", "them", "need", "a", "smaller", "value", "to", "escalade" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2052-L2113
21,283
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.get_business_rule_output
def get_business_rule_output(self, hosts, services, macromodulations, timeperiods): # pylint: disable=too-many-locals, too-many-branches """ Returns a status string for business rules based items formatted using business_rule_output_template attribute as template. The template may embed output formatting for itself, and for its child (dependent) items. Child format string is expanded into the $( and )$, using the string between brackets as format string. Any business rule based item or child macro may be used. In addition, the $STATUS$, $SHORTSTATUS$ and $FULLNAME$ macro which name is common to hosts and services may be used to ease template writing. Caution: only children in state not OK are displayed. Example: A business rule with a format string looking like "$STATUS$ [ $($TATUS$: $HOSTNAME$,$SERVICEDESC$ )$ ]" Would return "CRITICAL [ CRITICAL: host1,srv1 WARNING: host2,srv2 ]" :param hosts: Hosts object to look for objects :type hosts: alignak.objects.host.Hosts :param services: Services object to look for objects :type services: alignak.objects.service.Services :param macromodulations: Macromodulations object to look for objects :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: Timeperiods object to look for objects :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: status for business rules :rtype: str """ got_business_rule = getattr(self, 'got_business_rule', False) # Checks that the service is a business rule. if got_business_rule is False or self.business_rule is None: return "" # Checks that the business rule has a format specified. output_template = self.business_rule_output_template if not output_template: return "" macroresolver = MacroResolver() # Extracts children template strings elts = re.findall(r"\$\((.*)\)\$", output_template) if not elts: child_template_string = "" else: child_template_string = elts[0] # Processes child services output children_output = "" ok_count = 0 # Expands child items format string macros. items = self.business_rule.list_all_elements() for item_uuid in items: if item_uuid in hosts: item = hosts[item_uuid] elif item_uuid in services: item = services[item_uuid] # Do not display children in OK state # todo: last_hard_state ? why not current state if state type is hard ? if item.last_hard_state_id == 0: ok_count += 1 continue data = item.get_data_for_checks(hosts) children_output += macroresolver.resolve_simple_macros_in_string(child_template_string, data, macromodulations, timeperiods) if ok_count == len(items): children_output = "all checks were successful." # Replaces children output string template_string = re.sub(r"\$\(.*\)\$", children_output, output_template) data = self.get_data_for_checks(hosts) output = macroresolver.resolve_simple_macros_in_string(template_string, data, macromodulations, timeperiods) return output.strip()
python
def get_business_rule_output(self, hosts, services, macromodulations, timeperiods): # pylint: disable=too-many-locals, too-many-branches got_business_rule = getattr(self, 'got_business_rule', False) # Checks that the service is a business rule. if got_business_rule is False or self.business_rule is None: return "" # Checks that the business rule has a format specified. output_template = self.business_rule_output_template if not output_template: return "" macroresolver = MacroResolver() # Extracts children template strings elts = re.findall(r"\$\((.*)\)\$", output_template) if not elts: child_template_string = "" else: child_template_string = elts[0] # Processes child services output children_output = "" ok_count = 0 # Expands child items format string macros. items = self.business_rule.list_all_elements() for item_uuid in items: if item_uuid in hosts: item = hosts[item_uuid] elif item_uuid in services: item = services[item_uuid] # Do not display children in OK state # todo: last_hard_state ? why not current state if state type is hard ? if item.last_hard_state_id == 0: ok_count += 1 continue data = item.get_data_for_checks(hosts) children_output += macroresolver.resolve_simple_macros_in_string(child_template_string, data, macromodulations, timeperiods) if ok_count == len(items): children_output = "all checks were successful." # Replaces children output string template_string = re.sub(r"\$\(.*\)\$", children_output, output_template) data = self.get_data_for_checks(hosts) output = macroresolver.resolve_simple_macros_in_string(template_string, data, macromodulations, timeperiods) return output.strip()
[ "def", "get_business_rule_output", "(", "self", ",", "hosts", ",", "services", ",", "macromodulations", ",", "timeperiods", ")", ":", "# pylint: disable=too-many-locals, too-many-branches", "got_business_rule", "=", "getattr", "(", "self", ",", "'got_business_rule'", ",",...
Returns a status string for business rules based items formatted using business_rule_output_template attribute as template. The template may embed output formatting for itself, and for its child (dependent) items. Child format string is expanded into the $( and )$, using the string between brackets as format string. Any business rule based item or child macro may be used. In addition, the $STATUS$, $SHORTSTATUS$ and $FULLNAME$ macro which name is common to hosts and services may be used to ease template writing. Caution: only children in state not OK are displayed. Example: A business rule with a format string looking like "$STATUS$ [ $($TATUS$: $HOSTNAME$,$SERVICEDESC$ )$ ]" Would return "CRITICAL [ CRITICAL: host1,srv1 WARNING: host2,srv2 ]" :param hosts: Hosts object to look for objects :type hosts: alignak.objects.host.Hosts :param services: Services object to look for objects :type services: alignak.objects.service.Services :param macromodulations: Macromodulations object to look for objects :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: Timeperiods object to look for objects :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: status for business rules :rtype: str
[ "Returns", "a", "status", "string", "for", "business", "rules", "based", "items", "formatted", "using", "business_rule_output_template", "attribute", "as", "template", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2612-L2692
21,284
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.business_rule_notification_is_blocked
def business_rule_notification_is_blocked(self, hosts, services): # pylint: disable=too-many-locals """Process business rule notifications behaviour. If all problems have been acknowledged, no notifications should be sent if state is not OK. By default, downtimes are ignored, unless explicitly told to be treated as acknowledgements through with the business_rule_downtime_as_ack set. :return: True if all source problem are acknowledged, otherwise False :rtype: bool """ # Walks through problems to check if all items in non ok are # acknowledged or in downtime period. acknowledged = 0 for src_prob_id in self.source_problems: if src_prob_id in hosts: src_prob = hosts[src_prob_id] else: src_prob = services[src_prob_id] if src_prob.last_hard_state_id != 0: if src_prob.problem_has_been_acknowledged: # Problem hast been acknowledged acknowledged += 1 # Only check problems under downtime if we are # explicitly told to do so. elif self.business_rule_downtime_as_ack is True: if src_prob.scheduled_downtime_depth > 0: # Problem is under downtime, and downtimes should be # treated as acknowledgements acknowledged += 1 elif hasattr(src_prob, "host") and \ hosts[src_prob.host].scheduled_downtime_depth > 0: # Host is under downtime, and downtimes should be # treated as acknowledgements acknowledged += 1 return acknowledged == len(self.source_problems)
python
def business_rule_notification_is_blocked(self, hosts, services): # pylint: disable=too-many-locals # Walks through problems to check if all items in non ok are # acknowledged or in downtime period. acknowledged = 0 for src_prob_id in self.source_problems: if src_prob_id in hosts: src_prob = hosts[src_prob_id] else: src_prob = services[src_prob_id] if src_prob.last_hard_state_id != 0: if src_prob.problem_has_been_acknowledged: # Problem hast been acknowledged acknowledged += 1 # Only check problems under downtime if we are # explicitly told to do so. elif self.business_rule_downtime_as_ack is True: if src_prob.scheduled_downtime_depth > 0: # Problem is under downtime, and downtimes should be # treated as acknowledgements acknowledged += 1 elif hasattr(src_prob, "host") and \ hosts[src_prob.host].scheduled_downtime_depth > 0: # Host is under downtime, and downtimes should be # treated as acknowledgements acknowledged += 1 return acknowledged == len(self.source_problems)
[ "def", "business_rule_notification_is_blocked", "(", "self", ",", "hosts", ",", "services", ")", ":", "# pylint: disable=too-many-locals", "# Walks through problems to check if all items in non ok are", "# acknowledged or in downtime period.", "acknowledged", "=", "0", "for", "src_...
Process business rule notifications behaviour. If all problems have been acknowledged, no notifications should be sent if state is not OK. By default, downtimes are ignored, unless explicitly told to be treated as acknowledgements through with the business_rule_downtime_as_ack set. :return: True if all source problem are acknowledged, otherwise False :rtype: bool
[ "Process", "business", "rule", "notifications", "behaviour", ".", "If", "all", "problems", "have", "been", "acknowledged", "no", "notifications", "should", "be", "sent", "if", "state", "is", "not", "OK", ".", "By", "default", "downtimes", "are", "ignored", "un...
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2694-L2729
21,285
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.fill_data_brok_from
def fill_data_brok_from(self, data, brok_type): """Fill data brok dependent on the brok_type :param data: data to fill :type data: dict :param brok_type: brok type :type: str :return: None """ super(SchedulingItem, self).fill_data_brok_from(data, brok_type) # workaround/easy trick to have the command_name of this # SchedulingItem in its check_result brok if brok_type == 'check_result': data['command_name'] = '' if self.check_command: data['command_name'] = self.check_command.command.command_name
python
def fill_data_brok_from(self, data, brok_type): super(SchedulingItem, self).fill_data_brok_from(data, brok_type) # workaround/easy trick to have the command_name of this # SchedulingItem in its check_result brok if brok_type == 'check_result': data['command_name'] = '' if self.check_command: data['command_name'] = self.check_command.command.command_name
[ "def", "fill_data_brok_from", "(", "self", ",", "data", ",", "brok_type", ")", ":", "super", "(", "SchedulingItem", ",", "self", ")", ".", "fill_data_brok_from", "(", "data", ",", "brok_type", ")", "# workaround/easy trick to have the command_name of this", "# Schedul...
Fill data brok dependent on the brok_type :param data: data to fill :type data: dict :param brok_type: brok type :type: str :return: None
[ "Fill", "data", "brok", "dependent", "on", "the", "brok_type" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2934-L2949
21,286
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.acknowledge_problem
def acknowledge_problem(self, notification_period, hosts, services, sticky, notify, author, comment, end_time=0): # pylint: disable=too-many-arguments """ Add an acknowledge :param sticky: acknowledge will be always present is host return in UP state :type sticky: integer :param notify: if to 1, send a notification :type notify: integer :param author: name of the author or the acknowledge :type author: str :param comment: comment (description) of the acknowledge :type comment: str :param end_time: end (timeout) of this acknowledge in seconds(timestamp) (0 to never end) :type end_time: int :return: None | alignak.comment.Comment """ comm = None logger.debug("Acknowledge requested for %s %s.", self.my_type, self.get_name()) if self.state != self.ok_up: # case have yet an acknowledge if self.problem_has_been_acknowledged and self.acknowledgement: self.del_comment(getattr(self.acknowledgement, 'comment_id', None)) if notify: self.create_notifications('ACKNOWLEDGEMENT', notification_period, hosts, services) self.problem_has_been_acknowledged = True sticky = sticky == 2 data = { 'ref': self.uuid, 'sticky': sticky, 'author': author, 'comment': comment, 'end_time': end_time, 'notify': notify } self.acknowledgement = Acknowledge(data) if self.my_type == 'host': comment_type = 1 self.broks.append(self.acknowledgement.get_raise_brok(self.get_name())) else: comment_type = 2 self.broks.append(self.acknowledgement.get_raise_brok(self.host_name, self.get_name())) data = { 'author': author, 'comment': comment, 'comment_type': comment_type, 'entry_type': 4, 'source': 0, 'expires': False, 'ref': self.uuid } comm = Comment(data) self.acknowledgement.comment_id = comm.uuid self.comments[comm.uuid] = comm self.broks.append(self.get_update_status_brok()) self.raise_acknowledge_log_entry() else: logger.debug("Acknowledge requested for %s %s but element state is OK/UP.", self.my_type, self.get_name()) # For an host, acknowledge all its services that are problems if self.my_type == 'host': for service_uuid in self.services: if service_uuid not in services: continue services[service_uuid].acknowledge_problem(notification_period, hosts, services, sticky, notify, author, comment, end_time) return comm
python
def acknowledge_problem(self, notification_period, hosts, services, sticky, notify, author, comment, end_time=0): # pylint: disable=too-many-arguments comm = None logger.debug("Acknowledge requested for %s %s.", self.my_type, self.get_name()) if self.state != self.ok_up: # case have yet an acknowledge if self.problem_has_been_acknowledged and self.acknowledgement: self.del_comment(getattr(self.acknowledgement, 'comment_id', None)) if notify: self.create_notifications('ACKNOWLEDGEMENT', notification_period, hosts, services) self.problem_has_been_acknowledged = True sticky = sticky == 2 data = { 'ref': self.uuid, 'sticky': sticky, 'author': author, 'comment': comment, 'end_time': end_time, 'notify': notify } self.acknowledgement = Acknowledge(data) if self.my_type == 'host': comment_type = 1 self.broks.append(self.acknowledgement.get_raise_brok(self.get_name())) else: comment_type = 2 self.broks.append(self.acknowledgement.get_raise_brok(self.host_name, self.get_name())) data = { 'author': author, 'comment': comment, 'comment_type': comment_type, 'entry_type': 4, 'source': 0, 'expires': False, 'ref': self.uuid } comm = Comment(data) self.acknowledgement.comment_id = comm.uuid self.comments[comm.uuid] = comm self.broks.append(self.get_update_status_brok()) self.raise_acknowledge_log_entry() else: logger.debug("Acknowledge requested for %s %s but element state is OK/UP.", self.my_type, self.get_name()) # For an host, acknowledge all its services that are problems if self.my_type == 'host': for service_uuid in self.services: if service_uuid not in services: continue services[service_uuid].acknowledge_problem(notification_period, hosts, services, sticky, notify, author, comment, end_time) return comm
[ "def", "acknowledge_problem", "(", "self", ",", "notification_period", ",", "hosts", ",", "services", ",", "sticky", ",", "notify", ",", "author", ",", "comment", ",", "end_time", "=", "0", ")", ":", "# pylint: disable=too-many-arguments", "comm", "=", "None", ...
Add an acknowledge :param sticky: acknowledge will be always present is host return in UP state :type sticky: integer :param notify: if to 1, send a notification :type notify: integer :param author: name of the author or the acknowledge :type author: str :param comment: comment (description) of the acknowledge :type comment: str :param end_time: end (timeout) of this acknowledge in seconds(timestamp) (0 to never end) :type end_time: int :return: None | alignak.comment.Comment
[ "Add", "an", "acknowledge" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L2951-L3017
21,287
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.check_for_expire_acknowledge
def check_for_expire_acknowledge(self): """ If have acknowledge and is expired, delete it :return: None """ if (self.acknowledgement and self.acknowledgement.end_time != 0 and self.acknowledgement.end_time < time.time()): self.unacknowledge_problem()
python
def check_for_expire_acknowledge(self): if (self.acknowledgement and self.acknowledgement.end_time != 0 and self.acknowledgement.end_time < time.time()): self.unacknowledge_problem()
[ "def", "check_for_expire_acknowledge", "(", "self", ")", ":", "if", "(", "self", ".", "acknowledgement", "and", "self", ".", "acknowledgement", ".", "end_time", "!=", "0", "and", "self", ".", "acknowledgement", ".", "end_time", "<", "time", ".", "time", "(",...
If have acknowledge and is expired, delete it :return: None
[ "If", "have", "acknowledge", "and", "is", "expired", "delete", "it" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3019-L3028
21,288
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.unacknowledge_problem
def unacknowledge_problem(self): """ Remove the acknowledge, reset the flag. The comment is deleted :return: None """ if self.problem_has_been_acknowledged: logger.debug("[item::%s] deleting acknowledge of %s", self.get_name(), self.get_full_name()) self.problem_has_been_acknowledged = False if self.my_type == 'host': self.broks.append(self.acknowledgement.get_expire_brok(self.get_name())) else: self.broks.append(self.acknowledgement.get_expire_brok(self.host_name, self.get_name())) # delete the comment of the item related with the acknowledge if hasattr(self.acknowledgement, 'comment_id') and \ self.acknowledgement.comment_id in self.comments: del self.comments[self.acknowledgement.comment_id] # Should not be deleted, a None is Good self.acknowledgement = None self.broks.append(self.get_update_status_brok()) self.raise_unacknowledge_log_entry()
python
def unacknowledge_problem(self): if self.problem_has_been_acknowledged: logger.debug("[item::%s] deleting acknowledge of %s", self.get_name(), self.get_full_name()) self.problem_has_been_acknowledged = False if self.my_type == 'host': self.broks.append(self.acknowledgement.get_expire_brok(self.get_name())) else: self.broks.append(self.acknowledgement.get_expire_brok(self.host_name, self.get_name())) # delete the comment of the item related with the acknowledge if hasattr(self.acknowledgement, 'comment_id') and \ self.acknowledgement.comment_id in self.comments: del self.comments[self.acknowledgement.comment_id] # Should not be deleted, a None is Good self.acknowledgement = None self.broks.append(self.get_update_status_brok()) self.raise_unacknowledge_log_entry()
[ "def", "unacknowledge_problem", "(", "self", ")", ":", "if", "self", ".", "problem_has_been_acknowledged", ":", "logger", ".", "debug", "(", "\"[item::%s] deleting acknowledge of %s\"", ",", "self", ".", "get_name", "(", ")", ",", "self", ".", "get_full_name", "("...
Remove the acknowledge, reset the flag. The comment is deleted :return: None
[ "Remove", "the", "acknowledge", "reset", "the", "flag", ".", "The", "comment", "is", "deleted" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3030-L3055
21,289
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.unacknowledge_problem_if_not_sticky
def unacknowledge_problem_if_not_sticky(self): """ Remove the acknowledge if it is not sticky :return: None """ if hasattr(self, 'acknowledgement') and self.acknowledgement is not None: if not self.acknowledgement.sticky: self.unacknowledge_problem()
python
def unacknowledge_problem_if_not_sticky(self): if hasattr(self, 'acknowledgement') and self.acknowledgement is not None: if not self.acknowledgement.sticky: self.unacknowledge_problem()
[ "def", "unacknowledge_problem_if_not_sticky", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'acknowledgement'", ")", "and", "self", ".", "acknowledgement", "is", "not", "None", ":", "if", "not", "self", ".", "acknowledgement", ".", "sticky", ":", ...
Remove the acknowledge if it is not sticky :return: None
[ "Remove", "the", "acknowledge", "if", "it", "is", "not", "sticky" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3057-L3065
21,290
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.set_impact_state
def set_impact_state(self): """We just go an impact, so we go unreachable But only if we enable this state change in the conf :return: None """ cls = self.__class__ if cls.enable_problem_impacts_states_change: logger.debug("%s is impacted and goes UNREACHABLE", self) # Track the old state (problem occured before a new check) self.state_before_impact = self.state self.state_id_before_impact = self.state_id # This flag will know if we override the impact state self.state_changed_since_impact = False # Set unreachable self.set_unreachable()
python
def set_impact_state(self): cls = self.__class__ if cls.enable_problem_impacts_states_change: logger.debug("%s is impacted and goes UNREACHABLE", self) # Track the old state (problem occured before a new check) self.state_before_impact = self.state self.state_id_before_impact = self.state_id # This flag will know if we override the impact state self.state_changed_since_impact = False # Set unreachable self.set_unreachable()
[ "def", "set_impact_state", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "if", "cls", ".", "enable_problem_impacts_states_change", ":", "logger", ".", "debug", "(", "\"%s is impacted and goes UNREACHABLE\"", ",", "self", ")", "# Track the old state (pro...
We just go an impact, so we go unreachable But only if we enable this state change in the conf :return: None
[ "We", "just", "go", "an", "impact", "so", "we", "go", "unreachable", "But", "only", "if", "we", "enable", "this", "state", "change", "in", "the", "conf" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3215-L3231
21,291
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItem.unset_impact_state
def unset_impact_state(self): """Unset impact, only if impact state change is set in configuration :return: None """ cls = self.__class__ if cls.enable_problem_impacts_states_change and not self.state_changed_since_impact: self.state = self.state_before_impact self.state_id = self.state_id_before_impact
python
def unset_impact_state(self): cls = self.__class__ if cls.enable_problem_impacts_states_change and not self.state_changed_since_impact: self.state = self.state_before_impact self.state_id = self.state_id_before_impact
[ "def", "unset_impact_state", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "if", "cls", ".", "enable_problem_impacts_states_change", "and", "not", "self", ".", "state_changed_since_impact", ":", "self", ".", "state", "=", "self", ".", "state_befor...
Unset impact, only if impact state change is set in configuration :return: None
[ "Unset", "impact", "only", "if", "impact", "state", "change", "is", "set", "in", "configuration" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3233-L3241
21,292
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItems.find_by_filter
def find_by_filter(self, filters, all_items): """ Find items by filters :param filters: list of filters :type filters: list :param all_items: monitoring items :type: dict :return: list of items :rtype: list """ items = [] for i in self: failed = False if hasattr(i, "host"): all_items["service"] = i else: all_items["host"] = i for filt in filters: if not filt(all_items): failed = True break if failed is False: items.append(i) return items
python
def find_by_filter(self, filters, all_items): items = [] for i in self: failed = False if hasattr(i, "host"): all_items["service"] = i else: all_items["host"] = i for filt in filters: if not filt(all_items): failed = True break if failed is False: items.append(i) return items
[ "def", "find_by_filter", "(", "self", ",", "filters", ",", "all_items", ")", ":", "items", "=", "[", "]", "for", "i", "in", "self", ":", "failed", "=", "False", "if", "hasattr", "(", "i", ",", "\"host\"", ")", ":", "all_items", "[", "\"service\"", "]...
Find items by filters :param filters: list of filters :type filters: list :param all_items: monitoring items :type: dict :return: list of items :rtype: list
[ "Find", "items", "by", "filters" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3379-L3403
21,293
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItems.add_act_dependency
def add_act_dependency(self, son_id, parent_id, notif_failure_criteria, dep_period, inherits_parents): """ Add a logical dependency for actions between two hosts or services. :param son_id: uuid of son host :type son_id: str :param parent_id: uuid of parent host :type parent_id: str :param notif_failure_criteria: notification failure criteria, notification for a dependent host may vary :type notif_failure_criteria: list :param dep_period: dependency period. Timeperiod for dependency may vary :type dep_period: str | None :param inherits_parents: if this dep will inherit from parents (timeperiod, status) :type inherits_parents: bool :return: """ if son_id in self: son = self[son_id] else: msg = "Dependency son (%s) unknown, configuration error" % son_id self.add_error(msg) parent = self[parent_id] son.act_depend_of.append((parent_id, notif_failure_criteria, dep_period, inherits_parents)) parent.act_depend_of_me.append((son_id, notif_failure_criteria, dep_period, inherits_parents)) # TODO: Is it necessary? We already have this info in act_depend_* attributes son.parent_dependencies.add(parent_id) parent.child_dependencies.add(son_id)
python
def add_act_dependency(self, son_id, parent_id, notif_failure_criteria, dep_period, inherits_parents): if son_id in self: son = self[son_id] else: msg = "Dependency son (%s) unknown, configuration error" % son_id self.add_error(msg) parent = self[parent_id] son.act_depend_of.append((parent_id, notif_failure_criteria, dep_period, inherits_parents)) parent.act_depend_of_me.append((son_id, notif_failure_criteria, dep_period, inherits_parents)) # TODO: Is it necessary? We already have this info in act_depend_* attributes son.parent_dependencies.add(parent_id) parent.child_dependencies.add(son_id)
[ "def", "add_act_dependency", "(", "self", ",", "son_id", ",", "parent_id", ",", "notif_failure_criteria", ",", "dep_period", ",", "inherits_parents", ")", ":", "if", "son_id", "in", "self", ":", "son", "=", "self", "[", "son_id", "]", "else", ":", "msg", "...
Add a logical dependency for actions between two hosts or services. :param son_id: uuid of son host :type son_id: str :param parent_id: uuid of parent host :type parent_id: str :param notif_failure_criteria: notification failure criteria, notification for a dependent host may vary :type notif_failure_criteria: list :param dep_period: dependency period. Timeperiod for dependency may vary :type dep_period: str | None :param inherits_parents: if this dep will inherit from parents (timeperiod, status) :type inherits_parents: bool :return:
[ "Add", "a", "logical", "dependency", "for", "actions", "between", "two", "hosts", "or", "services", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3405-L3435
21,294
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItems.del_act_dependency
def del_act_dependency(self, son_id, parent_id): # pragma: no cover, not yet tested """Remove act_dependency between two hosts or services. TODO: do we really intend to remove dynamically ? :param son_id: uuid of son host/service :type son_id: str :param parent_id: uuid of parent host/service :type parent_id: str :return: None """ son = self[son_id] parent = self[parent_id] to_del = [] # First we remove in my list for (host, status, timeperiod, inherits_parent) in son.act_depend_of: if host == parent_id: to_del.append((host, status, timeperiod, inherits_parent)) for tup in to_del: son.act_depend_of.remove(tup) # And now in the father part to_del = [] for (host, status, timeperiod, inherits_parent) in parent.act_depend_of_me: if host == son_id: to_del.append((host, status, timeperiod, inherits_parent)) for tup in to_del: parent.act_depend_of_me.remove(tup) # Remove in child/parents dependencies too # Me in father list parent.child_dependencies.remove(son_id) # and father list in mine son.parent_dependencies.remove(parent_id)
python
def del_act_dependency(self, son_id, parent_id): # pragma: no cover, not yet tested son = self[son_id] parent = self[parent_id] to_del = [] # First we remove in my list for (host, status, timeperiod, inherits_parent) in son.act_depend_of: if host == parent_id: to_del.append((host, status, timeperiod, inherits_parent)) for tup in to_del: son.act_depend_of.remove(tup) # And now in the father part to_del = [] for (host, status, timeperiod, inherits_parent) in parent.act_depend_of_me: if host == son_id: to_del.append((host, status, timeperiod, inherits_parent)) for tup in to_del: parent.act_depend_of_me.remove(tup) # Remove in child/parents dependencies too # Me in father list parent.child_dependencies.remove(son_id) # and father list in mine son.parent_dependencies.remove(parent_id)
[ "def", "del_act_dependency", "(", "self", ",", "son_id", ",", "parent_id", ")", ":", "# pragma: no cover, not yet tested", "son", "=", "self", "[", "son_id", "]", "parent", "=", "self", "[", "parent_id", "]", "to_del", "=", "[", "]", "# First we remove in my lis...
Remove act_dependency between two hosts or services. TODO: do we really intend to remove dynamically ? :param son_id: uuid of son host/service :type son_id: str :param parent_id: uuid of parent host/service :type parent_id: str :return: None
[ "Remove", "act_dependency", "between", "two", "hosts", "or", "services", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3437-L3470
21,295
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItems.add_chk_dependency
def add_chk_dependency(self, son_id, parent_id, notif_failure_criteria, dep_period, inherits_parents): """ Add a logical dependency for checks between two hosts or services. :param son_id: uuid of son host/service :type son_id: str :param parent_id: uuid of parent host/service :type parent_id: str :param notif_failure_criteria: notification failure criteria, notification for a dependent host may vary :type notif_failure_criteria: list :param dep_period: dependency period. Timeperiod for dependency may vary :type dep_period: str :param inherits_parents: if this dep will inherit from parents (timeperiod, status) :type inherits_parents: bool :return: """ son = self[son_id] parent = self[parent_id] son.chk_depend_of.append((parent_id, notif_failure_criteria, 'logic_dep', dep_period, inherits_parents)) parent.chk_depend_of_me.append((son_id, notif_failure_criteria, 'logic_dep', dep_period, inherits_parents)) # TODO: Is it necessary? We already have this info in act_depend_* attributes son.parent_dependencies.add(parent_id) parent.child_dependencies.add(son_id)
python
def add_chk_dependency(self, son_id, parent_id, notif_failure_criteria, dep_period, inherits_parents): son = self[son_id] parent = self[parent_id] son.chk_depend_of.append((parent_id, notif_failure_criteria, 'logic_dep', dep_period, inherits_parents)) parent.chk_depend_of_me.append((son_id, notif_failure_criteria, 'logic_dep', dep_period, inherits_parents)) # TODO: Is it necessary? We already have this info in act_depend_* attributes son.parent_dependencies.add(parent_id) parent.child_dependencies.add(son_id)
[ "def", "add_chk_dependency", "(", "self", ",", "son_id", ",", "parent_id", ",", "notif_failure_criteria", ",", "dep_period", ",", "inherits_parents", ")", ":", "son", "=", "self", "[", "son_id", "]", "parent", "=", "self", "[", "parent_id", "]", "son", ".", ...
Add a logical dependency for checks between two hosts or services. :param son_id: uuid of son host/service :type son_id: str :param parent_id: uuid of parent host/service :type parent_id: str :param notif_failure_criteria: notification failure criteria, notification for a dependent host may vary :type notif_failure_criteria: list :param dep_period: dependency period. Timeperiod for dependency may vary :type dep_period: str :param inherits_parents: if this dep will inherit from parents (timeperiod, status) :type inherits_parents: bool :return:
[ "Add", "a", "logical", "dependency", "for", "checks", "between", "two", "hosts", "or", "services", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3472-L3499
21,296
Alignak-monitoring/alignak
alignak/objects/schedulingitem.py
SchedulingItems.create_business_rules
def create_business_rules(self, hosts, services, hostgroups, servicegroups, macromodulations, timeperiods): """ Loop on hosts or services and call SchedulingItem.create_business_rules :param hosts: hosts to link to :type hosts: alignak.objects.host.Hosts :param services: services to link to :type services: alignak.objects.service.Services :param hostgroups: hostgroups to link to :type hostgroups: alignak.objects.hostgroup.Hostgroups :param servicegroups: servicegroups to link to :type servicegroups: alignak.objects.servicegroup.Servicegroups :param macromodulations: macromodulations to link to :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: timeperiods to link to :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None """ for item in self: item.create_business_rules(hosts, services, hostgroups, servicegroups, macromodulations, timeperiods)
python
def create_business_rules(self, hosts, services, hostgroups, servicegroups, macromodulations, timeperiods): for item in self: item.create_business_rules(hosts, services, hostgroups, servicegroups, macromodulations, timeperiods)
[ "def", "create_business_rules", "(", "self", ",", "hosts", ",", "services", ",", "hostgroups", ",", "servicegroups", ",", "macromodulations", ",", "timeperiods", ")", ":", "for", "item", "in", "self", ":", "item", ".", "create_business_rules", "(", "hosts", ",...
Loop on hosts or services and call SchedulingItem.create_business_rules :param hosts: hosts to link to :type hosts: alignak.objects.host.Hosts :param services: services to link to :type services: alignak.objects.service.Services :param hostgroups: hostgroups to link to :type hostgroups: alignak.objects.hostgroup.Hostgroups :param servicegroups: servicegroups to link to :type servicegroups: alignak.objects.servicegroup.Servicegroups :param macromodulations: macromodulations to link to :type macromodulations: alignak.objects.macromodulation.Macromodulations :param timeperiods: timeperiods to link to :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None
[ "Loop", "on", "hosts", "or", "services", "and", "call", "SchedulingItem", ".", "create_business_rules" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/schedulingitem.py#L3501-L3522
21,297
Alignak-monitoring/alignak
alignak/objects/servicegroup.py
Servicegroup.get_services_by_explosion
def get_services_by_explosion(self, servicegroups): # pylint: disable=access-member-before-definition """ Get all services of this servicegroup and add it in members container :param servicegroups: servicegroups object :type servicegroups: alignak.objects.servicegroup.Servicegroups :return: return empty string or list of members :rtype: str or list """ # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every HG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[servicegroup::%s] got a loop in servicegroup definition", self.get_name()) if hasattr(self, 'members'): return self.members return '' # Ok, not a loop, we tag it and continue self.rec_tag = True sg_mbrs = self.get_servicegroup_members() for sg_mbr in sg_mbrs: servicegroup = servicegroups.find_by_name(sg_mbr.strip()) if servicegroup is not None: value = servicegroup.get_services_by_explosion(servicegroups) if value is not None: self.add_members(value) if hasattr(self, 'members'): return self.members return ''
python
def get_services_by_explosion(self, servicegroups): # pylint: disable=access-member-before-definition # First we tag the hg so it will not be explode # if a son of it already call it self.already_exploded = True # Now the recursive part # rec_tag is set to False every HG we explode # so if True here, it must be a loop in HG # calls... not GOOD! if self.rec_tag: logger.error("[servicegroup::%s] got a loop in servicegroup definition", self.get_name()) if hasattr(self, 'members'): return self.members return '' # Ok, not a loop, we tag it and continue self.rec_tag = True sg_mbrs = self.get_servicegroup_members() for sg_mbr in sg_mbrs: servicegroup = servicegroups.find_by_name(sg_mbr.strip()) if servicegroup is not None: value = servicegroup.get_services_by_explosion(servicegroups) if value is not None: self.add_members(value) if hasattr(self, 'members'): return self.members return ''
[ "def", "get_services_by_explosion", "(", "self", ",", "servicegroups", ")", ":", "# pylint: disable=access-member-before-definition", "# First we tag the hg so it will not be explode", "# if a son of it already call it", "self", ".", "already_exploded", "=", "True", "# Now the recurs...
Get all services of this servicegroup and add it in members container :param servicegroups: servicegroups object :type servicegroups: alignak.objects.servicegroup.Servicegroups :return: return empty string or list of members :rtype: str or list
[ "Get", "all", "services", "of", "this", "servicegroup", "and", "add", "it", "in", "members", "container" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicegroup.py#L115-L154
21,298
Alignak-monitoring/alignak
alignak/objects/servicegroup.py
Servicegroups.explode
def explode(self): """ Get services and put them in members container :return: None """ # We do not want a same service group to be exploded again and again # so we tag it for tmp_sg in list(self.items.values()): tmp_sg.already_exploded = False for servicegroup in list(self.items.values()): if servicegroup.already_exploded: continue # get_services_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_sg in list(self.items.values()): tmp_sg.rec_tag = False servicegroup.get_services_by_explosion(self) # We clean the tags for tmp_sg in list(self.items.values()): if hasattr(tmp_sg, 'rec_tag'): del tmp_sg.rec_tag del tmp_sg.already_exploded
python
def explode(self): # We do not want a same service group to be exploded again and again # so we tag it for tmp_sg in list(self.items.values()): tmp_sg.already_exploded = False for servicegroup in list(self.items.values()): if servicegroup.already_exploded: continue # get_services_by_explosion is a recursive # function, so we must tag hg so we do not loop for tmp_sg in list(self.items.values()): tmp_sg.rec_tag = False servicegroup.get_services_by_explosion(self) # We clean the tags for tmp_sg in list(self.items.values()): if hasattr(tmp_sg, 'rec_tag'): del tmp_sg.rec_tag del tmp_sg.already_exploded
[ "def", "explode", "(", "self", ")", ":", "# We do not want a same service group to be exploded again and again", "# so we tag it", "for", "tmp_sg", "in", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ":", "tmp_sg", ".", "already_exploded", "=", ...
Get services and put them in members container :return: None
[ "Get", "services", "and", "put", "them", "in", "members", "container" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/servicegroup.py#L260-L285
21,299
Alignak-monitoring/alignak
alignak/log.py
setup_logger
def setup_logger(logger_configuration_file, log_dir=None, process_name='', log_file=''): # pylint: disable=too-many-branches """ Configure the provided logger - get and update the content of the Json configuration file - configure the logger with this file If a log_dir and process_name are provided, the format and filename in the configuration file are updated with the provided values if they contain the patterns %(logdir)s and %(daemon)s If no log_dir and process_name are provided, this function will truncate the log file defined in the configuration file. If a log file name is provided, it will override the default defined log file name. At first, this function checks if the logger is still existing and initialized to update the handlers and formatters. This mainly happens during the unit tests. :param logger_configuration_file: Python Json logger configuration file :rtype logger_configuration_file: str :param log_dir: default log directory to update the defined logging handlers :rtype log_dir: str :param process_name: process name to update the defined logging formatters :rtype process_name: str :param log_file: log file name to update the defined log file :rtype log_file: str :return: None """ logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) for handler in logger_.handlers: if not process_name: break # Logger is already configured? if getattr(handler, '_name', None) == 'daemons': # Update the declared formats and file names with the process name # This is for unit tests purpose only: alignak_tests will be replaced # with the provided process name for hdlr in logger_.handlers: # print("- handler : %s (%s)" % (hdlr, hdlr.formatter._fmt)) if 'alignak_tests' in hdlr.formatter._fmt: formatter = logging.Formatter(hdlr.formatter._fmt.replace("alignak_tests", process_name)) hdlr.setFormatter(formatter) if getattr(hdlr, 'filename', None) and 'alignak_tests' in hdlr.filename: hdlr.filename = hdlr.filename._fmt.replace("alignak_tests", process_name) # print("- handler : %s (%s) -> %s" % (hdlr, hdlr.formatter._fmt, # hdlr.filename)) # else: # print("- handler : %s (%s)" % (hdlr, hdlr.formatter._fmt)) break else: if not logger_configuration_file or not os.path.exists(logger_configuration_file): print("The logger configuration file does not exist: %s" % logger_configuration_file) return with open(logger_configuration_file, 'rt') as _file: config = json.load(_file) truncate = False if not process_name and not log_dir: truncate = True if not process_name: process_name = 'alignak_tests' if not log_dir: log_dir = '/tmp' # Update the declared formats with the process name for formatter in config['formatters']: if 'format' not in config['formatters'][formatter]: continue config['formatters'][formatter]['format'] = \ config['formatters'][formatter]['format'].replace("%(daemon)s", process_name) # Update the declared log file names with the log directory for hdlr in config['handlers']: if 'filename' not in config['handlers'][hdlr]: continue if log_file and hdlr == 'daemons': config['handlers'][hdlr]['filename'] = log_file else: config['handlers'][hdlr]['filename'] = \ config['handlers'][hdlr]['filename'].replace("%(logdir)s", log_dir) config['handlers'][hdlr]['filename'] = \ config['handlers'][hdlr]['filename'].replace("%(daemon)s", process_name) if truncate and os.path.exists(config['handlers'][hdlr]['filename']): with open(config['handlers'][hdlr]['filename'], "w") as file_log_file: file_log_file.truncate() # Configure the logger, any error will raise an exception logger_dictConfig(config)
python
def setup_logger(logger_configuration_file, log_dir=None, process_name='', log_file=''): # pylint: disable=too-many-branches logger_ = logging.getLogger(ALIGNAK_LOGGER_NAME) for handler in logger_.handlers: if not process_name: break # Logger is already configured? if getattr(handler, '_name', None) == 'daemons': # Update the declared formats and file names with the process name # This is for unit tests purpose only: alignak_tests will be replaced # with the provided process name for hdlr in logger_.handlers: # print("- handler : %s (%s)" % (hdlr, hdlr.formatter._fmt)) if 'alignak_tests' in hdlr.formatter._fmt: formatter = logging.Formatter(hdlr.formatter._fmt.replace("alignak_tests", process_name)) hdlr.setFormatter(formatter) if getattr(hdlr, 'filename', None) and 'alignak_tests' in hdlr.filename: hdlr.filename = hdlr.filename._fmt.replace("alignak_tests", process_name) # print("- handler : %s (%s) -> %s" % (hdlr, hdlr.formatter._fmt, # hdlr.filename)) # else: # print("- handler : %s (%s)" % (hdlr, hdlr.formatter._fmt)) break else: if not logger_configuration_file or not os.path.exists(logger_configuration_file): print("The logger configuration file does not exist: %s" % logger_configuration_file) return with open(logger_configuration_file, 'rt') as _file: config = json.load(_file) truncate = False if not process_name and not log_dir: truncate = True if not process_name: process_name = 'alignak_tests' if not log_dir: log_dir = '/tmp' # Update the declared formats with the process name for formatter in config['formatters']: if 'format' not in config['formatters'][formatter]: continue config['formatters'][formatter]['format'] = \ config['formatters'][formatter]['format'].replace("%(daemon)s", process_name) # Update the declared log file names with the log directory for hdlr in config['handlers']: if 'filename' not in config['handlers'][hdlr]: continue if log_file and hdlr == 'daemons': config['handlers'][hdlr]['filename'] = log_file else: config['handlers'][hdlr]['filename'] = \ config['handlers'][hdlr]['filename'].replace("%(logdir)s", log_dir) config['handlers'][hdlr]['filename'] = \ config['handlers'][hdlr]['filename'].replace("%(daemon)s", process_name) if truncate and os.path.exists(config['handlers'][hdlr]['filename']): with open(config['handlers'][hdlr]['filename'], "w") as file_log_file: file_log_file.truncate() # Configure the logger, any error will raise an exception logger_dictConfig(config)
[ "def", "setup_logger", "(", "logger_configuration_file", ",", "log_dir", "=", "None", ",", "process_name", "=", "''", ",", "log_file", "=", "''", ")", ":", "# pylint: disable=too-many-branches", "logger_", "=", "logging", ".", "getLogger", "(", "ALIGNAK_LOGGER_NAME"...
Configure the provided logger - get and update the content of the Json configuration file - configure the logger with this file If a log_dir and process_name are provided, the format and filename in the configuration file are updated with the provided values if they contain the patterns %(logdir)s and %(daemon)s If no log_dir and process_name are provided, this function will truncate the log file defined in the configuration file. If a log file name is provided, it will override the default defined log file name. At first, this function checks if the logger is still existing and initialized to update the handlers and formatters. This mainly happens during the unit tests. :param logger_configuration_file: Python Json logger configuration file :rtype logger_configuration_file: str :param log_dir: default log directory to update the defined logging handlers :rtype log_dir: str :param process_name: process name to update the defined logging formatters :rtype process_name: str :param log_file: log file name to update the defined log file :rtype log_file: str :return: None
[ "Configure", "the", "provided", "logger", "-", "get", "and", "update", "the", "content", "of", "the", "Json", "configuration", "file", "-", "configure", "the", "logger", "with", "this", "file" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/log.py#L111-L198