Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def resolve_simple_macros_in_string(self, c_line, data, macromodulations, timeperiods, args=None): # pylint: disable=too-many-locals, too-many-branches, too-many-nested-blocks # Now we prepare the classes for l...
[ "Replace macro in the command line with the real value\n\n :param c_line: command line to modify\n :type c_line: str\n :param data: objects list, use to look for a specific macro\n :type data:\n :param macromodulations: the available macro modulations\n :type macromodulatio...
Please provide a description of the function:def resolve_command(self, com, data, macromodulations, timeperiods): logger.debug("Resolving: macros in: %s, arguments: %s", com.command.command_line, com.args) return self.resolve_simple_macros_in_string(com.command.command_line...
[ "Resolve command macros with data\n\n :param com: check / event handler or command call object\n :type com: object\n :param data: objects list, used to search for a specific macro (custom or object related)\n :type data:\n :return: command line with '$MACRO$' replaced with values\...
Please provide a description of the function:def _get_type_of_macro(macros, objs): r for macro in macros: # ARGN Macros if re.match(r'ARG\d', macro): macros[macro]['type'] = 'ARGN' continue # USERN macros # are managed in th...
[ "Set macros types\n\n Example::\n\n ARG\\d -> ARGN,\n HOSTBLABLA -> class one and set Host in class)\n _HOSTTOTO -> HOST CUSTOM MACRO TOTO\n SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1\n\n :param macros: macros list in a dictionary\n...
Please provide a description of the function:def _resolve_argn(macro, args): # first, get the number of args _id = None matches = re.search(r'ARG(?P<id>\d+)', macro) if matches is not None: _id = int(matches.group('id')) - 1 try: return ar...
[ "Get argument from macro name\n ie : $ARG3$ -> args[2]\n\n :param macro: macro to parse\n :type macro:\n :param args: args given to command line\n :type args:\n :return: argument at position N-1 in args table (where N is the int parsed)\n :rtype: None | str\n ...
Please provide a description of the function:def _resolve_ondemand(self, macro, data): # pylint: disable=too-many-locals elts = macro.split(':') nb_parts = len(elts) macro_name = elts[0] # 3 parts for a service, 2 for all others types... if nb_parts == 3: ...
[ "Get on demand macro value\n\n If the macro cannot be resolved, this function will return 'n/a' rather than\n an empty string, this to alert the caller of a potential problem.\n\n :param macro: macro to parse\n :type macro:\n :param data: data to get value from\n :type data...
Please provide a description of the function:def _tot_hosts_by_state(self, state=None, state_type=None): if state is None and state_type is None: return len(self.hosts) if state_type: return sum(1 for h in self.hosts if h.state == state and h.state_type == state_type) ...
[ "Generic function to get the number of host in the specified state\n\n :param state: state to filter on\n :type state: str\n :param state_type: state type to filter on (HARD, SOFT)\n :type state_type: str\n :return: number of host in state *state*\n :rtype: int\n " ]
Please provide a description of the function:def _tot_unhandled_hosts_by_state(self, state): return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and h.is_problem and not h.problem_has_been_acknowledged)
[ "Generic function to get the number of unhandled problem hosts in the specified state\n\n :param state: state to filter on\n :type state:\n :return: number of host in state *state* and which are not acknowledged problems\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_hosts_problems_unhandled(self): return sum(1 for h in self.hosts if h.is_problem and not h.problem_has_been_acknowledged)
[ "\n Get the number of host problems not handled\n\n :return: Number of hosts which are problems and not handled\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_hosts_problems_handled(self): return sum(1 for h in self.hosts if h.is_problem and h.problem_has_been_acknowledged)
[ "\n Get the number of host problems not handled\n\n :return: Number of hosts which are problems and not handled\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_hosts_not_monitored(self): return sum(1 for h in self.hosts if not h.active_checks_enabled and not h.passive_checks_enabled)
[ "\n Get the number of host not monitored (active and passive checks disabled)\n\n :return: Number of hosts which are not monitored\n :rtype: int\n " ]
Please provide a description of the function:def _tot_services_by_state(self, state=None, state_type=None): if state is None and state_type is None: return len(self.services) if state_type: return sum(1 for s in self.services if s.state == state and s.state_type == state...
[ "Generic function to get the number of services in the specified state\n\n :param state: state to filter on\n :type state: str\n :param state_type: state type to filter on (HARD, SOFT)\n :type state_type: str\n :return: number of host in state *state*\n :rtype: int\n ...
Please provide a description of the function:def _tot_unhandled_services_by_state(self, state): return sum(1 for s in self.services if s.state == state and s.is_problem and not s.problem_has_been_acknowledged)
[ "Generic function to get the number of unhandled problem services in the specified state\n\n :param state: state to filter on\n :type state:\n :return: number of service in state *state* and which are not acknowledged problems\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_services_problems_unhandled(self): return sum(1 for s in self.services if s.is_problem and not s.problem_has_been_acknowledged)
[ "Get the number of services that are a problem and that are not acknowledged\n\n :return: number of problem services which are not acknowledged\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_services_problems_handled(self): return sum(1 for s in self.services if s.is_problem and s.problem_has_been_acknowledged)
[ "\n Get the number of service problems not handled\n\n :return: Number of services which are problems and not handled\n :rtype: int\n " ]
Please provide a description of the function:def _get_total_services_not_monitored(self): return sum(1 for s in self.services if not s.active_checks_enabled and not s.passive_checks_enabled)
[ "\n Get the number of service not monitored (active and passive checks disabled)\n\n :return: Number of services which are not monitored\n :rtype: int\n " ]
Please provide a description of the function:def add_data(self, metric, value, ts=None): if not ts: ts = time.time() if self.__data_lock.acquire(): self.__data.append((metric, (ts, value))) self.__data_lock.release() return True return Fal...
[ "\n Add data to queue\n\n :param metric: the metric name\n :type metric: str\n :param value: the value of data\n :type value: int\n :param ts: the timestamp\n :type ts: int | None\n :return: True if added successfully, otherwise False\n :rtype: bool\n ...
Please provide a description of the function:def add_data_dict(self, dd): # pragma: no cover - never used... if self.__data_lock.acquire(): for k, v in list(dd.items()): ts = v.get('ts', time.time()) value = v.get('value') self.__data.append(...
[ "\n dd must be a dictionary where keys are the metric name,\n each key contains a dictionary which at least must have 'value' key (optionally 'ts')\n\n dd = {'experiment1.subsystem.block.metric1': {'value': 12.3, 'ts': 1379491605.55},\n 'experiment1.subsystem.block.metric2': {'valu...
Please provide a description of the function:def add_data_list(self, dl): # pragma: no cover - never used... if self.__data_lock.acquire(): self.__data.extend(dl) self.__data_lock.release() return True return False
[ "\n dl must be a list of tuples like:\n dl = [('metricname', (timestamp, value)),\n ('metricname', (timestamp, value)),\n ...]\n " ]
Please provide a description of the function:def send_data(self, data=None): save_in_error = False if not data: if self.__data_lock.acquire(): data = self.__data self.__data = [] save_in_error = True self.__data_lock.re...
[ "If data is empty, current buffer is sent. Otherwise data must be like:\n data = [('metricname', (timestamp, value)),\n ('metricname', (timestamp, value)),\n ...]\n " ]
Please provide a description of the function:def set_daemon_name(self, daemon_name): self.daemon_name = daemon_name for instance in self.instances: instance.set_loaded_into(daemon_name)
[ "Set the daemon name of the daemon which this manager is attached to\n and propagate this daemon name to our managed modules\n\n :param daemon_name:\n :return:\n " ]
Please provide a description of the function:def load_and_init(self, modules): self.load(modules) self.get_instances() return len(self.configuration_errors) == 0
[ "Import, instantiate & \"init\" the modules we manage\n\n :param modules: list of the managed modules\n :return: True if no errors\n " ]
Please provide a description of the function:def load(self, modules): self.modules_assoc = [] for module in modules: if not module.enabled: logger.info("Module %s is declared but not enabled", module.name) # Store in our modules list but do not try to...
[ "Load Python modules and check their usability\n\n :param modules: list of the modules that must be loaded\n :return:\n " ]
Please provide a description of the function:def try_instance_init(self, instance, late_start=False): try: instance.init_try += 1 # Maybe it's a retry if not late_start and instance.init_try > 1: # Do not try until too frequently, or it's too loopy ...
[ "Try to \"initialize\" the given module instance.\n\n :param instance: instance to init\n :type instance: object\n :param late_start: If late_start, don't look for last_init_try\n :type late_start: bool\n :return: True on successful init. False if instance init method raised any E...
Please provide a description of the function:def clear_instances(self, instances=None): if instances is None: instances = self.instances[:] # have to make a copy of the list for instance in instances: self.remove_instance(instance)
[ "Request to \"remove\" the given instances list or all if not provided\n\n :param instances: instances to remove (all instances are removed if None)\n :type instances:\n :return: None\n " ]
Please provide a description of the function:def set_to_restart(self, instance): self.to_restart.append(instance) if instance.is_external: instance.proc = None
[ "Put an instance to the restart queue\n\n :param instance: instance to restart\n :type instance: object\n :return: None\n " ]
Please provide a description of the function:def get_instances(self): self.clear_instances() for (alignak_module, python_module) in self.modules_assoc: alignak_module.properties = python_module.properties.copy() alignak_module.my_daemon = self.daemon logger....
[ "Create, init and then returns the list of module instances that the caller needs.\n\n This method is called once the Python modules are loaded to initialize the modules.\n\n If an instance can't be created or initialized then only log is doneand that\n instance is skipped. The previous modules...
Please provide a description of the function:def start_external_instances(self, late_start=False): for instance in [i for i in self.instances if i.is_external]: # But maybe the init failed a bit, so bypass this ones from now if not self.try_instance_init(instance, late_start=lat...
[ "Launch external instances that are load correctly\n\n :param late_start: If late_start, don't look for last_init_try\n :type late_start: bool\n :return: None\n " ]
Please provide a description of the function:def remove_instance(self, instance): # External instances need to be close before (process + queues) if instance.is_external: logger.info("Request external process to stop for %s", instance.name) instance.stop_process() ...
[ "Request to cleanly remove the given instance.\n If instance is external also shutdown it cleanly\n\n :param instance: instance to remove\n :type instance: object\n :return: None\n " ]
Please provide a description of the function:def check_alive_instances(self): # Only for external for instance in self.instances: if instance in self.to_restart: continue if instance.is_external and instance.process and not instance.process.is_alive(): ...
[ "Check alive instances.\n If not, log error and try to restart it\n\n :return: None\n " ]
Please provide a description of the function:def try_to_restart_deads(self): to_restart = self.to_restart[:] del self.to_restart[:] for instance in to_restart: logger.warning("Trying to restart module: %s", instance.name) if self.try_instance_init(instance): ...
[ "Try to reinit and restart dead instances\n\n :return: None\n " ]
Please provide a description of the function:def get_internal_instances(self, phase=None): if phase is None: return [instance for instance in self.instances if not instance.is_external] return [instance for instance in self.instances if not instance.is_external and ...
[ "Get a list of internal instances (in a specific phase)\n\n If phase is None, return all internal instances whtever the phase\n\n :param phase: phase to filter (never used)\n :type phase:\n :return: internal instances list\n :rtype: list\n " ]
Please provide a description of the function:def get_external_instances(self, phase=None): if phase is None: return [instance for instance in self.instances if instance.is_external] return [instance for instance in self.instances if instance.is_external and phase in...
[ "Get a list of external instances (in a specific phase)\n\n If phase is None, return all external instances whtever the phase\n\n :param phase: phase to filter (never used)\n :type phase:\n :return: external instances list\n :rtype: list\n " ]
Please provide a description of the function:def stop_all(self): logger.info('Shutting down modules...') # Ask internal to quit if they can for instance in self.get_internal_instances(): if hasattr(instance, 'quit') and isinstance(instance.quit, collections.Callable): ...
[ "Stop all module instances\n\n :return: None\n " ]
Please provide a description of the function:def main(): parsed_configuration = AlignakConfigParser() try: parsed_configuration.parse() except configparser.ParsingError as exp: print("Environment file parsing error: %s", exp) if parsed_configuration.export: # Export Alignak...
[ "\n Main function\n " ]
Please provide a description of the function:def parse(self): # pylint: disable=too-many-branches # Search if some ini files existe in an alignak.d sub-directory sub_directory = 'alignak.d' dir_name = os.path.dirname(self.configuration_file) dir_name = os.path.join(dir_n...
[ "\n Check if some extra configuration files are existing in an `alignak.d` sub directory\n near the found configuration file.\n\n Parse the Alignak configuration file(s)\n\n Exit the script if some errors are encountered.\n\n :return: True/False\n " ]
Please provide a description of the function:def write(self, env_file): try: with open(env_file, "w") as out_file: self.config.write(out_file) except Exception as exp: # pylint: disable=broad-except print("Dumping environment file raised an error: %s. " ...
[ "\n Write the Alignak configuration to a file\n\n :param env_file: file name to dump the configuration\n :type env_file: str\n :return: True/False\n " ]
Please provide a description of the function:def _search_sections(self, searched_sections=''): found_sections = {} # Get the daemons related properties for section in self.config.sections(): if not section.startswith(searched_sections): continue ...
[ "\n Search sections in the configuration which name starts with the provided search criteria\n :param searched_sections:\n :return: a dict containing the found sections and their parameters\n " ]
Please provide a description of the function:def get_alignak_macros(self): macros = self.get_alignak_configuration(macros=True) sections = self._search_sections('pack.') for name, _ in list(sections.items()): section_macros = self.get_alignak_configuration(section=name, mac...
[ "\n Get the Alignak macros.\n\n :return: a dict containing the Alignak macros\n " ]
Please provide a description of the function:def get_alignak_configuration(self, section=SECTION_CONFIGURATION, legacy_cfg=False, macros=False): configuration = self._search_sections(section) if section not in configuration: return [] for pr...
[ "\n Get the Alignak configuration parameters. All the variables included in\n the SECTION_CONFIGURATION section except the variables starting with 'cfg'\n and the macros.\n\n If `lecagy_cfg` is True, this function only returns the variables included in\n the SECTION_CONFIGURATION ...
Please provide a description of the function:def get_daemons(self, daemon_name=None, daemon_type=None): if daemon_name is not None: sections = self._search_sections('daemon.%s' % daemon_name) if 'daemon.%s' % daemon_name in sections: return sections['daemon.' + d...
[ "\n Get the daemons configuration parameters\n\n If name is provided, get the configuration for this daemon, else,\n If type is provided, get the configuration for all the daemons of this type, else\n get the configuration of all the daemons.\n\n :param daemon_name: the searched d...
Please provide a description of the function:def get_modules(self, name=None, daemon_name=None, names_only=True): if name is not None: sections = self._search_sections('module.' + name) if 'module.' + name in sections: return sections['module.' + name] ...
[ "\n Get the modules configuration parameters\n\n If name is provided, get the configuration for this module, else,\n If daemon_name is provided, get the configuration for all the modules of this daemon, else\n get the configuration of all the modules.\n\n :param name: the searched...
Please provide a description of the function:def copy_shell(self): cls = self.__class__ new_i = cls() # create a new group new_i.uuid = self.uuid # with the same id # Copy all properties for prop in cls.properties: if hasattr(self, prop): i...
[ "\n Copy the group properties EXCEPT the members.\n Members need to be filled after manually\n\n :return: Itemgroup object\n :rtype: alignak.objects.itemgroup.Itemgroup\n :return: None\n " ]
Please provide a description of the function:def add_members(self, members): if not isinstance(members, list): members = [members] if not getattr(self, 'members', None): self.members = members else: self.members.extend(members)
[ "Add a new member to the members list\n\n :param members: member name\n :type members: str\n :return: None\n " ]
Please provide a description of the function:def add_unknown_members(self, members): if not isinstance(members, list): members = [members] if not hasattr(self, 'unknown_members'): self.unknown_members = members else: self.unknown_members.extend(membe...
[ "Add a new member to the unknown members list\n\n :param member: member name\n :type member: str\n :return: None\n " ]
Please provide a description of the function:def is_correct(self): state = True # Make members unique, remove duplicates if self.members: self.members = list(set(self.members)) if self.unknown_members: for member in self.unknown_members: ...
[ "\n Check if a group is valid.\n Valid mean all members exists, so list of unknown_members is empty\n\n :return: True if group is correct, otherwise False\n :rtype: bool\n " ]
Please provide a description of the function:def get_initial_status_brok(self, extra=None): # Here members is a list of identifiers and we need their names if extra and isinstance(extra, Items): members = [] for member_id in self.members: member = extra[m...
[ "\n Get a brok with the group properties\n\n `members` contains a list of uuid which we must provide the names. Thus we will replace\n the default provided uuid with the members short name. The `extra` parameter, if present,\n is containing the Items to search for...\n\n :param e...
Please provide a description of the function:def check_dir(self, dirname): try: os.makedirs(dirname) dir_stat = os.stat(dirname) print("Created the directory: %s, stat: %s" % (dirname, dir_stat)) if not dir_stat.st_uid == self.uid: os.chow...
[ "Check and create directory\n\n :param dirname: file name\n :type dirname; str\n\n :return: None\n " ]
Please provide a description of the function:def do_stop(self): logger.info("Stopping %s...", self.name) if self.sync_manager: logger.info("Shutting down synchronization manager...") self.sync_manager.shutdown() self.sync_manager = None # Maybe the ...
[ "Execute the stop of this daemon:\n - request the daemon to stop\n - request the http thread to stop, else force stop the thread\n - Close the http socket\n - Shutdown the manager\n - Stop and join all started \"modules\"\n\n :return: None\n " ]
Please provide a description of the function:def request_stop(self, message='', exit_code=0): # Log an error message if exit code is not 0 # Force output to stderr if exit_code: if message: logger.error(message) try: sys.st...
[ "Remove pid and stop daemon\n\n :return: None\n " ]
Please provide a description of the function:def get_links_of_type(self, s_type=''): satellites = { 'arbiter': getattr(self, 'arbiters', []), 'scheduler': getattr(self, 'schedulers', []), 'broker': getattr(self, 'brokers', []), 'poller': getattr(self, 'po...
[ "Return the `s_type` satellite list (eg. schedulers)\n\n If s_type is None, returns a dictionary of all satellites, else returns the dictionary\n of the s_type satellites\n\n The returned dict is indexed with the satellites uuid.\n\n :param s_type: satellite type\n :type s_type: s...
Please provide a description of the function:def daemon_connection_init(self, s_link, set_wait_new_conf=False): logger.debug("Daemon connection initialization: %s %s", s_link.type, s_link.name) # If the link is not not active, I do not try to initialize the connection, just useless ;) ...
[ "Initialize a connection with the daemon for the provided satellite link\n\n Initialize the connection (HTTP client) to the daemon and get its running identifier.\n Returns True if it succeeds else if any error occur or the daemon is inactive\n it returns False.\n\n Assume the daemon sho...
Please provide a description of the function:def do_main_loop(self): # pylint: disable=too-many-branches, too-many-statements, too-many-locals # Increased on each loop turn if self.loop_count is None: self.loop_count = 0 # Daemon start timestamp if self.star...
[ "Main loop for an Alignak daemon\n\n :return: None\n " ]
Please provide a description of the function:def do_load_modules(self, modules): _ts = time.time() logger.info("Loading modules...") if self.modules_manager.load_and_init(modules): if self.modules_manager.instances: logger.info("I correctly loaded my modules...
[ "Wrapper for calling load_and_init method of modules_manager attribute\n\n :param modules: list of modules that should be loaded by the daemon\n :return: None\n " ]
Please provide a description of the function:def dump_environment(self): # Dump the Alignak configuration to a temporary ini file path = os.path.join(tempfile.gettempdir(), 'dump-env-%s-%s-%d.ini' % (self.type, self.name, int(time.time()))) try: ...
[ " Try to dump memory\n\n Not currently implemented feature\n\n :return: None\n " ]
Please provide a description of the function:def change_to_workdir(self): logger.info("Changing working directory to: %s", self.workdir) self.check_dir(self.workdir) try: os.chdir(self.workdir) except OSError as exp: self.exit_on_error("Error changing to...
[ "Change working directory to working attribute\n\n :return: None\n " ]
Please provide a description of the function:def unlink(self): logger.debug("Unlinking %s", self.pid_filename) try: os.unlink(self.pid_filename) except OSError as exp: logger.debug("Got an error unlinking our pid file: %s", exp)
[ "Remove the daemon's pid file\n\n :return: None\n " ]
Please provide a description of the function:def check_shm(): import stat shm_path = '/dev/shm' if os.name == 'posix' and os.path.exists(shm_path): # We get the access rights, and we check them mode = stat.S_IMODE(os.lstat(shm_path)[stat.ST_MODE]) if ...
[ " Check /dev/shm right permissions\n\n :return: None\n " ]
Please provide a description of the function:def __open_pidfile(self, write=False): # if problem on opening or creating file it'll be raised to the caller: try: self.pre_log.append(("DEBUG", "Opening %s pid file: %s" % ('existing' if ...
[ "Open pid file in read or write mod\n\n :param write: boolean to open file in write mod (true = write)\n :type write: bool\n :return: None\n " ]
Please provide a description of the function:def check_parallel_run(self): # pragma: no cover, not with unit tests... # TODO: other daemon run on nt if os.name == 'nt': # pragma: no cover, not currently tested with Windows... logger.warning("The parallel daemon check is not availa...
[ "Check (in pid file) if there isn't already a daemon running.\n If yes and do_replace: kill it.\n Keep in self.fpid the File object to the pid file. Will be used by writepid.\n\n :return: None\n " ]
Please provide a description of the function:def write_pid(self, pid): self.fpid.seek(0) self.fpid.truncate() self.fpid.write("%d" % pid) self.fpid.close() del self.fpid
[ " Write pid to the pid file\n\n :param pid: pid of the process\n :type pid: None | int\n :return: None\n " ]
Please provide a description of the function:def close_fds(self, skip_close_fds): # pragma: no cover, not with unit tests... # First we manage the file descriptor, because debug file can be # relative to pwd max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if max_fds == ...
[ "Close all the process file descriptors.\n Skip the descriptors present in the skip_close_fds list\n\n :param skip_close_fds: list of file descriptor to preserve from closing\n :type skip_close_fds: list\n :return: None\n " ]
Please provide a description of the function:def daemonize(self): # pragma: no cover, not for unit tests... self.pre_log.append(("INFO", "Daemonizing...")) print("Daemonizing %s..." % self.name) # Set umask os.umask(UMASK) # Close all file descriptors except the one w...
[ "Go in \"daemon\" mode: close unused fds, redirect stdout/err,\n chdir, umask, fork-setsid-fork-writepid\n Do the double fork to properly go daemon\n\n This is 'almost' as recommended by PEP3143 but it would be better to rewrite this\n daemonization thanks to the python-daemon library!\n...
Please provide a description of the function:def do_daemon_init_and_start(self, set_proc_title=True): if set_proc_title: self.set_proctitle(self.name) # Change to configured user/group account self.change_to_user_group() # Change the working directory self....
[ "Main daemon function.\n Clean, allocates, initializes and starts all necessary resources to go in daemon mode.\n\n The set_proc_title parameter is mainly useful for the Alignak unit tests.\n This to avoid changing the test process name!\n\n :param set_proc_title: if set (default), the p...
Please provide a description of the function:def setup_communication_daemon(self): # pylint: disable=no-member ca_cert = ssl_cert = ssl_key = server_dh = None # The SSL part if self.use_ssl: ssl_cert = os.path.abspath(self.server_cert) if not os.path.exi...
[ " Setup HTTP server daemon to listen\n for incoming HTTP requests from other Alignak daemons\n\n :return: True if initialization is ok, else False\n " ]
Please provide a description of the function:def change_to_user_group(self): # TODO: change user on nt if os.name == 'nt': # pragma: no cover, no Windows implementation currently logger.warning("You can't change user on this system") return if (self.user == 'ro...
[ " Change to configured user/group for the running program.\n If user/group are not valid, we exit with code 1\n If change failed we exit with code 2\n\n :return: None\n " ]
Please provide a description of the function:def manage_signal(self, sig, frame): # pylint: disable=unused-argument logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig]) if sig == signal.SIGUSR1: # if USR1, ask a memory dump self.need_dump_environment = True eli...
[ "Manage signals caught by the daemon\n signal.SIGUSR1 : dump_environment\n signal.SIGUSR2 : dump_object (nothing)\n signal.SIGTERM, signal.SIGINT : terminate process\n\n :param sig: signal caught by daemon\n :type sig: str\n :param frame: current stack frame\n :type ...
Please provide a description of the function:def set_proctitle(self, daemon_name=None): logger.debug("Setting my process name: %s", daemon_name) if daemon_name: setproctitle("alignak-%s %s" % (self.type, daemon_name)) if self.modules_manager: self.modules...
[ "Set the proctitle of the daemon\n\n :param daemon_name: daemon instance name (eg. arbiter-master). If not provided, only the\n daemon type (eg. arbiter) will be used for the process title\n :type daemon_name: str\n :return: None\n " ]
Please provide a description of the function:def get_header(self, configuration=False): header = [u"-----", u" █████╗ ██╗ ██╗ ██████╗ ███╗ ██╗ █████╗ ██╗ ██╗", u" ██╔══██╗██║ ██║██╔════╝ ████╗ ██║██╔══██╗██║ ██╔╝", u" ███████║██║ ...
[ "Get the log file header\n\n If configuration is True, this returns the daemon configuration\n\n :return: A string list containing project name, daemon name, version, licence etc.\n :rtype: list\n " ]
Please provide a description of the function:def http_daemon_thread(self): logger.debug("HTTP thread running") try: # This function is a blocking function serving HTTP protocol self.http_daemon.run() except PortNotFree as exp: logger.exception('The HT...
[ "Main function of the http daemon thread will loop forever unless we stop the root daemon\n\n The main thing is to have a pool of X concurrent requests for the http_daemon,\n so \"no_lock\" calls can always be directly answer without having a \"locked\" version to\n finish. This is achieved tha...
Please provide a description of the function:def make_a_pause(self, timeout=0.0001, check_time_change=True): if timeout == 0: timeout = 0.0001 if not check_time_change: # Time to sleep time.sleep(timeout) self.sleep_time += timeout re...
[ " Wait up to timeout and check for system time change.\n\n This function checks if the system time changed since the last call. If so,\n the difference is returned to the caller.\n The duration of this call is removed from the timeout. If this duration is\n greater than the required time...
Please provide a description of the function:def wait_for_initial_conf(self, timeout=1.0): logger.info("Waiting for initial configuration") # Arbiter do not already set our have_conf param _ts = time.time() while not self.new_conf and not self.interrupted: # Make a p...
[ "Wait initial configuration from the arbiter.\n Basically sleep 1.0 and check if new_conf is here\n\n :param timeout: timeout to wait\n :type timeout: int\n :return: None\n " ]
Please provide a description of the function:def watch_for_new_conf(self, timeout=0): logger.debug("Watching for a new configuration, timeout: %s", timeout) self.make_a_pause(timeout=timeout, check_time_change=False) return any(self.new_conf)
[ "Check if a new configuration was sent to the daemon\n\n This function is called on each daemon loop turn. Basically it is a sleep...\n\n If a new configuration was posted, this function returns True\n\n :param timeout: timeout to wait. Default is no wait time.\n :type timeout: float\n ...
Please provide a description of the function:def hook_point(self, hook_name, handle=None): full_hook_name = 'hook_' + hook_name for module in self.modules_manager.instances: _ts = time.time() if not hasattr(module, full_hook_name): continue f...
[ "Used to call module function that may define a hook function for hook_name\n\n Available hook points:\n - `tick`, called on each daemon loop turn\n - `save_retention`; called by the scheduler when live state\n saving is to be done\n - `load_retention`; called by the scheduler...
Please provide a description of the function:def get_id(self, details=False): # pylint: disable=unused-argument # Modules information res = { "alignak": getattr(self, 'alignak_name', 'unknown'), "type": getattr(self, 'type', 'unknown'), "name": getattr(self,...
[ "Get daemon identification information\n\n :return: A dict with the following structure\n ::\n {\n \"alignak\": selfAlignak instance name\n \"type\": daemon type\n \"name\": daemon name\n \"version\": Alignak version\n }...
Please provide a description of the function:def get_daemon_stats(self, details=False): # pylint: disable=unused-argument res = self.get_id() res.update({ "program_start": self.program_start, "spare": self.spare, 'counters': {}, 'metrics': [], ...
[ "Get state of modules and create a scheme for stats data of daemon\n This may be overridden in subclasses (and it is...)\n\n :return: A dict with the following structure\n ::\n {\n 'modules': {\n 'internal': {'name': \"MYMODULE1\", 'state': 'ok'},\n ...
Please provide a description of the function:def exit_ok(self, message, exit_code=None): logger.info("Exiting...") if message: logger.info("-----") logger.error("Exit message: %s", message) logger.info("-----") self.request_stop() if exit_co...
[ "Log a message and exit\n\n :param exit_code: if not None, exit with the provided value as exit code\n :type exit_code: int\n :param message: message for the exit reason\n :type message: str\n :return: None\n " ]
Please provide a description of the function:def exit_on_error(self, message, exit_code=1): # pylint: disable=no-self-use log = "I got an unrecoverable error. I have to exit." if message: log += "\n-----\nError message: %s" % message print("Error message: %s" % m...
[ "Log generic message when getting an error and exit\n\n :param exit_code: if not None, exit with the provided value as exit code\n :type exit_code: int\n :param message: message for the exit reason\n :type message: str\n :return: None\n " ]
Please provide a description of the function:def exit_on_exception(self, raised_exception, message='', exit_code=99): self.exit_on_error(message=message, exit_code=None) logger.critical("-----\nException: %s\nBack trace of the error:\n%s", str(raised_exception), traceba...
[ "Log generic message when getting an unrecoverable error\n\n :param raised_exception: raised Exception\n :type raised_exception: Exception\n :param message: message for the exit reason\n :type message: str\n :param exit_code: exit with the provided value as exit code\n :typ...
Please provide a description of the function:def get_objects_from_from_queues(self): _t0 = time.time() had_some_objects = False for module in self.modules_manager.get_external_instances(): queue = module.from_q if not queue: continue w...
[ " Get objects from \"from\" queues and add them.\n\n :return: True if we got something in the queue, False otherwise.\n :rtype: bool\n " ]
Please provide a description of the function:def setup_alignak_logger(self): # Configure the daemon logger try: # Make sure that the log directory is existing self.check_dir(self.logdir) setup_logger(logger_configuration_file=self.logger_configuration, ...
[ " Setup alignak logger:\n - with the daemon log configuration properties\n - configure the global daemon handler (root logger)\n - log the daemon Alignak header\n\n - configure the global Alignak monitoring log\n\n This function is called very early on daemon start. The daemon is ...
Please provide a description of the function:def enter(self, timeperiods, hosts, services): if self.ref in hosts: item = hosts[self.ref] else: item = services[self.ref] broks = [] self.is_in_effect = True if self.fixed is False: now = ...
[ "Set ref in scheduled downtime and raise downtime log entry (start)\n\n :param hosts: hosts objects to get item ref\n :type hosts: alignak.objects.host.Hosts\n :param services: services objects to get item ref\n :type services: alignak.objects.service.Services\n :return: broks\n ...
Please provide a description of the function:def exit(self, timeperiods, hosts, services): if self.ref in hosts: item = hosts[self.ref] else: item = services[self.ref] broks = [] # If not is_in_effect means that ot was probably a flexible downtime which ...
[ "Remove ref in scheduled downtime and raise downtime log entry (exit)\n\n :param hosts: hosts objects to get item ref\n :type hosts: alignak.objects.host.Hosts\n :param services: services objects to get item ref\n :type services: alignak.objects.service.Services\n :return: [], alw...
Please provide a description of the function:def cancel(self, timeperiods, hosts, services): if self.ref in hosts: item = hosts[self.ref] else: item = services[self.ref] broks = [] self.is_in_effect = False item.scheduled_downtime_depth -= 1 ...
[ "Remove ref in scheduled downtime and raise downtime log entry (cancel)\n\n :param hosts: hosts objects to get item ref\n :type hosts: alignak.objects.host.Hosts\n :param services: services objects to get item ref\n :type services: alignak.objects.service.Services\n :return: [], a...
Please provide a description of the function:def add_automatic_comment(self, ref): if self.fixed is True: text = (DOWNTIME_FIXED_MESSAGE % (ref.my_type, time.strftime("%Y-%m-%d %H:%M:%S", ...
[ "Add comment on ref for downtime\n\n :param ref: the host/service we want to link a comment to\n :type ref: alignak.objects.schedulingitem.SchedulingItem\n\n :return: None\n " ]
Please provide a description of the function:def get_raise_brok(self, host_name, service_name=''): data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_raise', 'data': data})
[ "Get a start downtime brok\n\n :param host_name: host concerned by the downtime\n :type host_name\n :param service_name: service concerned by the downtime\n :type service_name\n :return: brok with wanted data\n :rtype: alignak.brok.Brok\n " ]
Please provide a description of the function:def get_expire_brok(self, host_name, service_name=''): data = self.serialize() data['host'] = host_name if service_name != '': data['service'] = service_name return Brok({'type': 'downtime_expire', 'data': data})
[ "Get an expire downtime brok\n\n :param host_name: host concerned by the downtime\n :type host_name\n :param service_name: service concerned by the downtime\n :type service_name\n :return: brok with wanted data\n :rtype: alignak.brok.Brok\n " ]
Please provide a description of the function:def fill_data_brok_from(self, data, brok_type): cls = self.__class__ # Now config properties for prop, entry in list(cls.properties.items()): # Is this property intended for broking? # if 'fill_brok' in entry[prop]: ...
[ "\n Add properties to data if fill_brok of these class properties\n is same as brok_type\n\n :param data: dictionnary of this command\n :type data: dict\n :param brok_type: type of brok\n :type brok_type: str\n :return: None\n " ]
Please provide a description of the function:def is_correct(self): state = True # _internal_host_check is for having an host check result # without running a check plugin if self.command_name.startswith('_internal_host_check'): # Command line may contain: [state_id]...
[ "Check if this object configuration is correct ::\n\n * Check our own specific properties\n * Call our parent class is_correct checker\n\n :return: True if the configuration is correct, otherwise False\n :rtype: bool\n " ]
Please provide a description of the function:def get_name(self): return getattr(self, 'dependent_host_name', '') + '/'\ + getattr(self, 'dependent_service_description', '') \ + '..' + getattr(self, 'host_name', '') + '/' \ + getattr(self, 'service_description', '')
[ "Get name based on 4 class attributes\n Each attribute is substituted by '' if attribute does not exist\n\n :return: dependent_host_name/dependent_service_description..host_name/service_description\n :rtype: str\n TODO: Clean this function (use format for string)\n " ]
Please provide a description of the function:def add_service_dependency(self, dep_host_name, dep_service_description, par_host_name, par_service_description): # We create a "standard" service_dep prop = { 'dependent_host_name': dep_host_name,...
[ "Instantiate and add a Servicedependency object to the items dict::\n\n * notification criteria is \"u,c,w\"\n * inherits_parent is True\n\n :param dep_host_name: dependent host name\n :type dep_host_name: str\n :param dep_service_description: dependent service description\n ...
Please provide a description of the function:def explode_hostgroup(self, svc_dep, hostgroups): # pylint: disable=too-many-locals # We will create a service dependency for each host part of the host group # First get services snames = [d.strip() for d in svc_dep.service_descript...
[ "Explode a service dependency for each member of hostgroup\n\n :param svc_dep: service dependency to explode\n :type svc_dep: alignak.objects.servicedependency.Servicedependency\n :param hostgroups: used to find hostgroup objects\n :type hostgroups: alignak.objects.hostgroup.Hostgroups\n...
Please provide a description of the function:def explode(self, hostgroups): # pylint: disable=too-many-locals, too-many-branches # The "old" services will be removed. All services with # more than one host or a host group will be in it srvdep_to_remove = [] # Then for e...
[ "Explode all service dependency for each member of hostgroups\n Each member of dependent hostgroup or hostgroup in dependency have to get a copy of\n service dependencies (quite complex to parse)\n\n :param hostgroups: used to look for hostgroup\n :type hostgroups: alignak.objects.hostgr...
Please provide a description of the function:def linkify(self, hosts, services, timeperiods): self.linkify_sd_by_s(hosts, services) self.linkify_sd_by_tp(timeperiods) self.linkify_s_by_sd(services)
[ "Create link between objects::\n\n * servicedependency -> host\n * servicedependency -> service\n * servicedependency -> timeperiods\n\n :param hosts: hosts to link\n :type hosts: alignak.objects.host.Hosts\n :param services: services to link\n :type services: ali...
Please provide a description of the function:def linkify_sd_by_s(self, hosts, services): to_del = [] errors = self.configuration_errors warns = self.configuration_warnings for servicedep in self: try: s_name = servicedep.dependent_service_description ...
[ "Replace dependent_service_description and service_description\n in service dependency by the real object\n\n :param hosts: host list, used to look for a specific one\n :type hosts: alignak.objects.host.Hosts\n :param services: service list to look for a specific one\n :type servi...
Please provide a description of the function:def linkify_sd_by_tp(self, timeperiods): for servicedep in self: try: tp_name = servicedep.dependency_period timeperiod = timeperiods.find_by_name(tp_name) if timeperiod: service...
[ "Replace dependency_period by a real object in service dependency\n\n :param timeperiods: list of timeperiod, used to look for a specific one\n :type timeperiods: alignak.objects.timeperiod.Timeperiods\n :return: None\n " ]
Please provide a description of the function:def linkify_s_by_sd(self, services): for servicedep in self: # Only used for debugging purpose when loops are detected setattr(servicedep, "service_description_string", "undefined") setattr(servicedep, "dependent_service_d...
[ "Add dependency in service objects\n\n :return: None\n " ]
Please provide a description of the function:def is_correct(self): state = True # Internal checks before executing inherited function... loop = self.no_loop_in_parents("service_description", "dependent_service_description") if loop: msg = "Loop detected while checki...
[ "Check if this servicedependency configuration is correct ::\n\n * Check our own specific properties\n * Call our parent class is_correct checker\n\n :return: True if the configuration is correct, otherwise False\n :rtype: bool\n " ]
Please provide a description of the function:def get_instance(mod_conf): logger.info("Giving an instance of %s for alias: %s", mod_conf.python_name, mod_conf.module_alias) return InnerMetrics(mod_conf)
[ "\n Return a module instance for the modules manager\n\n :param mod_conf: the module properties as defined globally in this file\n :return:\n " ]
Please provide a description of the function:def init(self): # pylint: disable=too-many-branches if not self.enabled: logger.info(" the module is disabled.") return True try: connections = self.test_connection() except Exception as exp: # pylint: d...
[ "Called by the daemon broker to initialize the module" ]
Please provide a description of the function:def get_metrics_from_perfdata(self, service, perf_data): result = [] metrics = PerfDatas(perf_data) for metric in metrics: logger.debug("service: %s, metric: %s (%s)", service, metric, metric.__dict__) if metric.name...
[ "Decode the performance data to build a metrics list" ]