repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Alignak-monitoring/alignak
alignak/objects/hostdependency.py
Hostdependencies.linkify_hd_by_tp
def linkify_hd_by_tp(self, timeperiods): """Replace dependency_period by a real object in host dependency :param timeperiods: list of timeperiod, used to look for a specific one :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None """ for hostdep in self: try: tp_name = hostdep.dependency_period timeperiod = timeperiods.find_by_name(tp_name) if timeperiod: hostdep.dependency_period = timeperiod.uuid else: hostdep.dependency_period = '' except AttributeError as exp: # pragma: no cover, simple protectionn logger.error("[hostdependency] fail to linkify by timeperiod: %s", exp)
python
def linkify_hd_by_tp(self, timeperiods): """Replace dependency_period by a real object in host dependency :param timeperiods: list of timeperiod, used to look for a specific one :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None """ for hostdep in self: try: tp_name = hostdep.dependency_period timeperiod = timeperiods.find_by_name(tp_name) if timeperiod: hostdep.dependency_period = timeperiod.uuid else: hostdep.dependency_period = '' except AttributeError as exp: # pragma: no cover, simple protectionn logger.error("[hostdependency] fail to linkify by timeperiod: %s", exp)
[ "def", "linkify_hd_by_tp", "(", "self", ",", "timeperiods", ")", ":", "for", "hostdep", "in", "self", ":", "try", ":", "tp_name", "=", "hostdep", ".", "dependency_period", "timeperiod", "=", "timeperiods", ".", "find_by_name", "(", "tp_name", ")", "if", "timeperiod", ":", "hostdep", ".", "dependency_period", "=", "timeperiod", ".", "uuid", "else", ":", "hostdep", ".", "dependency_period", "=", "''", "except", "AttributeError", "as", "exp", ":", "# pragma: no cover, simple protectionn", "logger", ".", "error", "(", "\"[hostdependency] fail to linkify by timeperiod: %s\"", ",", "exp", ")" ]
Replace dependency_period by a real object in host dependency :param timeperiods: list of timeperiod, used to look for a specific one :type timeperiods: alignak.objects.timeperiod.Timeperiods :return: None
[ "Replace", "dependency_period", "by", "a", "real", "object", "in", "host", "dependency" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostdependency.py#L253-L269
train
Alignak-monitoring/alignak
alignak/objects/hostextinfo.py
HostsExtInfo.merge_extinfo
def merge_extinfo(host, extinfo): """Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None """ # Note that 2d_coords and 3d_coords are never merged, so not usable ! properties = ['notes', 'notes_url', 'icon_image', 'icon_image_alt', 'vrml_image', 'statusmap_image'] # host properties have precedence over hostextinfo properties for prop in properties: if getattr(host, prop) == '' and getattr(extinfo, prop) != '': setattr(host, prop, getattr(extinfo, prop))
python
def merge_extinfo(host, extinfo): """Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None """ # Note that 2d_coords and 3d_coords are never merged, so not usable ! properties = ['notes', 'notes_url', 'icon_image', 'icon_image_alt', 'vrml_image', 'statusmap_image'] # host properties have precedence over hostextinfo properties for prop in properties: if getattr(host, prop) == '' and getattr(extinfo, prop) != '': setattr(host, prop, getattr(extinfo, prop))
[ "def", "merge_extinfo", "(", "host", ",", "extinfo", ")", ":", "# Note that 2d_coords and 3d_coords are never merged, so not usable !", "properties", "=", "[", "'notes'", ",", "'notes_url'", ",", "'icon_image'", ",", "'icon_image_alt'", ",", "'vrml_image'", ",", "'statusmap_image'", "]", "# host properties have precedence over hostextinfo properties", "for", "prop", "in", "properties", ":", "if", "getattr", "(", "host", ",", "prop", ")", "==", "''", "and", "getattr", "(", "extinfo", ",", "prop", ")", "!=", "''", ":", "setattr", "(", "host", ",", "prop", ",", "getattr", "(", "extinfo", ",", "prop", ")", ")" ]
Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None
[ "Merge", "extended", "host", "information", "into", "a", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostextinfo.py#L136-L151
train
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.set_proxy
def set_proxy(self, proxy): # pragma: no cover, not with unit tests """Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None """ if proxy: logger.debug('PROXY SETTING PROXY %s', proxy) self._requests_con.proxies = { 'http': proxy, 'https': proxy, }
python
def set_proxy(self, proxy): # pragma: no cover, not with unit tests """Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None """ if proxy: logger.debug('PROXY SETTING PROXY %s', proxy) self._requests_con.proxies = { 'http': proxy, 'https': proxy, }
[ "def", "set_proxy", "(", "self", ",", "proxy", ")", ":", "# pragma: no cover, not with unit tests", "if", "proxy", ":", "logger", ".", "debug", "(", "'PROXY SETTING PROXY %s'", ",", "proxy", ")", "self", ".", "_requests_con", ".", "proxies", "=", "{", "'http'", ":", "proxy", ",", "'https'", ":", "proxy", ",", "}" ]
Set HTTP proxy :param proxy: proxy url :type proxy: str :return: None
[ "Set", "HTTP", "proxy" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L176-L188
train
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.post
def post(self, path, args, wait=False): """POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) for (key, value) in list(args.items()): args[key] = serialize(value, True) try: logger.debug("post: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.post(uri, json=args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
python
def post(self, path, args, wait=False): """POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) for (key, value) in list(args.items()): args[key] = serialize(value, True) try: logger.debug("post: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.post(uri, json=args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
[ "def", "post", "(", "self", ",", "path", ",", "args", ",", "wait", "=", "False", ")", ":", "uri", "=", "self", ".", "make_uri", "(", "path", ")", "timeout", "=", "self", ".", "make_timeout", "(", "wait", ")", "for", "(", "key", ",", "value", ")", "in", "list", "(", "args", ".", "items", "(", ")", ")", ":", "args", "[", "key", "]", "=", "serialize", "(", "value", ",", "True", ")", "try", ":", "logger", ".", "debug", "(", "\"post: %s, timeout: %s, params: %s\"", ",", "uri", ",", "timeout", ",", "args", ")", "rsp", "=", "self", ".", "_requests_con", ".", "post", "(", "uri", ",", "json", "=", "args", ",", "timeout", "=", "timeout", ",", "verify", "=", "self", ".", "strong_ssl", ")", "logger", ".", "debug", "(", "\"got: %d - %s\"", ",", "rsp", ".", "status_code", ",", "rsp", ".", "text", ")", "if", "rsp", ".", "status_code", "!=", "200", ":", "raise", "HTTPClientDataException", "(", "rsp", ".", "status_code", ",", "rsp", ".", "text", ",", "uri", ")", "return", "rsp", ".", "content", "except", "(", "requests", ".", "Timeout", ",", "requests", ".", "ConnectTimeout", ")", ":", "raise", "HTTPClientTimeoutException", "(", "timeout", ",", "uri", ")", "except", "requests", ".", "ConnectionError", "as", "exp", ":", "raise", "HTTPClientConnectionException", "(", "uri", ",", "exp", ".", "args", "[", "0", "]", ")", "except", "Exception", "as", "exp", ":", "raise", "HTTPClientException", "(", "'Request error to %s: %s'", "%", "(", "uri", ",", "exp", ")", ")" ]
POST an HTTP request to a daemon :param path: path to do the request :type path: str :param args: args to add in the request :type args: dict :param wait: True for a long timeout :type wait: bool :return: Content of the HTTP response if server returned 200 :rtype: str
[ "POST", "an", "HTTP", "request", "to", "a", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L219-L247
train
Alignak-monitoring/alignak
alignak/http/client.py
HTTPClient.put
def put(self, path, args, wait=False): # pragma: no cover, looks never used! # todo: remove this because it looks never used anywhere... """PUT and HTTP request to a daemon :param path: path to do the request :type path: str :param args: data to send in the request :type args: :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) try: logger.debug("put: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.put(uri, args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
python
def put(self, path, args, wait=False): # pragma: no cover, looks never used! # todo: remove this because it looks never used anywhere... """PUT and HTTP request to a daemon :param path: path to do the request :type path: str :param args: data to send in the request :type args: :return: Content of the HTTP response if server returned 200 :rtype: str """ uri = self.make_uri(path) timeout = self.make_timeout(wait) try: logger.debug("put: %s, timeout: %s, params: %s", uri, timeout, args) rsp = self._requests_con.put(uri, args, timeout=timeout, verify=self.strong_ssl) logger.debug("got: %d - %s", rsp.status_code, rsp.text) if rsp.status_code != 200: raise HTTPClientDataException(rsp.status_code, rsp.text, uri) return rsp.content except (requests.Timeout, requests.ConnectTimeout): raise HTTPClientTimeoutException(timeout, uri) except requests.ConnectionError as exp: raise HTTPClientConnectionException(uri, exp.args[0]) except Exception as exp: raise HTTPClientException('Request error to %s: %s' % (uri, exp))
[ "def", "put", "(", "self", ",", "path", ",", "args", ",", "wait", "=", "False", ")", ":", "# pragma: no cover, looks never used!", "# todo: remove this because it looks never used anywhere...", "uri", "=", "self", ".", "make_uri", "(", "path", ")", "timeout", "=", "self", ".", "make_timeout", "(", "wait", ")", "try", ":", "logger", ".", "debug", "(", "\"put: %s, timeout: %s, params: %s\"", ",", "uri", ",", "timeout", ",", "args", ")", "rsp", "=", "self", ".", "_requests_con", ".", "put", "(", "uri", ",", "args", ",", "timeout", "=", "timeout", ",", "verify", "=", "self", ".", "strong_ssl", ")", "logger", ".", "debug", "(", "\"got: %d - %s\"", ",", "rsp", ".", "status_code", ",", "rsp", ".", "text", ")", "if", "rsp", ".", "status_code", "!=", "200", ":", "raise", "HTTPClientDataException", "(", "rsp", ".", "status_code", ",", "rsp", ".", "text", ",", "uri", ")", "return", "rsp", ".", "content", "except", "(", "requests", ".", "Timeout", ",", "requests", ".", "ConnectTimeout", ")", ":", "raise", "HTTPClientTimeoutException", "(", "timeout", ",", "uri", ")", "except", "requests", ".", "ConnectionError", "as", "exp", ":", "raise", "HTTPClientConnectionException", "(", "uri", ",", "exp", ".", "args", "[", "0", "]", ")", "except", "Exception", "as", "exp", ":", "raise", "HTTPClientException", "(", "'Request error to %s: %s'", "%", "(", "uri", ",", "exp", ")", ")" ]
PUT and HTTP request to a daemon :param path: path to do the request :type path: str :param args: data to send in the request :type args: :return: Content of the HTTP response if server returned 200 :rtype: str
[ "PUT", "and", "HTTP", "request", "to", "a", "daemon" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/client.py#L249-L274
train
Alignak-monitoring/alignak
alignak/objects/hostescalation.py
Hostescalations.explode
def explode(self, escalations): """Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None """ # Now we explode all escalations (host_name, hostgroup_name) to escalations for escalation in self: properties = escalation.__class__.properties name = getattr(escalation, 'host_name', getattr(escalation, 'hostgroup_name', '')) creation_dict = { 'escalation_name': 'Generated-HE-%s-%s' % (name, escalation.uuid) } for prop in properties: if hasattr(escalation, prop): creation_dict[prop] = getattr(escalation, prop) escalations.add_escalation(Escalation(creation_dict))
python
def explode(self, escalations): """Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None """ # Now we explode all escalations (host_name, hostgroup_name) to escalations for escalation in self: properties = escalation.__class__.properties name = getattr(escalation, 'host_name', getattr(escalation, 'hostgroup_name', '')) creation_dict = { 'escalation_name': 'Generated-HE-%s-%s' % (name, escalation.uuid) } for prop in properties: if hasattr(escalation, prop): creation_dict[prop] = getattr(escalation, prop) escalations.add_escalation(Escalation(creation_dict))
[ "def", "explode", "(", "self", ",", "escalations", ")", ":", "# Now we explode all escalations (host_name, hostgroup_name) to escalations", "for", "escalation", "in", "self", ":", "properties", "=", "escalation", ".", "__class__", ".", "properties", "name", "=", "getattr", "(", "escalation", ",", "'host_name'", ",", "getattr", "(", "escalation", ",", "'hostgroup_name'", ",", "''", ")", ")", "creation_dict", "=", "{", "'escalation_name'", ":", "'Generated-HE-%s-%s'", "%", "(", "name", ",", "escalation", ".", "uuid", ")", "}", "for", "prop", "in", "properties", ":", "if", "hasattr", "(", "escalation", ",", "prop", ")", ":", "creation_dict", "[", "prop", "]", "=", "getattr", "(", "escalation", ",", "prop", ")", "escalations", ".", "add_escalation", "(", "Escalation", "(", "creation_dict", ")", ")" ]
Create instance of Escalation for each HostEscalation object :param escalations: list of escalation, used to add new ones :type escalations: alignak.objects.escalation.Escalations :return: None
[ "Create", "instance", "of", "Escalation", "for", "each", "HostEscalation", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostescalation.py#L109-L128
train
Alignak-monitoring/alignak
alignak/stats.py
Stats.register
def register(self, name, _type, statsd_host='localhost', statsd_port=8125, statsd_prefix='alignak', statsd_enabled=False, broks_enabled=False): """Init instance with real values :param name: daemon name :type name: str :param _type: daemon type :type _type: :param statsd_host: host to post data :type statsd_host: str :param statsd_port: port to post data :type statsd_port: int :param statsd_prefix: prefix to add to metric :type statsd_prefix: str :param statsd_enabled: bool to enable statsd :type statsd_enabled: bool :param broks_enabled: bool to enable broks sending :type broks_enabled: bool :return: None """ self.name = name # This attribute is not used, but I keep ascending compatibility with former interface! self._type = _type # local statsd part self.statsd_host = statsd_host self.statsd_port = int(statsd_port) self.statsd_prefix = statsd_prefix self.statsd_enabled = statsd_enabled # local broks part self.broks_enabled = broks_enabled logger.debug("StatsD configuration for %s - %s:%s, prefix: %s, " "enabled: %s, broks: %s, file: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix, self.statsd_enabled, self.broks_enabled, self.stats_file) if self.statsd_enabled and self.statsd_host is not None and self.statsd_host != 'None': logger.info("Sending %s statistics to: %s:%s, prefix: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix) if self.load_statsd(): logger.info('Alignak internal statistics are sent to StatsD.') else: logger.info('StatsD server is not available.') if self.stats_file: try: self.file_d = open(self.stats_file, 'a') logger.info("Alignak internal statistics are written in the file %s", self.stats_file) except OSError as exp: # pragma: no cover, should never happen... logger.exception("Error when opening the file '%s' : %s", self.stats_file, exp) self.file_d = None return self.statsd_enabled
python
def register(self, name, _type, statsd_host='localhost', statsd_port=8125, statsd_prefix='alignak', statsd_enabled=False, broks_enabled=False): """Init instance with real values :param name: daemon name :type name: str :param _type: daemon type :type _type: :param statsd_host: host to post data :type statsd_host: str :param statsd_port: port to post data :type statsd_port: int :param statsd_prefix: prefix to add to metric :type statsd_prefix: str :param statsd_enabled: bool to enable statsd :type statsd_enabled: bool :param broks_enabled: bool to enable broks sending :type broks_enabled: bool :return: None """ self.name = name # This attribute is not used, but I keep ascending compatibility with former interface! self._type = _type # local statsd part self.statsd_host = statsd_host self.statsd_port = int(statsd_port) self.statsd_prefix = statsd_prefix self.statsd_enabled = statsd_enabled # local broks part self.broks_enabled = broks_enabled logger.debug("StatsD configuration for %s - %s:%s, prefix: %s, " "enabled: %s, broks: %s, file: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix, self.statsd_enabled, self.broks_enabled, self.stats_file) if self.statsd_enabled and self.statsd_host is not None and self.statsd_host != 'None': logger.info("Sending %s statistics to: %s:%s, prefix: %s", self.name, self.statsd_host, self.statsd_port, self.statsd_prefix) if self.load_statsd(): logger.info('Alignak internal statistics are sent to StatsD.') else: logger.info('StatsD server is not available.') if self.stats_file: try: self.file_d = open(self.stats_file, 'a') logger.info("Alignak internal statistics are written in the file %s", self.stats_file) except OSError as exp: # pragma: no cover, should never happen... logger.exception("Error when opening the file '%s' : %s", self.stats_file, exp) self.file_d = None return self.statsd_enabled
[ "def", "register", "(", "self", ",", "name", ",", "_type", ",", "statsd_host", "=", "'localhost'", ",", "statsd_port", "=", "8125", ",", "statsd_prefix", "=", "'alignak'", ",", "statsd_enabled", "=", "False", ",", "broks_enabled", "=", "False", ")", ":", "self", ".", "name", "=", "name", "# This attribute is not used, but I keep ascending compatibility with former interface!", "self", ".", "_type", "=", "_type", "# local statsd part", "self", ".", "statsd_host", "=", "statsd_host", "self", ".", "statsd_port", "=", "int", "(", "statsd_port", ")", "self", ".", "statsd_prefix", "=", "statsd_prefix", "self", ".", "statsd_enabled", "=", "statsd_enabled", "# local broks part", "self", ".", "broks_enabled", "=", "broks_enabled", "logger", ".", "debug", "(", "\"StatsD configuration for %s - %s:%s, prefix: %s, \"", "\"enabled: %s, broks: %s, file: %s\"", ",", "self", ".", "name", ",", "self", ".", "statsd_host", ",", "self", ".", "statsd_port", ",", "self", ".", "statsd_prefix", ",", "self", ".", "statsd_enabled", ",", "self", ".", "broks_enabled", ",", "self", ".", "stats_file", ")", "if", "self", ".", "statsd_enabled", "and", "self", ".", "statsd_host", "is", "not", "None", "and", "self", ".", "statsd_host", "!=", "'None'", ":", "logger", ".", "info", "(", "\"Sending %s statistics to: %s:%s, prefix: %s\"", ",", "self", ".", "name", ",", "self", ".", "statsd_host", ",", "self", ".", "statsd_port", ",", "self", ".", "statsd_prefix", ")", "if", "self", ".", "load_statsd", "(", ")", ":", "logger", ".", "info", "(", "'Alignak internal statistics are sent to StatsD.'", ")", "else", ":", "logger", ".", "info", "(", "'StatsD server is not available.'", ")", "if", "self", ".", "stats_file", ":", "try", ":", "self", ".", "file_d", "=", "open", "(", "self", ".", "stats_file", ",", "'a'", ")", "logger", ".", "info", "(", "\"Alignak internal statistics are written in the file %s\"", ",", "self", ".", "stats_file", ")", "except", "OSError", "as", "exp", ":", "# pragma: no cover, should never happen...", "logger", ".", "exception", "(", "\"Error when opening the file '%s' : %s\"", ",", "self", ".", "stats_file", ",", "exp", ")", "self", ".", "file_d", "=", "None", "return", "self", ".", "statsd_enabled" ]
Init instance with real values :param name: daemon name :type name: str :param _type: daemon type :type _type: :param statsd_host: host to post data :type statsd_host: str :param statsd_port: port to post data :type statsd_port: int :param statsd_prefix: prefix to add to metric :type statsd_prefix: str :param statsd_enabled: bool to enable statsd :type statsd_enabled: bool :param broks_enabled: bool to enable broks sending :type broks_enabled: bool :return: None
[ "Init", "instance", "with", "real", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L166-L222
train
Alignak-monitoring/alignak
alignak/stats.py
Stats.load_statsd
def load_statsd(self): """Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised """ if not self.statsd_enabled: logger.info('Stats reporting is not enabled, connection is not allowed') return False if self.statsd_enabled and self.carbon: self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, 'connection-test']), (int(time.time()), int(time.time())))) self.carbon.add_data_list(self.my_metrics) self.flush(log=True) else: try: logger.info('Trying to contact StatsD server...') self.statsd_addr = (socket.gethostbyname(self.statsd_host.encode('utf-8')), self.statsd_port) self.statsd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except (socket.error, socket.gaierror) as exp: logger.warning('Cannot create StatsD socket: %s', exp) return False except Exception as exp: # pylint: disable=broad-except logger.exception('Cannot create StatsD socket (other): %s', exp) return False logger.info('StatsD server contacted') return True
python
def load_statsd(self): """Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised """ if not self.statsd_enabled: logger.info('Stats reporting is not enabled, connection is not allowed') return False if self.statsd_enabled and self.carbon: self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, 'connection-test']), (int(time.time()), int(time.time())))) self.carbon.add_data_list(self.my_metrics) self.flush(log=True) else: try: logger.info('Trying to contact StatsD server...') self.statsd_addr = (socket.gethostbyname(self.statsd_host.encode('utf-8')), self.statsd_port) self.statsd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except (socket.error, socket.gaierror) as exp: logger.warning('Cannot create StatsD socket: %s', exp) return False except Exception as exp: # pylint: disable=broad-except logger.exception('Cannot create StatsD socket (other): %s', exp) return False logger.info('StatsD server contacted') return True
[ "def", "load_statsd", "(", "self", ")", ":", "if", "not", "self", ".", "statsd_enabled", ":", "logger", ".", "info", "(", "'Stats reporting is not enabled, connection is not allowed'", ")", "return", "False", "if", "self", ".", "statsd_enabled", "and", "self", ".", "carbon", ":", "self", ".", "my_metrics", ".", "append", "(", "(", "'.'", ".", "join", "(", "[", "self", ".", "statsd_prefix", ",", "self", ".", "name", ",", "'connection-test'", "]", ")", ",", "(", "int", "(", "time", ".", "time", "(", ")", ")", ",", "int", "(", "time", ".", "time", "(", ")", ")", ")", ")", ")", "self", ".", "carbon", ".", "add_data_list", "(", "self", ".", "my_metrics", ")", "self", ".", "flush", "(", "log", "=", "True", ")", "else", ":", "try", ":", "logger", ".", "info", "(", "'Trying to contact StatsD server...'", ")", "self", ".", "statsd_addr", "=", "(", "socket", ".", "gethostbyname", "(", "self", ".", "statsd_host", ".", "encode", "(", "'utf-8'", ")", ")", ",", "self", ".", "statsd_port", ")", "self", ".", "statsd_sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "except", "(", "socket", ".", "error", ",", "socket", ".", "gaierror", ")", "as", "exp", ":", "logger", ".", "warning", "(", "'Cannot create StatsD socket: %s'", ",", "exp", ")", "return", "False", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "logger", ".", "exception", "(", "'Cannot create StatsD socket (other): %s'", ",", "exp", ")", "return", "False", "logger", ".", "info", "(", "'StatsD server contacted'", ")", "return", "True" ]
Create socket connection to statsd host Note that because of the UDP protocol used by StatsD, if no server is listening the socket connection will be accepted anyway :) :return: True if socket got created else False and an exception log is raised
[ "Create", "socket", "connection", "to", "statsd", "host" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L224-L255
train
Alignak-monitoring/alignak
alignak/stats.py
Stats.flush
def flush(self, log=False): """Send inner stored metrics to the defined Graphite Returns False if the sending failed with a warning log if log parameter is set :return: bool """ if not self.my_metrics: logger.debug("Flushing - no metrics to send") return True now = int(time.time()) if self.last_failure and self.last_failure + self.metrics_flush_pause > now: if not self.log_metrics_flush_pause: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) self.log_metrics_flush_pause = True return True try: logger.debug("Flushing %d metrics to Graphite/carbon", self.metrics_count) if self.carbon.send_data(): self.my_metrics = [] else: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) if log: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) return False if self.log_metrics_flush_pause: logger.warning("Metrics flush restored. " "Remaining stored metric: %d", self.metrics_count) self.last_failure = 0 self.log_metrics_flush_pause = False except Exception as exp: # pylint: disable=broad-except if not self.log_metrics_flush_pause: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) else: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) logger.warning("Exception: %s", str(exp)) self.last_failure = now return False return True
python
def flush(self, log=False): """Send inner stored metrics to the defined Graphite Returns False if the sending failed with a warning log if log parameter is set :return: bool """ if not self.my_metrics: logger.debug("Flushing - no metrics to send") return True now = int(time.time()) if self.last_failure and self.last_failure + self.metrics_flush_pause > now: if not self.log_metrics_flush_pause: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) self.log_metrics_flush_pause = True return True try: logger.debug("Flushing %d metrics to Graphite/carbon", self.metrics_count) if self.carbon.send_data(): self.my_metrics = [] else: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) if log: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) return False if self.log_metrics_flush_pause: logger.warning("Metrics flush restored. " "Remaining stored metric: %d", self.metrics_count) self.last_failure = 0 self.log_metrics_flush_pause = False except Exception as exp: # pylint: disable=broad-except if not self.log_metrics_flush_pause: logger.warning("Failed sending metrics to Graphite/carbon. " "Inner stored metric: %d", self.metrics_count) else: date = datetime.datetime.fromtimestamp( self.last_failure).strftime(self.date_fmt) logger.warning("Metrics flush paused on connection error " "(last failed: %s). " "Inner stored metric: %d. Trying to send...", date, self.metrics_count) logger.warning("Exception: %s", str(exp)) self.last_failure = now return False return True
[ "def", "flush", "(", "self", ",", "log", "=", "False", ")", ":", "if", "not", "self", ".", "my_metrics", ":", "logger", ".", "debug", "(", "\"Flushing - no metrics to send\"", ")", "return", "True", "now", "=", "int", "(", "time", ".", "time", "(", ")", ")", "if", "self", ".", "last_failure", "and", "self", ".", "last_failure", "+", "self", ".", "metrics_flush_pause", ">", "now", ":", "if", "not", "self", ".", "log_metrics_flush_pause", ":", "date", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "self", ".", "last_failure", ")", ".", "strftime", "(", "self", ".", "date_fmt", ")", "logger", ".", "warning", "(", "\"Metrics flush paused on connection error \"", "\"(last failed: %s). \"", "\"Inner stored metric: %d. Trying to send...\"", ",", "date", ",", "self", ".", "metrics_count", ")", "self", ".", "log_metrics_flush_pause", "=", "True", "return", "True", "try", ":", "logger", ".", "debug", "(", "\"Flushing %d metrics to Graphite/carbon\"", ",", "self", ".", "metrics_count", ")", "if", "self", ".", "carbon", ".", "send_data", "(", ")", ":", "self", ".", "my_metrics", "=", "[", "]", "else", ":", "logger", ".", "warning", "(", "\"Failed sending metrics to Graphite/carbon. \"", "\"Inner stored metric: %d\"", ",", "self", ".", "metrics_count", ")", "if", "log", ":", "logger", ".", "warning", "(", "\"Failed sending metrics to Graphite/carbon. \"", "\"Inner stored metric: %d\"", ",", "self", ".", "metrics_count", ")", "return", "False", "if", "self", ".", "log_metrics_flush_pause", ":", "logger", ".", "warning", "(", "\"Metrics flush restored. \"", "\"Remaining stored metric: %d\"", ",", "self", ".", "metrics_count", ")", "self", ".", "last_failure", "=", "0", "self", ".", "log_metrics_flush_pause", "=", "False", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "if", "not", "self", ".", "log_metrics_flush_pause", ":", "logger", ".", "warning", "(", "\"Failed sending metrics to Graphite/carbon. \"", "\"Inner stored metric: %d\"", ",", "self", ".", "metrics_count", ")", "else", ":", "date", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "self", ".", "last_failure", ")", ".", "strftime", "(", "self", ".", "date_fmt", ")", "logger", ".", "warning", "(", "\"Metrics flush paused on connection error \"", "\"(last failed: %s). \"", "\"Inner stored metric: %d. Trying to send...\"", ",", "date", ",", "self", ".", "metrics_count", ")", "logger", ".", "warning", "(", "\"Exception: %s\"", ",", "str", "(", "exp", ")", ")", "self", ".", "last_failure", "=", "now", "return", "False", "return", "True" ]
Send inner stored metrics to the defined Graphite Returns False if the sending failed with a warning log if log parameter is set :return: bool
[ "Send", "inner", "stored", "metrics", "to", "the", "defined", "Graphite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L308-L362
train
Alignak-monitoring/alignak
alignak/stats.py
Stats.send_to_graphite
def send_to_graphite(self, metric, value, timestamp=None): """ Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: metric timestamp :type timestamp: int """ # Manage Graphite part if not self.statsd_enabled or not self.carbon: return if timestamp is None: timestamp = int(time.time()) self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, metric]), (timestamp, value))) if self.metrics_count >= self.metrics_flush_count: self.carbon.add_data_list(self.my_metrics) self.flush()
python
def send_to_graphite(self, metric, value, timestamp=None): """ Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: metric timestamp :type timestamp: int """ # Manage Graphite part if not self.statsd_enabled or not self.carbon: return if timestamp is None: timestamp = int(time.time()) self.my_metrics.append(('.'.join([self.statsd_prefix, self.name, metric]), (timestamp, value))) if self.metrics_count >= self.metrics_flush_count: self.carbon.add_data_list(self.my_metrics) self.flush()
[ "def", "send_to_graphite", "(", "self", ",", "metric", ",", "value", ",", "timestamp", "=", "None", ")", ":", "# Manage Graphite part", "if", "not", "self", ".", "statsd_enabled", "or", "not", "self", ".", "carbon", ":", "return", "if", "timestamp", "is", "None", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "self", ".", "my_metrics", ".", "append", "(", "(", "'.'", ".", "join", "(", "[", "self", ".", "statsd_prefix", ",", "self", ".", "name", ",", "metric", "]", ")", ",", "(", "timestamp", ",", "value", ")", ")", ")", "if", "self", ".", "metrics_count", ">=", "self", ".", "metrics_flush_count", ":", "self", ".", "carbon", ".", "add_data_list", "(", "self", ".", "my_metrics", ")", "self", ".", "flush", "(", ")" ]
Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: metric timestamp :type timestamp: int
[ "Inner", "store", "a", "new", "metric", "and", "flush", "to", "Graphite", "if", "the", "flush", "threshold", "is", "reached", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L364-L388
train
Alignak-monitoring/alignak
alignak/stats.py
Stats.counter
def counter(self, key, value, timestamp=None): """Set a counter value If the inner key does not exist is is created :param key: counter to update :type key: str :param value: counter value :type value: float :return: An alignak_stat brok if broks are enabled else None """ _min, _max, count, _sum = self.stats.get(key, (None, None, 0, 0)) count += 1 _sum += value if _min is None or value < _min: _min = value if _max is None or value > _max: _max = value self.stats[key] = (_min, _max, count, _sum) # Manage local statsd part if self.statsd_enabled and self.statsd_sock: # beware, we are sending ms here, timer is in seconds packet = '%s.%s.%s:%d|c' % (self.statsd_prefix, self.name, key, value) packet = packet.encode('utf-8') try: self.statsd_sock.sendto(packet, self.statsd_addr) except (socket.error, socket.gaierror): pass # cannot send? ok not a huge problem here and we cannot # log because it will be far too verbose :p # Manage Graphite part if self.statsd_enabled and self.carbon: self.send_to_graphite(key, value, timestamp=timestamp) # Manage file part if self.statsd_enabled and self.file_d: if timestamp is None: timestamp = int(time.time()) packet = self.line_fmt if not self.date_fmt: date = "%s" % timestamp else: date = datetime.datetime.fromtimestamp(timestamp).strftime(self.date_fmt) packet = packet.replace("#date#", date) packet = packet.replace("#counter#", '%s.%s.%s' % (self.statsd_prefix, self.name, key)) packet = packet.replace("#value#", '%d' % value) packet = packet.replace("#uom#", 'c') try: self.file_d.write(packet) except IOError: logger.warning("Could not write to the file: %s", packet) if self.broks_enabled: logger.debug("alignak stat brok: %s = %s", key, value) if timestamp is None: timestamp = int(time.time()) return Brok({'type': 'alignak_stat', 'data': { 'ts': timestamp, 'type': 'counter', 'metric': '%s.%s.%s' % (self.statsd_prefix, self.name, key), 'value': value, 'uom': 'c' }}) return None
python
def counter(self, key, value, timestamp=None): """Set a counter value If the inner key does not exist is is created :param key: counter to update :type key: str :param value: counter value :type value: float :return: An alignak_stat brok if broks are enabled else None """ _min, _max, count, _sum = self.stats.get(key, (None, None, 0, 0)) count += 1 _sum += value if _min is None or value < _min: _min = value if _max is None or value > _max: _max = value self.stats[key] = (_min, _max, count, _sum) # Manage local statsd part if self.statsd_enabled and self.statsd_sock: # beware, we are sending ms here, timer is in seconds packet = '%s.%s.%s:%d|c' % (self.statsd_prefix, self.name, key, value) packet = packet.encode('utf-8') try: self.statsd_sock.sendto(packet, self.statsd_addr) except (socket.error, socket.gaierror): pass # cannot send? ok not a huge problem here and we cannot # log because it will be far too verbose :p # Manage Graphite part if self.statsd_enabled and self.carbon: self.send_to_graphite(key, value, timestamp=timestamp) # Manage file part if self.statsd_enabled and self.file_d: if timestamp is None: timestamp = int(time.time()) packet = self.line_fmt if not self.date_fmt: date = "%s" % timestamp else: date = datetime.datetime.fromtimestamp(timestamp).strftime(self.date_fmt) packet = packet.replace("#date#", date) packet = packet.replace("#counter#", '%s.%s.%s' % (self.statsd_prefix, self.name, key)) packet = packet.replace("#value#", '%d' % value) packet = packet.replace("#uom#", 'c') try: self.file_d.write(packet) except IOError: logger.warning("Could not write to the file: %s", packet) if self.broks_enabled: logger.debug("alignak stat brok: %s = %s", key, value) if timestamp is None: timestamp = int(time.time()) return Brok({'type': 'alignak_stat', 'data': { 'ts': timestamp, 'type': 'counter', 'metric': '%s.%s.%s' % (self.statsd_prefix, self.name, key), 'value': value, 'uom': 'c' }}) return None
[ "def", "counter", "(", "self", ",", "key", ",", "value", ",", "timestamp", "=", "None", ")", ":", "_min", ",", "_max", ",", "count", ",", "_sum", "=", "self", ".", "stats", ".", "get", "(", "key", ",", "(", "None", ",", "None", ",", "0", ",", "0", ")", ")", "count", "+=", "1", "_sum", "+=", "value", "if", "_min", "is", "None", "or", "value", "<", "_min", ":", "_min", "=", "value", "if", "_max", "is", "None", "or", "value", ">", "_max", ":", "_max", "=", "value", "self", ".", "stats", "[", "key", "]", "=", "(", "_min", ",", "_max", ",", "count", ",", "_sum", ")", "# Manage local statsd part", "if", "self", ".", "statsd_enabled", "and", "self", ".", "statsd_sock", ":", "# beware, we are sending ms here, timer is in seconds", "packet", "=", "'%s.%s.%s:%d|c'", "%", "(", "self", ".", "statsd_prefix", ",", "self", ".", "name", ",", "key", ",", "value", ")", "packet", "=", "packet", ".", "encode", "(", "'utf-8'", ")", "try", ":", "self", ".", "statsd_sock", ".", "sendto", "(", "packet", ",", "self", ".", "statsd_addr", ")", "except", "(", "socket", ".", "error", ",", "socket", ".", "gaierror", ")", ":", "pass", "# cannot send? ok not a huge problem here and we cannot", "# log because it will be far too verbose :p", "# Manage Graphite part", "if", "self", ".", "statsd_enabled", "and", "self", ".", "carbon", ":", "self", ".", "send_to_graphite", "(", "key", ",", "value", ",", "timestamp", "=", "timestamp", ")", "# Manage file part", "if", "self", ".", "statsd_enabled", "and", "self", ".", "file_d", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "packet", "=", "self", ".", "line_fmt", "if", "not", "self", ".", "date_fmt", ":", "date", "=", "\"%s\"", "%", "timestamp", "else", ":", "date", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "timestamp", ")", ".", "strftime", "(", "self", ".", "date_fmt", ")", "packet", "=", "packet", ".", "replace", "(", "\"#date#\"", ",", "date", ")", "packet", "=", "packet", ".", "replace", "(", "\"#counter#\"", ",", "'%s.%s.%s'", "%", "(", "self", ".", "statsd_prefix", ",", "self", ".", "name", ",", "key", ")", ")", "packet", "=", "packet", ".", "replace", "(", "\"#value#\"", ",", "'%d'", "%", "value", ")", "packet", "=", "packet", ".", "replace", "(", "\"#uom#\"", ",", "'c'", ")", "try", ":", "self", ".", "file_d", ".", "write", "(", "packet", ")", "except", "IOError", ":", "logger", ".", "warning", "(", "\"Could not write to the file: %s\"", ",", "packet", ")", "if", "self", ".", "broks_enabled", ":", "logger", ".", "debug", "(", "\"alignak stat brok: %s = %s\"", ",", "key", ",", "value", ")", "if", "timestamp", "is", "None", ":", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "return", "Brok", "(", "{", "'type'", ":", "'alignak_stat'", ",", "'data'", ":", "{", "'ts'", ":", "timestamp", ",", "'type'", ":", "'counter'", ",", "'metric'", ":", "'%s.%s.%s'", "%", "(", "self", ".", "statsd_prefix", ",", "self", ".", "name", ",", "key", ")", ",", "'value'", ":", "value", ",", "'uom'", ":", "'c'", "}", "}", ")", "return", "None" ]
Set a counter value If the inner key does not exist is is created :param key: counter to update :type key: str :param value: counter value :type value: float :return: An alignak_stat brok if broks are enabled else None
[ "Set", "a", "counter", "value" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/stats.py#L467-L536
train
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_managed_configurations
def get_managed_configurations(self): """Get the configurations managed by this satellite The configurations managed by a satellite is a list of the configuration attached to the schedulers related to the satellites. A broker linked to several schedulers will return the list of the configuration parts of its scheduler links. :return: a dict of scheduler links with instance_id as key and hash, push_flavor and configuration identifier as values :rtype: dict """ res = {} for scheduler_link in list(self.schedulers.values()): res[scheduler_link.instance_id] = { 'hash': scheduler_link.hash, 'push_flavor': scheduler_link.push_flavor, 'managed_conf_id': scheduler_link.managed_conf_id } logger.debug("Get managed configuration: %s", res) return res
python
def get_managed_configurations(self): """Get the configurations managed by this satellite The configurations managed by a satellite is a list of the configuration attached to the schedulers related to the satellites. A broker linked to several schedulers will return the list of the configuration parts of its scheduler links. :return: a dict of scheduler links with instance_id as key and hash, push_flavor and configuration identifier as values :rtype: dict """ res = {} for scheduler_link in list(self.schedulers.values()): res[scheduler_link.instance_id] = { 'hash': scheduler_link.hash, 'push_flavor': scheduler_link.push_flavor, 'managed_conf_id': scheduler_link.managed_conf_id } logger.debug("Get managed configuration: %s", res) return res
[ "def", "get_managed_configurations", "(", "self", ")", ":", "res", "=", "{", "}", "for", "scheduler_link", "in", "list", "(", "self", ".", "schedulers", ".", "values", "(", ")", ")", ":", "res", "[", "scheduler_link", ".", "instance_id", "]", "=", "{", "'hash'", ":", "scheduler_link", ".", "hash", ",", "'push_flavor'", ":", "scheduler_link", ".", "push_flavor", ",", "'managed_conf_id'", ":", "scheduler_link", ".", "managed_conf_id", "}", "logger", ".", "debug", "(", "\"Get managed configuration: %s\"", ",", "res", ")", "return", "res" ]
Get the configurations managed by this satellite The configurations managed by a satellite is a list of the configuration attached to the schedulers related to the satellites. A broker linked to several schedulers will return the list of the configuration parts of its scheduler links. :return: a dict of scheduler links with instance_id as key and hash, push_flavor and configuration identifier as values :rtype: dict
[ "Get", "the", "configurations", "managed", "by", "this", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L132-L151
train
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_scheduler_from_hostname
def get_scheduler_from_hostname(self, host_name): """Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict """ scheduler_uuid = self.hosts_schedulers.get(host_name, None) return self.schedulers.get(scheduler_uuid, None)
python
def get_scheduler_from_hostname(self, host_name): """Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict """ scheduler_uuid = self.hosts_schedulers.get(host_name, None) return self.schedulers.get(scheduler_uuid, None)
[ "def", "get_scheduler_from_hostname", "(", "self", ",", "host_name", ")", ":", "scheduler_uuid", "=", "self", ".", "hosts_schedulers", ".", "get", "(", "host_name", ",", "None", ")", "return", "self", ".", "schedulers", ".", "get", "(", "scheduler_uuid", ",", "None", ")" ]
Get scheduler linked to the given host_name :param host_name: host_name we want the scheduler from :type host_name: str :return: scheduler with id corresponding to the mapping table :rtype: dict
[ "Get", "scheduler", "linked", "to", "the", "given", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L153-L162
train
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_external_commands
def get_external_commands(self): """Get the external commands :return: External commands list :rtype: list """ res = self.external_commands logger.debug("Get and clear external commands list: %s", res) self.external_commands = [] return res
python
def get_external_commands(self): """Get the external commands :return: External commands list :rtype: list """ res = self.external_commands logger.debug("Get and clear external commands list: %s", res) self.external_commands = [] return res
[ "def", "get_external_commands", "(", "self", ")", ":", "res", "=", "self", ".", "external_commands", "logger", ".", "debug", "(", "\"Get and clear external commands list: %s\"", ",", "res", ")", "self", ".", "external_commands", "=", "[", "]", "return", "res" ]
Get the external commands :return: External commands list :rtype: list
[ "Get", "the", "external", "commands" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L164-L173
train
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_results_from_passive
def get_results_from_passive(self, scheduler_instance_id): """Get executed actions results from a passive satellite for a specific scheduler :param scheduler_instance_id: scheduler id :type scheduler_instance_id: int :return: Results list :rtype: list """ # Do I know this scheduler? # logger.info("My schedulers: %s %s", self.schedulers, type(self.schedulers)) if not self.schedulers: # Probably not yet configured ... logger.debug("I do not have any scheduler: %s", self.schedulers) return [] scheduler_link = None for link in list(self.schedulers.values()): if scheduler_instance_id == link.instance_id: scheduler_link = link break else: logger.warning("I do not know this scheduler: %s", scheduler_instance_id) return [] logger.debug("Get results for the scheduler: %s", scheduler_instance_id) ret, scheduler_link.wait_homerun = scheduler_link.wait_homerun, {} logger.debug("Results: %s" % (list(ret.values())) if ret else "No results available") return list(ret.values())
python
def get_results_from_passive(self, scheduler_instance_id): """Get executed actions results from a passive satellite for a specific scheduler :param scheduler_instance_id: scheduler id :type scheduler_instance_id: int :return: Results list :rtype: list """ # Do I know this scheduler? # logger.info("My schedulers: %s %s", self.schedulers, type(self.schedulers)) if not self.schedulers: # Probably not yet configured ... logger.debug("I do not have any scheduler: %s", self.schedulers) return [] scheduler_link = None for link in list(self.schedulers.values()): if scheduler_instance_id == link.instance_id: scheduler_link = link break else: logger.warning("I do not know this scheduler: %s", scheduler_instance_id) return [] logger.debug("Get results for the scheduler: %s", scheduler_instance_id) ret, scheduler_link.wait_homerun = scheduler_link.wait_homerun, {} logger.debug("Results: %s" % (list(ret.values())) if ret else "No results available") return list(ret.values())
[ "def", "get_results_from_passive", "(", "self", ",", "scheduler_instance_id", ")", ":", "# Do I know this scheduler?", "# logger.info(\"My schedulers: %s %s\", self.schedulers, type(self.schedulers))", "if", "not", "self", ".", "schedulers", ":", "# Probably not yet configured ...", "logger", ".", "debug", "(", "\"I do not have any scheduler: %s\"", ",", "self", ".", "schedulers", ")", "return", "[", "]", "scheduler_link", "=", "None", "for", "link", "in", "list", "(", "self", ".", "schedulers", ".", "values", "(", ")", ")", ":", "if", "scheduler_instance_id", "==", "link", ".", "instance_id", ":", "scheduler_link", "=", "link", "break", "else", ":", "logger", ".", "warning", "(", "\"I do not know this scheduler: %s\"", ",", "scheduler_instance_id", ")", "return", "[", "]", "logger", ".", "debug", "(", "\"Get results for the scheduler: %s\"", ",", "scheduler_instance_id", ")", "ret", ",", "scheduler_link", ".", "wait_homerun", "=", "scheduler_link", ".", "wait_homerun", ",", "{", "}", "logger", ".", "debug", "(", "\"Results: %s\"", "%", "(", "list", "(", "ret", ".", "values", "(", ")", ")", ")", "if", "ret", "else", "\"No results available\"", ")", "return", "list", "(", "ret", ".", "values", "(", ")", ")" ]
Get executed actions results from a passive satellite for a specific scheduler :param scheduler_instance_id: scheduler id :type scheduler_instance_id: int :return: Results list :rtype: list
[ "Get", "executed", "actions", "results", "from", "a", "passive", "satellite", "for", "a", "specific", "scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L175-L203
train
Alignak-monitoring/alignak
alignak/satellite.py
BaseSatellite.get_events
def get_events(self): """Get event list from satellite :return: A copy of the events list :rtype: list """ res = copy.copy(self.events) del self.events[:] return res
python
def get_events(self): """Get event list from satellite :return: A copy of the events list :rtype: list """ res = copy.copy(self.events) del self.events[:] return res
[ "def", "get_events", "(", "self", ")", ":", "res", "=", "copy", ".", "copy", "(", "self", ".", "events", ")", "del", "self", ".", "events", "[", ":", "]", "return", "res" ]
Get event list from satellite :return: A copy of the events list :rtype: list
[ "Get", "event", "list", "from", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L352-L360
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.manage_action_return
def manage_action_return(self, action): """Manage action return from Workers We just put them into the corresponding sched and we clean unused properties like my_scheduler :param action: the action to manage :type action: alignak.action.Action :return: None """ # Maybe our workers send us something else than an action # if so, just add this in other queues and return # todo: test a class instance if action.__class__.my_type not in ['check', 'notification', 'eventhandler']: self.add(action) return # Ok, it's a result. Get the concerned scheduler uuid scheduler_uuid = action.my_scheduler logger.debug("Got action return: %s / %s", scheduler_uuid, action.uuid) try: # Now that we know where to put the action result, we do not need any reference to # the scheduler nor the worker del action.my_scheduler del action.my_worker except AttributeError: # pragma: no cover, simple protection logger.error("AttributeError Got action return: %s / %s", scheduler_uuid, action) # And we remove it from the actions queue of the scheduler too try: del self.schedulers[scheduler_uuid].actions[action.uuid] except KeyError as exp: logger.error("KeyError del scheduler action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp)) # We tag it as "return wanted", and move it in the wait return queue try: self.schedulers[scheduler_uuid].wait_homerun[action.uuid] = action except KeyError: # pragma: no cover, simple protection logger.error("KeyError Add home run action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp))
python
def manage_action_return(self, action): """Manage action return from Workers We just put them into the corresponding sched and we clean unused properties like my_scheduler :param action: the action to manage :type action: alignak.action.Action :return: None """ # Maybe our workers send us something else than an action # if so, just add this in other queues and return # todo: test a class instance if action.__class__.my_type not in ['check', 'notification', 'eventhandler']: self.add(action) return # Ok, it's a result. Get the concerned scheduler uuid scheduler_uuid = action.my_scheduler logger.debug("Got action return: %s / %s", scheduler_uuid, action.uuid) try: # Now that we know where to put the action result, we do not need any reference to # the scheduler nor the worker del action.my_scheduler del action.my_worker except AttributeError: # pragma: no cover, simple protection logger.error("AttributeError Got action return: %s / %s", scheduler_uuid, action) # And we remove it from the actions queue of the scheduler too try: del self.schedulers[scheduler_uuid].actions[action.uuid] except KeyError as exp: logger.error("KeyError del scheduler action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp)) # We tag it as "return wanted", and move it in the wait return queue try: self.schedulers[scheduler_uuid].wait_homerun[action.uuid] = action except KeyError: # pragma: no cover, simple protection logger.error("KeyError Add home run action: %s / %s - %s", scheduler_uuid, action.uuid, str(exp))
[ "def", "manage_action_return", "(", "self", ",", "action", ")", ":", "# Maybe our workers send us something else than an action", "# if so, just add this in other queues and return", "# todo: test a class instance", "if", "action", ".", "__class__", ".", "my_type", "not", "in", "[", "'check'", ",", "'notification'", ",", "'eventhandler'", "]", ":", "self", ".", "add", "(", "action", ")", "return", "# Ok, it's a result. Get the concerned scheduler uuid", "scheduler_uuid", "=", "action", ".", "my_scheduler", "logger", ".", "debug", "(", "\"Got action return: %s / %s\"", ",", "scheduler_uuid", ",", "action", ".", "uuid", ")", "try", ":", "# Now that we know where to put the action result, we do not need any reference to", "# the scheduler nor the worker", "del", "action", ".", "my_scheduler", "del", "action", ".", "my_worker", "except", "AttributeError", ":", "# pragma: no cover, simple protection", "logger", ".", "error", "(", "\"AttributeError Got action return: %s / %s\"", ",", "scheduler_uuid", ",", "action", ")", "# And we remove it from the actions queue of the scheduler too", "try", ":", "del", "self", ".", "schedulers", "[", "scheduler_uuid", "]", ".", "actions", "[", "action", ".", "uuid", "]", "except", "KeyError", "as", "exp", ":", "logger", ".", "error", "(", "\"KeyError del scheduler action: %s / %s - %s\"", ",", "scheduler_uuid", ",", "action", ".", "uuid", ",", "str", "(", "exp", ")", ")", "# We tag it as \"return wanted\", and move it in the wait return queue", "try", ":", "self", ".", "schedulers", "[", "scheduler_uuid", "]", ".", "wait_homerun", "[", "action", ".", "uuid", "]", "=", "action", "except", "KeyError", ":", "# pragma: no cover, simple protection", "logger", ".", "error", "(", "\"KeyError Add home run action: %s / %s - %s\"", ",", "scheduler_uuid", ",", "action", ".", "uuid", ",", "str", "(", "exp", ")", ")" ]
Manage action return from Workers We just put them into the corresponding sched and we clean unused properties like my_scheduler :param action: the action to manage :type action: alignak.action.Action :return: None
[ "Manage", "action", "return", "from", "Workers", "We", "just", "put", "them", "into", "the", "corresponding", "sched", "and", "we", "clean", "unused", "properties", "like", "my_scheduler" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L462-L502
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.create_and_launch_worker
def create_and_launch_worker(self, module_name='fork'): """Create and launch a new worker, and put it into self.workers It can be mortal or not :param module_name: the module name related to the worker default is "fork" for no module Indeed, it is actually the module 'python_name' :type module_name: str :return: None """ logger.info("Allocating new '%s' worker...", module_name) # If we are in the fork module, we do not specify a target target = None __warned = [] if module_name == 'fork': target = None else: for module in self.modules_manager.instances: # First, see if the module name matches... if module.get_name() == module_name: # ... and then if is a 'worker' module one or not if not module.properties.get('worker_capable', False): raise NotWorkerMod target = module.work if target is None: if module_name not in __warned: logger.warning("No target found for %s, NOT creating a worker for it...", module_name) __warned.append(module_name) return # We give to the Worker the instance name of the daemon (eg. poller-master) # and not the daemon type (poller) queue = Queue() worker = Worker(module_name, queue, self.returns_queue, self.processes_by_worker, max_plugins_output_length=self.max_plugins_output_length, target=target, loaded_into=self.name) # worker.module_name = module_name # save this worker self.workers[worker.get_id()] = worker # And save the Queue of this worker, with key = worker id # self.q_by_mod[module_name][worker.uuid] = queue self.q_by_mod[module_name][worker.get_id()] = queue # Ok, all is good. Start it! worker.start() logger.info("Started '%s' worker: %s (pid=%d)", module_name, worker.get_id(), worker.get_pid())
python
def create_and_launch_worker(self, module_name='fork'): """Create and launch a new worker, and put it into self.workers It can be mortal or not :param module_name: the module name related to the worker default is "fork" for no module Indeed, it is actually the module 'python_name' :type module_name: str :return: None """ logger.info("Allocating new '%s' worker...", module_name) # If we are in the fork module, we do not specify a target target = None __warned = [] if module_name == 'fork': target = None else: for module in self.modules_manager.instances: # First, see if the module name matches... if module.get_name() == module_name: # ... and then if is a 'worker' module one or not if not module.properties.get('worker_capable', False): raise NotWorkerMod target = module.work if target is None: if module_name not in __warned: logger.warning("No target found for %s, NOT creating a worker for it...", module_name) __warned.append(module_name) return # We give to the Worker the instance name of the daemon (eg. poller-master) # and not the daemon type (poller) queue = Queue() worker = Worker(module_name, queue, self.returns_queue, self.processes_by_worker, max_plugins_output_length=self.max_plugins_output_length, target=target, loaded_into=self.name) # worker.module_name = module_name # save this worker self.workers[worker.get_id()] = worker # And save the Queue of this worker, with key = worker id # self.q_by_mod[module_name][worker.uuid] = queue self.q_by_mod[module_name][worker.get_id()] = queue # Ok, all is good. Start it! worker.start() logger.info("Started '%s' worker: %s (pid=%d)", module_name, worker.get_id(), worker.get_pid())
[ "def", "create_and_launch_worker", "(", "self", ",", "module_name", "=", "'fork'", ")", ":", "logger", ".", "info", "(", "\"Allocating new '%s' worker...\"", ",", "module_name", ")", "# If we are in the fork module, we do not specify a target", "target", "=", "None", "__warned", "=", "[", "]", "if", "module_name", "==", "'fork'", ":", "target", "=", "None", "else", ":", "for", "module", "in", "self", ".", "modules_manager", ".", "instances", ":", "# First, see if the module name matches...", "if", "module", ".", "get_name", "(", ")", "==", "module_name", ":", "# ... and then if is a 'worker' module one or not", "if", "not", "module", ".", "properties", ".", "get", "(", "'worker_capable'", ",", "False", ")", ":", "raise", "NotWorkerMod", "target", "=", "module", ".", "work", "if", "target", "is", "None", ":", "if", "module_name", "not", "in", "__warned", ":", "logger", ".", "warning", "(", "\"No target found for %s, NOT creating a worker for it...\"", ",", "module_name", ")", "__warned", ".", "append", "(", "module_name", ")", "return", "# We give to the Worker the instance name of the daemon (eg. poller-master)", "# and not the daemon type (poller)", "queue", "=", "Queue", "(", ")", "worker", "=", "Worker", "(", "module_name", ",", "queue", ",", "self", ".", "returns_queue", ",", "self", ".", "processes_by_worker", ",", "max_plugins_output_length", "=", "self", ".", "max_plugins_output_length", ",", "target", "=", "target", ",", "loaded_into", "=", "self", ".", "name", ")", "# worker.module_name = module_name", "# save this worker", "self", ".", "workers", "[", "worker", ".", "get_id", "(", ")", "]", "=", "worker", "# And save the Queue of this worker, with key = worker id", "# self.q_by_mod[module_name][worker.uuid] = queue", "self", ".", "q_by_mod", "[", "module_name", "]", "[", "worker", ".", "get_id", "(", ")", "]", "=", "queue", "# Ok, all is good. Start it!", "worker", ".", "start", "(", ")", "logger", ".", "info", "(", "\"Started '%s' worker: %s (pid=%d)\"", ",", "module_name", ",", "worker", ".", "get_id", "(", ")", ",", "worker", ".", "get_pid", "(", ")", ")" ]
Create and launch a new worker, and put it into self.workers It can be mortal or not :param module_name: the module name related to the worker default is "fork" for no module Indeed, it is actually the module 'python_name' :type module_name: str :return: None
[ "Create", "and", "launch", "a", "new", "worker", "and", "put", "it", "into", "self", ".", "workers", "It", "can", "be", "mortal", "or", "not" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L540-L589
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.do_stop_workers
def do_stop_workers(self): """Stop all workers :return: None """ logger.info("Stopping all workers (%d)", len(self.workers)) for worker in list(self.workers.values()): try: logger.info(" - stopping '%s'", worker.get_id()) worker.terminate() worker.join(timeout=1) logger.info(" - stopped") # A already dead worker or in a worker except (AttributeError, AssertionError): pass except Exception as exp: # pylint: disable=broad-except logger.error("exception: %s", str(exp))
python
def do_stop_workers(self): """Stop all workers :return: None """ logger.info("Stopping all workers (%d)", len(self.workers)) for worker in list(self.workers.values()): try: logger.info(" - stopping '%s'", worker.get_id()) worker.terminate() worker.join(timeout=1) logger.info(" - stopped") # A already dead worker or in a worker except (AttributeError, AssertionError): pass except Exception as exp: # pylint: disable=broad-except logger.error("exception: %s", str(exp))
[ "def", "do_stop_workers", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Stopping all workers (%d)\"", ",", "len", "(", "self", ".", "workers", ")", ")", "for", "worker", "in", "list", "(", "self", ".", "workers", ".", "values", "(", ")", ")", ":", "try", ":", "logger", ".", "info", "(", "\" - stopping '%s'\"", ",", "worker", ".", "get_id", "(", ")", ")", "worker", ".", "terminate", "(", ")", "worker", ".", "join", "(", "timeout", "=", "1", ")", "logger", ".", "info", "(", "\" - stopped\"", ")", "# A already dead worker or in a worker", "except", "(", "AttributeError", ",", "AssertionError", ")", ":", "pass", "except", "Exception", "as", "exp", ":", "# pylint: disable=broad-except", "logger", ".", "error", "(", "\"exception: %s\"", ",", "str", "(", "exp", ")", ")" ]
Stop all workers :return: None
[ "Stop", "all", "workers" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L591-L607
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.get_broks
def get_broks(self): """Get brok list from satellite :return: A copy of the broks list :rtype: list """ res = copy.copy(self.broks) del self.broks[:] return res
python
def get_broks(self): """Get brok list from satellite :return: A copy of the broks list :rtype: list """ res = copy.copy(self.broks) del self.broks[:] return res
[ "def", "get_broks", "(", "self", ")", ":", "res", "=", "copy", ".", "copy", "(", "self", ".", "broks", ")", "del", "self", ".", "broks", "[", ":", "]", "return", "res" ]
Get brok list from satellite :return: A copy of the broks list :rtype: list
[ "Get", "brok", "list", "from", "satellite" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L644-L652
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.check_and_del_zombie_workers
def check_and_del_zombie_workers(self): # pragma: no cover, not with unit tests... # pylint: disable= not-callable """Check if worker are fine and kill them if not. Dispatch the actions in the worker to another one TODO: see if unit tests would allow to check this code? :return: None """ # Active children make a join with everyone, useful :) # active_children() for p in active_children(): logger.debug("got child: %s", p) w_to_del = [] for worker in list(self.workers.values()): # If a worker goes down and we did not ask him, it's not # good: we can think that we have a worker and it's not True # So we del it logger.debug("checking if worker %s (pid=%d) is alive", worker.get_id(), worker.get_pid()) if not self.interrupted and not worker.is_alive(): logger.warning("The worker %s (pid=%d) went down unexpectedly!", worker.get_id(), worker.get_pid()) # Terminate immediately worker.terminate() worker.join(timeout=1) w_to_del.append(worker.get_id()) # OK, now really del workers from queues # And requeue the actions it was managed for worker_id in w_to_del: worker = self.workers[worker_id] # Del the queue of the module queue del self.q_by_mod[worker.module_name][worker.get_id()] for scheduler_uuid in self.schedulers: sched = self.schedulers[scheduler_uuid] for act in list(sched.actions.values()): if act.status == ACT_STATUS_QUEUED and act.my_worker == worker_id: # Got a check that will NEVER return if we do not restart it self.assign_to_a_queue(act) # So now we can really forgot it del self.workers[worker_id]
python
def check_and_del_zombie_workers(self): # pragma: no cover, not with unit tests... # pylint: disable= not-callable """Check if worker are fine and kill them if not. Dispatch the actions in the worker to another one TODO: see if unit tests would allow to check this code? :return: None """ # Active children make a join with everyone, useful :) # active_children() for p in active_children(): logger.debug("got child: %s", p) w_to_del = [] for worker in list(self.workers.values()): # If a worker goes down and we did not ask him, it's not # good: we can think that we have a worker and it's not True # So we del it logger.debug("checking if worker %s (pid=%d) is alive", worker.get_id(), worker.get_pid()) if not self.interrupted and not worker.is_alive(): logger.warning("The worker %s (pid=%d) went down unexpectedly!", worker.get_id(), worker.get_pid()) # Terminate immediately worker.terminate() worker.join(timeout=1) w_to_del.append(worker.get_id()) # OK, now really del workers from queues # And requeue the actions it was managed for worker_id in w_to_del: worker = self.workers[worker_id] # Del the queue of the module queue del self.q_by_mod[worker.module_name][worker.get_id()] for scheduler_uuid in self.schedulers: sched = self.schedulers[scheduler_uuid] for act in list(sched.actions.values()): if act.status == ACT_STATUS_QUEUED and act.my_worker == worker_id: # Got a check that will NEVER return if we do not restart it self.assign_to_a_queue(act) # So now we can really forgot it del self.workers[worker_id]
[ "def", "check_and_del_zombie_workers", "(", "self", ")", ":", "# pragma: no cover, not with unit tests...", "# pylint: disable= not-callable", "# Active children make a join with everyone, useful :)", "# active_children()", "for", "p", "in", "active_children", "(", ")", ":", "logger", ".", "debug", "(", "\"got child: %s\"", ",", "p", ")", "w_to_del", "=", "[", "]", "for", "worker", "in", "list", "(", "self", ".", "workers", ".", "values", "(", ")", ")", ":", "# If a worker goes down and we did not ask him, it's not", "# good: we can think that we have a worker and it's not True", "# So we del it", "logger", ".", "debug", "(", "\"checking if worker %s (pid=%d) is alive\"", ",", "worker", ".", "get_id", "(", ")", ",", "worker", ".", "get_pid", "(", ")", ")", "if", "not", "self", ".", "interrupted", "and", "not", "worker", ".", "is_alive", "(", ")", ":", "logger", ".", "warning", "(", "\"The worker %s (pid=%d) went down unexpectedly!\"", ",", "worker", ".", "get_id", "(", ")", ",", "worker", ".", "get_pid", "(", ")", ")", "# Terminate immediately", "worker", ".", "terminate", "(", ")", "worker", ".", "join", "(", "timeout", "=", "1", ")", "w_to_del", ".", "append", "(", "worker", ".", "get_id", "(", ")", ")", "# OK, now really del workers from queues", "# And requeue the actions it was managed", "for", "worker_id", "in", "w_to_del", ":", "worker", "=", "self", ".", "workers", "[", "worker_id", "]", "# Del the queue of the module queue", "del", "self", ".", "q_by_mod", "[", "worker", ".", "module_name", "]", "[", "worker", ".", "get_id", "(", ")", "]", "for", "scheduler_uuid", "in", "self", ".", "schedulers", ":", "sched", "=", "self", ".", "schedulers", "[", "scheduler_uuid", "]", "for", "act", "in", "list", "(", "sched", ".", "actions", ".", "values", "(", ")", ")", ":", "if", "act", ".", "status", "==", "ACT_STATUS_QUEUED", "and", "act", ".", "my_worker", "==", "worker_id", ":", "# Got a check that will NEVER return if we do not restart it", "self", ".", "assign_to_a_queue", "(", "act", ")", "# So now we can really forgot it", "del", "self", ".", "workers", "[", "worker_id", "]" ]
Check if worker are fine and kill them if not. Dispatch the actions in the worker to another one TODO: see if unit tests would allow to check this code? :return: None
[ "Check", "if", "worker", "are", "fine", "and", "kill", "them", "if", "not", ".", "Dispatch", "the", "actions", "in", "the", "worker", "to", "another", "one" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L654-L699
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.adjust_worker_number_by_load
def adjust_worker_number_by_load(self): """Try to create the minimum workers specified in the configuration :return: None """ if self.interrupted: logger.debug("Trying to adjust worker number. Ignoring because we are stopping.") return to_del = [] logger.debug("checking worker count." " Currently: %d workers, min per module : %d, max per module : %d", len(self.workers), self.min_workers, self.max_workers) # I want at least min_workers by module then if I can, I add worker for load balancing for mod in self.q_by_mod: # At least min_workers todo = max(0, self.min_workers - len(self.q_by_mod[mod])) for _ in range(todo): try: self.create_and_launch_worker(module_name=mod) # Maybe this modules is not a true worker one. # if so, just delete if from q_by_mod except NotWorkerMod: to_del.append(mod) break for mod in to_del: logger.warning("The module %s is not a worker one, I remove it from the worker list.", mod) del self.q_by_mod[mod]
python
def adjust_worker_number_by_load(self): """Try to create the minimum workers specified in the configuration :return: None """ if self.interrupted: logger.debug("Trying to adjust worker number. Ignoring because we are stopping.") return to_del = [] logger.debug("checking worker count." " Currently: %d workers, min per module : %d, max per module : %d", len(self.workers), self.min_workers, self.max_workers) # I want at least min_workers by module then if I can, I add worker for load balancing for mod in self.q_by_mod: # At least min_workers todo = max(0, self.min_workers - len(self.q_by_mod[mod])) for _ in range(todo): try: self.create_and_launch_worker(module_name=mod) # Maybe this modules is not a true worker one. # if so, just delete if from q_by_mod except NotWorkerMod: to_del.append(mod) break for mod in to_del: logger.warning("The module %s is not a worker one, I remove it from the worker list.", mod) del self.q_by_mod[mod]
[ "def", "adjust_worker_number_by_load", "(", "self", ")", ":", "if", "self", ".", "interrupted", ":", "logger", ".", "debug", "(", "\"Trying to adjust worker number. Ignoring because we are stopping.\"", ")", "return", "to_del", "=", "[", "]", "logger", ".", "debug", "(", "\"checking worker count.\"", "\" Currently: %d workers, min per module : %d, max per module : %d\"", ",", "len", "(", "self", ".", "workers", ")", ",", "self", ".", "min_workers", ",", "self", ".", "max_workers", ")", "# I want at least min_workers by module then if I can, I add worker for load balancing", "for", "mod", "in", "self", ".", "q_by_mod", ":", "# At least min_workers", "todo", "=", "max", "(", "0", ",", "self", ".", "min_workers", "-", "len", "(", "self", ".", "q_by_mod", "[", "mod", "]", ")", ")", "for", "_", "in", "range", "(", "todo", ")", ":", "try", ":", "self", ".", "create_and_launch_worker", "(", "module_name", "=", "mod", ")", "# Maybe this modules is not a true worker one.", "# if so, just delete if from q_by_mod", "except", "NotWorkerMod", ":", "to_del", ".", "append", "(", "mod", ")", "break", "for", "mod", "in", "to_del", ":", "logger", ".", "warning", "(", "\"The module %s is not a worker one, I remove it from the worker list.\"", ",", "mod", ")", "del", "self", ".", "q_by_mod", "[", "mod", "]" ]
Try to create the minimum workers specified in the configuration :return: None
[ "Try", "to", "create", "the", "minimum", "workers", "specified", "in", "the", "configuration" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L701-L731
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite._get_queue_for_the_action
def _get_queue_for_the_action(self, action): """Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no queue for the module_type :rtype: tuple """ # get the module name, if not, take fork mod = getattr(action, 'module_type', 'fork') queues = list(self.q_by_mod[mod].items()) # Maybe there is no more queue, it's very bad! if not queues: return (0, None) # if not get action round robin index to get action queue based # on the action id self.rr_qid = (self.rr_qid + 1) % len(queues) (worker_id, queue) = queues[self.rr_qid] # return the id of the worker (i), and its queue return (worker_id, queue)
python
def _get_queue_for_the_action(self, action): """Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no queue for the module_type :rtype: tuple """ # get the module name, if not, take fork mod = getattr(action, 'module_type', 'fork') queues = list(self.q_by_mod[mod].items()) # Maybe there is no more queue, it's very bad! if not queues: return (0, None) # if not get action round robin index to get action queue based # on the action id self.rr_qid = (self.rr_qid + 1) % len(queues) (worker_id, queue) = queues[self.rr_qid] # return the id of the worker (i), and its queue return (worker_id, queue)
[ "def", "_get_queue_for_the_action", "(", "self", ",", "action", ")", ":", "# get the module name, if not, take fork", "mod", "=", "getattr", "(", "action", ",", "'module_type'", ",", "'fork'", ")", "queues", "=", "list", "(", "self", ".", "q_by_mod", "[", "mod", "]", ".", "items", "(", ")", ")", "# Maybe there is no more queue, it's very bad!", "if", "not", "queues", ":", "return", "(", "0", ",", "None", ")", "# if not get action round robin index to get action queue based", "# on the action id", "self", ".", "rr_qid", "=", "(", "self", ".", "rr_qid", "+", "1", ")", "%", "len", "(", "queues", ")", "(", "worker_id", ",", "queue", ")", "=", "queues", "[", "self", ".", "rr_qid", "]", "# return the id of the worker (i), and its queue", "return", "(", "worker_id", ",", "queue", ")" ]
Find action queue for the action depending on the module. The id is found with action modulo on action id :param a: the action that need action queue to be assigned :type action: object :return: worker id and queue. (0, None) if no queue for the module_type :rtype: tuple
[ "Find", "action", "queue", "for", "the", "action", "depending", "on", "the", "module", ".", "The", "id", "is", "found", "with", "action", "modulo", "on", "action", "id" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L734-L757
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.add_actions
def add_actions(self, actions_list, scheduler_instance_id): """Add a list of actions to the satellite queues :param actions_list: Actions list to add :type actions_list: list :param scheduler_instance_id: sheduler link to assign the actions to :type scheduler_instance_id: SchedulerLink :return: None """ # We check for new check in each schedulers and put the result in new_checks scheduler_link = None for scheduler_id in self.schedulers: logger.debug("Trying to add an action, scheduler: %s", self.schedulers[scheduler_id]) if scheduler_instance_id == self.schedulers[scheduler_id].instance_id: scheduler_link = self.schedulers[scheduler_id] break else: logger.error("Trying to add actions from an unknwown scheduler: %s", scheduler_instance_id) return if not scheduler_link: logger.error("Trying to add actions, but scheduler link is not found for: %s, " "actions: %s", scheduler_instance_id, actions_list) return logger.debug("Found scheduler link: %s", scheduler_link) for action in actions_list: # First we look if the action is identified uuid = getattr(action, 'uuid', None) if uuid is None: try: action = unserialize(action, no_load=True) uuid = action.uuid except AlignakClassLookupException: logger.error('Cannot un-serialize action: %s', action) continue # If we already have this action, we are already working for it! if uuid in scheduler_link.actions: continue # Action is attached to a scheduler action.my_scheduler = scheduler_link.uuid scheduler_link.actions[action.uuid] = action self.assign_to_a_queue(action)
python
def add_actions(self, actions_list, scheduler_instance_id): """Add a list of actions to the satellite queues :param actions_list: Actions list to add :type actions_list: list :param scheduler_instance_id: sheduler link to assign the actions to :type scheduler_instance_id: SchedulerLink :return: None """ # We check for new check in each schedulers and put the result in new_checks scheduler_link = None for scheduler_id in self.schedulers: logger.debug("Trying to add an action, scheduler: %s", self.schedulers[scheduler_id]) if scheduler_instance_id == self.schedulers[scheduler_id].instance_id: scheduler_link = self.schedulers[scheduler_id] break else: logger.error("Trying to add actions from an unknwown scheduler: %s", scheduler_instance_id) return if not scheduler_link: logger.error("Trying to add actions, but scheduler link is not found for: %s, " "actions: %s", scheduler_instance_id, actions_list) return logger.debug("Found scheduler link: %s", scheduler_link) for action in actions_list: # First we look if the action is identified uuid = getattr(action, 'uuid', None) if uuid is None: try: action = unserialize(action, no_load=True) uuid = action.uuid except AlignakClassLookupException: logger.error('Cannot un-serialize action: %s', action) continue # If we already have this action, we are already working for it! if uuid in scheduler_link.actions: continue # Action is attached to a scheduler action.my_scheduler = scheduler_link.uuid scheduler_link.actions[action.uuid] = action self.assign_to_a_queue(action)
[ "def", "add_actions", "(", "self", ",", "actions_list", ",", "scheduler_instance_id", ")", ":", "# We check for new check in each schedulers and put the result in new_checks", "scheduler_link", "=", "None", "for", "scheduler_id", "in", "self", ".", "schedulers", ":", "logger", ".", "debug", "(", "\"Trying to add an action, scheduler: %s\"", ",", "self", ".", "schedulers", "[", "scheduler_id", "]", ")", "if", "scheduler_instance_id", "==", "self", ".", "schedulers", "[", "scheduler_id", "]", ".", "instance_id", ":", "scheduler_link", "=", "self", ".", "schedulers", "[", "scheduler_id", "]", "break", "else", ":", "logger", ".", "error", "(", "\"Trying to add actions from an unknwown scheduler: %s\"", ",", "scheduler_instance_id", ")", "return", "if", "not", "scheduler_link", ":", "logger", ".", "error", "(", "\"Trying to add actions, but scheduler link is not found for: %s, \"", "\"actions: %s\"", ",", "scheduler_instance_id", ",", "actions_list", ")", "return", "logger", ".", "debug", "(", "\"Found scheduler link: %s\"", ",", "scheduler_link", ")", "for", "action", "in", "actions_list", ":", "# First we look if the action is identified", "uuid", "=", "getattr", "(", "action", ",", "'uuid'", ",", "None", ")", "if", "uuid", "is", "None", ":", "try", ":", "action", "=", "unserialize", "(", "action", ",", "no_load", "=", "True", ")", "uuid", "=", "action", ".", "uuid", "except", "AlignakClassLookupException", ":", "logger", ".", "error", "(", "'Cannot un-serialize action: %s'", ",", "action", ")", "continue", "# If we already have this action, we are already working for it!", "if", "uuid", "in", "scheduler_link", ".", "actions", ":", "continue", "# Action is attached to a scheduler", "action", ".", "my_scheduler", "=", "scheduler_link", ".", "uuid", "scheduler_link", ".", "actions", "[", "action", ".", "uuid", "]", "=", "action", "self", ".", "assign_to_a_queue", "(", "action", ")" ]
Add a list of actions to the satellite queues :param actions_list: Actions list to add :type actions_list: list :param scheduler_instance_id: sheduler link to assign the actions to :type scheduler_instance_id: SchedulerLink :return: None
[ "Add", "a", "list", "of", "actions", "to", "the", "satellite", "queues" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L759-L802
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.assign_to_a_queue
def assign_to_a_queue(self, action): """Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None """ (worker_id, queue) = self._get_queue_for_the_action(action) if not worker_id: return # Tag the action as "in the worker i" action.my_worker = worker_id action.status = ACT_STATUS_QUEUED msg = Message(_type='Do', data=action, source=self.name) logger.debug("Queuing message: %s", msg) queue.put_nowait(msg) logger.debug("Queued")
python
def assign_to_a_queue(self, action): """Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None """ (worker_id, queue) = self._get_queue_for_the_action(action) if not worker_id: return # Tag the action as "in the worker i" action.my_worker = worker_id action.status = ACT_STATUS_QUEUED msg = Message(_type='Do', data=action, source=self.name) logger.debug("Queuing message: %s", msg) queue.put_nowait(msg) logger.debug("Queued")
[ "def", "assign_to_a_queue", "(", "self", ",", "action", ")", ":", "(", "worker_id", ",", "queue", ")", "=", "self", ".", "_get_queue_for_the_action", "(", "action", ")", "if", "not", "worker_id", ":", "return", "# Tag the action as \"in the worker i\"", "action", ".", "my_worker", "=", "worker_id", "action", ".", "status", "=", "ACT_STATUS_QUEUED", "msg", "=", "Message", "(", "_type", "=", "'Do'", ",", "data", "=", "action", ",", "source", "=", "self", ".", "name", ")", "logger", ".", "debug", "(", "\"Queuing message: %s\"", ",", "msg", ")", "queue", ".", "put_nowait", "(", "msg", ")", "logger", ".", "debug", "(", "\"Queued\"", ")" ]
Take an action and put it to a worker actions queue :param action: action to put :type action: alignak.action.Action :return: None
[ "Take", "an", "action", "and", "put", "it", "to", "a", "worker", "actions", "queue" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L804-L822
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.get_new_actions
def get_new_actions(self): """ Wrapper function for do_get_new_actions For stats purpose :return: None TODO: Use a decorator for timing this function """ try: _t0 = time.time() self.do_get_new_actions() statsmgr.timer('actions.got.time', time.time() - _t0) except RuntimeError: logger.error("Exception like issue #1007")
python
def get_new_actions(self): """ Wrapper function for do_get_new_actions For stats purpose :return: None TODO: Use a decorator for timing this function """ try: _t0 = time.time() self.do_get_new_actions() statsmgr.timer('actions.got.time', time.time() - _t0) except RuntimeError: logger.error("Exception like issue #1007")
[ "def", "get_new_actions", "(", "self", ")", ":", "try", ":", "_t0", "=", "time", ".", "time", "(", ")", "self", ".", "do_get_new_actions", "(", ")", "statsmgr", ".", "timer", "(", "'actions.got.time'", ",", "time", ".", "time", "(", ")", "-", "_t0", ")", "except", "RuntimeError", ":", "logger", ".", "error", "(", "\"Exception like issue #1007\"", ")" ]
Wrapper function for do_get_new_actions For stats purpose :return: None TODO: Use a decorator for timing this function
[ "Wrapper", "function", "for", "do_get_new_actions", "For", "stats", "purpose" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L824-L836
train
Alignak-monitoring/alignak
alignak/satellite.py
Satellite.main
def main(self): """Main satellite function. Do init and then mainloop :return: None """ try: # Start the daemon mode if not self.do_daemon_init_and_start(): self.exit_on_error(message="Daemon initialization error", exit_code=3) self.do_post_daemon_init() # We wait for initial conf self.wait_for_initial_conf() if self.new_conf: # Setup the received configuration self.setup_new_conf() # Allocate Mortal Threads self.adjust_worker_number_by_load() # Now main loop self.do_main_loop() logger.info("Exited from the main loop.") self.request_stop() except Exception: # pragma: no cover, this should never happen indeed ;) self.exit_on_exception(traceback.format_exc()) raise
python
def main(self): """Main satellite function. Do init and then mainloop :return: None """ try: # Start the daemon mode if not self.do_daemon_init_and_start(): self.exit_on_error(message="Daemon initialization error", exit_code=3) self.do_post_daemon_init() # We wait for initial conf self.wait_for_initial_conf() if self.new_conf: # Setup the received configuration self.setup_new_conf() # Allocate Mortal Threads self.adjust_worker_number_by_load() # Now main loop self.do_main_loop() logger.info("Exited from the main loop.") self.request_stop() except Exception: # pragma: no cover, this should never happen indeed ;) self.exit_on_exception(traceback.format_exc()) raise
[ "def", "main", "(", "self", ")", ":", "try", ":", "# Start the daemon mode", "if", "not", "self", ".", "do_daemon_init_and_start", "(", ")", ":", "self", ".", "exit_on_error", "(", "message", "=", "\"Daemon initialization error\"", ",", "exit_code", "=", "3", ")", "self", ".", "do_post_daemon_init", "(", ")", "# We wait for initial conf", "self", ".", "wait_for_initial_conf", "(", ")", "if", "self", ".", "new_conf", ":", "# Setup the received configuration", "self", ".", "setup_new_conf", "(", ")", "# Allocate Mortal Threads", "self", ".", "adjust_worker_number_by_load", "(", ")", "# Now main loop", "self", ".", "do_main_loop", "(", ")", "logger", ".", "info", "(", "\"Exited from the main loop.\"", ")", "self", ".", "request_stop", "(", ")", "except", "Exception", ":", "# pragma: no cover, this should never happen indeed ;)", "self", ".", "exit_on_exception", "(", "traceback", ".", "format_exc", "(", ")", ")", "raise" ]
Main satellite function. Do init and then mainloop :return: None
[ "Main", "satellite", "function", ".", "Do", "init", "and", "then", "mainloop" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/satellite.py#L1108-L1136
train
Alignak-monitoring/alignak
alignak/contactdowntime.py
ContactDowntime.check_activation
def check_activation(self, contacts): """Enter or exit downtime if necessary :return: None """ now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) # Raise a log entry when we get in the downtime if not was_is_in_effect and self.is_in_effect: self.enter(contacts) # Same for exit purpose if was_is_in_effect and not self.is_in_effect: self.exit(contacts)
python
def check_activation(self, contacts): """Enter or exit downtime if necessary :return: None """ now = time.time() was_is_in_effect = self.is_in_effect self.is_in_effect = (self.start_time <= now <= self.end_time) # Raise a log entry when we get in the downtime if not was_is_in_effect and self.is_in_effect: self.enter(contacts) # Same for exit purpose if was_is_in_effect and not self.is_in_effect: self.exit(contacts)
[ "def", "check_activation", "(", "self", ",", "contacts", ")", ":", "now", "=", "time", ".", "time", "(", ")", "was_is_in_effect", "=", "self", ".", "is_in_effect", "self", ".", "is_in_effect", "=", "(", "self", ".", "start_time", "<=", "now", "<=", "self", ".", "end_time", ")", "# Raise a log entry when we get in the downtime", "if", "not", "was_is_in_effect", "and", "self", ".", "is_in_effect", ":", "self", ".", "enter", "(", "contacts", ")", "# Same for exit purpose", "if", "was_is_in_effect", "and", "not", "self", ".", "is_in_effect", ":", "self", ".", "exit", "(", "contacts", ")" ]
Enter or exit downtime if necessary :return: None
[ "Enter", "or", "exit", "downtime", "if", "necessary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/contactdowntime.py#L90-L105
train
Alignak-monitoring/alignak
alignak/util.py
split_semicolon
def split_semicolon(line, maxsplit=None): r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g'] """ # Split on ';' character split_line = line.split(';') split_line_size = len(split_line) # if maxsplit is not specified, we set it to the number of part if maxsplit is None or maxsplit < 0: maxsplit = split_line_size # Join parts to the next one, if ends with a '\' # because we mustn't split if the semicolon is escaped i = 0 while i < split_line_size - 1: # for each part, check if its ends with a '\' ends = split_line[i].endswith('\\') if ends: # remove the last character '\' split_line[i] = split_line[i][:-1] # append the next part to the current if it is not the last and the current # ends with '\' or if there is more than maxsplit parts if (ends or i >= maxsplit) and i < split_line_size - 1: split_line[i] = ";".join([split_line[i], split_line[i + 1]]) # delete the next part del split_line[i + 1] split_line_size -= 1 # increase i only if we don't have append because after append the new # string can end with '\' else: i += 1 return split_line
python
def split_semicolon(line, maxsplit=None): r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g'] """ # Split on ';' character split_line = line.split(';') split_line_size = len(split_line) # if maxsplit is not specified, we set it to the number of part if maxsplit is None or maxsplit < 0: maxsplit = split_line_size # Join parts to the next one, if ends with a '\' # because we mustn't split if the semicolon is escaped i = 0 while i < split_line_size - 1: # for each part, check if its ends with a '\' ends = split_line[i].endswith('\\') if ends: # remove the last character '\' split_line[i] = split_line[i][:-1] # append the next part to the current if it is not the last and the current # ends with '\' or if there is more than maxsplit parts if (ends or i >= maxsplit) and i < split_line_size - 1: split_line[i] = ";".join([split_line[i], split_line[i + 1]]) # delete the next part del split_line[i + 1] split_line_size -= 1 # increase i only if we don't have append because after append the new # string can end with '\' else: i += 1 return split_line
[ "def", "split_semicolon", "(", "line", ",", "maxsplit", "=", "None", ")", ":", "# Split on ';' character", "split_line", "=", "line", ".", "split", "(", "';'", ")", "split_line_size", "=", "len", "(", "split_line", ")", "# if maxsplit is not specified, we set it to the number of part", "if", "maxsplit", "is", "None", "or", "maxsplit", "<", "0", ":", "maxsplit", "=", "split_line_size", "# Join parts to the next one, if ends with a '\\'", "# because we mustn't split if the semicolon is escaped", "i", "=", "0", "while", "i", "<", "split_line_size", "-", "1", ":", "# for each part, check if its ends with a '\\'", "ends", "=", "split_line", "[", "i", "]", ".", "endswith", "(", "'\\\\'", ")", "if", "ends", ":", "# remove the last character '\\'", "split_line", "[", "i", "]", "=", "split_line", "[", "i", "]", "[", ":", "-", "1", "]", "# append the next part to the current if it is not the last and the current", "# ends with '\\' or if there is more than maxsplit parts", "if", "(", "ends", "or", "i", ">=", "maxsplit", ")", "and", "i", "<", "split_line_size", "-", "1", ":", "split_line", "[", "i", "]", "=", "\";\"", ".", "join", "(", "[", "split_line", "[", "i", "]", ",", "split_line", "[", "i", "+", "1", "]", "]", ")", "# delete the next part", "del", "split_line", "[", "i", "+", "1", "]", "split_line_size", "-=", "1", "# increase i only if we don't have append because after append the new", "# string can end with '\\'", "else", ":", "i", "+=", "1", "return", "split_line" ]
r"""Split a line on semicolons characters but not on the escaped semicolons :param line: line to split :type line: str :param maxsplit: maximal number of split (if None, no limit) :type maxsplit: None | int :return: split line :rtype: list >>> split_semicolon('a,b;c;;g') ['a,b', 'c', '', 'g'] >>> split_semicolon('a,b;c;;g', 2) ['a,b', 'c', ';g'] >>> split_semicolon(r'a,b;c\;;g', 2) ['a,b', 'c;', 'g']
[ "r", "Split", "a", "line", "on", "semicolons", "characters", "but", "not", "on", "the", "escaped", "semicolons" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L110-L165
train
Alignak-monitoring/alignak
alignak/util.py
format_t_into_dhms_format
def format_t_into_dhms_format(timestamp): """ Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s' """ mins, timestamp = divmod(timestamp, 60) hour, mins = divmod(mins, 60) day, hour = divmod(hour, 24) return '%sd %sh %sm %ss' % (day, hour, mins, timestamp)
python
def format_t_into_dhms_format(timestamp): """ Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s' """ mins, timestamp = divmod(timestamp, 60) hour, mins = divmod(mins, 60) day, hour = divmod(hour, 24) return '%sd %sh %sm %ss' % (day, hour, mins, timestamp)
[ "def", "format_t_into_dhms_format", "(", "timestamp", ")", ":", "mins", ",", "timestamp", "=", "divmod", "(", "timestamp", ",", "60", ")", "hour", ",", "mins", "=", "divmod", "(", "mins", ",", "60", ")", "day", ",", "hour", "=", "divmod", "(", "hour", ",", "24", ")", "return", "'%sd %sh %sm %ss'", "%", "(", "day", ",", "hour", ",", "mins", ",", "timestamp", ")" ]
Convert an amount of second into day, hour, min and sec :param timestamp: seconds :type timestamp: int :return: 'Ad Bh Cm Ds' :rtype: str >>> format_t_into_dhms_format(456189) '5d 6h 43m 9s' >>> format_t_into_dhms_format(3600) '0d 1h 0m 0s'
[ "Convert", "an", "amount", "of", "second", "into", "day", "hour", "min", "and", "sec" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L230-L248
train
Alignak-monitoring/alignak
alignak/util.py
merge_periods
def merge_periods(data): """ Merge periods to have better continous periods. Like 350-450, 400-600 => 350-600 :param data: list of periods :type data: list :return: better continous periods :rtype: list """ # sort by start date newdata = sorted(data, key=lambda drange: drange[0]) end = 0 for period in newdata: if period[0] != end and period[0] != (end - 1): end = period[1] # dat = np.array(newdata) dat = newdata new_intervals = [] cur_start = None cur_end = None for (dt_start, dt_end) in dat: if cur_end is None: cur_start = dt_start cur_end = dt_end continue else: if cur_end >= dt_start: # merge, keep existing cur_start, extend cur_end cur_end = dt_end else: # new interval, save previous and reset current to this new_intervals.append((cur_start, cur_end)) cur_start = dt_start cur_end = dt_end # make sure final interval is saved new_intervals.append((cur_start, cur_end)) return new_intervals
python
def merge_periods(data): """ Merge periods to have better continous periods. Like 350-450, 400-600 => 350-600 :param data: list of periods :type data: list :return: better continous periods :rtype: list """ # sort by start date newdata = sorted(data, key=lambda drange: drange[0]) end = 0 for period in newdata: if period[0] != end and period[0] != (end - 1): end = period[1] # dat = np.array(newdata) dat = newdata new_intervals = [] cur_start = None cur_end = None for (dt_start, dt_end) in dat: if cur_end is None: cur_start = dt_start cur_end = dt_end continue else: if cur_end >= dt_start: # merge, keep existing cur_start, extend cur_end cur_end = dt_end else: # new interval, save previous and reset current to this new_intervals.append((cur_start, cur_end)) cur_start = dt_start cur_end = dt_end # make sure final interval is saved new_intervals.append((cur_start, cur_end)) return new_intervals
[ "def", "merge_periods", "(", "data", ")", ":", "# sort by start date", "newdata", "=", "sorted", "(", "data", ",", "key", "=", "lambda", "drange", ":", "drange", "[", "0", "]", ")", "end", "=", "0", "for", "period", "in", "newdata", ":", "if", "period", "[", "0", "]", "!=", "end", "and", "period", "[", "0", "]", "!=", "(", "end", "-", "1", ")", ":", "end", "=", "period", "[", "1", "]", "# dat = np.array(newdata)", "dat", "=", "newdata", "new_intervals", "=", "[", "]", "cur_start", "=", "None", "cur_end", "=", "None", "for", "(", "dt_start", ",", "dt_end", ")", "in", "dat", ":", "if", "cur_end", "is", "None", ":", "cur_start", "=", "dt_start", "cur_end", "=", "dt_end", "continue", "else", ":", "if", "cur_end", ">=", "dt_start", ":", "# merge, keep existing cur_start, extend cur_end", "cur_end", "=", "dt_end", "else", ":", "# new interval, save previous and reset current to this", "new_intervals", ".", "append", "(", "(", "cur_start", ",", "cur_end", ")", ")", "cur_start", "=", "dt_start", "cur_end", "=", "dt_end", "# make sure final interval is saved", "new_intervals", ".", "append", "(", "(", "cur_start", ",", "cur_end", ")", ")", "return", "new_intervals" ]
Merge periods to have better continous periods. Like 350-450, 400-600 => 350-600 :param data: list of periods :type data: list :return: better continous periods :rtype: list
[ "Merge", "periods", "to", "have", "better", "continous", "periods", ".", "Like", "350", "-", "450", "400", "-", "600", "=", ">", "350", "-", "600" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L251-L289
train
Alignak-monitoring/alignak
alignak/util.py
list_split
def list_split(val, split_on_comma=True): """Try to split each member of a list with comma separator. If we don't have to split just return val :param val: value to split :type val: :param split_on_comma: :type split_on_comma: bool :return: list with members split on comma :rtype: list >>> list_split(['a,b,c'], False) ['a,b,c'] >>> list_split(['a,b,c']) ['a', 'b', 'c'] >>> list_split('') [] """ if not split_on_comma: return val new_val = [] for subval in val: # This may happen when re-serializing if isinstance(subval, list): continue new_val.extend(subval.split(',')) return new_val
python
def list_split(val, split_on_comma=True): """Try to split each member of a list with comma separator. If we don't have to split just return val :param val: value to split :type val: :param split_on_comma: :type split_on_comma: bool :return: list with members split on comma :rtype: list >>> list_split(['a,b,c'], False) ['a,b,c'] >>> list_split(['a,b,c']) ['a', 'b', 'c'] >>> list_split('') [] """ if not split_on_comma: return val new_val = [] for subval in val: # This may happen when re-serializing if isinstance(subval, list): continue new_val.extend(subval.split(',')) return new_val
[ "def", "list_split", "(", "val", ",", "split_on_comma", "=", "True", ")", ":", "if", "not", "split_on_comma", ":", "return", "val", "new_val", "=", "[", "]", "for", "subval", "in", "val", ":", "# This may happen when re-serializing", "if", "isinstance", "(", "subval", ",", "list", ")", ":", "continue", "new_val", ".", "extend", "(", "subval", ".", "split", "(", "','", ")", ")", "return", "new_val" ]
Try to split each member of a list with comma separator. If we don't have to split just return val :param val: value to split :type val: :param split_on_comma: :type split_on_comma: bool :return: list with members split on comma :rtype: list >>> list_split(['a,b,c'], False) ['a,b,c'] >>> list_split(['a,b,c']) ['a', 'b', 'c'] >>> list_split('') []
[ "Try", "to", "split", "each", "member", "of", "a", "list", "with", "comma", "separator", ".", "If", "we", "don", "t", "have", "to", "split", "just", "return", "val" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L364-L393
train
Alignak-monitoring/alignak
alignak/util.py
to_best_int_float
def to_best_int_float(val): """Get best type for value between int and float :param val: value :type val: :return: int(float(val)) if int(float(val)) == float(val), else float(val) :rtype: int | float >>> to_best_int_float("20.1") 20.1 >>> to_best_int_float("20.0") 20 >>> to_best_int_float("20") 20 """ integer = int(float(val)) flt = float(val) # If the f is a .0 value, # best match is int if integer == flt: return integer return flt
python
def to_best_int_float(val): """Get best type for value between int and float :param val: value :type val: :return: int(float(val)) if int(float(val)) == float(val), else float(val) :rtype: int | float >>> to_best_int_float("20.1") 20.1 >>> to_best_int_float("20.0") 20 >>> to_best_int_float("20") 20 """ integer = int(float(val)) flt = float(val) # If the f is a .0 value, # best match is int if integer == flt: return integer return flt
[ "def", "to_best_int_float", "(", "val", ")", ":", "integer", "=", "int", "(", "float", "(", "val", ")", ")", "flt", "=", "float", "(", "val", ")", "# If the f is a .0 value,", "# best match is int", "if", "integer", "==", "flt", ":", "return", "integer", "return", "flt" ]
Get best type for value between int and float :param val: value :type val: :return: int(float(val)) if int(float(val)) == float(val), else float(val) :rtype: int | float >>> to_best_int_float("20.1") 20.1 >>> to_best_int_float("20.0") 20 >>> to_best_int_float("20") 20
[ "Get", "best", "type", "for", "value", "between", "int", "and", "float" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L396-L419
train
Alignak-monitoring/alignak
alignak/util.py
dict_to_serialized_dict
def dict_to_serialized_dict(ref, the_dict): """Serialize the list of elements to a dictionary Used for the retention store :param ref: Not used :type ref: :param the_dict: dictionary to convert :type the_dict: dict :return: dict of serialized :rtype: dict """ result = {} for elt in list(the_dict.values()): if not getattr(elt, 'serialize', None): continue result[elt.uuid] = elt.serialize() return result
python
def dict_to_serialized_dict(ref, the_dict): """Serialize the list of elements to a dictionary Used for the retention store :param ref: Not used :type ref: :param the_dict: dictionary to convert :type the_dict: dict :return: dict of serialized :rtype: dict """ result = {} for elt in list(the_dict.values()): if not getattr(elt, 'serialize', None): continue result[elt.uuid] = elt.serialize() return result
[ "def", "dict_to_serialized_dict", "(", "ref", ",", "the_dict", ")", ":", "result", "=", "{", "}", "for", "elt", "in", "list", "(", "the_dict", ".", "values", "(", ")", ")", ":", "if", "not", "getattr", "(", "elt", ",", "'serialize'", ",", "None", ")", ":", "continue", "result", "[", "elt", ".", "uuid", "]", "=", "elt", ".", "serialize", "(", ")", "return", "result" ]
Serialize the list of elements to a dictionary Used for the retention store :param ref: Not used :type ref: :param the_dict: dictionary to convert :type the_dict: dict :return: dict of serialized :rtype: dict
[ "Serialize", "the", "list", "of", "elements", "to", "a", "dictionary" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L587-L604
train
Alignak-monitoring/alignak
alignak/util.py
list_to_serialized
def list_to_serialized(ref, the_list): """Serialize the list of elements Used for the retention store :param ref: Not used :type ref: :param the_list: dictionary to convert :type the_list: dict :return: dict of serialized :rtype: dict """ result = [] for elt in the_list: if not getattr(elt, 'serialize', None): continue result.append(elt.serialize()) return result
python
def list_to_serialized(ref, the_list): """Serialize the list of elements Used for the retention store :param ref: Not used :type ref: :param the_list: dictionary to convert :type the_list: dict :return: dict of serialized :rtype: dict """ result = [] for elt in the_list: if not getattr(elt, 'serialize', None): continue result.append(elt.serialize()) return result
[ "def", "list_to_serialized", "(", "ref", ",", "the_list", ")", ":", "result", "=", "[", "]", "for", "elt", "in", "the_list", ":", "if", "not", "getattr", "(", "elt", ",", "'serialize'", ",", "None", ")", ":", "continue", "result", ".", "append", "(", "elt", ".", "serialize", "(", ")", ")", "return", "result" ]
Serialize the list of elements Used for the retention store :param ref: Not used :type ref: :param the_list: dictionary to convert :type the_list: dict :return: dict of serialized :rtype: dict
[ "Serialize", "the", "list", "of", "elements" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L607-L624
train
Alignak-monitoring/alignak
alignak/util.py
to_hostnames_list
def to_hostnames_list(ref, tab): # pragma: no cover, to be deprecated? """Convert Host list into a list of host_name :param ref: Not used :type ref: :param tab: Host list :type tab: list[alignak.objects.host.Host] :return: host_name list :rtype: list """ res = [] for host in tab: if hasattr(host, 'host_name'): res.append(host.host_name) return res
python
def to_hostnames_list(ref, tab): # pragma: no cover, to be deprecated? """Convert Host list into a list of host_name :param ref: Not used :type ref: :param tab: Host list :type tab: list[alignak.objects.host.Host] :return: host_name list :rtype: list """ res = [] for host in tab: if hasattr(host, 'host_name'): res.append(host.host_name) return res
[ "def", "to_hostnames_list", "(", "ref", ",", "tab", ")", ":", "# pragma: no cover, to be deprecated?", "res", "=", "[", "]", "for", "host", "in", "tab", ":", "if", "hasattr", "(", "host", ",", "'host_name'", ")", ":", "res", ".", "append", "(", "host", ".", "host_name", ")", "return", "res" ]
Convert Host list into a list of host_name :param ref: Not used :type ref: :param tab: Host list :type tab: list[alignak.objects.host.Host] :return: host_name list :rtype: list
[ "Convert", "Host", "list", "into", "a", "list", "of", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L642-L656
train
Alignak-monitoring/alignak
alignak/util.py
sort_by_number_values
def sort_by_number_values(x00, y00): # pragma: no cover, looks like not used! """Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int """ if len(x00) < len(y00): return 1 if len(x00) > len(y00): return -1 # So is equal return 0
python
def sort_by_number_values(x00, y00): # pragma: no cover, looks like not used! """Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int """ if len(x00) < len(y00): return 1 if len(x00) > len(y00): return -1 # So is equal return 0
[ "def", "sort_by_number_values", "(", "x00", ",", "y00", ")", ":", "# pragma: no cover, looks like not used!", "if", "len", "(", "x00", ")", "<", "len", "(", "y00", ")", ":", "return", "1", "if", "len", "(", "x00", ")", ">", "len", "(", "y00", ")", ":", "return", "-", "1", "# So is equal", "return", "0" ]
Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int
[ "Compare", "x00", "y00", "base", "on", "number", "of", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L738-L753
train
Alignak-monitoring/alignak
alignak/util.py
strip_and_uniq
def strip_and_uniq(tab): """Strip every element of a list and keep a list of ordered unique values :param tab: list to strip :type tab: list :return: stripped list with unique values :rtype: list """ _list = [] for elt in tab: val = elt.strip() if val and val not in _list: _list.append(val) return _list
python
def strip_and_uniq(tab): """Strip every element of a list and keep a list of ordered unique values :param tab: list to strip :type tab: list :return: stripped list with unique values :rtype: list """ _list = [] for elt in tab: val = elt.strip() if val and val not in _list: _list.append(val) return _list
[ "def", "strip_and_uniq", "(", "tab", ")", ":", "_list", "=", "[", "]", "for", "elt", "in", "tab", ":", "val", "=", "elt", ".", "strip", "(", ")", "if", "val", "and", "val", "not", "in", "_list", ":", "_list", ".", "append", "(", "val", ")", "return", "_list" ]
Strip every element of a list and keep a list of ordered unique values :param tab: list to strip :type tab: list :return: stripped list with unique values :rtype: list
[ "Strip", "every", "element", "of", "a", "list", "and", "keep", "a", "list", "of", "ordered", "unique", "values" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L777-L790
train
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_name
def filter_host_by_name(name): """Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if host_name == name""" host = items["host"] if host is None: return False return host.host_name == name return inner_filter
python
def filter_host_by_name(name): """Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if host_name == name""" host = items["host"] if host is None: return False return host.host_name == name return inner_filter
[ "def", "filter_host_by_name", "(", "name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if host_name == name\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "return", "host", ".", "host_name", "==", "name", "return", "inner_filter" ]
Filter for host Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L938-L955
train
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_regex
def filter_host_by_regex(regex): """Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for host. Accept if regex match host_name""" host = items["host"] if host is None: return False return host_re.match(host.host_name) is not None return inner_filter
python
def filter_host_by_regex(regex): """Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for host. Accept if regex match host_name""" host = items["host"] if host is None: return False return host_re.match(host.host_name) is not None return inner_filter
[ "def", "filter_host_by_regex", "(", "regex", ")", ":", "host_re", "=", "re", ".", "compile", "(", "regex", ")", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if regex match host_name\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "return", "host_re", ".", "match", "(", "host", ".", "host_name", ")", "is", "not", "None", "return", "inner_filter" ]
Filter for host Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "regex" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L958-L976
train
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_group
def filter_host_by_group(group): """Filter for host Filter on group :param group: group name to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if group in host.hostgroups""" host = items["host"] if host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
python
def filter_host_by_group(group): """Filter for host Filter on group :param group: group name to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if group in host.hostgroups""" host = items["host"] if host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
[ "def", "filter_host_by_group", "(", "group", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if group in host.hostgroups\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "return", "group", "in", "[", "items", "[", "\"hostgroups\"", "]", "[", "g", "]", ".", "hostgroup_name", "for", "g", "in", "host", ".", "hostgroups", "]", "return", "inner_filter" ]
Filter for host Filter on group :param group: group name to filter :type group: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "group" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L979-L996
train
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_tag
def filter_host_by_tag(tpl): """Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if tag in host.tags""" host = items["host"] if host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
python
def filter_host_by_tag(tpl): """Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if tag in host.tags""" host = items["host"] if host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
[ "def", "filter_host_by_tag", "(", "tpl", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if tag in host.tags\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "return", "tpl", "in", "[", "t", ".", "strip", "(", ")", "for", "t", "in", "host", ".", "tags", "]", "return", "inner_filter" ]
Filter for host Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "tag" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L999-L1016
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_name
def filter_service_by_name(name): """Filter for service Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if service_description == name""" service = items["service"] if service is None: return False return service.service_description == name return inner_filter
python
def filter_service_by_name(name): """Filter for service Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if service_description == name""" service = items["service"] if service is None: return False return service.service_description == name return inner_filter
[ "def", "filter_service_by_name", "(", "name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if service_description == name\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "if", "service", "is", "None", ":", "return", "False", "return", "service", ".", "service_description", "==", "name", "return", "inner_filter" ]
Filter for service Filter on name :param name: name to filter :type name: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1019-L1036
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_regex_name
def filter_service_by_regex_name(regex): """Filter for service Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for service. Accept if regex match service_description""" service = items["service"] if service is None: return False return host_re.match(service.service_description) is not None return inner_filter
python
def filter_service_by_regex_name(regex): """Filter for service Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for service. Accept if regex match service_description""" service = items["service"] if service is None: return False return host_re.match(service.service_description) is not None return inner_filter
[ "def", "filter_service_by_regex_name", "(", "regex", ")", ":", "host_re", "=", "re", ".", "compile", "(", "regex", ")", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if regex match service_description\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "if", "service", "is", "None", ":", "return", "False", "return", "host_re", ".", "match", "(", "service", ".", "service_description", ")", "is", "not", "None", "return", "inner_filter" ]
Filter for service Filter on regex :param regex: regex to filter :type regex: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "regex" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1039-L1057
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_host_name
def filter_service_by_host_name(host_name): """Filter for service Filter on host_name :param host_name: host_name to filter :type host_name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if service.host.host_name == host_name""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return host.host_name == host_name return inner_filter
python
def filter_service_by_host_name(host_name): """Filter for service Filter on host_name :param host_name: host_name to filter :type host_name: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if service.host.host_name == host_name""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return host.host_name == host_name return inner_filter
[ "def", "filter_service_by_host_name", "(", "host_name", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if service.host.host_name == host_name\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "host", "=", "items", "[", "\"hosts\"", "]", "[", "service", ".", "host", "]", "if", "service", "is", "None", "or", "host", "is", "None", ":", "return", "False", "return", "host", ".", "host_name", "==", "host_name", "return", "inner_filter" ]
Filter for service Filter on host_name :param host_name: host_name to filter :type host_name: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1060-L1078
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_regex_host_name
def filter_service_by_regex_host_name(regex): """Filter for service Filter on regex host_name :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for service. Accept if regex match service.host.host_name""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return host_re.match(host.host_name) is not None return inner_filter
python
def filter_service_by_regex_host_name(regex): """Filter for service Filter on regex host_name :param regex: regex to filter :type regex: str :return: Filter :rtype: bool """ host_re = re.compile(regex) def inner_filter(items): """Inner filter for service. Accept if regex match service.host.host_name""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return host_re.match(host.host_name) is not None return inner_filter
[ "def", "filter_service_by_regex_host_name", "(", "regex", ")", ":", "host_re", "=", "re", ".", "compile", "(", "regex", ")", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if regex match service.host.host_name\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "host", "=", "items", "[", "\"hosts\"", "]", "[", "service", ".", "host", "]", "if", "service", "is", "None", "or", "host", "is", "None", ":", "return", "False", "return", "host_re", ".", "match", "(", "host", ".", "host_name", ")", "is", "not", "None", "return", "inner_filter" ]
Filter for service Filter on regex host_name :param regex: regex to filter :type regex: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "regex", "host_name" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1081-L1100
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_hostgroup_name
def filter_service_by_hostgroup_name(group): """Filter for service Filter on hostgroup :param group: hostgroup to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if hostgroup in service.host.hostgroups""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
python
def filter_service_by_hostgroup_name(group): """Filter for service Filter on hostgroup :param group: hostgroup to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if hostgroup in service.host.hostgroups""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return group in [items["hostgroups"][g].hostgroup_name for g in host.hostgroups] return inner_filter
[ "def", "filter_service_by_hostgroup_name", "(", "group", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if hostgroup in service.host.hostgroups\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "host", "=", "items", "[", "\"hosts\"", "]", "[", "service", ".", "host", "]", "if", "service", "is", "None", "or", "host", "is", "None", ":", "return", "False", "return", "group", "in", "[", "items", "[", "\"hostgroups\"", "]", "[", "g", "]", ".", "hostgroup_name", "for", "g", "in", "host", ".", "hostgroups", "]", "return", "inner_filter" ]
Filter for service Filter on hostgroup :param group: hostgroup to filter :type group: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "hostgroup" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1103-L1121
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_host_tag_name
def filter_service_by_host_tag_name(tpl): """Filter for service Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if tpl in service.host.tags""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
python
def filter_service_by_host_tag_name(tpl): """Filter for service Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if tpl in service.host.tags""" service = items["service"] host = items["hosts"][service.host] if service is None or host is None: return False return tpl in [t.strip() for t in host.tags] return inner_filter
[ "def", "filter_service_by_host_tag_name", "(", "tpl", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if tpl in service.host.tags\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "host", "=", "items", "[", "\"hosts\"", "]", "[", "service", ".", "host", "]", "if", "service", "is", "None", "or", "host", "is", "None", ":", "return", "False", "return", "tpl", "in", "[", "t", ".", "strip", "(", ")", "for", "t", "in", "host", ".", "tags", "]", "return", "inner_filter" ]
Filter for service Filter on tag :param tpl: tag to filter :type tpl: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "tag" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1124-L1142
train
Alignak-monitoring/alignak
alignak/util.py
filter_service_by_servicegroup_name
def filter_service_by_servicegroup_name(group): """Filter for service Filter on group :param group: group to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if group in service.servicegroups""" service = items["service"] if service is None: return False return group in [items["servicegroups"][g].servicegroup_name for g in service.servicegroups] return inner_filter
python
def filter_service_by_servicegroup_name(group): """Filter for service Filter on group :param group: group to filter :type group: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for service. Accept if group in service.servicegroups""" service = items["service"] if service is None: return False return group in [items["servicegroups"][g].servicegroup_name for g in service.servicegroups] return inner_filter
[ "def", "filter_service_by_servicegroup_name", "(", "group", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for service. Accept if group in service.servicegroups\"\"\"", "service", "=", "items", "[", "\"service\"", "]", "if", "service", "is", "None", ":", "return", "False", "return", "group", "in", "[", "items", "[", "\"servicegroups\"", "]", "[", "g", "]", ".", "servicegroup_name", "for", "g", "in", "service", ".", "servicegroups", "]", "return", "inner_filter" ]
Filter for service Filter on group :param group: group to filter :type group: str :return: Filter :rtype: bool
[ "Filter", "for", "service", "Filter", "on", "group" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1145-L1162
train
Alignak-monitoring/alignak
alignak/util.py
filter_host_by_bp_rule_label
def filter_host_by_bp_rule_label(label): """Filter for host Filter on label :param label: label to filter :type label: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if label in host.labels""" host = items["host"] if host is None: return False return label in host.labels return inner_filter
python
def filter_host_by_bp_rule_label(label): """Filter for host Filter on label :param label: label to filter :type label: str :return: Filter :rtype: bool """ def inner_filter(items): """Inner filter for host. Accept if label in host.labels""" host = items["host"] if host is None: return False return label in host.labels return inner_filter
[ "def", "filter_host_by_bp_rule_label", "(", "label", ")", ":", "def", "inner_filter", "(", "items", ")", ":", "\"\"\"Inner filter for host. Accept if label in host.labels\"\"\"", "host", "=", "items", "[", "\"host\"", "]", "if", "host", "is", "None", ":", "return", "False", "return", "label", "in", "host", ".", "labels", "return", "inner_filter" ]
Filter for host Filter on label :param label: label to filter :type label: str :return: Filter :rtype: bool
[ "Filter", "for", "host", "Filter", "on", "label" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/util.py#L1165-L1182
train
Alignak-monitoring/alignak
alignak/worker.py
Worker.manage_signal
def manage_signal(self, sig, frame): # pylint: disable=unused-argument """Manage signals caught by the process but I do not do anything... our master daemon is managing our termination. :param sig: signal caught by daemon :type sig: str :param frame: current stack frame :type frame: :return: None """ logger.info("worker '%s' (pid=%d) received a signal: %s", self._id, os.getpid(), SIGNALS_TO_NAMES_DICT[sig]) # Do not do anything... our master daemon is managing our termination. self.interrupted = True
python
def manage_signal(self, sig, frame): # pylint: disable=unused-argument """Manage signals caught by the process but I do not do anything... our master daemon is managing our termination. :param sig: signal caught by daemon :type sig: str :param frame: current stack frame :type frame: :return: None """ logger.info("worker '%s' (pid=%d) received a signal: %s", self._id, os.getpid(), SIGNALS_TO_NAMES_DICT[sig]) # Do not do anything... our master daemon is managing our termination. self.interrupted = True
[ "def", "manage_signal", "(", "self", ",", "sig", ",", "frame", ")", ":", "# pylint: disable=unused-argument", "logger", ".", "info", "(", "\"worker '%s' (pid=%d) received a signal: %s\"", ",", "self", ".", "_id", ",", "os", ".", "getpid", "(", ")", ",", "SIGNALS_TO_NAMES_DICT", "[", "sig", "]", ")", "# Do not do anything... our master daemon is managing our termination.", "self", ".", "interrupted", "=", "True" ]
Manage signals caught by the process but I do not do anything... our master daemon is managing our termination. :param sig: signal caught by daemon :type sig: str :param frame: current stack frame :type frame: :return: None
[ "Manage", "signals", "caught", "by", "the", "process", "but", "I", "do", "not", "do", "anything", "...", "our", "master", "daemon", "is", "managing", "our", "termination", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/worker.py#L183-L196
train
Alignak-monitoring/alignak
alignak/worker.py
Worker.check_for_system_time_change
def check_for_system_time_change(self): # pragma: no cover, hardly testable with unit tests... """Check if our system time change. If so, change our :return: 0 if the difference < 900, difference else :rtype: int """ now = time.time() difference = now - self.t_each_loop # Now set the new value for the tick loop self.t_each_loop = now # If we have more than 15 min time change, we need to compensate it # todo: confirm that 15 minutes is a good choice... if abs(difference) > 900: # pragma: no cover, not with unit tests... return difference return 0
python
def check_for_system_time_change(self): # pragma: no cover, hardly testable with unit tests... """Check if our system time change. If so, change our :return: 0 if the difference < 900, difference else :rtype: int """ now = time.time() difference = now - self.t_each_loop # Now set the new value for the tick loop self.t_each_loop = now # If we have more than 15 min time change, we need to compensate it # todo: confirm that 15 minutes is a good choice... if abs(difference) > 900: # pragma: no cover, not with unit tests... return difference return 0
[ "def", "check_for_system_time_change", "(", "self", ")", ":", "# pragma: no cover, hardly testable with unit tests...", "now", "=", "time", ".", "time", "(", ")", "difference", "=", "now", "-", "self", ".", "t_each_loop", "# Now set the new value for the tick loop", "self", ".", "t_each_loop", "=", "now", "# If we have more than 15 min time change, we need to compensate it", "# todo: confirm that 15 minutes is a good choice...", "if", "abs", "(", "difference", ")", ">", "900", ":", "# pragma: no cover, not with unit tests...", "return", "difference", "return", "0" ]
Check if our system time change. If so, change our :return: 0 if the difference < 900, difference else :rtype: int
[ "Check", "if", "our", "system", "time", "change", ".", "If", "so", "change", "our" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/worker.py#L343-L360
train
Alignak-monitoring/alignak
alignak/worker.py
Worker.work
def work(self, actions_queue, returns_queue, control_queue=None): # pragma: no cover """Wrapper function for do_work in order to catch the exception to see the real work, look at do_work :param actions_queue: Global Queue Master->Slave :type actions_queue: Queue.Queue :param returns_queue: queue managed by manager :type returns_queue: Queue.Queue :return: None """ try: logger.info("[%s] (pid=%d) starting my job...", self._id, os.getpid()) self.do_work(actions_queue, returns_queue, control_queue) logger.info("[%s] (pid=%d) stopped", self._id, os.getpid()) except ActionError as exp: logger.error("[%s] exited with an ActionError exception : %s", self._id, str(exp)) logger.exception(exp) raise # Catch any exception, log the exception and exit anyway except Exception as exp: # pragma: no cover, this should never happen indeed ;) logger.error("[%s] exited with an unmanaged exception : %s", self._id, str(exp)) logger.exception(exp) raise
python
def work(self, actions_queue, returns_queue, control_queue=None): # pragma: no cover """Wrapper function for do_work in order to catch the exception to see the real work, look at do_work :param actions_queue: Global Queue Master->Slave :type actions_queue: Queue.Queue :param returns_queue: queue managed by manager :type returns_queue: Queue.Queue :return: None """ try: logger.info("[%s] (pid=%d) starting my job...", self._id, os.getpid()) self.do_work(actions_queue, returns_queue, control_queue) logger.info("[%s] (pid=%d) stopped", self._id, os.getpid()) except ActionError as exp: logger.error("[%s] exited with an ActionError exception : %s", self._id, str(exp)) logger.exception(exp) raise # Catch any exception, log the exception and exit anyway except Exception as exp: # pragma: no cover, this should never happen indeed ;) logger.error("[%s] exited with an unmanaged exception : %s", self._id, str(exp)) logger.exception(exp) raise
[ "def", "work", "(", "self", ",", "actions_queue", ",", "returns_queue", ",", "control_queue", "=", "None", ")", ":", "# pragma: no cover", "try", ":", "logger", ".", "info", "(", "\"[%s] (pid=%d) starting my job...\"", ",", "self", ".", "_id", ",", "os", ".", "getpid", "(", ")", ")", "self", ".", "do_work", "(", "actions_queue", ",", "returns_queue", ",", "control_queue", ")", "logger", ".", "info", "(", "\"[%s] (pid=%d) stopped\"", ",", "self", ".", "_id", ",", "os", ".", "getpid", "(", ")", ")", "except", "ActionError", "as", "exp", ":", "logger", ".", "error", "(", "\"[%s] exited with an ActionError exception : %s\"", ",", "self", ".", "_id", ",", "str", "(", "exp", ")", ")", "logger", ".", "exception", "(", "exp", ")", "raise", "# Catch any exception, log the exception and exit anyway", "except", "Exception", "as", "exp", ":", "# pragma: no cover, this should never happen indeed ;)", "logger", ".", "error", "(", "\"[%s] exited with an unmanaged exception : %s\"", ",", "self", ".", "_id", ",", "str", "(", "exp", ")", ")", "logger", ".", "exception", "(", "exp", ")", "raise" ]
Wrapper function for do_work in order to catch the exception to see the real work, look at do_work :param actions_queue: Global Queue Master->Slave :type actions_queue: Queue.Queue :param returns_queue: queue managed by manager :type returns_queue: Queue.Queue :return: None
[ "Wrapper", "function", "for", "do_work", "in", "order", "to", "catch", "the", "exception", "to", "see", "the", "real", "work", "look", "at", "do_work" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/worker.py#L362-L384
train
Alignak-monitoring/alignak
setup.py
read_requirements
def read_requirements(filename='requirements.txt'): """Reads the list of requirements from given file. :param filename: Filename to read the requirements from. Uses ``'requirements.txt'`` by default. :return: Requirments as list of strings. """ # allow for some leeway with the argument if not filename.startswith('requirements'): filename = 'requirements-' + filename if not os.path.splitext(filename)[1]: filename += '.txt' # no extension, add default def valid_line(line): line = line.strip() return line and not any(line.startswith(p) for p in ('#', '-')) def extract_requirement(line): egg_eq = '#egg=' if egg_eq in line: _, requirement = line.split(egg_eq, 1) return requirement return line with open(filename) as f: lines = f.readlines() return list(map(extract_requirement, filter(valid_line, lines)))
python
def read_requirements(filename='requirements.txt'): """Reads the list of requirements from given file. :param filename: Filename to read the requirements from. Uses ``'requirements.txt'`` by default. :return: Requirments as list of strings. """ # allow for some leeway with the argument if not filename.startswith('requirements'): filename = 'requirements-' + filename if not os.path.splitext(filename)[1]: filename += '.txt' # no extension, add default def valid_line(line): line = line.strip() return line and not any(line.startswith(p) for p in ('#', '-')) def extract_requirement(line): egg_eq = '#egg=' if egg_eq in line: _, requirement = line.split(egg_eq, 1) return requirement return line with open(filename) as f: lines = f.readlines() return list(map(extract_requirement, filter(valid_line, lines)))
[ "def", "read_requirements", "(", "filename", "=", "'requirements.txt'", ")", ":", "# allow for some leeway with the argument", "if", "not", "filename", ".", "startswith", "(", "'requirements'", ")", ":", "filename", "=", "'requirements-'", "+", "filename", "if", "not", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", ":", "filename", "+=", "'.txt'", "# no extension, add default", "def", "valid_line", "(", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "return", "line", "and", "not", "any", "(", "line", ".", "startswith", "(", "p", ")", "for", "p", "in", "(", "'#'", ",", "'-'", ")", ")", "def", "extract_requirement", "(", "line", ")", ":", "egg_eq", "=", "'#egg='", "if", "egg_eq", "in", "line", ":", "_", ",", "requirement", "=", "line", ".", "split", "(", "egg_eq", ",", "1", ")", "return", "requirement", "return", "line", "with", "open", "(", "filename", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "return", "list", "(", "map", "(", "extract_requirement", ",", "filter", "(", "valid_line", ",", "lines", ")", ")", ")" ]
Reads the list of requirements from given file. :param filename: Filename to read the requirements from. Uses ``'requirements.txt'`` by default. :return: Requirments as list of strings.
[ "Reads", "the", "list", "of", "requirements", "from", "given", "file", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/setup.py#L21-L48
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.init_running_properties
def init_running_properties(self): """ Initialize the running_properties. Each instance have own property. :return: None """ for prop, entry in list(self.__class__.running_properties.items()): val = entry.default # Make a copy of the value for complex iterable types # As such, each instance has its own copy and not a simple reference setattr(self, prop, copy(val) if isinstance(val, (set, list, dict)) else val)
python
def init_running_properties(self): """ Initialize the running_properties. Each instance have own property. :return: None """ for prop, entry in list(self.__class__.running_properties.items()): val = entry.default # Make a copy of the value for complex iterable types # As such, each instance has its own copy and not a simple reference setattr(self, prop, copy(val) if isinstance(val, (set, list, dict)) else val)
[ "def", "init_running_properties", "(", "self", ")", ":", "for", "prop", ",", "entry", "in", "list", "(", "self", ".", "__class__", ".", "running_properties", ".", "items", "(", ")", ")", ":", "val", "=", "entry", ".", "default", "# Make a copy of the value for complex iterable types", "# As such, each instance has its own copy and not a simple reference", "setattr", "(", "self", ",", "prop", ",", "copy", "(", "val", ")", "if", "isinstance", "(", "val", ",", "(", "set", ",", "list", ",", "dict", ")", ")", "else", "val", ")" ]
Initialize the running_properties. Each instance have own property. :return: None
[ "Initialize", "the", "running_properties", ".", "Each", "instance", "have", "own", "property", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L247-L258
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.copy
def copy(self): """ Get a copy of this item but with a new id :return: copy of this object with a new id :rtype: object """ # New dummy item with it's own running properties copied_item = self.__class__({}) # Now, copy the properties for prop in self.__class__.properties: if prop in ['uuid']: continue val = getattr(self, prop, None) if val is not None: setattr(copied_item, prop, val) # Also copy some running properties # The custom variables if hasattr(self, "customs"): copied_item.customs = copy(self.customs) # And tags/templates if hasattr(self, "tags"): copied_item.tags = copy(self.tags) if hasattr(self, "templates"): copied_item.templates = copy(self.templates) return copied_item
python
def copy(self): """ Get a copy of this item but with a new id :return: copy of this object with a new id :rtype: object """ # New dummy item with it's own running properties copied_item = self.__class__({}) # Now, copy the properties for prop in self.__class__.properties: if prop in ['uuid']: continue val = getattr(self, prop, None) if val is not None: setattr(copied_item, prop, val) # Also copy some running properties # The custom variables if hasattr(self, "customs"): copied_item.customs = copy(self.customs) # And tags/templates if hasattr(self, "tags"): copied_item.tags = copy(self.tags) if hasattr(self, "templates"): copied_item.templates = copy(self.templates) return copied_item
[ "def", "copy", "(", "self", ")", ":", "# New dummy item with it's own running properties", "copied_item", "=", "self", ".", "__class__", "(", "{", "}", ")", "# Now, copy the properties", "for", "prop", "in", "self", ".", "__class__", ".", "properties", ":", "if", "prop", "in", "[", "'uuid'", "]", ":", "continue", "val", "=", "getattr", "(", "self", ",", "prop", ",", "None", ")", "if", "val", "is", "not", "None", ":", "setattr", "(", "copied_item", ",", "prop", ",", "val", ")", "# Also copy some running properties", "# The custom variables", "if", "hasattr", "(", "self", ",", "\"customs\"", ")", ":", "copied_item", ".", "customs", "=", "copy", "(", "self", ".", "customs", ")", "# And tags/templates", "if", "hasattr", "(", "self", ",", "\"tags\"", ")", ":", "copied_item", ".", "tags", "=", "copy", "(", "self", ".", "tags", ")", "if", "hasattr", "(", "self", ",", "\"templates\"", ")", ":", "copied_item", ".", "templates", "=", "copy", "(", "self", ".", "templates", ")", "return", "copied_item" ]
Get a copy of this item but with a new id :return: copy of this object with a new id :rtype: object
[ "Get", "a", "copy", "of", "this", "item", "but", "with", "a", "new", "id" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L260-L287
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.clean
def clean(self): """ Clean properties only needed for initialization and configuration :return: None """ for prop in ('imported_from', 'use', 'plus', 'templates', 'register'): try: delattr(self, prop) except AttributeError: pass for prop in ('configuration_warnings', 'configuration_errors'): try: if getattr(self, prop, None) is not None and not getattr(self, prop): delattr(self, prop) except AttributeError: pass
python
def clean(self): """ Clean properties only needed for initialization and configuration :return: None """ for prop in ('imported_from', 'use', 'plus', 'templates', 'register'): try: delattr(self, prop) except AttributeError: pass for prop in ('configuration_warnings', 'configuration_errors'): try: if getattr(self, prop, None) is not None and not getattr(self, prop): delattr(self, prop) except AttributeError: pass
[ "def", "clean", "(", "self", ")", ":", "for", "prop", "in", "(", "'imported_from'", ",", "'use'", ",", "'plus'", ",", "'templates'", ",", "'register'", ")", ":", "try", ":", "delattr", "(", "self", ",", "prop", ")", "except", "AttributeError", ":", "pass", "for", "prop", "in", "(", "'configuration_warnings'", ",", "'configuration_errors'", ")", ":", "try", ":", "if", "getattr", "(", "self", ",", "prop", ",", "None", ")", "is", "not", "None", "and", "not", "getattr", "(", "self", ",", "prop", ")", ":", "delattr", "(", "self", ",", "prop", ")", "except", "AttributeError", ":", "pass" ]
Clean properties only needed for initialization and configuration :return: None
[ "Clean", "properties", "only", "needed", "for", "initialization", "and", "configuration" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L289-L305
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.load_global_conf
def load_global_conf(cls, global_configuration): """ Apply global Alignak configuration. Some objects inherit some properties from the global configuration if they do not define their own value. E.g. the global 'accept_passive_service_checks' is inherited by the services as 'accept_passive_checks' :param cls: parent object :type cls: object :param global_configuration: current object (child) :type global_configuration: object :return: None """ logger.debug("Propagate global parameter for %s:", cls) for prop, entry in global_configuration.properties.items(): # If some global managed configuration properties have a class_inherit clause, if not entry.managed or not getattr(entry, 'class_inherit'): continue for (cls_dest, change_name) in entry.class_inherit: if cls_dest == cls: # ok, we've got something to get value = getattr(global_configuration, prop) logger.debug("- global parameter %s=%s -> %s=%s", prop, getattr(global_configuration, prop), change_name, value) if change_name is None: setattr(cls, prop, value) else: setattr(cls, change_name, value)
python
def load_global_conf(cls, global_configuration): """ Apply global Alignak configuration. Some objects inherit some properties from the global configuration if they do not define their own value. E.g. the global 'accept_passive_service_checks' is inherited by the services as 'accept_passive_checks' :param cls: parent object :type cls: object :param global_configuration: current object (child) :type global_configuration: object :return: None """ logger.debug("Propagate global parameter for %s:", cls) for prop, entry in global_configuration.properties.items(): # If some global managed configuration properties have a class_inherit clause, if not entry.managed or not getattr(entry, 'class_inherit'): continue for (cls_dest, change_name) in entry.class_inherit: if cls_dest == cls: # ok, we've got something to get value = getattr(global_configuration, prop) logger.debug("- global parameter %s=%s -> %s=%s", prop, getattr(global_configuration, prop), change_name, value) if change_name is None: setattr(cls, prop, value) else: setattr(cls, change_name, value)
[ "def", "load_global_conf", "(", "cls", ",", "global_configuration", ")", ":", "logger", ".", "debug", "(", "\"Propagate global parameter for %s:\"", ",", "cls", ")", "for", "prop", ",", "entry", "in", "global_configuration", ".", "properties", ".", "items", "(", ")", ":", "# If some global managed configuration properties have a class_inherit clause,", "if", "not", "entry", ".", "managed", "or", "not", "getattr", "(", "entry", ",", "'class_inherit'", ")", ":", "continue", "for", "(", "cls_dest", ",", "change_name", ")", "in", "entry", ".", "class_inherit", ":", "if", "cls_dest", "==", "cls", ":", "# ok, we've got something to get", "value", "=", "getattr", "(", "global_configuration", ",", "prop", ")", "logger", ".", "debug", "(", "\"- global parameter %s=%s -> %s=%s\"", ",", "prop", ",", "getattr", "(", "global_configuration", ",", "prop", ")", ",", "change_name", ",", "value", ")", "if", "change_name", "is", "None", ":", "setattr", "(", "cls", ",", "prop", ",", "value", ")", "else", ":", "setattr", "(", "cls", ",", "change_name", ",", "value", ")" ]
Apply global Alignak configuration. Some objects inherit some properties from the global configuration if they do not define their own value. E.g. the global 'accept_passive_service_checks' is inherited by the services as 'accept_passive_checks' :param cls: parent object :type cls: object :param global_configuration: current object (child) :type global_configuration: object :return: None
[ "Apply", "global", "Alignak", "configuration", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L350-L378
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_templates
def get_templates(self): """ Get list of templates this object use :return: list of templates :rtype: list """ use = getattr(self, 'use', '') if isinstance(use, list): return [n.strip() for n in use if n.strip()] return [n.strip() for n in use.split(',') if n.strip()]
python
def get_templates(self): """ Get list of templates this object use :return: list of templates :rtype: list """ use = getattr(self, 'use', '') if isinstance(use, list): return [n.strip() for n in use if n.strip()] return [n.strip() for n in use.split(',') if n.strip()]
[ "def", "get_templates", "(", "self", ")", ":", "use", "=", "getattr", "(", "self", ",", "'use'", ",", "''", ")", "if", "isinstance", "(", "use", ",", "list", ")", ":", "return", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "use", "if", "n", ".", "strip", "(", ")", "]", "return", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "use", ".", "split", "(", "','", ")", "if", "n", ".", "strip", "(", ")", "]" ]
Get list of templates this object use :return: list of templates :rtype: list
[ "Get", "list", "of", "templates", "this", "object", "use" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L380-L391
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_all_plus_and_delete
def get_all_plus_and_delete(self): """ Get all self.plus items of list. We copy it, delete the original and return the copy list :return: list of self.plus :rtype: list """ res = {} props = list(self.plus.keys()) # we delete entries, so no for ... in ... for prop in props: res[prop] = self.get_plus_and_delete(prop) return res
python
def get_all_plus_and_delete(self): """ Get all self.plus items of list. We copy it, delete the original and return the copy list :return: list of self.plus :rtype: list """ res = {} props = list(self.plus.keys()) # we delete entries, so no for ... in ... for prop in props: res[prop] = self.get_plus_and_delete(prop) return res
[ "def", "get_all_plus_and_delete", "(", "self", ")", ":", "res", "=", "{", "}", "props", "=", "list", "(", "self", ".", "plus", ".", "keys", "(", ")", ")", "# we delete entries, so no for ... in ...", "for", "prop", "in", "props", ":", "res", "[", "prop", "]", "=", "self", ".", "get_plus_and_delete", "(", "prop", ")", "return", "res" ]
Get all self.plus items of list. We copy it, delete the original and return the copy list :return: list of self.plus :rtype: list
[ "Get", "all", "self", ".", "plus", "items", "of", "list", ".", "We", "copy", "it", "delete", "the", "original", "and", "return", "the", "copy", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L409-L420
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.add_error
def add_error(self, txt): """Add a message in the configuration errors list so we can print them all in one place Set the object configuration as not correct :param txt: error message :type txt: str :return: None """ self.configuration_errors.append(txt) self.conf_is_correct = False
python
def add_error(self, txt): """Add a message in the configuration errors list so we can print them all in one place Set the object configuration as not correct :param txt: error message :type txt: str :return: None """ self.configuration_errors.append(txt) self.conf_is_correct = False
[ "def", "add_error", "(", "self", ",", "txt", ")", ":", "self", ".", "configuration_errors", ".", "append", "(", "txt", ")", "self", ".", "conf_is_correct", "=", "False" ]
Add a message in the configuration errors list so we can print them all in one place Set the object configuration as not correct :param txt: error message :type txt: str :return: None
[ "Add", "a", "message", "in", "the", "configuration", "errors", "list", "so", "we", "can", "print", "them", "all", "in", "one", "place" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L436-L447
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.is_correct
def is_correct(self): """ Check if this object is correct This function: - checks if the required properties are defined, ignoring special_properties if some exist - logs the previously found warnings and errors :return: True if it's correct, otherwise False :rtype: bool """ state = self.conf_is_correct properties = self.__class__.properties for prop, entry in list(properties.items()): if hasattr(self, 'special_properties') and prop in getattr(self, 'special_properties'): continue if not hasattr(self, prop) and entry.required: msg = "[%s::%s] %s property is missing" % (self.my_type, self.get_name(), prop) self.add_error(msg) state = state & self.conf_is_correct return state
python
def is_correct(self): """ Check if this object is correct This function: - checks if the required properties are defined, ignoring special_properties if some exist - logs the previously found warnings and errors :return: True if it's correct, otherwise False :rtype: bool """ state = self.conf_is_correct properties = self.__class__.properties for prop, entry in list(properties.items()): if hasattr(self, 'special_properties') and prop in getattr(self, 'special_properties'): continue if not hasattr(self, prop) and entry.required: msg = "[%s::%s] %s property is missing" % (self.my_type, self.get_name(), prop) self.add_error(msg) state = state & self.conf_is_correct return state
[ "def", "is_correct", "(", "self", ")", ":", "state", "=", "self", ".", "conf_is_correct", "properties", "=", "self", ".", "__class__", ".", "properties", "for", "prop", ",", "entry", "in", "list", "(", "properties", ".", "items", "(", ")", ")", ":", "if", "hasattr", "(", "self", ",", "'special_properties'", ")", "and", "prop", "in", "getattr", "(", "self", ",", "'special_properties'", ")", ":", "continue", "if", "not", "hasattr", "(", "self", ",", "prop", ")", "and", "entry", ".", "required", ":", "msg", "=", "\"[%s::%s] %s property is missing\"", "%", "(", "self", ".", "my_type", ",", "self", ".", "get_name", "(", ")", ",", "prop", ")", "self", ".", "add_error", "(", "msg", ")", "state", "=", "state", "&", "self", ".", "conf_is_correct", "return", "state" ]
Check if this object is correct This function: - checks if the required properties are defined, ignoring special_properties if some exist - logs the previously found warnings and errors :return: True if it's correct, otherwise False :rtype: bool
[ "Check", "if", "this", "object", "is", "correct" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L459-L481
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.old_properties_names_to_new
def old_properties_names_to_new(self): """ This function is used by service and hosts to transform Nagios2 parameters to Nagios3 ones, like normal_check_interval to check_interval. There is a old_parameters tab in Classes that give such modifications to do. :return: None """ old_properties = getattr(self.__class__, "old_properties", {}) for old_name, new_name in list(old_properties.items()): # Ok, if we got old_name and NO new name, # we switch the name if hasattr(self, old_name) and not hasattr(self, new_name): value = getattr(self, old_name) setattr(self, new_name, value) delattr(self, old_name)
python
def old_properties_names_to_new(self): """ This function is used by service and hosts to transform Nagios2 parameters to Nagios3 ones, like normal_check_interval to check_interval. There is a old_parameters tab in Classes that give such modifications to do. :return: None """ old_properties = getattr(self.__class__, "old_properties", {}) for old_name, new_name in list(old_properties.items()): # Ok, if we got old_name and NO new name, # we switch the name if hasattr(self, old_name) and not hasattr(self, new_name): value = getattr(self, old_name) setattr(self, new_name, value) delattr(self, old_name)
[ "def", "old_properties_names_to_new", "(", "self", ")", ":", "old_properties", "=", "getattr", "(", "self", ".", "__class__", ",", "\"old_properties\"", ",", "{", "}", ")", "for", "old_name", ",", "new_name", "in", "list", "(", "old_properties", ".", "items", "(", ")", ")", ":", "# Ok, if we got old_name and NO new name,", "# we switch the name", "if", "hasattr", "(", "self", ",", "old_name", ")", "and", "not", "hasattr", "(", "self", ",", "new_name", ")", ":", "value", "=", "getattr", "(", "self", ",", "old_name", ")", "setattr", "(", "self", ",", "new_name", ",", "value", ")", "delattr", "(", "self", ",", "old_name", ")" ]
This function is used by service and hosts to transform Nagios2 parameters to Nagios3 ones, like normal_check_interval to check_interval. There is a old_parameters tab in Classes that give such modifications to do. :return: None
[ "This", "function", "is", "used", "by", "service", "and", "hosts", "to", "transform", "Nagios2", "parameters", "to", "Nagios3", "ones", "like", "normal_check_interval", "to", "check_interval", ".", "There", "is", "a", "old_parameters", "tab", "in", "Classes", "that", "give", "such", "modifications", "to", "do", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L483-L498
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_raw_import_values
def get_raw_import_values(self): # pragma: no cover, never used """ Get properties => values of this object TODO: never called anywhere, still useful? :return: dictionary of properties => values :rtype: dict """ res = {} properties = list(self.__class__.properties.keys()) # Register is not by default in the properties if 'register' not in properties: properties.append('register') for prop in properties: if hasattr(self, prop): val = getattr(self, prop) res[prop] = val return res
python
def get_raw_import_values(self): # pragma: no cover, never used """ Get properties => values of this object TODO: never called anywhere, still useful? :return: dictionary of properties => values :rtype: dict """ res = {} properties = list(self.__class__.properties.keys()) # Register is not by default in the properties if 'register' not in properties: properties.append('register') for prop in properties: if hasattr(self, prop): val = getattr(self, prop) res[prop] = val return res
[ "def", "get_raw_import_values", "(", "self", ")", ":", "# pragma: no cover, never used", "res", "=", "{", "}", "properties", "=", "list", "(", "self", ".", "__class__", ".", "properties", ".", "keys", "(", ")", ")", "# Register is not by default in the properties", "if", "'register'", "not", "in", "properties", ":", "properties", ".", "append", "(", "'register'", ")", "for", "prop", "in", "properties", ":", "if", "hasattr", "(", "self", ",", "prop", ")", ":", "val", "=", "getattr", "(", "self", ",", "prop", ")", "res", "[", "prop", "]", "=", "val", "return", "res" ]
Get properties => values of this object TODO: never called anywhere, still useful? :return: dictionary of properties => values :rtype: dict
[ "Get", "properties", "=", ">", "values", "of", "this", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L500-L519
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.del_downtime
def del_downtime(self, downtime_id): """ Delete a downtime in this object :param downtime_id: id of the downtime to delete :type downtime_id: int :return: None """ if downtime_id in self.downtimes: self.downtimes[downtime_id].can_be_deleted = True del self.downtimes[downtime_id]
python
def del_downtime(self, downtime_id): """ Delete a downtime in this object :param downtime_id: id of the downtime to delete :type downtime_id: int :return: None """ if downtime_id in self.downtimes: self.downtimes[downtime_id].can_be_deleted = True del self.downtimes[downtime_id]
[ "def", "del_downtime", "(", "self", ",", "downtime_id", ")", ":", "if", "downtime_id", "in", "self", ".", "downtimes", ":", "self", ".", "downtimes", "[", "downtime_id", "]", ".", "can_be_deleted", "=", "True", "del", "self", ".", "downtimes", "[", "downtime_id", "]" ]
Delete a downtime in this object :param downtime_id: id of the downtime to delete :type downtime_id: int :return: None
[ "Delete", "a", "downtime", "in", "this", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L531-L541
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_property_value_for_brok
def get_property_value_for_brok(self, prop, tab): """ Get the property of an object and brok_transformation if needed and return the value :param prop: property name :type prop: str :param tab: object with all properties of an object :type tab: object :return: value of the property original or brok converted :rtype: str """ entry = tab[prop] # Get the current value, or the default if need value = getattr(self, prop, entry.default) # Apply brok_transformation if need # Look if we must preprocess the value first pre_op = entry.brok_transformation if pre_op is not None: value = pre_op(self, value) return value
python
def get_property_value_for_brok(self, prop, tab): """ Get the property of an object and brok_transformation if needed and return the value :param prop: property name :type prop: str :param tab: object with all properties of an object :type tab: object :return: value of the property original or brok converted :rtype: str """ entry = tab[prop] # Get the current value, or the default if need value = getattr(self, prop, entry.default) # Apply brok_transformation if need # Look if we must preprocess the value first pre_op = entry.brok_transformation if pre_op is not None: value = pre_op(self, value) return value
[ "def", "get_property_value_for_brok", "(", "self", ",", "prop", ",", "tab", ")", ":", "entry", "=", "tab", "[", "prop", "]", "# Get the current value, or the default if need", "value", "=", "getattr", "(", "self", ",", "prop", ",", "entry", ".", "default", ")", "# Apply brok_transformation if need", "# Look if we must preprocess the value first", "pre_op", "=", "entry", ".", "brok_transformation", "if", "pre_op", "is", "not", "None", ":", "value", "=", "pre_op", "(", "self", ",", "value", ")", "return", "value" ]
Get the property of an object and brok_transformation if needed and return the value :param prop: property name :type prop: str :param tab: object with all properties of an object :type tab: object :return: value of the property original or brok converted :rtype: str
[ "Get", "the", "property", "of", "an", "object", "and", "brok_transformation", "if", "needed", "and", "return", "the", "value" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L564-L585
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.fill_data_brok_from
def fill_data_brok_from(self, data, brok_type): """ Add properties to 'data' parameter with properties of this object when 'brok_type' parameter is defined in fill_brok of these properties :param data: object to fill :type data: object :param brok_type: name of brok_type :type brok_type: var :return: None """ cls = self.__class__ # Configuration properties for prop, entry in list(cls.properties.items()): # Is this property intended for broking? if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.properties) # And the running properties if hasattr(cls, 'running_properties'): # We've got prop in running_properties too for prop, entry in list(cls.running_properties.items()): # if 'fill_brok' in cls.running_properties[prop]: if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.running_properties)
python
def fill_data_brok_from(self, data, brok_type): """ Add properties to 'data' parameter with properties of this object when 'brok_type' parameter is defined in fill_brok of these properties :param data: object to fill :type data: object :param brok_type: name of brok_type :type brok_type: var :return: None """ cls = self.__class__ # Configuration properties for prop, entry in list(cls.properties.items()): # Is this property intended for broking? if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.properties) # And the running properties if hasattr(cls, 'running_properties'): # We've got prop in running_properties too for prop, entry in list(cls.running_properties.items()): # if 'fill_brok' in cls.running_properties[prop]: if brok_type in entry.fill_brok: data[prop] = self.get_property_value_for_brok(prop, cls.running_properties)
[ "def", "fill_data_brok_from", "(", "self", ",", "data", ",", "brok_type", ")", ":", "cls", "=", "self", ".", "__class__", "# Configuration properties", "for", "prop", ",", "entry", "in", "list", "(", "cls", ".", "properties", ".", "items", "(", ")", ")", ":", "# Is this property intended for broking?", "if", "brok_type", "in", "entry", ".", "fill_brok", ":", "data", "[", "prop", "]", "=", "self", ".", "get_property_value_for_brok", "(", "prop", ",", "cls", ".", "properties", ")", "# And the running properties", "if", "hasattr", "(", "cls", ",", "'running_properties'", ")", ":", "# We've got prop in running_properties too", "for", "prop", ",", "entry", "in", "list", "(", "cls", ".", "running_properties", ".", "items", "(", ")", ")", ":", "# if 'fill_brok' in cls.running_properties[prop]:", "if", "brok_type", "in", "entry", ".", "fill_brok", ":", "data", "[", "prop", "]", "=", "self", ".", "get_property_value_for_brok", "(", "prop", ",", "cls", ".", "running_properties", ")" ]
Add properties to 'data' parameter with properties of this object when 'brok_type' parameter is defined in fill_brok of these properties :param data: object to fill :type data: object :param brok_type: name of brok_type :type brok_type: var :return: None
[ "Add", "properties", "to", "data", "parameter", "with", "properties", "of", "this", "object", "when", "brok_type", "parameter", "is", "defined", "in", "fill_brok", "of", "these", "properties" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L587-L611
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_initial_status_brok
def get_initial_status_brok(self, extra=None): """ Create an initial status brok :param extra: some extra information to be added in the brok data :type extra: dict :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'full_status') if extra: data.update(extra) return Brok({'type': 'initial_' + self.my_type + '_status', 'data': data})
python
def get_initial_status_brok(self, extra=None): """ Create an initial status brok :param extra: some extra information to be added in the brok data :type extra: dict :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'full_status') if extra: data.update(extra) return Brok({'type': 'initial_' + self.my_type + '_status', 'data': data})
[ "def", "get_initial_status_brok", "(", "self", ",", "extra", "=", "None", ")", ":", "data", "=", "{", "'uuid'", ":", "self", ".", "uuid", "}", "self", ".", "fill_data_brok_from", "(", "data", ",", "'full_status'", ")", "if", "extra", ":", "data", ".", "update", "(", "extra", ")", "return", "Brok", "(", "{", "'type'", ":", "'initial_'", "+", "self", ".", "my_type", "+", "'_status'", ",", "'data'", ":", "data", "}", ")" ]
Create an initial status brok :param extra: some extra information to be added in the brok data :type extra: dict :return: Brok object :rtype: alignak.Brok
[ "Create", "an", "initial", "status", "brok" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L613-L626
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_update_status_brok
def get_update_status_brok(self): """ Create an update item brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'full_status') return Brok({'type': 'update_' + self.my_type + '_status', 'data': data})
python
def get_update_status_brok(self): """ Create an update item brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'full_status') return Brok({'type': 'update_' + self.my_type + '_status', 'data': data})
[ "def", "get_update_status_brok", "(", "self", ")", ":", "data", "=", "{", "'uuid'", ":", "self", ".", "uuid", "}", "self", ".", "fill_data_brok_from", "(", "data", ",", "'full_status'", ")", "return", "Brok", "(", "{", "'type'", ":", "'update_'", "+", "self", ".", "my_type", "+", "'_status'", ",", "'data'", ":", "data", "}", ")" ]
Create an update item brok :return: Brok object :rtype: alignak.Brok
[ "Create", "an", "update", "item", "brok" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L639-L648
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.get_check_result_brok
def get_check_result_brok(self): """ Create check_result brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'check_result') return Brok({'type': self.my_type + '_check_result', 'data': data})
python
def get_check_result_brok(self): """ Create check_result brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'check_result') return Brok({'type': self.my_type + '_check_result', 'data': data})
[ "def", "get_check_result_brok", "(", "self", ")", ":", "data", "=", "{", "'uuid'", ":", "self", ".", "uuid", "}", "self", ".", "fill_data_brok_from", "(", "data", ",", "'check_result'", ")", "return", "Brok", "(", "{", "'type'", ":", "self", ".", "my_type", "+", "'_check_result'", ",", "'data'", ":", "data", "}", ")" ]
Create check_result brok :return: Brok object :rtype: alignak.Brok
[ "Create", "check_result", "brok" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L650-L659
train
Alignak-monitoring/alignak
alignak/objects/item.py
Item.dump
def dump(self, dump_file_name=None): # pragma: no cover, never called # pylint: disable=unused-argument """ Dump Item object properties :return: dictionary with properties :rtype: dict """ dump = {} for prop in self.properties: if not hasattr(self, prop): continue attr = getattr(self, prop) if isinstance(attr, list) and attr and isinstance(attr[0], Item): dump[prop] = [i.dump() for i in attr] elif isinstance(attr, Item): dump[prop] = attr.dump() elif attr: dump[prop] = getattr(self, prop) return dump
python
def dump(self, dump_file_name=None): # pragma: no cover, never called # pylint: disable=unused-argument """ Dump Item object properties :return: dictionary with properties :rtype: dict """ dump = {} for prop in self.properties: if not hasattr(self, prop): continue attr = getattr(self, prop) if isinstance(attr, list) and attr and isinstance(attr[0], Item): dump[prop] = [i.dump() for i in attr] elif isinstance(attr, Item): dump[prop] = attr.dump() elif attr: dump[prop] = getattr(self, prop) return dump
[ "def", "dump", "(", "self", ",", "dump_file_name", "=", "None", ")", ":", "# pragma: no cover, never called", "# pylint: disable=unused-argument", "dump", "=", "{", "}", "for", "prop", "in", "self", ".", "properties", ":", "if", "not", "hasattr", "(", "self", ",", "prop", ")", ":", "continue", "attr", "=", "getattr", "(", "self", ",", "prop", ")", "if", "isinstance", "(", "attr", ",", "list", ")", "and", "attr", "and", "isinstance", "(", "attr", "[", "0", "]", ",", "Item", ")", ":", "dump", "[", "prop", "]", "=", "[", "i", ".", "dump", "(", ")", "for", "i", "in", "attr", "]", "elif", "isinstance", "(", "attr", ",", "Item", ")", ":", "dump", "[", "prop", "]", "=", "attr", ".", "dump", "(", ")", "elif", "attr", ":", "dump", "[", "prop", "]", "=", "getattr", "(", "self", ",", "prop", ")", "return", "dump" ]
Dump Item object properties :return: dictionary with properties :rtype: dict
[ "Dump", "Item", "object", "properties" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L692-L711
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.add_items
def add_items(self, items, index_items): """ Add items to template if is template, else add in item list :param items: items list to add :type items: alignak.objects.item.Items :param index_items: Flag indicating if the items should be indexed on the fly. :type index_items: bool :return: None """ count_templates = 0 count_items = 0 generated_items = [] for item in items: if item.is_tpl(): self.add_template(item) count_templates = count_templates + 1 else: new_items = self.add_item(item, index_items) count_items = count_items + max(1, len(new_items)) if new_items: generated_items.extend(new_items) if count_templates: logger.info(' indexed %d template(s)', count_templates) if count_items: logger.info(' created %d %s(s).', count_items, self.inner_class.my_type)
python
def add_items(self, items, index_items): """ Add items to template if is template, else add in item list :param items: items list to add :type items: alignak.objects.item.Items :param index_items: Flag indicating if the items should be indexed on the fly. :type index_items: bool :return: None """ count_templates = 0 count_items = 0 generated_items = [] for item in items: if item.is_tpl(): self.add_template(item) count_templates = count_templates + 1 else: new_items = self.add_item(item, index_items) count_items = count_items + max(1, len(new_items)) if new_items: generated_items.extend(new_items) if count_templates: logger.info(' indexed %d template(s)', count_templates) if count_items: logger.info(' created %d %s(s).', count_items, self.inner_class.my_type)
[ "def", "add_items", "(", "self", ",", "items", ",", "index_items", ")", ":", "count_templates", "=", "0", "count_items", "=", "0", "generated_items", "=", "[", "]", "for", "item", "in", "items", ":", "if", "item", ".", "is_tpl", "(", ")", ":", "self", ".", "add_template", "(", "item", ")", "count_templates", "=", "count_templates", "+", "1", "else", ":", "new_items", "=", "self", ".", "add_item", "(", "item", ",", "index_items", ")", "count_items", "=", "count_items", "+", "max", "(", "1", ",", "len", "(", "new_items", ")", ")", "if", "new_items", ":", "generated_items", ".", "extend", "(", "new_items", ")", "if", "count_templates", ":", "logger", ".", "info", "(", "' indexed %d template(s)'", ",", "count_templates", ")", "if", "count_items", ":", "logger", ".", "info", "(", "' created %d %s(s).'", ",", "count_items", ",", "self", ".", "inner_class", ".", "my_type", ")" ]
Add items to template if is template, else add in item list :param items: items list to add :type items: alignak.objects.item.Items :param index_items: Flag indicating if the items should be indexed on the fly. :type index_items: bool :return: None
[ "Add", "items", "to", "template", "if", "is", "template", "else", "add", "in", "item", "list" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L816-L841
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.manage_conflict
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
python
def manage_conflict(self, item, name): """ Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object """ if item.is_tpl(): existing = self.name_to_template[name] else: existing = self.name_to_item[name] if existing == item: return item existing_prio = getattr( existing, "definition_order", existing.properties["definition_order"].default) item_prio = getattr( item, "definition_order", item.properties["definition_order"].default) if existing_prio < item_prio: # Existing item has lower priority, so it has precedence. return existing if existing_prio > item_prio: # New item has lower priority, so it has precedence. # Existing item will be deleted below pass else: # Don't know which one to keep, lastly defined has precedence objcls = getattr(self.inner_class, "my_type", "[unknown]") mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \ "You may manually set the definition_order parameter to avoid this message." \ % (objcls, name, item.imported_from, existing.imported_from) item.configuration_warnings.append(mesg) if item.is_tpl(): self.remove_template(existing) else: self.remove_item(existing) return item
[ "def", "manage_conflict", "(", "self", ",", "item", ",", "name", ")", ":", "if", "item", ".", "is_tpl", "(", ")", ":", "existing", "=", "self", ".", "name_to_template", "[", "name", "]", "else", ":", "existing", "=", "self", ".", "name_to_item", "[", "name", "]", "if", "existing", "==", "item", ":", "return", "item", "existing_prio", "=", "getattr", "(", "existing", ",", "\"definition_order\"", ",", "existing", ".", "properties", "[", "\"definition_order\"", "]", ".", "default", ")", "item_prio", "=", "getattr", "(", "item", ",", "\"definition_order\"", ",", "item", ".", "properties", "[", "\"definition_order\"", "]", ".", "default", ")", "if", "existing_prio", "<", "item_prio", ":", "# Existing item has lower priority, so it has precedence.", "return", "existing", "if", "existing_prio", ">", "item_prio", ":", "# New item has lower priority, so it has precedence.", "# Existing item will be deleted below", "pass", "else", ":", "# Don't know which one to keep, lastly defined has precedence", "objcls", "=", "getattr", "(", "self", ".", "inner_class", ",", "\"my_type\"", ",", "\"[unknown]\"", ")", "mesg", "=", "\"duplicate %s '%s', from: '%s' and '%s', using lastly defined. \"", "\"You may manually set the definition_order parameter to avoid this message.\"", "%", "(", "objcls", ",", "name", ",", "item", ".", "imported_from", ",", "existing", ".", "imported_from", ")", "item", ".", "configuration_warnings", ".", "append", "(", "mesg", ")", "if", "item", ".", "is_tpl", "(", ")", ":", "self", ".", "remove_template", "(", "existing", ")", "else", ":", "self", ".", "remove_item", "(", "existing", ")", "return", "item" ]
Checks if an object holding the same name already exists in the index. If so, it compares their definition order: the lowest definition order is kept. If definition order equal, an error is risen.Item The method returns the item that should be added after it has decided which one should be kept. If the new item has precedence over the New existing one, the existing is removed for the new to replace it. :param item: object to check for conflict :type item: alignak.objects.item.Item :param name: name of the object :type name: str :return: 'item' parameter modified :rtype: object
[ "Checks", "if", "an", "object", "holding", "the", "same", "name", "already", "exists", "in", "the", "index", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L843-L896
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.add_template
def add_template(self, tpl): """ Add and index a template into the `templates` container. :param tpl: The template to add :type tpl: alignak.objects.item.Item :return: None """ tpl = self.index_template(tpl) self.templates[tpl.uuid] = tpl
python
def add_template(self, tpl): """ Add and index a template into the `templates` container. :param tpl: The template to add :type tpl: alignak.objects.item.Item :return: None """ tpl = self.index_template(tpl) self.templates[tpl.uuid] = tpl
[ "def", "add_template", "(", "self", ",", "tpl", ")", ":", "tpl", "=", "self", ".", "index_template", "(", "tpl", ")", "self", ".", "templates", "[", "tpl", ".", "uuid", "]", "=", "tpl" ]
Add and index a template into the `templates` container. :param tpl: The template to add :type tpl: alignak.objects.item.Item :return: None
[ "Add", "and", "index", "a", "template", "into", "the", "templates", "container", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L898-L907
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.index_template
def index_template(self, tpl): """ Indexes a template by `name` into the `name_to_template` dictionary. :param tpl: The template to index :type tpl: alignak.objects.item.Item :return: None """ objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') if not name: mesg = "a %s template has been defined without name, from: %s" % \ (objcls, tpl.imported_from) tpl.add_error(mesg) elif name in self.name_to_template: tpl = self.manage_conflict(tpl, name) self.name_to_template[name] = tpl logger.debug("Indexed a %s template: %s, uses: %s", tpl.my_type, name, getattr(tpl, 'use', 'Nothing')) return tpl
python
def index_template(self, tpl): """ Indexes a template by `name` into the `name_to_template` dictionary. :param tpl: The template to index :type tpl: alignak.objects.item.Item :return: None """ objcls = self.inner_class.my_type name = getattr(tpl, 'name', '') if not name: mesg = "a %s template has been defined without name, from: %s" % \ (objcls, tpl.imported_from) tpl.add_error(mesg) elif name in self.name_to_template: tpl = self.manage_conflict(tpl, name) self.name_to_template[name] = tpl logger.debug("Indexed a %s template: %s, uses: %s", tpl.my_type, name, getattr(tpl, 'use', 'Nothing')) return tpl
[ "def", "index_template", "(", "self", ",", "tpl", ")", ":", "objcls", "=", "self", ".", "inner_class", ".", "my_type", "name", "=", "getattr", "(", "tpl", ",", "'name'", ",", "''", ")", "if", "not", "name", ":", "mesg", "=", "\"a %s template has been defined without name, from: %s\"", "%", "(", "objcls", ",", "tpl", ".", "imported_from", ")", "tpl", ".", "add_error", "(", "mesg", ")", "elif", "name", "in", "self", ".", "name_to_template", ":", "tpl", "=", "self", ".", "manage_conflict", "(", "tpl", ",", "name", ")", "self", ".", "name_to_template", "[", "name", "]", "=", "tpl", "logger", ".", "debug", "(", "\"Indexed a %s template: %s, uses: %s\"", ",", "tpl", ".", "my_type", ",", "name", ",", "getattr", "(", "tpl", ",", "'use'", ",", "'Nothing'", ")", ")", "return", "tpl" ]
Indexes a template by `name` into the `name_to_template` dictionary. :param tpl: The template to index :type tpl: alignak.objects.item.Item :return: None
[ "Indexes", "a", "template", "by", "name", "into", "the", "name_to_template", "dictionary", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L909-L928
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.remove_template
def remove_template(self, tpl): """ Removes and un-index a template from the `templates` container. :param tpl: The template to remove :type tpl: alignak.objects.item.Item :return: None """ try: del self.templates[tpl.uuid] except KeyError: # pragma: no cover, simple protection pass self.unindex_template(tpl)
python
def remove_template(self, tpl): """ Removes and un-index a template from the `templates` container. :param tpl: The template to remove :type tpl: alignak.objects.item.Item :return: None """ try: del self.templates[tpl.uuid] except KeyError: # pragma: no cover, simple protection pass self.unindex_template(tpl)
[ "def", "remove_template", "(", "self", ",", "tpl", ")", ":", "try", ":", "del", "self", ".", "templates", "[", "tpl", ".", "uuid", "]", "except", "KeyError", ":", "# pragma: no cover, simple protection", "pass", "self", ".", "unindex_template", "(", "tpl", ")" ]
Removes and un-index a template from the `templates` container. :param tpl: The template to remove :type tpl: alignak.objects.item.Item :return: None
[ "Removes", "and", "un", "-", "index", "a", "template", "from", "the", "templates", "container", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L930-L942
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.unindex_template
def unindex_template(self, tpl): """ Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None """ name = getattr(tpl, 'name', '') try: del self.name_to_template[name] except KeyError: # pragma: no cover, simple protection pass
python
def unindex_template(self, tpl): """ Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None """ name = getattr(tpl, 'name', '') try: del self.name_to_template[name] except KeyError: # pragma: no cover, simple protection pass
[ "def", "unindex_template", "(", "self", ",", "tpl", ")", ":", "name", "=", "getattr", "(", "tpl", ",", "'name'", ",", "''", ")", "try", ":", "del", "self", ".", "name_to_template", "[", "name", "]", "except", "KeyError", ":", "# pragma: no cover, simple protection", "pass" ]
Unindex a template from the `templates` container. :param tpl: The template to un-index :type tpl: alignak.objects.item.Item :return: None
[ "Unindex", "a", "template", "from", "the", "templates", "container", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L944-L956
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.add_item
def add_item(self, item, index=True): # pylint: disable=too-many-branches, too-many-locals, too-many-nested-blocks """ Add an item into our containers, and index it depending on the `index` flag. :param item: object to add :type item: alignak.objects.item.Item :param index: Flag indicating if the item should be indexed :type index: bool :return: the new items created :rtype list """ name_property = getattr(self.__class__, "name_property", None) # Check if some hosts are to be self-generated... generated_hosts = [] if name_property: name = getattr(item, name_property, None) if name and '[' in name and ']' in name: # We can create several objects from the same configuration! pattern = name[name.find("[")+1:name.find("]")] if '-' in pattern: logger.debug("Found an host with a patterned name: %s", pattern) # pattern is format-min-max # format is optional limits = pattern.split('-') fmt = "%d" min_v = 1 max_v = 1 if len(limits) == 3: fmt = limits[2] new_name = name.replace('[%s-%s-%s]' % (limits[0], limits[1], fmt), '***') else: new_name = name.replace('[%s-%s]' % (limits[0], limits[1]), '***') try: min_v = int(limits[0]) except ValueError: pass try: max_v = int(limits[1]) except ValueError: pass for idx in range(min_v, max_v + 1): logger.debug("- cloning host: %s", new_name.replace('***', fmt % idx)) new_host = deepcopy(item) new_host.uuid = get_a_new_object_id() new_host.host_name = new_name.replace('***', fmt % idx) # Update some fields with the newly generated host name for prop in ['display_name', 'alias', 'notes', 'notes_url', 'action_url']: if getattr(new_host, prop, None) is None: continue value = getattr(new_host, prop) if '$HOSTNAME$' in value: setattr(new_host, prop, value.replace('$HOSTNAME$', new_host.host_name)) generated_hosts.append(new_host) if generated_hosts: for new_host in generated_hosts: if index is True: new_host = self.index_item(new_host) self.items[new_host.uuid] = new_host logger.info(" cloned %d hosts from %s", len(generated_hosts), item.get_name()) else: if index is True and name_property: item = self.index_item(item) self.items[item.uuid] = item return generated_hosts
python
def add_item(self, item, index=True): # pylint: disable=too-many-branches, too-many-locals, too-many-nested-blocks """ Add an item into our containers, and index it depending on the `index` flag. :param item: object to add :type item: alignak.objects.item.Item :param index: Flag indicating if the item should be indexed :type index: bool :return: the new items created :rtype list """ name_property = getattr(self.__class__, "name_property", None) # Check if some hosts are to be self-generated... generated_hosts = [] if name_property: name = getattr(item, name_property, None) if name and '[' in name and ']' in name: # We can create several objects from the same configuration! pattern = name[name.find("[")+1:name.find("]")] if '-' in pattern: logger.debug("Found an host with a patterned name: %s", pattern) # pattern is format-min-max # format is optional limits = pattern.split('-') fmt = "%d" min_v = 1 max_v = 1 if len(limits) == 3: fmt = limits[2] new_name = name.replace('[%s-%s-%s]' % (limits[0], limits[1], fmt), '***') else: new_name = name.replace('[%s-%s]' % (limits[0], limits[1]), '***') try: min_v = int(limits[0]) except ValueError: pass try: max_v = int(limits[1]) except ValueError: pass for idx in range(min_v, max_v + 1): logger.debug("- cloning host: %s", new_name.replace('***', fmt % idx)) new_host = deepcopy(item) new_host.uuid = get_a_new_object_id() new_host.host_name = new_name.replace('***', fmt % idx) # Update some fields with the newly generated host name for prop in ['display_name', 'alias', 'notes', 'notes_url', 'action_url']: if getattr(new_host, prop, None) is None: continue value = getattr(new_host, prop) if '$HOSTNAME$' in value: setattr(new_host, prop, value.replace('$HOSTNAME$', new_host.host_name)) generated_hosts.append(new_host) if generated_hosts: for new_host in generated_hosts: if index is True: new_host = self.index_item(new_host) self.items[new_host.uuid] = new_host logger.info(" cloned %d hosts from %s", len(generated_hosts), item.get_name()) else: if index is True and name_property: item = self.index_item(item) self.items[item.uuid] = item return generated_hosts
[ "def", "add_item", "(", "self", ",", "item", ",", "index", "=", "True", ")", ":", "# pylint: disable=too-many-branches, too-many-locals, too-many-nested-blocks", "name_property", "=", "getattr", "(", "self", ".", "__class__", ",", "\"name_property\"", ",", "None", ")", "# Check if some hosts are to be self-generated...", "generated_hosts", "=", "[", "]", "if", "name_property", ":", "name", "=", "getattr", "(", "item", ",", "name_property", ",", "None", ")", "if", "name", "and", "'['", "in", "name", "and", "']'", "in", "name", ":", "# We can create several objects from the same configuration!", "pattern", "=", "name", "[", "name", ".", "find", "(", "\"[\"", ")", "+", "1", ":", "name", ".", "find", "(", "\"]\"", ")", "]", "if", "'-'", "in", "pattern", ":", "logger", ".", "debug", "(", "\"Found an host with a patterned name: %s\"", ",", "pattern", ")", "# pattern is format-min-max", "# format is optional", "limits", "=", "pattern", ".", "split", "(", "'-'", ")", "fmt", "=", "\"%d\"", "min_v", "=", "1", "max_v", "=", "1", "if", "len", "(", "limits", ")", "==", "3", ":", "fmt", "=", "limits", "[", "2", "]", "new_name", "=", "name", ".", "replace", "(", "'[%s-%s-%s]'", "%", "(", "limits", "[", "0", "]", ",", "limits", "[", "1", "]", ",", "fmt", ")", ",", "'***'", ")", "else", ":", "new_name", "=", "name", ".", "replace", "(", "'[%s-%s]'", "%", "(", "limits", "[", "0", "]", ",", "limits", "[", "1", "]", ")", ",", "'***'", ")", "try", ":", "min_v", "=", "int", "(", "limits", "[", "0", "]", ")", "except", "ValueError", ":", "pass", "try", ":", "max_v", "=", "int", "(", "limits", "[", "1", "]", ")", "except", "ValueError", ":", "pass", "for", "idx", "in", "range", "(", "min_v", ",", "max_v", "+", "1", ")", ":", "logger", ".", "debug", "(", "\"- cloning host: %s\"", ",", "new_name", ".", "replace", "(", "'***'", ",", "fmt", "%", "idx", ")", ")", "new_host", "=", "deepcopy", "(", "item", ")", "new_host", ".", "uuid", "=", "get_a_new_object_id", "(", ")", "new_host", ".", "host_name", "=", "new_name", ".", "replace", "(", "'***'", ",", "fmt", "%", "idx", ")", "# Update some fields with the newly generated host name", "for", "prop", "in", "[", "'display_name'", ",", "'alias'", ",", "'notes'", ",", "'notes_url'", ",", "'action_url'", "]", ":", "if", "getattr", "(", "new_host", ",", "prop", ",", "None", ")", "is", "None", ":", "continue", "value", "=", "getattr", "(", "new_host", ",", "prop", ")", "if", "'$HOSTNAME$'", "in", "value", ":", "setattr", "(", "new_host", ",", "prop", ",", "value", ".", "replace", "(", "'$HOSTNAME$'", ",", "new_host", ".", "host_name", ")", ")", "generated_hosts", ".", "append", "(", "new_host", ")", "if", "generated_hosts", ":", "for", "new_host", "in", "generated_hosts", ":", "if", "index", "is", "True", ":", "new_host", "=", "self", ".", "index_item", "(", "new_host", ")", "self", ".", "items", "[", "new_host", ".", "uuid", "]", "=", "new_host", "logger", ".", "info", "(", "\" cloned %d hosts from %s\"", ",", "len", "(", "generated_hosts", ")", ",", "item", ".", "get_name", "(", ")", ")", "else", ":", "if", "index", "is", "True", "and", "name_property", ":", "item", "=", "self", ".", "index_item", "(", "item", ")", "self", ".", "items", "[", "item", ".", "uuid", "]", "=", "item", "return", "generated_hosts" ]
Add an item into our containers, and index it depending on the `index` flag. :param item: object to add :type item: alignak.objects.item.Item :param index: Flag indicating if the item should be indexed :type index: bool :return: the new items created :rtype list
[ "Add", "an", "item", "into", "our", "containers", "and", "index", "it", "depending", "on", "the", "index", "flag", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L958-L1029
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.old_properties_names_to_new
def old_properties_names_to_new(self): # pragma: no cover, never called """Convert old Nagios2 names to Nagios3 new names TODO: still useful? :return: None """ for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): i.old_properties_names_to_new()
python
def old_properties_names_to_new(self): # pragma: no cover, never called """Convert old Nagios2 names to Nagios3 new names TODO: still useful? :return: None """ for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): i.old_properties_names_to_new()
[ "def", "old_properties_names_to_new", "(", "self", ")", ":", "# pragma: no cover, never called", "for", "i", "in", "itertools", ".", "chain", "(", "iter", "(", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ")", ",", "iter", "(", "list", "(", "self", ".", "templates", ".", "values", "(", ")", ")", ")", ")", ":", "i", ".", "old_properties_names_to_new", "(", ")" ]
Convert old Nagios2 names to Nagios3 new names TODO: still useful? :return: None
[ "Convert", "old", "Nagios2", "names", "to", "Nagios3", "new", "names" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1092-L1101
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.get_all_tags
def get_all_tags(self, item): """ Get all tags of an item :param item: an item :type item: Item :return: list of tags :rtype: list """ all_tags = item.get_templates() for template_id in item.templates: template = self.templates[template_id] all_tags.append(template.name) all_tags.extend(self.get_all_tags(template)) return list(set(all_tags))
python
def get_all_tags(self, item): """ Get all tags of an item :param item: an item :type item: Item :return: list of tags :rtype: list """ all_tags = item.get_templates() for template_id in item.templates: template = self.templates[template_id] all_tags.append(template.name) all_tags.extend(self.get_all_tags(template)) return list(set(all_tags))
[ "def", "get_all_tags", "(", "self", ",", "item", ")", ":", "all_tags", "=", "item", ".", "get_templates", "(", ")", "for", "template_id", "in", "item", ".", "templates", ":", "template", "=", "self", ".", "templates", "[", "template_id", "]", "all_tags", ".", "append", "(", "template", ".", "name", ")", "all_tags", ".", "extend", "(", "self", ".", "get_all_tags", "(", "template", ")", ")", "return", "list", "(", "set", "(", "all_tags", ")", ")" ]
Get all tags of an item :param item: an item :type item: Item :return: list of tags :rtype: list
[ "Get", "all", "tags", "of", "an", "item" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1114-L1129
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_templates
def linkify_templates(self): """ Link all templates, and create the template graph too :return: None """ # First we create a list of all templates for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): self.linkify_item_templates(i) for i in self: i.tags = self.get_all_tags(i)
python
def linkify_templates(self): """ Link all templates, and create the template graph too :return: None """ # First we create a list of all templates for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): self.linkify_item_templates(i) for i in self: i.tags = self.get_all_tags(i)
[ "def", "linkify_templates", "(", "self", ")", ":", "# First we create a list of all templates", "for", "i", "in", "itertools", ".", "chain", "(", "iter", "(", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ")", ",", "iter", "(", "list", "(", "self", ".", "templates", ".", "values", "(", ")", ")", ")", ")", ":", "self", ".", "linkify_item_templates", "(", "i", ")", "for", "i", "in", "self", ":", "i", ".", "tags", "=", "self", ".", "get_all_tags", "(", "i", ")" ]
Link all templates, and create the template graph too :return: None
[ "Link", "all", "templates", "and", "create", "the", "template", "graph", "too" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1156-L1167
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.apply_partial_inheritance
def apply_partial_inheritance(self, prop): """ Define property with inheritance value of the property :param prop: property :type prop: str :return: None """ for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): self.get_property_by_inheritance(i, prop) # If a "null" attribute was inherited, delete it try: if getattr(i, prop) == 'null': delattr(i, prop) except AttributeError: # pragma: no cover, simple protection pass
python
def apply_partial_inheritance(self, prop): """ Define property with inheritance value of the property :param prop: property :type prop: str :return: None """ for i in itertools.chain(iter(list(self.items.values())), iter(list(self.templates.values()))): self.get_property_by_inheritance(i, prop) # If a "null" attribute was inherited, delete it try: if getattr(i, prop) == 'null': delattr(i, prop) except AttributeError: # pragma: no cover, simple protection pass
[ "def", "apply_partial_inheritance", "(", "self", ",", "prop", ")", ":", "for", "i", "in", "itertools", ".", "chain", "(", "iter", "(", "list", "(", "self", ".", "items", ".", "values", "(", ")", ")", ")", ",", "iter", "(", "list", "(", "self", ".", "templates", ".", "values", "(", ")", ")", ")", ")", ":", "self", ".", "get_property_by_inheritance", "(", "i", ",", "prop", ")", "# If a \"null\" attribute was inherited, delete it", "try", ":", "if", "getattr", "(", "i", ",", "prop", ")", "==", "'null'", ":", "delattr", "(", "i", ",", "prop", ")", "except", "AttributeError", ":", "# pragma: no cover, simple protection", "pass" ]
Define property with inheritance value of the property :param prop: property :type prop: str :return: None
[ "Define", "property", "with", "inheritance", "value", "of", "the", "property" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1258-L1274
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_with_contacts
def linkify_with_contacts(self, contacts): """ Link items with contacts items :param contacts: all contacts object :type contacts: alignak.objects.contact.Contacts :return: None """ for i in self: if not hasattr(i, 'contacts'): continue links_list = strip_and_uniq(i.contacts) new = [] for name in [e for e in links_list if e]: contact = contacts.find_by_name(name) if contact is not None and contact.uuid not in new: new.append(contact.uuid) else: i.add_error("the contact '%s' defined for '%s' is unknown" % (name, i.get_name())) i.contacts = new
python
def linkify_with_contacts(self, contacts): """ Link items with contacts items :param contacts: all contacts object :type contacts: alignak.objects.contact.Contacts :return: None """ for i in self: if not hasattr(i, 'contacts'): continue links_list = strip_and_uniq(i.contacts) new = [] for name in [e for e in links_list if e]: contact = contacts.find_by_name(name) if contact is not None and contact.uuid not in new: new.append(contact.uuid) else: i.add_error("the contact '%s' defined for '%s' is unknown" % (name, i.get_name())) i.contacts = new
[ "def", "linkify_with_contacts", "(", "self", ",", "contacts", ")", ":", "for", "i", "in", "self", ":", "if", "not", "hasattr", "(", "i", ",", "'contacts'", ")", ":", "continue", "links_list", "=", "strip_and_uniq", "(", "i", ".", "contacts", ")", "new", "=", "[", "]", "for", "name", "in", "[", "e", "for", "e", "in", "links_list", "if", "e", "]", ":", "contact", "=", "contacts", ".", "find_by_name", "(", "name", ")", "if", "contact", "is", "not", "None", "and", "contact", ".", "uuid", "not", "in", "new", ":", "new", ".", "append", "(", "contact", ".", "uuid", ")", "else", ":", "i", ".", "add_error", "(", "\"the contact '%s' defined for '%s' is unknown\"", "%", "(", "name", ",", "i", ".", "get_name", "(", ")", ")", ")", "i", ".", "contacts", "=", "new" ]
Link items with contacts items :param contacts: all contacts object :type contacts: alignak.objects.contact.Contacts :return: None
[ "Link", "items", "with", "contacts", "items" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1291-L1313
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_with_escalations
def linkify_with_escalations(self, escalations): """ Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None """ for i in self: if not hasattr(i, 'escalations'): continue links_list = strip_and_uniq(i.escalations) new = [] for name in [e for e in links_list if e]: escalation = escalations.find_by_name(name) if escalation is not None and escalation.uuid not in new: new.append(escalation.uuid) else: i.add_error("the escalation '%s' defined for '%s' is unknown" % (name, i.get_name())) i.escalations = new
python
def linkify_with_escalations(self, escalations): """ Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None """ for i in self: if not hasattr(i, 'escalations'): continue links_list = strip_and_uniq(i.escalations) new = [] for name in [e for e in links_list if e]: escalation = escalations.find_by_name(name) if escalation is not None and escalation.uuid not in new: new.append(escalation.uuid) else: i.add_error("the escalation '%s' defined for '%s' is unknown" % (name, i.get_name())) i.escalations = new
[ "def", "linkify_with_escalations", "(", "self", ",", "escalations", ")", ":", "for", "i", "in", "self", ":", "if", "not", "hasattr", "(", "i", ",", "'escalations'", ")", ":", "continue", "links_list", "=", "strip_and_uniq", "(", "i", ".", "escalations", ")", "new", "=", "[", "]", "for", "name", "in", "[", "e", "for", "e", "in", "links_list", "if", "e", "]", ":", "escalation", "=", "escalations", ".", "find_by_name", "(", "name", ")", "if", "escalation", "is", "not", "None", "and", "escalation", ".", "uuid", "not", "in", "new", ":", "new", ".", "append", "(", "escalation", ".", "uuid", ")", "else", ":", "i", ".", "add_error", "(", "\"the escalation '%s' defined for '%s' is unknown\"", "%", "(", "name", ",", "i", ".", "get_name", "(", ")", ")", ")", "i", ".", "escalations", "=", "new" ]
Link with escalations :param escalations: all escalations object :type escalations: alignak.objects.escalation.Escalations :return: None
[ "Link", "with", "escalations" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1315-L1337
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.explode_contact_groups_into_contacts
def explode_contact_groups_into_contacts(item, contactgroups): """ Get all contacts of contact_groups and put them in contacts container :param item: item where have contact_groups property :type item: object :param contactgroups: all contactgroups object :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: None """ if not hasattr(item, 'contact_groups'): return # TODO : See if we can remove this if cgnames = '' if item.contact_groups: if isinstance(item.contact_groups, list): cgnames = item.contact_groups else: cgnames = item.contact_groups.split(',') cgnames = strip_and_uniq(cgnames) for cgname in cgnames: contactgroup = contactgroups.find_by_name(cgname) if not contactgroup: item.add_error("The contact group '%s' defined on the %s '%s' do not exist" % (cgname, item.__class__.my_type, item.get_name())) continue cnames = contactgroups.get_members_of_group(cgname) # We add contacts into our contacts if cnames: if hasattr(item, 'contacts'): # Fix #1054 - bad contact explosion # item.contacts.extend(cnames) item.contacts = item.contacts + cnames else: item.contacts = cnames
python
def explode_contact_groups_into_contacts(item, contactgroups): """ Get all contacts of contact_groups and put them in contacts container :param item: item where have contact_groups property :type item: object :param contactgroups: all contactgroups object :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: None """ if not hasattr(item, 'contact_groups'): return # TODO : See if we can remove this if cgnames = '' if item.contact_groups: if isinstance(item.contact_groups, list): cgnames = item.contact_groups else: cgnames = item.contact_groups.split(',') cgnames = strip_and_uniq(cgnames) for cgname in cgnames: contactgroup = contactgroups.find_by_name(cgname) if not contactgroup: item.add_error("The contact group '%s' defined on the %s '%s' do not exist" % (cgname, item.__class__.my_type, item.get_name())) continue cnames = contactgroups.get_members_of_group(cgname) # We add contacts into our contacts if cnames: if hasattr(item, 'contacts'): # Fix #1054 - bad contact explosion # item.contacts.extend(cnames) item.contacts = item.contacts + cnames else: item.contacts = cnames
[ "def", "explode_contact_groups_into_contacts", "(", "item", ",", "contactgroups", ")", ":", "if", "not", "hasattr", "(", "item", ",", "'contact_groups'", ")", ":", "return", "# TODO : See if we can remove this if", "cgnames", "=", "''", "if", "item", ".", "contact_groups", ":", "if", "isinstance", "(", "item", ".", "contact_groups", ",", "list", ")", ":", "cgnames", "=", "item", ".", "contact_groups", "else", ":", "cgnames", "=", "item", ".", "contact_groups", ".", "split", "(", "','", ")", "cgnames", "=", "strip_and_uniq", "(", "cgnames", ")", "for", "cgname", "in", "cgnames", ":", "contactgroup", "=", "contactgroups", ".", "find_by_name", "(", "cgname", ")", "if", "not", "contactgroup", ":", "item", ".", "add_error", "(", "\"The contact group '%s' defined on the %s '%s' do not exist\"", "%", "(", "cgname", ",", "item", ".", "__class__", ".", "my_type", ",", "item", ".", "get_name", "(", ")", ")", ")", "continue", "cnames", "=", "contactgroups", ".", "get_members_of_group", "(", "cgname", ")", "# We add contacts into our contacts", "if", "cnames", ":", "if", "hasattr", "(", "item", ",", "'contacts'", ")", ":", "# Fix #1054 - bad contact explosion", "# item.contacts.extend(cnames)", "item", ".", "contacts", "=", "item", ".", "contacts", "+", "cnames", "else", ":", "item", ".", "contacts", "=", "cnames" ]
Get all contacts of contact_groups and put them in contacts container :param item: item where have contact_groups property :type item: object :param contactgroups: all contactgroups object :type contactgroups: alignak.objects.contactgroup.Contactgroups :return: None
[ "Get", "all", "contacts", "of", "contact_groups", "and", "put", "them", "in", "contacts", "container" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1390-L1425
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_with_timeperiods
def linkify_with_timeperiods(self, timeperiods, prop): """ Link items with timeperiods items :param timeperiods: all timeperiods object :type timeperiods: alignak.objects.timeperiod.Timeperiods :param prop: property name :type prop: str :return: None """ for i in self: if not hasattr(i, prop): continue tpname = getattr(i, prop).strip() # some default values are '', so set None if not tpname: setattr(i, prop, '') continue # Ok, get a real name, search for it timeperiod = timeperiods.find_by_name(tpname) if timeperiod is None: i.add_error("The %s of the %s '%s' named '%s' is unknown!" % (prop, i.__class__.my_type, i.get_name(), tpname)) continue setattr(i, prop, timeperiod.uuid)
python
def linkify_with_timeperiods(self, timeperiods, prop): """ Link items with timeperiods items :param timeperiods: all timeperiods object :type timeperiods: alignak.objects.timeperiod.Timeperiods :param prop: property name :type prop: str :return: None """ for i in self: if not hasattr(i, prop): continue tpname = getattr(i, prop).strip() # some default values are '', so set None if not tpname: setattr(i, prop, '') continue # Ok, get a real name, search for it timeperiod = timeperiods.find_by_name(tpname) if timeperiod is None: i.add_error("The %s of the %s '%s' named '%s' is unknown!" % (prop, i.__class__.my_type, i.get_name(), tpname)) continue setattr(i, prop, timeperiod.uuid)
[ "def", "linkify_with_timeperiods", "(", "self", ",", "timeperiods", ",", "prop", ")", ":", "for", "i", "in", "self", ":", "if", "not", "hasattr", "(", "i", ",", "prop", ")", ":", "continue", "tpname", "=", "getattr", "(", "i", ",", "prop", ")", ".", "strip", "(", ")", "# some default values are '', so set None", "if", "not", "tpname", ":", "setattr", "(", "i", ",", "prop", ",", "''", ")", "continue", "# Ok, get a real name, search for it", "timeperiod", "=", "timeperiods", ".", "find_by_name", "(", "tpname", ")", "if", "timeperiod", "is", "None", ":", "i", ".", "add_error", "(", "\"The %s of the %s '%s' named '%s' is unknown!\"", "%", "(", "prop", ",", "i", ".", "__class__", ".", "my_type", ",", "i", ".", "get_name", "(", ")", ",", "tpname", ")", ")", "continue", "setattr", "(", "i", ",", "prop", ",", "timeperiod", ".", "uuid", ")" ]
Link items with timeperiods items :param timeperiods: all timeperiods object :type timeperiods: alignak.objects.timeperiod.Timeperiods :param prop: property name :type prop: str :return: None
[ "Link", "items", "with", "timeperiods", "items" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1427-L1454
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_with_checkmodulations
def linkify_with_checkmodulations(self, checkmodulations): """ Link checkmodulation object :param checkmodulations: checkmodulations object :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations :return: None """ for i in self: if not hasattr(i, 'checkmodulations'): continue links_list = strip_and_uniq(i.checkmodulations) new = [] for name in [e for e in links_list if e]: modulation = checkmodulations.find_by_name(name) if modulation is not None and modulation.uuid not in new: new.append(modulation.uuid) else: i.add_error("The checkmodulations of the %s '%s' named " "'%s' is unknown!" % (i.__class__.my_type, i.get_name(), name)) i.checkmodulations = new
python
def linkify_with_checkmodulations(self, checkmodulations): """ Link checkmodulation object :param checkmodulations: checkmodulations object :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations :return: None """ for i in self: if not hasattr(i, 'checkmodulations'): continue links_list = strip_and_uniq(i.checkmodulations) new = [] for name in [e for e in links_list if e]: modulation = checkmodulations.find_by_name(name) if modulation is not None and modulation.uuid not in new: new.append(modulation.uuid) else: i.add_error("The checkmodulations of the %s '%s' named " "'%s' is unknown!" % (i.__class__.my_type, i.get_name(), name)) i.checkmodulations = new
[ "def", "linkify_with_checkmodulations", "(", "self", ",", "checkmodulations", ")", ":", "for", "i", "in", "self", ":", "if", "not", "hasattr", "(", "i", ",", "'checkmodulations'", ")", ":", "continue", "links_list", "=", "strip_and_uniq", "(", "i", ".", "checkmodulations", ")", "new", "=", "[", "]", "for", "name", "in", "[", "e", "for", "e", "in", "links_list", "if", "e", "]", ":", "modulation", "=", "checkmodulations", ".", "find_by_name", "(", "name", ")", "if", "modulation", "is", "not", "None", "and", "modulation", ".", "uuid", "not", "in", "new", ":", "new", ".", "append", "(", "modulation", ".", "uuid", ")", "else", ":", "i", ".", "add_error", "(", "\"The checkmodulations of the %s '%s' named \"", "\"'%s' is unknown!\"", "%", "(", "i", ".", "__class__", ".", "my_type", ",", "i", ".", "get_name", "(", ")", ",", "name", ")", ")", "i", ".", "checkmodulations", "=", "new" ]
Link checkmodulation object :param checkmodulations: checkmodulations object :type checkmodulations: alignak.objects.checkmodulation.Checkmodulations :return: None
[ "Link", "checkmodulation", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1456-L1478
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.linkify_s_by_module
def linkify_s_by_module(self, modules): """ Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None """ for i in self: links_list = strip_and_uniq(i.modules) new = [] for name in [e for e in links_list if e]: module = modules.find_by_name(name) if module is not None and module.uuid not in new: new.append(module) else: i.add_error("Error: the module %s is unknown for %s" % (name, i.get_name())) i.modules = new
python
def linkify_s_by_module(self, modules): """ Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None """ for i in self: links_list = strip_and_uniq(i.modules) new = [] for name in [e for e in links_list if e]: module = modules.find_by_name(name) if module is not None and module.uuid not in new: new.append(module) else: i.add_error("Error: the module %s is unknown for %s" % (name, i.get_name())) i.modules = new
[ "def", "linkify_s_by_module", "(", "self", ",", "modules", ")", ":", "for", "i", "in", "self", ":", "links_list", "=", "strip_and_uniq", "(", "i", ".", "modules", ")", "new", "=", "[", "]", "for", "name", "in", "[", "e", "for", "e", "in", "links_list", "if", "e", "]", ":", "module", "=", "modules", ".", "find_by_name", "(", "name", ")", "if", "module", "is", "not", "None", "and", "module", ".", "uuid", "not", "in", "new", ":", "new", ".", "append", "(", "module", ")", "else", ":", "i", ".", "add_error", "(", "\"Error: the module %s is unknown for %s\"", "%", "(", "name", ",", "i", ".", "get_name", "(", ")", ")", ")", "i", ".", "modules", "=", "new" ]
Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None
[ "Link", "modules", "to", "items" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1504-L1523
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.evaluate_hostgroup_expression
def evaluate_hostgroup_expression(expr, hosts, hostgroups, look_in='hostgroups'): """ Evaluate hostgroup expression :param expr: an expression :type expr: str :param hosts: hosts object (all hosts) :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :param look_in: item name where search :type look_in: str :return: return list of hostgroups :rtype: list """ # Maybe exp is a list, like numerous hostgroups entries in a service, link them if isinstance(expr, list): expr = '|'.join(expr) if look_in == 'hostgroups': node = ComplexExpressionFactory(look_in, hostgroups, hosts) else: # templates node = ComplexExpressionFactory(look_in, hosts, hosts) expr_tree = node.eval_cor_pattern(expr) set_res = expr_tree.resolve_elements() # HOOK DBG return list(set_res)
python
def evaluate_hostgroup_expression(expr, hosts, hostgroups, look_in='hostgroups'): """ Evaluate hostgroup expression :param expr: an expression :type expr: str :param hosts: hosts object (all hosts) :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :param look_in: item name where search :type look_in: str :return: return list of hostgroups :rtype: list """ # Maybe exp is a list, like numerous hostgroups entries in a service, link them if isinstance(expr, list): expr = '|'.join(expr) if look_in == 'hostgroups': node = ComplexExpressionFactory(look_in, hostgroups, hosts) else: # templates node = ComplexExpressionFactory(look_in, hosts, hosts) expr_tree = node.eval_cor_pattern(expr) set_res = expr_tree.resolve_elements() # HOOK DBG return list(set_res)
[ "def", "evaluate_hostgroup_expression", "(", "expr", ",", "hosts", ",", "hostgroups", ",", "look_in", "=", "'hostgroups'", ")", ":", "# Maybe exp is a list, like numerous hostgroups entries in a service, link them", "if", "isinstance", "(", "expr", ",", "list", ")", ":", "expr", "=", "'|'", ".", "join", "(", "expr", ")", "if", "look_in", "==", "'hostgroups'", ":", "node", "=", "ComplexExpressionFactory", "(", "look_in", ",", "hostgroups", ",", "hosts", ")", "else", ":", "# templates", "node", "=", "ComplexExpressionFactory", "(", "look_in", ",", "hosts", ",", "hosts", ")", "expr_tree", "=", "node", ".", "eval_cor_pattern", "(", "expr", ")", "set_res", "=", "expr_tree", ".", "resolve_elements", "(", ")", "# HOOK DBG", "return", "list", "(", "set_res", ")" ]
Evaluate hostgroup expression :param expr: an expression :type expr: str :param hosts: hosts object (all hosts) :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :param look_in: item name where search :type look_in: str :return: return list of hostgroups :rtype: list
[ "Evaluate", "hostgroup", "expression" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1526-L1553
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.get_hosts_from_hostgroups
def get_hosts_from_hostgroups(hgname, hostgroups): """ Get hosts of hostgroups :param hgname: hostgroup name :type hgname: str :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: list of hosts :rtype: list """ if not isinstance(hgname, list): hgname = [e.strip() for e in hgname.split(',') if e.strip()] host_names = [] for name in hgname: hostgroup = hostgroups.find_by_name(name) if hostgroup is None: raise ValueError("the hostgroup '%s' is unknown" % hgname) mbrs = [h.strip() for h in hostgroup.get_hosts() if h.strip()] host_names.extend(mbrs) return host_names
python
def get_hosts_from_hostgroups(hgname, hostgroups): """ Get hosts of hostgroups :param hgname: hostgroup name :type hgname: str :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: list of hosts :rtype: list """ if not isinstance(hgname, list): hgname = [e.strip() for e in hgname.split(',') if e.strip()] host_names = [] for name in hgname: hostgroup = hostgroups.find_by_name(name) if hostgroup is None: raise ValueError("the hostgroup '%s' is unknown" % hgname) mbrs = [h.strip() for h in hostgroup.get_hosts() if h.strip()] host_names.extend(mbrs) return host_names
[ "def", "get_hosts_from_hostgroups", "(", "hgname", ",", "hostgroups", ")", ":", "if", "not", "isinstance", "(", "hgname", ",", "list", ")", ":", "hgname", "=", "[", "e", ".", "strip", "(", ")", "for", "e", "in", "hgname", ".", "split", "(", "','", ")", "if", "e", ".", "strip", "(", ")", "]", "host_names", "=", "[", "]", "for", "name", "in", "hgname", ":", "hostgroup", "=", "hostgroups", ".", "find_by_name", "(", "name", ")", "if", "hostgroup", "is", "None", ":", "raise", "ValueError", "(", "\"the hostgroup '%s' is unknown\"", "%", "hgname", ")", "mbrs", "=", "[", "h", ".", "strip", "(", ")", "for", "h", "in", "hostgroup", ".", "get_hosts", "(", ")", "if", "h", ".", "strip", "(", ")", "]", "host_names", ".", "extend", "(", "mbrs", ")", "return", "host_names" ]
Get hosts of hostgroups :param hgname: hostgroup name :type hgname: str :param hostgroups: hostgroups object (all hostgroups) :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: list of hosts :rtype: list
[ "Get", "hosts", "of", "hostgroups" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1556-L1578
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.explode_host_groups_into_hosts
def explode_host_groups_into_hosts(self, item, hosts, hostgroups): """ Get all hosts of hostgroups and add all in host_name container :param item: the item object :type item: alignak.objects.item.Item :param hosts: hosts object :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: None """ hnames_list = [] # Gets item's hostgroup_name hgnames = getattr(item, "hostgroup_name", '') or '' # Defines if hostgroup is a complex expression # Expands hostgroups if is_complex_expr(hgnames): hnames_list.extend(self.evaluate_hostgroup_expression( item.hostgroup_name, hosts, hostgroups)) elif hgnames: try: hnames_list.extend( self.get_hosts_from_hostgroups(hgnames, hostgroups)) except ValueError as err: # pragma: no cover, simple protection item.add_error(str(err)) # Expands host names hname = getattr(item, "host_name", '') hnames_list.extend([n.strip() for n in hname.split(',') if n.strip()]) hnames = set() for host in hnames_list: # If the host start with a !, it's to be removed from # the hostgroup get list if host.startswith('!'): hst_to_remove = host[1:].strip() try: hnames.remove(hst_to_remove) except KeyError: pass elif host == '*': hnames.update([host.host_name for host in hosts.items.values() if getattr(host, 'host_name', '')]) # Else it's a host to add, but maybe it's ALL else: hnames.add(host) item.host_name = ','.join(hnames)
python
def explode_host_groups_into_hosts(self, item, hosts, hostgroups): """ Get all hosts of hostgroups and add all in host_name container :param item: the item object :type item: alignak.objects.item.Item :param hosts: hosts object :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: None """ hnames_list = [] # Gets item's hostgroup_name hgnames = getattr(item, "hostgroup_name", '') or '' # Defines if hostgroup is a complex expression # Expands hostgroups if is_complex_expr(hgnames): hnames_list.extend(self.evaluate_hostgroup_expression( item.hostgroup_name, hosts, hostgroups)) elif hgnames: try: hnames_list.extend( self.get_hosts_from_hostgroups(hgnames, hostgroups)) except ValueError as err: # pragma: no cover, simple protection item.add_error(str(err)) # Expands host names hname = getattr(item, "host_name", '') hnames_list.extend([n.strip() for n in hname.split(',') if n.strip()]) hnames = set() for host in hnames_list: # If the host start with a !, it's to be removed from # the hostgroup get list if host.startswith('!'): hst_to_remove = host[1:].strip() try: hnames.remove(hst_to_remove) except KeyError: pass elif host == '*': hnames.update([host.host_name for host in hosts.items.values() if getattr(host, 'host_name', '')]) # Else it's a host to add, but maybe it's ALL else: hnames.add(host) item.host_name = ','.join(hnames)
[ "def", "explode_host_groups_into_hosts", "(", "self", ",", "item", ",", "hosts", ",", "hostgroups", ")", ":", "hnames_list", "=", "[", "]", "# Gets item's hostgroup_name", "hgnames", "=", "getattr", "(", "item", ",", "\"hostgroup_name\"", ",", "''", ")", "or", "''", "# Defines if hostgroup is a complex expression", "# Expands hostgroups", "if", "is_complex_expr", "(", "hgnames", ")", ":", "hnames_list", ".", "extend", "(", "self", ".", "evaluate_hostgroup_expression", "(", "item", ".", "hostgroup_name", ",", "hosts", ",", "hostgroups", ")", ")", "elif", "hgnames", ":", "try", ":", "hnames_list", ".", "extend", "(", "self", ".", "get_hosts_from_hostgroups", "(", "hgnames", ",", "hostgroups", ")", ")", "except", "ValueError", "as", "err", ":", "# pragma: no cover, simple protection", "item", ".", "add_error", "(", "str", "(", "err", ")", ")", "# Expands host names", "hname", "=", "getattr", "(", "item", ",", "\"host_name\"", ",", "''", ")", "hnames_list", ".", "extend", "(", "[", "n", ".", "strip", "(", ")", "for", "n", "in", "hname", ".", "split", "(", "','", ")", "if", "n", ".", "strip", "(", ")", "]", ")", "hnames", "=", "set", "(", ")", "for", "host", "in", "hnames_list", ":", "# If the host start with a !, it's to be removed from", "# the hostgroup get list", "if", "host", ".", "startswith", "(", "'!'", ")", ":", "hst_to_remove", "=", "host", "[", "1", ":", "]", ".", "strip", "(", ")", "try", ":", "hnames", ".", "remove", "(", "hst_to_remove", ")", "except", "KeyError", ":", "pass", "elif", "host", "==", "'*'", ":", "hnames", ".", "update", "(", "[", "host", ".", "host_name", "for", "host", "in", "hosts", ".", "items", ".", "values", "(", ")", "if", "getattr", "(", "host", ",", "'host_name'", ",", "''", ")", "]", ")", "# Else it's a host to add, but maybe it's ALL", "else", ":", "hnames", ".", "add", "(", "host", ")", "item", ".", "host_name", "=", "','", ".", "join", "(", "hnames", ")" ]
Get all hosts of hostgroups and add all in host_name container :param item: the item object :type item: alignak.objects.item.Item :param hosts: hosts object :type hosts: alignak.objects.host.Hosts :param hostgroups: hostgroups object :type hostgroups: alignak.objects.hostgroup.Hostgroups :return: None
[ "Get", "all", "hosts", "of", "hostgroups", "and", "add", "all", "in", "host_name", "container" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1580-L1629
train
Alignak-monitoring/alignak
alignak/objects/item.py
Items.get_customs_properties_by_inheritance
def get_customs_properties_by_inheritance(self, obj): """ Get custom properties from the templates defined in this object :param obj: the oject to search the property :type obj: alignak.objects.item.Item :return: list of custom properties :rtype: list """ for t_id in obj.templates: template = self.templates[t_id] tpl_cv = self.get_customs_properties_by_inheritance(template) if tpl_cv: for prop in tpl_cv: if prop not in obj.customs: value = tpl_cv[prop] else: value = obj.customs[prop] if obj.has_plus(prop): value.insert(0, obj.get_plus_and_delete(prop)) # value = self.get_plus_and_delete(prop) + ',' + value obj.customs[prop] = value for prop in obj.customs: value = obj.customs[prop] if obj.has_plus(prop): value.insert(0, obj.get_plus_and_delete(prop)) obj.customs[prop] = value # We can get custom properties in plus, we need to get all # entires and put # them into customs cust_in_plus = obj.get_all_plus_and_delete() for prop in cust_in_plus: obj.customs[prop] = cust_in_plus[prop] return obj.customs
python
def get_customs_properties_by_inheritance(self, obj): """ Get custom properties from the templates defined in this object :param obj: the oject to search the property :type obj: alignak.objects.item.Item :return: list of custom properties :rtype: list """ for t_id in obj.templates: template = self.templates[t_id] tpl_cv = self.get_customs_properties_by_inheritance(template) if tpl_cv: for prop in tpl_cv: if prop not in obj.customs: value = tpl_cv[prop] else: value = obj.customs[prop] if obj.has_plus(prop): value.insert(0, obj.get_plus_and_delete(prop)) # value = self.get_plus_and_delete(prop) + ',' + value obj.customs[prop] = value for prop in obj.customs: value = obj.customs[prop] if obj.has_plus(prop): value.insert(0, obj.get_plus_and_delete(prop)) obj.customs[prop] = value # We can get custom properties in plus, we need to get all # entires and put # them into customs cust_in_plus = obj.get_all_plus_and_delete() for prop in cust_in_plus: obj.customs[prop] = cust_in_plus[prop] return obj.customs
[ "def", "get_customs_properties_by_inheritance", "(", "self", ",", "obj", ")", ":", "for", "t_id", "in", "obj", ".", "templates", ":", "template", "=", "self", ".", "templates", "[", "t_id", "]", "tpl_cv", "=", "self", ".", "get_customs_properties_by_inheritance", "(", "template", ")", "if", "tpl_cv", ":", "for", "prop", "in", "tpl_cv", ":", "if", "prop", "not", "in", "obj", ".", "customs", ":", "value", "=", "tpl_cv", "[", "prop", "]", "else", ":", "value", "=", "obj", ".", "customs", "[", "prop", "]", "if", "obj", ".", "has_plus", "(", "prop", ")", ":", "value", ".", "insert", "(", "0", ",", "obj", ".", "get_plus_and_delete", "(", "prop", ")", ")", "# value = self.get_plus_and_delete(prop) + ',' + value", "obj", ".", "customs", "[", "prop", "]", "=", "value", "for", "prop", "in", "obj", ".", "customs", ":", "value", "=", "obj", ".", "customs", "[", "prop", "]", "if", "obj", ".", "has_plus", "(", "prop", ")", ":", "value", ".", "insert", "(", "0", ",", "obj", ".", "get_plus_and_delete", "(", "prop", ")", ")", "obj", ".", "customs", "[", "prop", "]", "=", "value", "# We can get custom properties in plus, we need to get all", "# entires and put", "# them into customs", "cust_in_plus", "=", "obj", ".", "get_all_plus_and_delete", "(", ")", "for", "prop", "in", "cust_in_plus", ":", "obj", ".", "customs", "[", "prop", "]", "=", "cust_in_plus", "[", "prop", "]", "return", "obj", ".", "customs" ]
Get custom properties from the templates defined in this object :param obj: the oject to search the property :type obj: alignak.objects.item.Item :return: list of custom properties :rtype: list
[ "Get", "custom", "properties", "from", "the", "templates", "defined", "in", "this", "object" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L1853-L1886
train
Alignak-monitoring/alignak
alignak/graph.py
Graph.add_edge
def add_edge(self, from_node, to_node): """Add edge between two node The edge is oriented :param from_node: node where edge starts :type from_node: object :param to_node: node where edge ends :type to_node: object :return: None """ # Maybe to_node is unknown if to_node not in self.nodes: self.add_node(to_node) try: self.nodes[from_node]["sons"].append(to_node) # If from_node does not exist, add it with its son except KeyError: self.nodes[from_node] = {"dfs_loop_status": "", "sons": [to_node]}
python
def add_edge(self, from_node, to_node): """Add edge between two node The edge is oriented :param from_node: node where edge starts :type from_node: object :param to_node: node where edge ends :type to_node: object :return: None """ # Maybe to_node is unknown if to_node not in self.nodes: self.add_node(to_node) try: self.nodes[from_node]["sons"].append(to_node) # If from_node does not exist, add it with its son except KeyError: self.nodes[from_node] = {"dfs_loop_status": "", "sons": [to_node]}
[ "def", "add_edge", "(", "self", ",", "from_node", ",", "to_node", ")", ":", "# Maybe to_node is unknown", "if", "to_node", "not", "in", "self", ".", "nodes", ":", "self", ".", "add_node", "(", "to_node", ")", "try", ":", "self", ".", "nodes", "[", "from_node", "]", "[", "\"sons\"", "]", ".", "append", "(", "to_node", ")", "# If from_node does not exist, add it with its son", "except", "KeyError", ":", "self", ".", "nodes", "[", "from_node", "]", "=", "{", "\"dfs_loop_status\"", ":", "\"\"", ",", "\"sons\"", ":", "[", "to_node", "]", "}" ]
Add edge between two node The edge is oriented :param from_node: node where edge starts :type from_node: object :param to_node: node where edge ends :type to_node: object :return: None
[ "Add", "edge", "between", "two", "node", "The", "edge", "is", "oriented" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/graph.py#L81-L99
train
Alignak-monitoring/alignak
alignak/graph.py
Graph.loop_check
def loop_check(self): """Check if we have a loop in the graph :return: Nodes in loop :rtype: list """ in_loop = [] # Add the tag for dfs check for node in list(self.nodes.values()): node['dfs_loop_status'] = 'DFS_UNCHECKED' # Now do the job for node_id, node in self.nodes.items(): # Run the dfs only if the node has not been already done */ if node['dfs_loop_status'] == 'DFS_UNCHECKED': self.dfs_loop_search(node_id) # If LOOP_INSIDE, must be returned if node['dfs_loop_status'] == 'DFS_LOOP_INSIDE': in_loop.append(node_id) # Remove the tag for node in list(self.nodes.values()): del node['dfs_loop_status'] return in_loop
python
def loop_check(self): """Check if we have a loop in the graph :return: Nodes in loop :rtype: list """ in_loop = [] # Add the tag for dfs check for node in list(self.nodes.values()): node['dfs_loop_status'] = 'DFS_UNCHECKED' # Now do the job for node_id, node in self.nodes.items(): # Run the dfs only if the node has not been already done */ if node['dfs_loop_status'] == 'DFS_UNCHECKED': self.dfs_loop_search(node_id) # If LOOP_INSIDE, must be returned if node['dfs_loop_status'] == 'DFS_LOOP_INSIDE': in_loop.append(node_id) # Remove the tag for node in list(self.nodes.values()): del node['dfs_loop_status'] return in_loop
[ "def", "loop_check", "(", "self", ")", ":", "in_loop", "=", "[", "]", "# Add the tag for dfs check", "for", "node", "in", "list", "(", "self", ".", "nodes", ".", "values", "(", ")", ")", ":", "node", "[", "'dfs_loop_status'", "]", "=", "'DFS_UNCHECKED'", "# Now do the job", "for", "node_id", ",", "node", "in", "self", ".", "nodes", ".", "items", "(", ")", ":", "# Run the dfs only if the node has not been already done */", "if", "node", "[", "'dfs_loop_status'", "]", "==", "'DFS_UNCHECKED'", ":", "self", ".", "dfs_loop_search", "(", "node_id", ")", "# If LOOP_INSIDE, must be returned", "if", "node", "[", "'dfs_loop_status'", "]", "==", "'DFS_LOOP_INSIDE'", ":", "in_loop", ".", "append", "(", "node_id", ")", "# Remove the tag", "for", "node", "in", "list", "(", "self", ".", "nodes", ".", "values", "(", ")", ")", ":", "del", "node", "[", "'dfs_loop_status'", "]", "return", "in_loop" ]
Check if we have a loop in the graph :return: Nodes in loop :rtype: list
[ "Check", "if", "we", "have", "a", "loop", "in", "the", "graph" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/graph.py#L101-L125
train
Alignak-monitoring/alignak
alignak/graph.py
Graph.dfs_loop_search
def dfs_loop_search(self, root): """Main algorithm to look for loop. It tags nodes and find ones stuck in loop. * Init all nodes with DFS_UNCHECKED value * DFS_TEMPORARY_CHECKED means we found it once * DFS_OK : this node (and all sons) are fine * DFS_NEAR_LOOP : One problem was found in of of the son * DFS_LOOP_INSIDE : This node is part of a loop :param root: Root of the dependency tree :type root: :return: None """ # Make the root temporary checked self.nodes[root]['dfs_loop_status'] = 'DFS_TEMPORARY_CHECKED' # We are scanning the sons for child in self.nodes[root]["sons"]: child_status = self.nodes[child]['dfs_loop_status'] # If a child is not checked, check it if child_status == 'DFS_UNCHECKED': self.dfs_loop_search(child) child_status = self.nodes[child]['dfs_loop_status'] # If a child has already been temporary checked, it's a problem, # loop inside, and its a checked status if child_status == 'DFS_TEMPORARY_CHECKED': self.nodes[child]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' self.nodes[root]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' # If a child has already been temporary checked, it's a problem, loop inside if child_status in ('DFS_NEAR_LOOP', 'DFS_LOOP_INSIDE'): # if a node is known to be part of a loop, do not let it be less if self.nodes[root]['dfs_loop_status'] != 'DFS_LOOP_INSIDE': self.nodes[root]['dfs_loop_status'] = 'DFS_NEAR_LOOP' # We've already seen this child, it's a problem self.nodes[child]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' # If root have been modified, do not set it OK # A node is OK if and only if all of its children are OK # if it does not have a child, goes ok if self.nodes[root]['dfs_loop_status'] == 'DFS_TEMPORARY_CHECKED': self.nodes[root]['dfs_loop_status'] = 'DFS_OK'
python
def dfs_loop_search(self, root): """Main algorithm to look for loop. It tags nodes and find ones stuck in loop. * Init all nodes with DFS_UNCHECKED value * DFS_TEMPORARY_CHECKED means we found it once * DFS_OK : this node (and all sons) are fine * DFS_NEAR_LOOP : One problem was found in of of the son * DFS_LOOP_INSIDE : This node is part of a loop :param root: Root of the dependency tree :type root: :return: None """ # Make the root temporary checked self.nodes[root]['dfs_loop_status'] = 'DFS_TEMPORARY_CHECKED' # We are scanning the sons for child in self.nodes[root]["sons"]: child_status = self.nodes[child]['dfs_loop_status'] # If a child is not checked, check it if child_status == 'DFS_UNCHECKED': self.dfs_loop_search(child) child_status = self.nodes[child]['dfs_loop_status'] # If a child has already been temporary checked, it's a problem, # loop inside, and its a checked status if child_status == 'DFS_TEMPORARY_CHECKED': self.nodes[child]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' self.nodes[root]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' # If a child has already been temporary checked, it's a problem, loop inside if child_status in ('DFS_NEAR_LOOP', 'DFS_LOOP_INSIDE'): # if a node is known to be part of a loop, do not let it be less if self.nodes[root]['dfs_loop_status'] != 'DFS_LOOP_INSIDE': self.nodes[root]['dfs_loop_status'] = 'DFS_NEAR_LOOP' # We've already seen this child, it's a problem self.nodes[child]['dfs_loop_status'] = 'DFS_LOOP_INSIDE' # If root have been modified, do not set it OK # A node is OK if and only if all of its children are OK # if it does not have a child, goes ok if self.nodes[root]['dfs_loop_status'] == 'DFS_TEMPORARY_CHECKED': self.nodes[root]['dfs_loop_status'] = 'DFS_OK'
[ "def", "dfs_loop_search", "(", "self", ",", "root", ")", ":", "# Make the root temporary checked", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_TEMPORARY_CHECKED'", "# We are scanning the sons", "for", "child", "in", "self", ".", "nodes", "[", "root", "]", "[", "\"sons\"", "]", ":", "child_status", "=", "self", ".", "nodes", "[", "child", "]", "[", "'dfs_loop_status'", "]", "# If a child is not checked, check it", "if", "child_status", "==", "'DFS_UNCHECKED'", ":", "self", ".", "dfs_loop_search", "(", "child", ")", "child_status", "=", "self", ".", "nodes", "[", "child", "]", "[", "'dfs_loop_status'", "]", "# If a child has already been temporary checked, it's a problem,", "# loop inside, and its a checked status", "if", "child_status", "==", "'DFS_TEMPORARY_CHECKED'", ":", "self", ".", "nodes", "[", "child", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_LOOP_INSIDE'", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_LOOP_INSIDE'", "# If a child has already been temporary checked, it's a problem, loop inside", "if", "child_status", "in", "(", "'DFS_NEAR_LOOP'", ",", "'DFS_LOOP_INSIDE'", ")", ":", "# if a node is known to be part of a loop, do not let it be less", "if", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "!=", "'DFS_LOOP_INSIDE'", ":", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_NEAR_LOOP'", "# We've already seen this child, it's a problem", "self", ".", "nodes", "[", "child", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_LOOP_INSIDE'", "# If root have been modified, do not set it OK", "# A node is OK if and only if all of its children are OK", "# if it does not have a child, goes ok", "if", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "==", "'DFS_TEMPORARY_CHECKED'", ":", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_OK'" ]
Main algorithm to look for loop. It tags nodes and find ones stuck in loop. * Init all nodes with DFS_UNCHECKED value * DFS_TEMPORARY_CHECKED means we found it once * DFS_OK : this node (and all sons) are fine * DFS_NEAR_LOOP : One problem was found in of of the son * DFS_LOOP_INSIDE : This node is part of a loop :param root: Root of the dependency tree :type root: :return: None
[ "Main", "algorithm", "to", "look", "for", "loop", ".", "It", "tags", "nodes", "and", "find", "ones", "stuck", "in", "loop", "." ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/graph.py#L127-L170
train
Alignak-monitoring/alignak
alignak/graph.py
Graph.dfs_get_all_childs
def dfs_get_all_childs(self, root): """Recursively get all sons of this node :param root: node to get sons :type root: :return: sons :rtype: list """ self.nodes[root]['dfs_loop_status'] = 'DFS_CHECKED' ret = set() # Me ret.add(root) # And my sons ret.update(self.nodes[root]['sons']) for child in self.nodes[root]['sons']: # I just don't care about already checked children if self.nodes[child]['dfs_loop_status'] == 'DFS_UNCHECKED': ret.update(self.dfs_get_all_childs(child)) return list(ret)
python
def dfs_get_all_childs(self, root): """Recursively get all sons of this node :param root: node to get sons :type root: :return: sons :rtype: list """ self.nodes[root]['dfs_loop_status'] = 'DFS_CHECKED' ret = set() # Me ret.add(root) # And my sons ret.update(self.nodes[root]['sons']) for child in self.nodes[root]['sons']: # I just don't care about already checked children if self.nodes[child]['dfs_loop_status'] == 'DFS_UNCHECKED': ret.update(self.dfs_get_all_childs(child)) return list(ret)
[ "def", "dfs_get_all_childs", "(", "self", ",", "root", ")", ":", "self", ".", "nodes", "[", "root", "]", "[", "'dfs_loop_status'", "]", "=", "'DFS_CHECKED'", "ret", "=", "set", "(", ")", "# Me", "ret", ".", "add", "(", "root", ")", "# And my sons", "ret", ".", "update", "(", "self", ".", "nodes", "[", "root", "]", "[", "'sons'", "]", ")", "for", "child", "in", "self", ".", "nodes", "[", "root", "]", "[", "'sons'", "]", ":", "# I just don't care about already checked children", "if", "self", ".", "nodes", "[", "child", "]", "[", "'dfs_loop_status'", "]", "==", "'DFS_UNCHECKED'", ":", "ret", ".", "update", "(", "self", ".", "dfs_get_all_childs", "(", "child", ")", ")", "return", "list", "(", "ret", ")" ]
Recursively get all sons of this node :param root: node to get sons :type root: :return: sons :rtype: list
[ "Recursively", "get", "all", "sons", "of", "this", "node" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/graph.py#L197-L218
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.identity
def identity(self): """Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict """ res = self.app.get_id() res.update({"start_time": self.start_time}) res.update({"running_id": self.running_id}) return res
python
def identity(self): """Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict """ res = self.app.get_id() res.update({"start_time": self.start_time}) res.update({"running_id": self.running_id}) return res
[ "def", "identity", "(", "self", ")", ":", "res", "=", "self", ".", "app", ".", "get_id", "(", ")", "res", ".", "update", "(", "{", "\"start_time\"", ":", "self", ".", "start_time", "}", ")", "res", ".", "update", "(", "{", "\"running_id\"", ":", "self", ".", "running_id", "}", ")", "return", "res" ]
Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict
[ "Get", "the", "daemon", "identity" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L76-L91
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.api
def api(self): """List the methods available on the daemon Web service interface :return: a list of methods and parameters :rtype: dict """ functions = [x[0]for x in inspect.getmembers(self, predicate=inspect.ismethod) if not x[0].startswith('_')] full_api = { 'doc': u"When posting data you have to use the JSON format.", 'api': [] } my_daemon_type = "%s" % getattr(self.app, 'type', 'unknown') my_address = getattr(self.app, 'host_name', getattr(self.app, 'name', 'unknown')) if getattr(self.app, 'address', '127.0.0.1') not in ['127.0.0.1']: # If an address is explicitely specified, I must use it! my_address = self.app.address for fun in functions: endpoint = { 'daemon': my_daemon_type, 'name': fun, 'doc': getattr(self, fun).__doc__, 'uri': '%s://%s:%s/%s' % (getattr(self.app, 'scheme', 'http'), my_address, self.app.port, fun), 'args': {} } try: spec = inspect.getfullargspec(getattr(self, fun)) except Exception: # pylint: disable=broad-except # pylint: disable=deprecated-method spec = inspect.getargspec(getattr(self, fun)) args = [a for a in spec.args if a not in ('self', 'cls')] if spec.defaults: a_dict = dict(list(zip(args, spec.defaults))) else: a_dict = dict(list(zip(args, ("No default value",) * len(args)))) endpoint["args"] = a_dict full_api['api'].append(endpoint) return full_api
python
def api(self): """List the methods available on the daemon Web service interface :return: a list of methods and parameters :rtype: dict """ functions = [x[0]for x in inspect.getmembers(self, predicate=inspect.ismethod) if not x[0].startswith('_')] full_api = { 'doc': u"When posting data you have to use the JSON format.", 'api': [] } my_daemon_type = "%s" % getattr(self.app, 'type', 'unknown') my_address = getattr(self.app, 'host_name', getattr(self.app, 'name', 'unknown')) if getattr(self.app, 'address', '127.0.0.1') not in ['127.0.0.1']: # If an address is explicitely specified, I must use it! my_address = self.app.address for fun in functions: endpoint = { 'daemon': my_daemon_type, 'name': fun, 'doc': getattr(self, fun).__doc__, 'uri': '%s://%s:%s/%s' % (getattr(self.app, 'scheme', 'http'), my_address, self.app.port, fun), 'args': {} } try: spec = inspect.getfullargspec(getattr(self, fun)) except Exception: # pylint: disable=broad-except # pylint: disable=deprecated-method spec = inspect.getargspec(getattr(self, fun)) args = [a for a in spec.args if a not in ('self', 'cls')] if spec.defaults: a_dict = dict(list(zip(args, spec.defaults))) else: a_dict = dict(list(zip(args, ("No default value",) * len(args)))) endpoint["args"] = a_dict full_api['api'].append(endpoint) return full_api
[ "def", "api", "(", "self", ")", ":", "functions", "=", "[", "x", "[", "0", "]", "for", "x", "in", "inspect", ".", "getmembers", "(", "self", ",", "predicate", "=", "inspect", ".", "ismethod", ")", "if", "not", "x", "[", "0", "]", ".", "startswith", "(", "'_'", ")", "]", "full_api", "=", "{", "'doc'", ":", "u\"When posting data you have to use the JSON format.\"", ",", "'api'", ":", "[", "]", "}", "my_daemon_type", "=", "\"%s\"", "%", "getattr", "(", "self", ".", "app", ",", "'type'", ",", "'unknown'", ")", "my_address", "=", "getattr", "(", "self", ".", "app", ",", "'host_name'", ",", "getattr", "(", "self", ".", "app", ",", "'name'", ",", "'unknown'", ")", ")", "if", "getattr", "(", "self", ".", "app", ",", "'address'", ",", "'127.0.0.1'", ")", "not", "in", "[", "'127.0.0.1'", "]", ":", "# If an address is explicitely specified, I must use it!", "my_address", "=", "self", ".", "app", ".", "address", "for", "fun", "in", "functions", ":", "endpoint", "=", "{", "'daemon'", ":", "my_daemon_type", ",", "'name'", ":", "fun", ",", "'doc'", ":", "getattr", "(", "self", ",", "fun", ")", ".", "__doc__", ",", "'uri'", ":", "'%s://%s:%s/%s'", "%", "(", "getattr", "(", "self", ".", "app", ",", "'scheme'", ",", "'http'", ")", ",", "my_address", ",", "self", ".", "app", ".", "port", ",", "fun", ")", ",", "'args'", ":", "{", "}", "}", "try", ":", "spec", "=", "inspect", ".", "getfullargspec", "(", "getattr", "(", "self", ",", "fun", ")", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "# pylint: disable=deprecated-method", "spec", "=", "inspect", ".", "getargspec", "(", "getattr", "(", "self", ",", "fun", ")", ")", "args", "=", "[", "a", "for", "a", "in", "spec", ".", "args", "if", "a", "not", "in", "(", "'self'", ",", "'cls'", ")", "]", "if", "spec", ".", "defaults", ":", "a_dict", "=", "dict", "(", "list", "(", "zip", "(", "args", ",", "spec", ".", "defaults", ")", ")", ")", "else", ":", "a_dict", "=", "dict", "(", "list", "(", "zip", "(", "args", ",", "(", "\"No default value\"", ",", ")", "*", "len", "(", "args", ")", ")", ")", ")", "endpoint", "[", "\"args\"", "]", "=", "a_dict", "full_api", "[", "'api'", "]", ".", "append", "(", "endpoint", ")", "return", "full_api" ]
List the methods available on the daemon Web service interface :return: a list of methods and parameters :rtype: dict
[ "List", "the", "methods", "available", "on", "the", "daemon", "Web", "service", "interface" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L95-L138
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.stop_request
def stop_request(self, stop_now='0'): """Request the daemon to stop If `stop_now` is set to '1' the daemon will stop now. Else, the daemon will enter the stop wait mode. In this mode the daemon stops its activity and waits until it receives a new `stop_now` request to stop really. :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: None """ self.app.interrupted = (stop_now == '1') self.app.will_stop = True return True
python
def stop_request(self, stop_now='0'): """Request the daemon to stop If `stop_now` is set to '1' the daemon will stop now. Else, the daemon will enter the stop wait mode. In this mode the daemon stops its activity and waits until it receives a new `stop_now` request to stop really. :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: None """ self.app.interrupted = (stop_now == '1') self.app.will_stop = True return True
[ "def", "stop_request", "(", "self", ",", "stop_now", "=", "'0'", ")", ":", "self", ".", "app", ".", "interrupted", "=", "(", "stop_now", "==", "'1'", ")", "self", ".", "app", ".", "will_stop", "=", "True", "return", "True" ]
Request the daemon to stop If `stop_now` is set to '1' the daemon will stop now. Else, the daemon will enter the stop wait mode. In this mode the daemon stops its activity and waits until it receives a new `stop_now` request to stop really. :param stop_now: stop now or go to stop wait mode :type stop_now: bool :return: None
[ "Request", "the", "daemon", "to", "stop" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L143-L157
train
Alignak-monitoring/alignak
alignak/http/generic_interface.py
GenericInterface.get_log_level
def get_log_level(self): """Get the current daemon log level Returns an object with the daemon identity and a `log_level` property. running_id :return: current log level :rtype: str """ level_names = { logging.DEBUG: 'DEBUG', logging.INFO: 'INFO', logging.WARNING: 'WARNING', logging.ERROR: 'ERROR', logging.CRITICAL: 'CRITICAL' } alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME) res = self.identity() res.update({"log_level": alignak_logger.getEffectiveLevel(), "log_level_name": level_names[alignak_logger.getEffectiveLevel()]}) return res
python
def get_log_level(self): """Get the current daemon log level Returns an object with the daemon identity and a `log_level` property. running_id :return: current log level :rtype: str """ level_names = { logging.DEBUG: 'DEBUG', logging.INFO: 'INFO', logging.WARNING: 'WARNING', logging.ERROR: 'ERROR', logging.CRITICAL: 'CRITICAL' } alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME) res = self.identity() res.update({"log_level": alignak_logger.getEffectiveLevel(), "log_level_name": level_names[alignak_logger.getEffectiveLevel()]}) return res
[ "def", "get_log_level", "(", "self", ")", ":", "level_names", "=", "{", "logging", ".", "DEBUG", ":", "'DEBUG'", ",", "logging", ".", "INFO", ":", "'INFO'", ",", "logging", ".", "WARNING", ":", "'WARNING'", ",", "logging", ".", "ERROR", ":", "'ERROR'", ",", "logging", ".", "CRITICAL", ":", "'CRITICAL'", "}", "alignak_logger", "=", "logging", ".", "getLogger", "(", "ALIGNAK_LOGGER_NAME", ")", "res", "=", "self", ".", "identity", "(", ")", "res", ".", "update", "(", "{", "\"log_level\"", ":", "alignak_logger", ".", "getEffectiveLevel", "(", ")", ",", "\"log_level_name\"", ":", "level_names", "[", "alignak_logger", ".", "getEffectiveLevel", "(", ")", "]", "}", ")", "return", "res" ]
Get the current daemon log level Returns an object with the daemon identity and a `log_level` property. running_id :return: current log level :rtype: str
[ "Get", "the", "current", "daemon", "log", "level" ]
f3c145207e83159b799d3714e4241399c7740a64
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L161-L179
train