id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20,900 | 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):
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",
"=",
"ite... | 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 |
20,901 | 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):
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",
... | 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 |
20,902 | 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):
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",
"="... | 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 |
20,903 | 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):
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",
... | 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 |
20,904 | 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):
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",
"[",
"\"hos... | 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 |
20,905 | 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):
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",
... | 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 |
20,906 | 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):
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",
... | 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 |
20,907 | 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
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... | 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 |
20,908 | 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...
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... | 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 |
20,909 | 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
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",
".",
... | 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 |
20,910 | 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'):
# 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"... | 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 |
20,911 | 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):
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 f... | 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 |
20,912 | 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):
# 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",
... | 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 |
20,913 | 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):
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",
":",
"pa... | 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 |
20,914 | 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):
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",
"(",
... | 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 |
20,915 | 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):
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",
"... | 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 |
20,916 | 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):
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",
... | 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 |
20,917 | 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):
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 |
20,918 | 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):
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",
"(",
")",
")",
":",
"i... | 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 |
20,919 | 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):
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",
... | 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",
"t... | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/item.py#L483-L498 |
20,920 | 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
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",
... | 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 |
20,921 | 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):
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",
"[",
"downti... | 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 |
20,922 | 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):
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",
")"... | 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 |
20,923 | 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):
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",
"(",
")",
")",
... | 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 |
20,924 | 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):
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",
".",
... | 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 |
20,925 | 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):
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_'",
"+",
"s... | 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 |
20,926 | 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):
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_typ... | 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 |
20,927 | 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 = {}
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",
... | 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 |
20,928 | 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):
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 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 |
20,929 | 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):
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",
"[",
... | 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 |
20,930 | 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):
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 |
20,931 | 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):
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 def... | 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 |
20,932 | 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):
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 |
20,933 | 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):
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 pr... | 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 |
20,934 | 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
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",
")"... | 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 |
20,935 | 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
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",
... | 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 |
20,936 | 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):
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",
... | 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 |
20,937 | 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):
# 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",
... | 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 |
20,938 | 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):
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",
".",... | 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 |
20,939 | 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):
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",
... | 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 |
20,940 | 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):
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",
")... | 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 |
20,941 | 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):
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_g... | 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 |
20,942 | 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):
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",
")",
".",
... | 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 |
20,943 | 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):
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",
".",
"che... | 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 |
20,944 | 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):
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... | 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 |
20,945 | 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'):
# 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",
")",
":",
... | 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 |
20,946 | 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):
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",
"(",
"','",
")... | 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 |
20,947 | 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):
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",
... | 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 |
20,948 | 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):
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"... | 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 |
20,949 | 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):
# 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_... | 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 |
20,950 | 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):
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'",
... | 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 |
20,951 | 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):
# 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",
".",... | 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 |
20,952 | 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):
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",
"re... | 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 |
20,953 | 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):
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\"",
":",
"s... | 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 |
20,954 | 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):
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... | 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 |
20,955 | 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'):
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 |
20,956 | 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):
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'",
... | 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 |
20,957 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface.set_log_level | def set_log_level(self, log_level=None):
"""Set the current log level for the daemon
The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]
In case of any error, this function returns an object containing some properties:
'_status': 'ERR' because of the error
`_message`: some more explanations about the error
Else, this function returns True
:param log_level: a value in one of the above
:type log_level: str
:return: see above
:rtype: dict
"""
if log_level is None:
log_level = cherrypy.request.json['log_level']
if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
return {'_status': u'ERR',
'_message': u"Required log level is not allowed: %s" % log_level}
alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME)
alignak_logger.setLevel(log_level)
return self.get_log_level() | python | def set_log_level(self, log_level=None):
if log_level is None:
log_level = cherrypy.request.json['log_level']
if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
return {'_status': u'ERR',
'_message': u"Required log level is not allowed: %s" % log_level}
alignak_logger = logging.getLogger(ALIGNAK_LOGGER_NAME)
alignak_logger.setLevel(log_level)
return self.get_log_level() | [
"def",
"set_log_level",
"(",
"self",
",",
"log_level",
"=",
"None",
")",
":",
"if",
"log_level",
"is",
"None",
":",
"log_level",
"=",
"cherrypy",
".",
"request",
".",
"json",
"[",
"'log_level'",
"]",
"if",
"log_level",
"not",
"in",
"[",
"'DEBUG'",
",",
... | Set the current log level for the daemon
The `log_level` parameter must be in [DEBUG, INFO, WARNING, ERROR, CRITICAL]
In case of any error, this function returns an object containing some properties:
'_status': 'ERR' because of the error
`_message`: some more explanations about the error
Else, this function returns True
:param log_level: a value in one of the above
:type log_level: str
:return: see above
:rtype: dict | [
"Set",
"the",
"current",
"log",
"level",
"for",
"the",
"daemon"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L184-L209 |
20,958 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface.stats | def stats(self, details=False):
"""Get statistics and information from the daemon
Returns an object with the daemon identity, the daemon start_time
and some extra properties depending upon the daemon type.
All daemons provide these ones:
- program_start: the Alignak start timestamp
- spare: to indicate if the daemon is a spare one
- load: the daemon load
- modules: the daemon modules information
- counters: the specific daemon counters
:param details: Details are required (different from 0)
:type details str
:return: daemon stats
:rtype: dict
"""
if details is not False:
details = bool(details)
res = self.identity()
res.update(self.app.get_daemon_stats(details=details))
return res | python | def stats(self, details=False):
if details is not False:
details = bool(details)
res = self.identity()
res.update(self.app.get_daemon_stats(details=details))
return res | [
"def",
"stats",
"(",
"self",
",",
"details",
"=",
"False",
")",
":",
"if",
"details",
"is",
"not",
"False",
":",
"details",
"=",
"bool",
"(",
"details",
")",
"res",
"=",
"self",
".",
"identity",
"(",
")",
"res",
".",
"update",
"(",
"self",
".",
"... | Get statistics and information from the daemon
Returns an object with the daemon identity, the daemon start_time
and some extra properties depending upon the daemon type.
All daemons provide these ones:
- program_start: the Alignak start timestamp
- spare: to indicate if the daemon is a spare one
- load: the daemon load
- modules: the daemon modules information
- counters: the specific daemon counters
:param details: Details are required (different from 0)
:type details str
:return: daemon stats
:rtype: dict | [
"Get",
"statistics",
"and",
"information",
"from",
"the",
"daemon"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L240-L263 |
20,959 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface._have_conf | def _have_conf(self, magic_hash=None):
"""Get the daemon current configuration state
If the daemon has received a configuration from its arbiter, this will
return True
If a `magic_hash` is provided it is compared with the one included in the
daemon configuration and this function returns True only if they match!
:return: boolean indicating if the daemon has a configuration
:rtype: bool
"""
self.app.have_conf = getattr(self.app, 'cur_conf', None) not in [None, {}]
if magic_hash is not None:
# Beware, we got an str in entry, not an int
magic_hash = int(magic_hash)
# I've got a conf and a good one
return self.app.have_conf and self.app.cur_conf.magic_hash == magic_hash
return self.app.have_conf | python | def _have_conf(self, magic_hash=None):
self.app.have_conf = getattr(self.app, 'cur_conf', None) not in [None, {}]
if magic_hash is not None:
# Beware, we got an str in entry, not an int
magic_hash = int(magic_hash)
# I've got a conf and a good one
return self.app.have_conf and self.app.cur_conf.magic_hash == magic_hash
return self.app.have_conf | [
"def",
"_have_conf",
"(",
"self",
",",
"magic_hash",
"=",
"None",
")",
":",
"self",
".",
"app",
".",
"have_conf",
"=",
"getattr",
"(",
"self",
".",
"app",
",",
"'cur_conf'",
",",
"None",
")",
"not",
"in",
"[",
"None",
",",
"{",
"}",
"]",
"if",
"m... | Get the daemon current configuration state
If the daemon has received a configuration from its arbiter, this will
return True
If a `magic_hash` is provided it is compared with the one included in the
daemon configuration and this function returns True only if they match!
:return: boolean indicating if the daemon has a configuration
:rtype: bool | [
"Get",
"the",
"daemon",
"current",
"configuration",
"state"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L310-L329 |
20,960 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface._results | def _results(self, scheduler_instance_id):
"""Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemons.
:param scheduler_instance_id: instance id of the scheduler
:type scheduler_instance_id: string
:return: serialized list
:rtype: str
"""
with self.app.lock:
res = self.app.get_results_from_passive(scheduler_instance_id)
return serialize(res, True) | python | def _results(self, scheduler_instance_id):
with self.app.lock:
res = self.app.get_results_from_passive(scheduler_instance_id)
return serialize(res, True) | [
"def",
"_results",
"(",
"self",
",",
"scheduler_instance_id",
")",
":",
"with",
"self",
".",
"app",
".",
"lock",
":",
"res",
"=",
"self",
".",
"app",
".",
"get_results_from_passive",
"(",
"scheduler_instance_id",
")",
"return",
"serialize",
"(",
"res",
",",
... | Get the results of the executed actions for the scheduler which instance id is provided
Calling this method for daemons that are not configured as passive do not make sense.
Indeed, this service should only be exposed on poller and reactionner daemons.
:param scheduler_instance_id: instance id of the scheduler
:type scheduler_instance_id: string
:return: serialized list
:rtype: str | [
"Get",
"the",
"results",
"of",
"the",
"executed",
"actions",
"for",
"the",
"scheduler",
"which",
"instance",
"id",
"is",
"provided"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L367-L380 |
20,961 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface._broks | def _broks(self, broker_name): # pylint: disable=unused-argument
"""Get the broks from the daemon
This is used by the brokers to get the broks list of a daemon
:return: Brok list serialized
:rtype: dict
"""
with self.app.broks_lock:
res = self.app.get_broks()
return serialize(res, True) | python | def _broks(self, broker_name): # pylint: disable=unused-argument
with self.app.broks_lock:
res = self.app.get_broks()
return serialize(res, True) | [
"def",
"_broks",
"(",
"self",
",",
"broker_name",
")",
":",
"# pylint: disable=unused-argument",
"with",
"self",
".",
"app",
".",
"broks_lock",
":",
"res",
"=",
"self",
".",
"app",
".",
"get_broks",
"(",
")",
"return",
"serialize",
"(",
"res",
",",
"True",... | Get the broks from the daemon
This is used by the brokers to get the broks list of a daemon
:return: Brok list serialized
:rtype: dict | [
"Get",
"the",
"broks",
"from",
"the",
"daemon"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L384-L394 |
20,962 | Alignak-monitoring/alignak | alignak/http/generic_interface.py | GenericInterface._events | def _events(self):
"""Get the monitoring events from the daemon
This is used by the arbiter to get the monitoring events from all its satellites
:return: Events list serialized
:rtype: list
"""
with self.app.events_lock:
res = self.app.get_events()
return serialize(res, True) | python | def _events(self):
with self.app.events_lock:
res = self.app.get_events()
return serialize(res, True) | [
"def",
"_events",
"(",
"self",
")",
":",
"with",
"self",
".",
"app",
".",
"events_lock",
":",
"res",
"=",
"self",
".",
"app",
".",
"get_events",
"(",
")",
"return",
"serialize",
"(",
"res",
",",
"True",
")"
] | Get the monitoring events from the daemon
This is used by the arbiter to get the monitoring events from all its satellites
:return: Events list serialized
:rtype: list | [
"Get",
"the",
"monitoring",
"events",
"from",
"the",
"daemon"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/generic_interface.py#L398-L408 |
20,963 | Alignak-monitoring/alignak | alignak/dependencynode.py | DependencyNode.get_state | def get_state(self, hosts, services):
"""Get node state by looking recursively over sons and applying operand
:param hosts: list of available hosts to search for
:param services: list of available services to search for
:return: Node state
:rtype: int
"""
# If we are a host or a service, we just got the host/service
# hard state
if self.operand == 'host':
host = hosts[self.sons[0]]
return self.get_host_node_state(host.last_hard_state_id,
host.problem_has_been_acknowledged,
host.in_scheduled_downtime)
if self.operand == 'service':
service = services[self.sons[0]]
return self.get_service_node_state(service.last_hard_state_id,
service.problem_has_been_acknowledged,
service.in_scheduled_downtime)
if self.operand == '|':
return self.get_complex_or_node_state(hosts, services)
if self.operand == '&':
return self.get_complex_and_node_state(hosts, services)
# It's an Xof rule
if self.operand == 'of:':
return self.get_complex_xof_node_state(hosts, services)
# We have an unknown node. Code is not reachable because we validate operands
return 4 | python | def get_state(self, hosts, services):
# If we are a host or a service, we just got the host/service
# hard state
if self.operand == 'host':
host = hosts[self.sons[0]]
return self.get_host_node_state(host.last_hard_state_id,
host.problem_has_been_acknowledged,
host.in_scheduled_downtime)
if self.operand == 'service':
service = services[self.sons[0]]
return self.get_service_node_state(service.last_hard_state_id,
service.problem_has_been_acknowledged,
service.in_scheduled_downtime)
if self.operand == '|':
return self.get_complex_or_node_state(hosts, services)
if self.operand == '&':
return self.get_complex_and_node_state(hosts, services)
# It's an Xof rule
if self.operand == 'of:':
return self.get_complex_xof_node_state(hosts, services)
# We have an unknown node. Code is not reachable because we validate operands
return 4 | [
"def",
"get_state",
"(",
"self",
",",
"hosts",
",",
"services",
")",
":",
"# If we are a host or a service, we just got the host/service",
"# hard state",
"if",
"self",
".",
"operand",
"==",
"'host'",
":",
"host",
"=",
"hosts",
"[",
"self",
".",
"sons",
"[",
"0"... | Get node state by looking recursively over sons and applying operand
:param hosts: list of available hosts to search for
:param services: list of available services to search for
:return: Node state
:rtype: int | [
"Get",
"node",
"state",
"by",
"looking",
"recursively",
"over",
"sons",
"and",
"applying",
"operand"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L140-L171 |
20,964 | Alignak-monitoring/alignak | alignak/dependencynode.py | DependencyNodeFactory.eval_cor_pattern | def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode
"""
pattern = pattern.strip()
complex_node = False
# Look if it's a complex pattern (with rule) or
# if it's a leaf of it, like a host/service
for char in '()&|':
if char in pattern:
complex_node = True
# If it's a simple node, evaluate it directly
if complex_node is False:
return self.eval_simple_cor_pattern(pattern, hosts, services,
hostgroups, servicegroups, running)
return self.eval_complex_cor_pattern(pattern, hosts, services,
hostgroups, servicegroups, running) | python | def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
pattern = pattern.strip()
complex_node = False
# Look if it's a complex pattern (with rule) or
# if it's a leaf of it, like a host/service
for char in '()&|':
if char in pattern:
complex_node = True
# If it's a simple node, evaluate it directly
if complex_node is False:
return self.eval_simple_cor_pattern(pattern, hosts, services,
hostgroups, servicegroups, running)
return self.eval_complex_cor_pattern(pattern, hosts, services,
hostgroups, servicegroups, running) | [
"def",
"eval_cor_pattern",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"pattern",
"=",
"pattern",
".",
"strip",
"(",
")",
"complex_node",
"=",
"False",
"# Look... | Parse and build recursively a tree of DependencyNode from pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"DependencyNode",
"from",
"pattern"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L417-L445 |
20,965 | Alignak-monitoring/alignak | alignak/dependencynode.py | DependencyNodeFactory.eval_complex_cor_pattern | def eval_complex_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
# pylint: disable=too-many-branches
"""Parse and build recursively a tree of DependencyNode from a complex pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode
"""
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern)
in_par = False
tmp = ''
son_is_not = False # We keep is the next son will be not or not
stacked_parenthesis = 0
for char in pattern:
if char == '(':
stacked_parenthesis += 1
in_par = True
tmp = tmp.strip()
# Maybe we just start a par, but we got some things in tmp
# that should not be good in fact !
if stacked_parenthesis == 1 and tmp != '':
# TODO : real error
print("ERROR : bad expression near", tmp)
continue
# If we are already in a par, add this (
# but not if it's the first one so
if stacked_parenthesis > 1:
tmp += char
elif char == ')':
stacked_parenthesis -= 1
if stacked_parenthesis < 0:
# TODO : real error
print("Error : bad expression near", tmp, "too much ')'")
continue
if stacked_parenthesis == 0:
tmp = tmp.strip()
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
in_par = False
# OK now clean the tmp so we start clean
tmp = ''
continue
# ok here we are still in a huge par, we just close one sub one
tmp += char
# Expressions in par will be parsed in a sub node after. So just
# stack pattern
elif in_par:
tmp += char
# Until here, we're not in par
# Manage the NOT for an expression. Only allow ! at the beginning
# of a host or a host,service expression.
elif char == '!':
tmp = tmp.strip()
if tmp and tmp[0] != '!':
print("Error : bad expression near", tmp, "wrong position for '!'")
continue
# Flags next node not state
son_is_not = True
# DO NOT keep the c in tmp, we consumed it
elif char in ['&', '|']:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
# Look at the rule viability
if node.operand is not None and node.operand != 'of:' and char != node.operand:
# Should be logged as a warning / info? :)
return None
if node.operand != 'of:':
node.operand = char
if tmp != '':
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
tmp = ''
# Maybe it's a classic character or we're in par, if so, continue
else:
tmp += char
# Be sure to manage the trainling part when the line is done
tmp = tmp.strip()
if tmp != '':
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
# We got our nodes, so we can update 0 values of of_values
# with the number of sons
node.switch_zeros_of_values()
return node | python | def eval_complex_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
# pylint: disable=too-many-branches
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern)
in_par = False
tmp = ''
son_is_not = False # We keep is the next son will be not or not
stacked_parenthesis = 0
for char in pattern:
if char == '(':
stacked_parenthesis += 1
in_par = True
tmp = tmp.strip()
# Maybe we just start a par, but we got some things in tmp
# that should not be good in fact !
if stacked_parenthesis == 1 and tmp != '':
# TODO : real error
print("ERROR : bad expression near", tmp)
continue
# If we are already in a par, add this (
# but not if it's the first one so
if stacked_parenthesis > 1:
tmp += char
elif char == ')':
stacked_parenthesis -= 1
if stacked_parenthesis < 0:
# TODO : real error
print("Error : bad expression near", tmp, "too much ')'")
continue
if stacked_parenthesis == 0:
tmp = tmp.strip()
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
in_par = False
# OK now clean the tmp so we start clean
tmp = ''
continue
# ok here we are still in a huge par, we just close one sub one
tmp += char
# Expressions in par will be parsed in a sub node after. So just
# stack pattern
elif in_par:
tmp += char
# Until here, we're not in par
# Manage the NOT for an expression. Only allow ! at the beginning
# of a host or a host,service expression.
elif char == '!':
tmp = tmp.strip()
if tmp and tmp[0] != '!':
print("Error : bad expression near", tmp, "wrong position for '!'")
continue
# Flags next node not state
son_is_not = True
# DO NOT keep the c in tmp, we consumed it
elif char in ['&', '|']:
# Oh we got a real cut in an expression, if so, cut it
tmp = tmp.strip()
# Look at the rule viability
if node.operand is not None and node.operand != 'of:' and char != node.operand:
# Should be logged as a warning / info? :)
return None
if node.operand != 'of:':
node.operand = char
if tmp != '':
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
tmp = ''
# Maybe it's a classic character or we're in par, if so, continue
else:
tmp += char
# Be sure to manage the trainling part when the line is done
tmp = tmp.strip()
if tmp != '':
son = self.eval_cor_pattern(tmp, hosts, services,
hostgroups, servicegroups, running)
# Maybe our son was notted
if son_is_not:
son.not_value = True
son_is_not = False
node.sons.append(son)
# We got our nodes, so we can update 0 values of of_values
# with the number of sons
node.switch_zeros_of_values()
return node | [
"def",
"eval_complex_cor_pattern",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"# pylint: disable=too-many-branches",
"node",
"=",
"DependencyNode",
"(",
")",
"pattern... | Parse and build recursively a tree of DependencyNode from a complex pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"DependencyNode",
"from",
"a",
"complex",
"pattern"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L477-L600 |
20,966 | Alignak-monitoring/alignak | alignak/dependencynode.py | DependencyNodeFactory.eval_simple_cor_pattern | def eval_simple_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode
"""
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern)
# If it's a not value, tag the node and find
# the name without this ! operator
if pattern.startswith('!'):
node.not_value = True
pattern = pattern[1:]
# Is the pattern an expression to be expanded?
if re.search(r"^([%s]+|\*):" % self.host_flags, pattern) or \
re.search(r",\s*([%s]+:.*|\*)$" % self.service_flags, pattern):
# o is just extracted its attributes, then trashed.
son = self.expand_expression(pattern, hosts, services,
hostgroups, servicegroups, running)
if node.operand != 'of:':
node.operand = '&'
node.sons.extend(son.sons)
node.configuration_errors.extend(son.configuration_errors)
node.switch_zeros_of_values()
else:
node.operand = 'object'
obj, error = self.find_object(pattern, hosts, services)
# here we have Alignak SchedulingItem object (Host/Service)
if obj is not None:
# Set host or service
# pylint: disable=E1101
node.operand = obj.__class__.my_type
node.sons.append(obj.uuid) # Only store the uuid, not the full object.
else:
if running is False:
node.configuration_errors.append(error)
else:
# As business rules are re-evaluated at run time on
# each scheduling loop, if the rule becomes invalid
# because of a badly written macro modulation, it
# should be notified upper for the error to be
# displayed in the check output.
raise Exception(error)
return node | python | def eval_simple_cor_pattern(self, pattern, hosts, services,
hostgroups, servicegroups, running=False):
node = DependencyNode()
pattern = self.eval_xof_pattern(node, pattern)
# If it's a not value, tag the node and find
# the name without this ! operator
if pattern.startswith('!'):
node.not_value = True
pattern = pattern[1:]
# Is the pattern an expression to be expanded?
if re.search(r"^([%s]+|\*):" % self.host_flags, pattern) or \
re.search(r",\s*([%s]+:.*|\*)$" % self.service_flags, pattern):
# o is just extracted its attributes, then trashed.
son = self.expand_expression(pattern, hosts, services,
hostgroups, servicegroups, running)
if node.operand != 'of:':
node.operand = '&'
node.sons.extend(son.sons)
node.configuration_errors.extend(son.configuration_errors)
node.switch_zeros_of_values()
else:
node.operand = 'object'
obj, error = self.find_object(pattern, hosts, services)
# here we have Alignak SchedulingItem object (Host/Service)
if obj is not None:
# Set host or service
# pylint: disable=E1101
node.operand = obj.__class__.my_type
node.sons.append(obj.uuid) # Only store the uuid, not the full object.
else:
if running is False:
node.configuration_errors.append(error)
else:
# As business rules are re-evaluated at run time on
# each scheduling loop, if the rule becomes invalid
# because of a badly written macro modulation, it
# should be notified upper for the error to be
# displayed in the check output.
raise Exception(error)
return node | [
"def",
"eval_simple_cor_pattern",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"node",
"=",
"DependencyNode",
"(",
")",
"pattern",
"=",
"self",
".",
"eval_xof_pat... | Parse and build recursively a tree of DependencyNode from a simple pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:param running: rules are evaluated at run time and parsing. True means runtime
:type running: bool
:return: root node of parsed tree
:rtype: alignak.dependencynode.DependencyNode | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"DependencyNode",
"from",
"a",
"simple",
"pattern"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L602-L655 |
20,967 | Alignak-monitoring/alignak | alignak/dependencynode.py | DependencyNodeFactory.find_object | def find_object(self, pattern, hosts, services):
"""Find object from pattern
:param pattern: text to search (host1,service1)
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:return: tuple with Host or Service object and error
:rtype: tuple
"""
obj = None
error = None
is_service = False
# h_name, service_desc are , separated
elts = pattern.split(',')
host_name = elts[0].strip()
# If host_name is empty, use the host_name the business rule is bound to
if not host_name:
host_name = self.bound_item.host_name
# Look if we have a service
if len(elts) > 1:
is_service = True
service_description = elts[1].strip()
if is_service:
obj = services.find_srv_by_name_and_hostname(host_name, service_description)
if not obj:
error = "Business rule uses unknown service %s/%s"\
% (host_name, service_description)
else:
obj = hosts.find_by_name(host_name)
if not obj:
error = "Business rule uses unknown host %s" % (host_name,)
return obj, error | python | def find_object(self, pattern, hosts, services):
obj = None
error = None
is_service = False
# h_name, service_desc are , separated
elts = pattern.split(',')
host_name = elts[0].strip()
# If host_name is empty, use the host_name the business rule is bound to
if not host_name:
host_name = self.bound_item.host_name
# Look if we have a service
if len(elts) > 1:
is_service = True
service_description = elts[1].strip()
if is_service:
obj = services.find_srv_by_name_and_hostname(host_name, service_description)
if not obj:
error = "Business rule uses unknown service %s/%s"\
% (host_name, service_description)
else:
obj = hosts.find_by_name(host_name)
if not obj:
error = "Business rule uses unknown host %s" % (host_name,)
return obj, error | [
"def",
"find_object",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
")",
":",
"obj",
"=",
"None",
"error",
"=",
"None",
"is_service",
"=",
"False",
"# h_name, service_desc are , separated",
"elts",
"=",
"pattern",
".",
"split",
"(",
"','",
")",... | Find object from pattern
:param pattern: text to search (host1,service1)
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
:type services: alignak.objects.service.Service
:return: tuple with Host or Service object and error
:rtype: tuple | [
"Find",
"object",
"from",
"pattern"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L657-L691 |
20,968 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.is_time_valid | def is_time_valid(self, timestamp):
"""
Check if a time is valid or not
:return: time is valid or not
:rtype: bool
"""
if hasattr(self, 'exclude'):
for daterange in self.exclude:
if daterange.is_time_valid(timestamp):
return False
for daterange in self.dateranges:
if daterange.is_time_valid(timestamp):
return True
return False | python | def is_time_valid(self, timestamp):
if hasattr(self, 'exclude'):
for daterange in self.exclude:
if daterange.is_time_valid(timestamp):
return False
for daterange in self.dateranges:
if daterange.is_time_valid(timestamp):
return True
return False | [
"def",
"is_time_valid",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'exclude'",
")",
":",
"for",
"daterange",
"in",
"self",
".",
"exclude",
":",
"if",
"daterange",
".",
"is_time_valid",
"(",
"timestamp",
")",
":",
"return... | Check if a time is valid or not
:return: time is valid or not
:rtype: bool | [
"Check",
"if",
"a",
"time",
"is",
"valid",
"or",
"not"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L274-L288 |
20,969 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.get_min_from_t | def get_min_from_t(self, timestamp):
"""
Get the first time > timestamp which is valid
:param timestamp: number of seconds
:type timestamp: int
:return: number of seconds
:rtype: int
TODO: not used, so delete it
"""
mins_incl = []
for daterange in self.dateranges:
mins_incl.append(daterange.get_min_from_t(timestamp))
return min(mins_incl) | python | def get_min_from_t(self, timestamp):
mins_incl = []
for daterange in self.dateranges:
mins_incl.append(daterange.get_min_from_t(timestamp))
return min(mins_incl) | [
"def",
"get_min_from_t",
"(",
"self",
",",
"timestamp",
")",
":",
"mins_incl",
"=",
"[",
"]",
"for",
"daterange",
"in",
"self",
".",
"dateranges",
":",
"mins_incl",
".",
"append",
"(",
"daterange",
".",
"get_min_from_t",
"(",
"timestamp",
")",
")",
"return... | Get the first time > timestamp which is valid
:param timestamp: number of seconds
:type timestamp: int
:return: number of seconds
:rtype: int
TODO: not used, so delete it | [
"Get",
"the",
"first",
"time",
">",
"timestamp",
"which",
"is",
"valid"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L291-L304 |
20,970 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.clean_cache | def clean_cache(self):
"""
Clean cache with entries older than now because not used in future ;)
:return: None
"""
now = int(time.time())
t_to_del = []
for timestamp in self.cache:
if timestamp < now:
t_to_del.append(timestamp)
for timestamp in t_to_del:
del self.cache[timestamp]
# same for the invalid cache
t_to_del = []
for timestamp in self.invalid_cache:
if timestamp < now:
t_to_del.append(timestamp)
for timestamp in t_to_del:
del self.invalid_cache[timestamp] | python | def clean_cache(self):
now = int(time.time())
t_to_del = []
for timestamp in self.cache:
if timestamp < now:
t_to_del.append(timestamp)
for timestamp in t_to_del:
del self.cache[timestamp]
# same for the invalid cache
t_to_del = []
for timestamp in self.invalid_cache:
if timestamp < now:
t_to_del.append(timestamp)
for timestamp in t_to_del:
del self.invalid_cache[timestamp] | [
"def",
"clean_cache",
"(",
"self",
")",
":",
"now",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"t_to_del",
"=",
"[",
"]",
"for",
"timestamp",
"in",
"self",
".",
"cache",
":",
"if",
"timestamp",
"<",
"now",
":",
"t_to_del",
".",
"append",
... | Clean cache with entries older than now because not used in future ;)
:return: None | [
"Clean",
"cache",
"with",
"entries",
"older",
"than",
"now",
"because",
"not",
"used",
"in",
"future",
";",
")"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L381-L401 |
20,971 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.get_next_valid_time_from_t | def get_next_valid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
"""
Get next valid time. If it's in cache, get it, otherwise define it.
The limit to find it is 1 year.
:param timestamp: number of seconds
:type timestamp: int or float
:return: Nothing or time in seconds
:rtype: None or int
"""
timestamp = int(timestamp)
original_t = timestamp
res_from_cache = self.find_next_valid_time_from_cache(timestamp)
if res_from_cache is not None:
return res_from_cache
still_loop = True
# Loop for all minutes...
while still_loop:
local_min = None
# Ok, not in cache...
dr_mins = []
for daterange in self.dateranges:
dr_mins.append(daterange.get_next_valid_time_from_t(timestamp))
s_dr_mins = sorted([d for d in dr_mins if d is not None])
for t01 in s_dr_mins:
if not self.exclude and still_loop:
# No Exclude so we are good
local_min = t01
still_loop = False
else:
for timeperiod in self.exclude:
if not timeperiod.is_time_valid(t01) and still_loop:
# OK we found a date that is not valid in any exclude timeperiod
local_min = t01
still_loop = False
if local_min is None:
# Looking for next invalid date
exc_mins = []
if s_dr_mins != []:
for timeperiod in self.exclude:
exc_mins.append(timeperiod.get_next_invalid_time_from_t(s_dr_mins[0]))
s_exc_mins = sorted([d for d in exc_mins if d is not None])
if s_exc_mins != []:
local_min = s_exc_mins[0]
if local_min is None:
still_loop = False
else:
timestamp = local_min
# No loop more than one year
if timestamp > original_t + 3600 * 24 * 366 + 1:
still_loop = False
local_min = None
# Ok, we update the cache...
self.cache[original_t] = local_min
return local_min | python | def get_next_valid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
timestamp = int(timestamp)
original_t = timestamp
res_from_cache = self.find_next_valid_time_from_cache(timestamp)
if res_from_cache is not None:
return res_from_cache
still_loop = True
# Loop for all minutes...
while still_loop:
local_min = None
# Ok, not in cache...
dr_mins = []
for daterange in self.dateranges:
dr_mins.append(daterange.get_next_valid_time_from_t(timestamp))
s_dr_mins = sorted([d for d in dr_mins if d is not None])
for t01 in s_dr_mins:
if not self.exclude and still_loop:
# No Exclude so we are good
local_min = t01
still_loop = False
else:
for timeperiod in self.exclude:
if not timeperiod.is_time_valid(t01) and still_loop:
# OK we found a date that is not valid in any exclude timeperiod
local_min = t01
still_loop = False
if local_min is None:
# Looking for next invalid date
exc_mins = []
if s_dr_mins != []:
for timeperiod in self.exclude:
exc_mins.append(timeperiod.get_next_invalid_time_from_t(s_dr_mins[0]))
s_exc_mins = sorted([d for d in exc_mins if d is not None])
if s_exc_mins != []:
local_min = s_exc_mins[0]
if local_min is None:
still_loop = False
else:
timestamp = local_min
# No loop more than one year
if timestamp > original_t + 3600 * 24 * 366 + 1:
still_loop = False
local_min = None
# Ok, we update the cache...
self.cache[original_t] = local_min
return local_min | [
"def",
"get_next_valid_time_from_t",
"(",
"self",
",",
"timestamp",
")",
":",
"# pylint: disable=too-many-branches",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"original_t",
"=",
"timestamp",
"res_from_cache",
"=",
"self",
".",
"find_next_valid_time_from_cache",
"(... | Get next valid time. If it's in cache, get it, otherwise define it.
The limit to find it is 1 year.
:param timestamp: number of seconds
:type timestamp: int or float
:return: Nothing or time in seconds
:rtype: None or int | [
"Get",
"next",
"valid",
"time",
".",
"If",
"it",
"s",
"in",
"cache",
"get",
"it",
"otherwise",
"define",
"it",
".",
"The",
"limit",
"to",
"find",
"it",
"is",
"1",
"year",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L403-L470 |
20,972 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.get_next_invalid_time_from_t | def get_next_invalid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
"""
Get the next invalid time
:param timestamp: timestamp in seconds (of course)
:type timestamp: int or float
:return: timestamp of next invalid time
:rtype: int or float
"""
timestamp = int(timestamp)
original_t = timestamp
dr_mins = []
for daterange in self.dateranges:
timestamp = original_t
cont = True
while cont:
start = daterange.get_next_valid_time_from_t(timestamp)
if start is not None:
end = daterange.get_next_invalid_time_from_t(start)
dr_mins.append((start, end))
timestamp = end
else:
cont = False
if timestamp > original_t + (3600 * 24 * 365):
cont = False
periods = merge_periods(dr_mins)
# manage exclude periods
dr_mins = []
for exclude in self.exclude:
for daterange in exclude.dateranges:
timestamp = original_t
cont = True
while cont:
start = daterange.get_next_valid_time_from_t(timestamp)
if start is not None:
end = daterange.get_next_invalid_time_from_t(start)
dr_mins.append((start, end))
timestamp = end
else:
cont = False
if timestamp > original_t + (3600 * 24 * 365):
cont = False
if not dr_mins:
periods_exclude = []
else:
periods_exclude = merge_periods(dr_mins)
if len(periods) >= 1:
# if first valid period is after original timestamp, the first invalid time
# is the original timestamp
if periods[0][0] > original_t:
return original_t
# check the first period + first period of exclude
if len(periods_exclude) >= 1:
if periods_exclude[0][0] < periods[0][1]:
return periods_exclude[0][0]
return periods[0][1]
return original_t | python | def get_next_invalid_time_from_t(self, timestamp):
# pylint: disable=too-many-branches
timestamp = int(timestamp)
original_t = timestamp
dr_mins = []
for daterange in self.dateranges:
timestamp = original_t
cont = True
while cont:
start = daterange.get_next_valid_time_from_t(timestamp)
if start is not None:
end = daterange.get_next_invalid_time_from_t(start)
dr_mins.append((start, end))
timestamp = end
else:
cont = False
if timestamp > original_t + (3600 * 24 * 365):
cont = False
periods = merge_periods(dr_mins)
# manage exclude periods
dr_mins = []
for exclude in self.exclude:
for daterange in exclude.dateranges:
timestamp = original_t
cont = True
while cont:
start = daterange.get_next_valid_time_from_t(timestamp)
if start is not None:
end = daterange.get_next_invalid_time_from_t(start)
dr_mins.append((start, end))
timestamp = end
else:
cont = False
if timestamp > original_t + (3600 * 24 * 365):
cont = False
if not dr_mins:
periods_exclude = []
else:
periods_exclude = merge_periods(dr_mins)
if len(periods) >= 1:
# if first valid period is after original timestamp, the first invalid time
# is the original timestamp
if periods[0][0] > original_t:
return original_t
# check the first period + first period of exclude
if len(periods_exclude) >= 1:
if periods_exclude[0][0] < periods[0][1]:
return periods_exclude[0][0]
return periods[0][1]
return original_t | [
"def",
"get_next_invalid_time_from_t",
"(",
"self",
",",
"timestamp",
")",
":",
"# pylint: disable=too-many-branches",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"original_t",
"=",
"timestamp",
"dr_mins",
"=",
"[",
"]",
"for",
"daterange",
"in",
"self",
".",
... | Get the next invalid time
:param timestamp: timestamp in seconds (of course)
:type timestamp: int or float
:return: timestamp of next invalid time
:rtype: int or float | [
"Get",
"the",
"next",
"invalid",
"time"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L472-L532 |
20,973 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.explode | def explode(self):
"""
Try to resolve all unresolved elements
:return: None
"""
for entry in self.unresolved:
self.resolve_daterange(self.dateranges, entry)
self.unresolved = [] | python | def explode(self):
for entry in self.unresolved:
self.resolve_daterange(self.dateranges, entry)
self.unresolved = [] | [
"def",
"explode",
"(",
"self",
")",
":",
"for",
"entry",
"in",
"self",
".",
"unresolved",
":",
"self",
".",
"resolve_daterange",
"(",
"self",
".",
"dateranges",
",",
"entry",
")",
"self",
".",
"unresolved",
"=",
"[",
"]"
] | Try to resolve all unresolved elements
:return: None | [
"Try",
"to",
"resolve",
"all",
"unresolved",
"elements"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L868-L876 |
20,974 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.linkify | def linkify(self, timeperiods):
"""
Will make timeperiod in exclude with id of the timeperiods
:param timeperiods: Timeperiods object
:type timeperiods:
:return: None
"""
new_exclude = []
if hasattr(self, 'exclude') and self.exclude != []:
logger.debug("[timeentry::%s] have excluded %s", self.get_name(), self.exclude)
excluded_tps = self.exclude
for tp_name in excluded_tps:
timepriod = timeperiods.find_by_name(tp_name.strip())
if timepriod is not None:
new_exclude.append(timepriod.uuid)
else:
msg = "[timeentry::%s] unknown %s timeperiod" % (self.get_name(), tp_name)
self.add_error(msg)
self.exclude = new_exclude | python | def linkify(self, timeperiods):
new_exclude = []
if hasattr(self, 'exclude') and self.exclude != []:
logger.debug("[timeentry::%s] have excluded %s", self.get_name(), self.exclude)
excluded_tps = self.exclude
for tp_name in excluded_tps:
timepriod = timeperiods.find_by_name(tp_name.strip())
if timepriod is not None:
new_exclude.append(timepriod.uuid)
else:
msg = "[timeentry::%s] unknown %s timeperiod" % (self.get_name(), tp_name)
self.add_error(msg)
self.exclude = new_exclude | [
"def",
"linkify",
"(",
"self",
",",
"timeperiods",
")",
":",
"new_exclude",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"self",
",",
"'exclude'",
")",
"and",
"self",
".",
"exclude",
"!=",
"[",
"]",
":",
"logger",
".",
"debug",
"(",
"\"[timeentry::%s] have exclu... | Will make timeperiod in exclude with id of the timeperiods
:param timeperiods: Timeperiods object
:type timeperiods:
:return: None | [
"Will",
"make",
"timeperiod",
"in",
"exclude",
"with",
"id",
"of",
"the",
"timeperiods"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L878-L897 |
20,975 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiod.check_exclude_rec | def check_exclude_rec(self):
# pylint: disable=access-member-before-definition
"""
Check if this timeperiod is tagged
:return: if tagged return false, if not true
:rtype: bool
"""
if self.rec_tag:
msg = "[timeentry::%s] is in a loop in exclude parameter" % (self.get_name())
self.add_error(msg)
return False
self.rec_tag = True
for timeperiod in self.exclude:
timeperiod.check_exclude_rec()
return True | python | def check_exclude_rec(self):
# pylint: disable=access-member-before-definition
if self.rec_tag:
msg = "[timeentry::%s] is in a loop in exclude parameter" % (self.get_name())
self.add_error(msg)
return False
self.rec_tag = True
for timeperiod in self.exclude:
timeperiod.check_exclude_rec()
return True | [
"def",
"check_exclude_rec",
"(",
"self",
")",
":",
"# pylint: disable=access-member-before-definition",
"if",
"self",
".",
"rec_tag",
":",
"msg",
"=",
"\"[timeentry::%s] is in a loop in exclude parameter\"",
"%",
"(",
"self",
".",
"get_name",
"(",
")",
")",
"self",
".... | Check if this timeperiod is tagged
:return: if tagged return false, if not true
:rtype: bool | [
"Check",
"if",
"this",
"timeperiod",
"is",
"tagged"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L899-L914 |
20,976 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiods.explode | def explode(self):
"""
Try to resolve each timeperiod
:return: None
"""
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.explode() | python | def explode(self):
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.explode() | [
"def",
"explode",
"(",
"self",
")",
":",
"for",
"t_id",
"in",
"self",
".",
"items",
":",
"timeperiod",
"=",
"self",
".",
"items",
"[",
"t_id",
"]",
"timeperiod",
".",
"explode",
"(",
")"
] | Try to resolve each timeperiod
:return: None | [
"Try",
"to",
"resolve",
"each",
"timeperiod"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L948-L956 |
20,977 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiods.linkify | def linkify(self):
"""
Check exclusion for each timeperiod
:return: None
"""
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.linkify(self) | python | def linkify(self):
for t_id in self.items:
timeperiod = self.items[t_id]
timeperiod.linkify(self) | [
"def",
"linkify",
"(",
"self",
")",
":",
"for",
"t_id",
"in",
"self",
".",
"items",
":",
"timeperiod",
"=",
"self",
".",
"items",
"[",
"t_id",
"]",
"timeperiod",
".",
"linkify",
"(",
"self",
")"
] | Check exclusion for each timeperiod
:return: None | [
"Check",
"exclusion",
"for",
"each",
"timeperiod"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L958-L966 |
20,978 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiods.apply_inheritance | def apply_inheritance(self):
"""
The only interesting property to inherit is exclude
:return: None
"""
self.apply_partial_inheritance('exclude')
for i in self:
self.get_customs_properties_by_inheritance(i)
# And now apply inheritance for unresolved properties
# like the dateranges in fact
for timeperiod in self:
self.get_unresolved_properties_by_inheritance(timeperiod) | python | def apply_inheritance(self):
self.apply_partial_inheritance('exclude')
for i in self:
self.get_customs_properties_by_inheritance(i)
# And now apply inheritance for unresolved properties
# like the dateranges in fact
for timeperiod in self:
self.get_unresolved_properties_by_inheritance(timeperiod) | [
"def",
"apply_inheritance",
"(",
"self",
")",
":",
"self",
".",
"apply_partial_inheritance",
"(",
"'exclude'",
")",
"for",
"i",
"in",
"self",
":",
"self",
".",
"get_customs_properties_by_inheritance",
"(",
"i",
")",
"# And now apply inheritance for unresolved properties... | The only interesting property to inherit is exclude
:return: None | [
"The",
"only",
"interesting",
"property",
"to",
"inherit",
"is",
"exclude"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L980-L993 |
20,979 | Alignak-monitoring/alignak | alignak/objects/timeperiod.py | Timeperiods.is_correct | def is_correct(self):
"""
check if each properties of timeperiods are valid
:return: True if is correct, otherwise False
:rtype: bool
"""
valid = True
# We do not want a same hg to be explode again and again
# so we tag it
for timeperiod in list(self.items.values()):
timeperiod.rec_tag = False
for timeperiod in list(self.items.values()):
for tmp_tp in list(self.items.values()):
tmp_tp.rec_tag = False
valid = timeperiod.check_exclude_rec() and valid
# We clean the tags and collect the warning/erro messages
for timeperiod in list(self.items.values()):
del timeperiod.rec_tag
# Now other checks
if not timeperiod.is_correct():
valid = False
source = getattr(timeperiod, 'imported_from', "unknown source")
msg = "Configuration in %s::%s is incorrect; from: %s" % (
timeperiod.my_type, timeperiod.get_name(), source
)
self.add_error(msg)
self.configuration_errors += timeperiod.configuration_errors
self.configuration_warnings += timeperiod.configuration_warnings
# And check all timeperiods for correct (sunday is false)
for timeperiod in self:
valid = timeperiod.is_correct() and valid
return valid | python | def is_correct(self):
valid = True
# We do not want a same hg to be explode again and again
# so we tag it
for timeperiod in list(self.items.values()):
timeperiod.rec_tag = False
for timeperiod in list(self.items.values()):
for tmp_tp in list(self.items.values()):
tmp_tp.rec_tag = False
valid = timeperiod.check_exclude_rec() and valid
# We clean the tags and collect the warning/erro messages
for timeperiod in list(self.items.values()):
del timeperiod.rec_tag
# Now other checks
if not timeperiod.is_correct():
valid = False
source = getattr(timeperiod, 'imported_from', "unknown source")
msg = "Configuration in %s::%s is incorrect; from: %s" % (
timeperiod.my_type, timeperiod.get_name(), source
)
self.add_error(msg)
self.configuration_errors += timeperiod.configuration_errors
self.configuration_warnings += timeperiod.configuration_warnings
# And check all timeperiods for correct (sunday is false)
for timeperiod in self:
valid = timeperiod.is_correct() and valid
return valid | [
"def",
"is_correct",
"(",
"self",
")",
":",
"valid",
"=",
"True",
"# We do not want a same hg to be explode again and again",
"# so we tag it",
"for",
"timeperiod",
"in",
"list",
"(",
"self",
".",
"items",
".",
"values",
"(",
")",
")",
":",
"timeperiod",
".",
"r... | check if each properties of timeperiods are valid
:return: True if is correct, otherwise False
:rtype: bool | [
"check",
"if",
"each",
"properties",
"of",
"timeperiods",
"are",
"valid"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/timeperiod.py#L995-L1033 |
20,980 | Alignak-monitoring/alignak | alignak/dispatcher.py | Dispatcher.check_status_and_get_events | def check_status_and_get_events(self):
# pylint: disable=too-many-branches
"""Get all the daemons status
:return: Dictionary with all the daemons returned information
:rtype: dict
"""
statistics = {}
events = []
for daemon_link in self.all_daemons_links:
if daemon_link == self.arbiter_link:
# I exclude myself from the polling, sure I am reachable ;)
continue
if not daemon_link.active:
# I exclude the daemons that are not active
continue
try:
# Do not get the details to avoid overloading the communication
daemon_link.statistics = daemon_link.get_daemon_stats(details=False)
if daemon_link.statistics:
daemon_link.statistics['_freshness'] = int(time.time())
statistics[daemon_link.name] = daemon_link.statistics
logger.debug("Daemon %s statistics: %s",
daemon_link.name, daemon_link.statistics)
except LinkError:
logger.warning("Daemon connection failed, I could not get statistics.")
try:
got = daemon_link.get_events()
if got:
events.extend(got)
logger.debug("Daemon %s has %d events: %s", daemon_link.name, len(got), got)
except LinkError:
logger.warning("Daemon connection failed, I could not get events.")
return events | python | def check_status_and_get_events(self):
# pylint: disable=too-many-branches
statistics = {}
events = []
for daemon_link in self.all_daemons_links:
if daemon_link == self.arbiter_link:
# I exclude myself from the polling, sure I am reachable ;)
continue
if not daemon_link.active:
# I exclude the daemons that are not active
continue
try:
# Do not get the details to avoid overloading the communication
daemon_link.statistics = daemon_link.get_daemon_stats(details=False)
if daemon_link.statistics:
daemon_link.statistics['_freshness'] = int(time.time())
statistics[daemon_link.name] = daemon_link.statistics
logger.debug("Daemon %s statistics: %s",
daemon_link.name, daemon_link.statistics)
except LinkError:
logger.warning("Daemon connection failed, I could not get statistics.")
try:
got = daemon_link.get_events()
if got:
events.extend(got)
logger.debug("Daemon %s has %d events: %s", daemon_link.name, len(got), got)
except LinkError:
logger.warning("Daemon connection failed, I could not get events.")
return events | [
"def",
"check_status_and_get_events",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"statistics",
"=",
"{",
"}",
"events",
"=",
"[",
"]",
"for",
"daemon_link",
"in",
"self",
".",
"all_daemons_links",
":",
"if",
"daemon_link",
"==",
"self",
".",
"... | Get all the daemons status
:return: Dictionary with all the daemons returned information
:rtype: dict | [
"Get",
"all",
"the",
"daemons",
"status"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L299-L337 |
20,981 | Alignak-monitoring/alignak | alignak/dispatcher.py | Dispatcher.get_scheduler_ordered_list | def get_scheduler_ordered_list(self, realm):
"""Get sorted scheduler list for a specific realm
List is ordered as: alive first, then spare (if any), then dead scheduler links
:param realm: realm we want scheduler from
:type realm: alignak.objects.realm.Realm
:return: sorted scheduler list
:rtype: list[alignak.objects.schedulerlink.SchedulerLink]
"""
# Get the schedulers for the required realm
scheduler_links = []
for scheduler_link_uuid in realm.schedulers:
scheduler_links.append(self.schedulers[scheduler_link_uuid])
# Now we sort the schedulers so we take alive, then spare, then dead,
alive = []
spare = []
deads = []
for sdata in scheduler_links:
if sdata.alive and not sdata.spare:
alive.append(sdata)
elif sdata.alive and sdata.spare:
spare.append(sdata)
else:
deads.append(sdata)
scheduler_links = []
scheduler_links.extend(alive)
scheduler_links.extend(spare)
scheduler_links.extend(deads)
scheduler_links.reverse() # I need to pop the list, so reverse the list...
return scheduler_links | python | def get_scheduler_ordered_list(self, realm):
# Get the schedulers for the required realm
scheduler_links = []
for scheduler_link_uuid in realm.schedulers:
scheduler_links.append(self.schedulers[scheduler_link_uuid])
# Now we sort the schedulers so we take alive, then spare, then dead,
alive = []
spare = []
deads = []
for sdata in scheduler_links:
if sdata.alive and not sdata.spare:
alive.append(sdata)
elif sdata.alive and sdata.spare:
spare.append(sdata)
else:
deads.append(sdata)
scheduler_links = []
scheduler_links.extend(alive)
scheduler_links.extend(spare)
scheduler_links.extend(deads)
scheduler_links.reverse() # I need to pop the list, so reverse the list...
return scheduler_links | [
"def",
"get_scheduler_ordered_list",
"(",
"self",
",",
"realm",
")",
":",
"# Get the schedulers for the required realm",
"scheduler_links",
"=",
"[",
"]",
"for",
"scheduler_link_uuid",
"in",
"realm",
".",
"schedulers",
":",
"scheduler_links",
".",
"append",
"(",
"self... | Get sorted scheduler list for a specific realm
List is ordered as: alive first, then spare (if any), then dead scheduler links
:param realm: realm we want scheduler from
:type realm: alignak.objects.realm.Realm
:return: sorted scheduler list
:rtype: list[alignak.objects.schedulerlink.SchedulerLink] | [
"Get",
"sorted",
"scheduler",
"list",
"for",
"a",
"specific",
"realm"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L466-L498 |
20,982 | Alignak-monitoring/alignak | alignak/dispatcher.py | Dispatcher.dispatch | def dispatch(self, test=False): # pylint: disable=too-many-branches
"""
Send configuration to satellites
:return: None
"""
if not self.new_to_dispatch:
raise DispatcherError("Dispatcher cannot dispatch, "
"because no configuration is prepared!")
if self.first_dispatch_done:
raise DispatcherError("Dispatcher cannot dispatch, "
"because the configuration is still dispatched!")
if self.dispatch_ok:
logger.info("Dispatching is already done and ok...")
return
logger.info("Trying to send configuration to the satellites...")
self.dispatch_ok = True
# todo: the 3 loops hereunder may be factorized
for link in self.arbiters:
# If not me and a spare arbiter...
if link == self.arbiter_link:
# I exclude myself from the dispatching, I have my configuration ;)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.spare:
# Do not dispatch to a master arbiter!
continue
if link.configuration_sent:
logger.debug("Arbiter %s already sent!", link.name)
continue
if not link.reachable:
logger.debug("Arbiter %s is not reachable to receive its configuration",
link.name)
continue
logger.info("Sending configuration to the arbiter %s", link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
# Now that the spare arbiter has a configuration, tell him it must not run,
# because I'm not dead ;)
link.do_not_run()
for link in self.schedulers:
if link.configuration_sent:
logger.debug("Scheduler %s already sent!", link.name)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.reachable:
logger.debug("Scheduler %s is not reachable to receive its configuration",
link.name)
continue
logger.info("Sending configuration to the scheduler %s", link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
for link in self.satellites:
if link.configuration_sent:
logger.debug("%s %s already sent!", link.type, link.name)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.reachable:
logger.warning("%s %s is not reachable to receive its configuration",
link.type, link.name)
continue
logger.info("Sending configuration to the %s %s", link.type, link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
if self.dispatch_ok:
# Newly prepared configuration got dispatched correctly
self.new_to_dispatch = False
self.first_dispatch_done = True | python | def dispatch(self, test=False): # pylint: disable=too-many-branches
if not self.new_to_dispatch:
raise DispatcherError("Dispatcher cannot dispatch, "
"because no configuration is prepared!")
if self.first_dispatch_done:
raise DispatcherError("Dispatcher cannot dispatch, "
"because the configuration is still dispatched!")
if self.dispatch_ok:
logger.info("Dispatching is already done and ok...")
return
logger.info("Trying to send configuration to the satellites...")
self.dispatch_ok = True
# todo: the 3 loops hereunder may be factorized
for link in self.arbiters:
# If not me and a spare arbiter...
if link == self.arbiter_link:
# I exclude myself from the dispatching, I have my configuration ;)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.spare:
# Do not dispatch to a master arbiter!
continue
if link.configuration_sent:
logger.debug("Arbiter %s already sent!", link.name)
continue
if not link.reachable:
logger.debug("Arbiter %s is not reachable to receive its configuration",
link.name)
continue
logger.info("Sending configuration to the arbiter %s", link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
# Now that the spare arbiter has a configuration, tell him it must not run,
# because I'm not dead ;)
link.do_not_run()
for link in self.schedulers:
if link.configuration_sent:
logger.debug("Scheduler %s already sent!", link.name)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.reachable:
logger.debug("Scheduler %s is not reachable to receive its configuration",
link.name)
continue
logger.info("Sending configuration to the scheduler %s", link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
for link in self.satellites:
if link.configuration_sent:
logger.debug("%s %s already sent!", link.type, link.name)
continue
if not link.active:
# I exclude the daemons that are not active
continue
if not link.reachable:
logger.warning("%s %s is not reachable to receive its configuration",
link.type, link.name)
continue
logger.info("Sending configuration to the %s %s", link.type, link.name)
logger.debug("- %s", link.cfg)
link.put_conf(link.cfg, test=test)
link.configuration_sent = True
logger.info("- sent")
if self.dispatch_ok:
# Newly prepared configuration got dispatched correctly
self.new_to_dispatch = False
self.first_dispatch_done = True | [
"def",
"dispatch",
"(",
"self",
",",
"test",
"=",
"False",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"self",
".",
"new_to_dispatch",
":",
"raise",
"DispatcherError",
"(",
"\"Dispatcher cannot dispatch, \"",
"\"because no configuration is prepared!\"",
... | Send configuration to satellites
:return: None | [
"Send",
"configuration",
"to",
"satellites"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L839-L944 |
20,983 | Alignak-monitoring/alignak | alignak/dispatcher.py | Dispatcher.stop_request | def stop_request(self, stop_now=False):
"""Send a stop request to all the daemons
:param stop_now: stop now or go to stop wait mode
:type stop_now: bool
:return: True if all daemons are reachable
"""
all_ok = True
for daemon_link in self.all_daemons_links:
logger.debug("Stopping: %s (%s)", daemon_link, stop_now)
if daemon_link == self.arbiter_link:
# I exclude myself from the process, I know we are going to stop ;)
continue
if not daemon_link.active:
# I exclude the daemons that are not active
continue
# Send a stop request to the daemon
try:
stop_ok = daemon_link.stop_request(stop_now=stop_now)
except LinkError:
stop_ok = True
logger.warning("Daemon stop request failed, %s probably stopped!", daemon_link)
all_ok = all_ok and stop_ok
daemon_link.stopping = True
self.stop_request_sent = all_ok
return self.stop_request_sent | python | def stop_request(self, stop_now=False):
all_ok = True
for daemon_link in self.all_daemons_links:
logger.debug("Stopping: %s (%s)", daemon_link, stop_now)
if daemon_link == self.arbiter_link:
# I exclude myself from the process, I know we are going to stop ;)
continue
if not daemon_link.active:
# I exclude the daemons that are not active
continue
# Send a stop request to the daemon
try:
stop_ok = daemon_link.stop_request(stop_now=stop_now)
except LinkError:
stop_ok = True
logger.warning("Daemon stop request failed, %s probably stopped!", daemon_link)
all_ok = all_ok and stop_ok
daemon_link.stopping = True
self.stop_request_sent = all_ok
return self.stop_request_sent | [
"def",
"stop_request",
"(",
"self",
",",
"stop_now",
"=",
"False",
")",
":",
"all_ok",
"=",
"True",
"for",
"daemon_link",
"in",
"self",
".",
"all_daemons_links",
":",
"logger",
".",
"debug",
"(",
"\"Stopping: %s (%s)\"",
",",
"daemon_link",
",",
"stop_now",
... | Send a stop request to all the daemons
:param stop_now: stop now or go to stop wait mode
:type stop_now: bool
:return: True if all daemons are reachable | [
"Send",
"a",
"stop",
"request",
"to",
"all",
"the",
"daemons"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dispatcher.py#L946-L976 |
20,984 | Alignak-monitoring/alignak | alignak/property.py | BoolProp.pythonize | def pythonize(self, val):
"""Convert value into a boolean
:param val: value to convert
:type val: bool, int, str
:return: boolean corresponding to value ::
{'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
:rtype: bool
"""
__boolean_states__ = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
if isinstance(val, bool):
return val
val = unique_value(val).lower()
if val in list(__boolean_states__.keys()):
return __boolean_states__[val]
raise PythonizeError("Cannot convert '%s' to a boolean value" % val) | python | def pythonize(self, val):
__boolean_states__ = {'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
if isinstance(val, bool):
return val
val = unique_value(val).lower()
if val in list(__boolean_states__.keys()):
return __boolean_states__[val]
raise PythonizeError("Cannot convert '%s' to a boolean value" % val) | [
"def",
"pythonize",
"(",
"self",
",",
"val",
")",
":",
"__boolean_states__",
"=",
"{",
"'1'",
":",
"True",
",",
"'yes'",
":",
"True",
",",
"'true'",
":",
"True",
",",
"'on'",
":",
"True",
",",
"'0'",
":",
"False",
",",
"'no'",
":",
"False",
",",
... | Convert value into a boolean
:param val: value to convert
:type val: bool, int, str
:return: boolean corresponding to value ::
{'1': True, 'yes': True, 'true': True, 'on': True,
'0': False, 'no': False, 'false': False, 'off': False}
:rtype: bool | [
"Convert",
"value",
"into",
"a",
"boolean"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/property.py#L222-L243 |
20,985 | Alignak-monitoring/alignak | alignak/property.py | ToGuessProp.pythonize | def pythonize(self, val):
"""If value is a single list element just return the element
does nothing otherwise
:param val: value to convert
:type val:
:return: converted value
:rtype:
"""
if isinstance(val, list) and len(set(val)) == 1:
# If we have a list with a unique value just use it
return val[0]
# Well, can't choose to remove something.
return val | python | def pythonize(self, val):
if isinstance(val, list) and len(set(val)) == 1:
# If we have a list with a unique value just use it
return val[0]
# Well, can't choose to remove something.
return val | [
"def",
"pythonize",
"(",
"self",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"list",
")",
"and",
"len",
"(",
"set",
"(",
"val",
")",
")",
"==",
"1",
":",
"# If we have a list with a unique value just use it",
"return",
"val",
"[",
"0",
"]"... | If value is a single list element just return the element
does nothing otherwise
:param val: value to convert
:type val:
:return: converted value
:rtype: | [
"If",
"value",
"is",
"a",
"single",
"list",
"element",
"just",
"return",
"the",
"element",
"does",
"nothing",
"otherwise"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/property.py#L471-L485 |
20,986 | Alignak-monitoring/alignak | alignak/monitor.py | MonitorConnection.login | def login(self, username, password):
"""
Log into the WS interface and get the authentication token
if login is:
- accepted, returns True
- refused, returns False
In case of any error, raises a BackendException
:param username: login name
:type username: str
:param password: password
:type password: str
:param generate: Can have these values: enabled | force | disabled
:type generate: str
:return: return True if authentication is successfull, otherwise False
:rtype: bool
"""
logger.debug("login for: %s", username)
# Configured as not authenticated WS
if not username and not password:
self.set_token(token=None)
return False
if not username or not password:
logger.error("Username or password cannot be None!")
self.set_token(token=None)
return False
endpoint = 'login'
json = {'username': username, 'password': password}
response = self.get_response(method='POST', endpoint=endpoint, json=json)
if response.status_code == 401:
logger.error("Access denied to %s", self.url_endpoint_root)
self.set_token(token=None)
return False
resp = self.decode(response=response)
if 'token' in resp:
self.set_token(token=resp['token'])
return True
return False | python | def login(self, username, password):
logger.debug("login for: %s", username)
# Configured as not authenticated WS
if not username and not password:
self.set_token(token=None)
return False
if not username or not password:
logger.error("Username or password cannot be None!")
self.set_token(token=None)
return False
endpoint = 'login'
json = {'username': username, 'password': password}
response = self.get_response(method='POST', endpoint=endpoint, json=json)
if response.status_code == 401:
logger.error("Access denied to %s", self.url_endpoint_root)
self.set_token(token=None)
return False
resp = self.decode(response=response)
if 'token' in resp:
self.set_token(token=resp['token'])
return True
return False | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"logger",
".",
"debug",
"(",
"\"login for: %s\"",
",",
"username",
")",
"# Configured as not authenticated WS",
"if",
"not",
"username",
"and",
"not",
"password",
":",
"self",
".",
"set_t... | Log into the WS interface and get the authentication token
if login is:
- accepted, returns True
- refused, returns False
In case of any error, raises a BackendException
:param username: login name
:type username: str
:param password: password
:type password: str
:param generate: Can have these values: enabled | force | disabled
:type generate: str
:return: return True if authentication is successfull, otherwise False
:rtype: bool | [
"Log",
"into",
"the",
"WS",
"interface",
"and",
"get",
"the",
"authentication",
"token"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L153-L198 |
20,987 | Alignak-monitoring/alignak | alignak/monitor.py | MonitorConnection.logout | def logout(self):
"""
Logout from the backend
:return: return True if logout is successfull, otherwise False
:rtype: bool
"""
logger.debug("request backend logout")
if not self.authenticated:
logger.warning("Unnecessary logout ...")
return True
endpoint = 'logout'
_ = self.get_response(method='POST', endpoint=endpoint)
self.session.close()
self.set_token(token=None)
return True | python | def logout(self):
logger.debug("request backend logout")
if not self.authenticated:
logger.warning("Unnecessary logout ...")
return True
endpoint = 'logout'
_ = self.get_response(method='POST', endpoint=endpoint)
self.session.close()
self.set_token(token=None)
return True | [
"def",
"logout",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"request backend logout\"",
")",
"if",
"not",
"self",
".",
"authenticated",
":",
"logger",
".",
"warning",
"(",
"\"Unnecessary logout ...\"",
")",
"return",
"True",
"endpoint",
"=",
"'logou... | Logout from the backend
:return: return True if logout is successfull, otherwise False
:rtype: bool | [
"Logout",
"from",
"the",
"backend"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L200-L219 |
20,988 | Alignak-monitoring/alignak | alignak/monitor.py | MonitorConnection.get | def get(self, endpoint, params=None):
"""
Get items or item in alignak backend
If an error occurs, a BackendException is raised.
This method builds a response as a dictionary that always contains: _items and _status::
{
u'_items': [
...
],
u'_status': u'OK'
}
:param endpoint: endpoint (API URL) relative from root endpoint
:type endpoint: str
:param params: parameters for the backend API
:type params: dict
:return: dictionary as specified upper
:rtype: dict
"""
response = self.get_response(method='GET', endpoint=endpoint, params=params)
resp = self.decode(response=response)
if '_status' not in resp: # pragma: no cover - need specific backend tests
resp['_status'] = u'OK' # TODO: Sure??
return resp | python | def get(self, endpoint, params=None):
response = self.get_response(method='GET', endpoint=endpoint, params=params)
resp = self.decode(response=response)
if '_status' not in resp: # pragma: no cover - need specific backend tests
resp['_status'] = u'OK' # TODO: Sure??
return resp | [
"def",
"get",
"(",
"self",
",",
"endpoint",
",",
"params",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"get_response",
"(",
"method",
"=",
"'GET'",
",",
"endpoint",
"=",
"endpoint",
",",
"params",
"=",
"params",
")",
"resp",
"=",
"self",
"."... | Get items or item in alignak backend
If an error occurs, a BackendException is raised.
This method builds a response as a dictionary that always contains: _items and _status::
{
u'_items': [
...
],
u'_status': u'OK'
}
:param endpoint: endpoint (API URL) relative from root endpoint
:type endpoint: str
:param params: parameters for the backend API
:type params: dict
:return: dictionary as specified upper
:rtype: dict | [
"Get",
"items",
"or",
"item",
"in",
"alignak",
"backend"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L221-L249 |
20,989 | Alignak-monitoring/alignak | alignak/monitor.py | MonitorConnection.post | def post(self, endpoint, data, files=None, headers=None):
# pylint: disable=unused-argument
"""
Create a new item
:param endpoint: endpoint (API URL)
:type endpoint: str
:param data: properties of item to create
:type data: dict
:param files: Not used. To be implemented
:type files: None
:param headers: headers (example: Content-Type)
:type headers: dict
:return: response (creation information)
:rtype: dict
"""
# We let Requests encode data to json
response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers)
resp = self.decode(response=response)
return resp | python | def post(self, endpoint, data, files=None, headers=None):
# pylint: disable=unused-argument
# We let Requests encode data to json
response = self.get_response(method='POST', endpoint=endpoint, json=data, headers=headers)
resp = self.decode(response=response)
return resp | [
"def",
"post",
"(",
"self",
",",
"endpoint",
",",
"data",
",",
"files",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"# We let Requests encode data to json",
"response",
"=",
"self",
".",
"get_response",
"(",
"method",
... | Create a new item
:param endpoint: endpoint (API URL)
:type endpoint: str
:param data: properties of item to create
:type data: dict
:param files: Not used. To be implemented
:type files: None
:param headers: headers (example: Content-Type)
:type headers: dict
:return: response (creation information)
:rtype: dict | [
"Create",
"a",
"new",
"item"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L251-L272 |
20,990 | Alignak-monitoring/alignak | alignak/monitor.py | MonitorConnection.patch | def patch(self, endpoint, data):
"""
Method to update an item
The headers must include an If-Match containing the object _etag.
headers = {'If-Match': contact_etag}
The data dictionary contain the fields that must be modified.
If the patching fails because the _etag object do not match with the provided one, a
BackendException is raised with code = 412.
If inception is True, this method makes e new get request on the endpoint to refresh the
_etag and then a new patch is called.
If an HTTP 412 error occurs, a BackendException is raised. This exception is:
- code: 412
- message: response content
- response: backend response
All other HTTP error raises a BackendException.
If some _issues are provided by the backend, this exception is:
- code: HTTP error code
- message: response content
- response: JSON encoded backend response (including '_issues' dictionary ...)
If no _issues are provided and an _error is signaled by the backend, this exception is:
- code: backend error code
- message: backend error message
- response: JSON encoded backend response
:param endpoint: endpoint (API URL)
:type endpoint: str
:param data: properties of item to update
:type data: dict
:param headers: headers (example: Content-Type). 'If-Match' required
:type headers: dict
:param inception: if True tries to get the last _etag
:type inception: bool
:return: dictionary containing patch response from the backend
:rtype: dict
"""
response = self.get_response(method='PATCH', endpoint=endpoint, json=data,
headers={'Content-Type': 'application/json'})
if response.status_code == 200:
return self.decode(response=response)
return response | python | def patch(self, endpoint, data):
response = self.get_response(method='PATCH', endpoint=endpoint, json=data,
headers={'Content-Type': 'application/json'})
if response.status_code == 200:
return self.decode(response=response)
return response | [
"def",
"patch",
"(",
"self",
",",
"endpoint",
",",
"data",
")",
":",
"response",
"=",
"self",
".",
"get_response",
"(",
"method",
"=",
"'PATCH'",
",",
"endpoint",
"=",
"endpoint",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"{",
"'Content-Type'",
":... | Method to update an item
The headers must include an If-Match containing the object _etag.
headers = {'If-Match': contact_etag}
The data dictionary contain the fields that must be modified.
If the patching fails because the _etag object do not match with the provided one, a
BackendException is raised with code = 412.
If inception is True, this method makes e new get request on the endpoint to refresh the
_etag and then a new patch is called.
If an HTTP 412 error occurs, a BackendException is raised. This exception is:
- code: 412
- message: response content
- response: backend response
All other HTTP error raises a BackendException.
If some _issues are provided by the backend, this exception is:
- code: HTTP error code
- message: response content
- response: JSON encoded backend response (including '_issues' dictionary ...)
If no _issues are provided and an _error is signaled by the backend, this exception is:
- code: backend error code
- message: backend error message
- response: JSON encoded backend response
:param endpoint: endpoint (API URL)
:type endpoint: str
:param data: properties of item to update
:type data: dict
:param headers: headers (example: Content-Type). 'If-Match' required
:type headers: dict
:param inception: if True tries to get the last _etag
:type inception: bool
:return: dictionary containing patch response from the backend
:rtype: dict | [
"Method",
"to",
"update",
"an",
"item"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/monitor.py#L274-L322 |
20,991 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver.init | def init(self, conf):
"""Initialize MacroResolver instance with conf.
Must be called at least once.
:param conf: configuration to load
:type conf: alignak.objects.Config
:return: None
"""
# For searching class and elements for on-demand
# we need link to types
self.my_conf = conf
self.lists_on_demand = []
self.hosts = self.my_conf.hosts
# For special void host_name handling...
self.host_class = self.hosts.inner_class
self.lists_on_demand.append(self.hosts)
self.services = self.my_conf.services
self.contacts = self.my_conf.contacts
self.lists_on_demand.append(self.contacts)
self.hostgroups = self.my_conf.hostgroups
self.lists_on_demand.append(self.hostgroups)
self.commands = self.my_conf.commands
self.servicegroups = self.my_conf.servicegroups
self.lists_on_demand.append(self.servicegroups)
self.contactgroups = self.my_conf.contactgroups
self.lists_on_demand.append(self.contactgroups)
self.illegal_macro_output_chars = self.my_conf.illegal_macro_output_chars
self.env_prefix = self.my_conf.env_variables_prefix | python | def init(self, conf):
# For searching class and elements for on-demand
# we need link to types
self.my_conf = conf
self.lists_on_demand = []
self.hosts = self.my_conf.hosts
# For special void host_name handling...
self.host_class = self.hosts.inner_class
self.lists_on_demand.append(self.hosts)
self.services = self.my_conf.services
self.contacts = self.my_conf.contacts
self.lists_on_demand.append(self.contacts)
self.hostgroups = self.my_conf.hostgroups
self.lists_on_demand.append(self.hostgroups)
self.commands = self.my_conf.commands
self.servicegroups = self.my_conf.servicegroups
self.lists_on_demand.append(self.servicegroups)
self.contactgroups = self.my_conf.contactgroups
self.lists_on_demand.append(self.contactgroups)
self.illegal_macro_output_chars = self.my_conf.illegal_macro_output_chars
self.env_prefix = self.my_conf.env_variables_prefix | [
"def",
"init",
"(",
"self",
",",
"conf",
")",
":",
"# For searching class and elements for on-demand",
"# we need link to types",
"self",
".",
"my_conf",
"=",
"conf",
"self",
".",
"lists_on_demand",
"=",
"[",
"]",
"self",
".",
"hosts",
"=",
"self",
".",
"my_conf... | Initialize MacroResolver instance with conf.
Must be called at least once.
:param conf: configuration to load
:type conf: alignak.objects.Config
:return: None | [
"Initialize",
"MacroResolver",
"instance",
"with",
"conf",
".",
"Must",
"be",
"called",
"at",
"least",
"once",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L146-L174 |
20,992 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._get_value_from_element | def _get_value_from_element(self, elt, prop):
# pylint: disable=too-many-return-statements
"""Get value from an element's property.
the property may be a function to call.
If the property is not resolved (because not implemented), this function will return 'n/a'
:param elt: element
:type elt: object
:param prop: element property
:type prop: str
:return: getattr(elt, prop) or getattr(elt, prop)() (call)
:rtype: str
"""
args = None
# We have args to provide to the function
if isinstance(prop, tuple):
prop, args = prop
value = getattr(elt, prop, None)
if value is None:
return 'n/a'
try:
# If the macro is set to a list property
if isinstance(value, list):
# Return the list items, comma separated and bracketed
return "[%s]" % ','.join(value)
# If the macro is not set as a function to call
if not isinstance(value, collections.Callable):
return value
# Case of a function call with no arguments
if not args:
return value()
# Case where we need args to the function
# ex : HOSTGROUPNAME (we need hostgroups)
# ex : SHORTSTATUS (we need hosts and services if bp_rule)
real_args = []
for arg in args:
real_args.append(getattr(self, arg, None))
return value(*real_args)
except AttributeError:
# Commented because there are many unresolved macros and this log is spamming :/
# # Raise a warning and return a strange value when macro cannot be resolved
# warnings.warn(
# 'Error when getting the property value for a macro: %s',
# MacroWarning, stacklevel=2)
# Return a strange value when macro cannot be resolved
return 'n/a'
except UnicodeError:
if isinstance(value, string_types):
return str(value, 'utf8', errors='ignore')
return 'n/a' | python | def _get_value_from_element(self, elt, prop):
# pylint: disable=too-many-return-statements
args = None
# We have args to provide to the function
if isinstance(prop, tuple):
prop, args = prop
value = getattr(elt, prop, None)
if value is None:
return 'n/a'
try:
# If the macro is set to a list property
if isinstance(value, list):
# Return the list items, comma separated and bracketed
return "[%s]" % ','.join(value)
# If the macro is not set as a function to call
if not isinstance(value, collections.Callable):
return value
# Case of a function call with no arguments
if not args:
return value()
# Case where we need args to the function
# ex : HOSTGROUPNAME (we need hostgroups)
# ex : SHORTSTATUS (we need hosts and services if bp_rule)
real_args = []
for arg in args:
real_args.append(getattr(self, arg, None))
return value(*real_args)
except AttributeError:
# Commented because there are many unresolved macros and this log is spamming :/
# # Raise a warning and return a strange value when macro cannot be resolved
# warnings.warn(
# 'Error when getting the property value for a macro: %s',
# MacroWarning, stacklevel=2)
# Return a strange value when macro cannot be resolved
return 'n/a'
except UnicodeError:
if isinstance(value, string_types):
return str(value, 'utf8', errors='ignore')
return 'n/a' | [
"def",
"_get_value_from_element",
"(",
"self",
",",
"elt",
",",
"prop",
")",
":",
"# pylint: disable=too-many-return-statements",
"args",
"=",
"None",
"# We have args to provide to the function",
"if",
"isinstance",
"(",
"prop",
",",
"tuple",
")",
":",
"prop",
",",
... | Get value from an element's property.
the property may be a function to call.
If the property is not resolved (because not implemented), this function will return 'n/a'
:param elt: element
:type elt: object
:param prop: element property
:type prop: str
:return: getattr(elt, prop) or getattr(elt, prop)() (call)
:rtype: str | [
"Get",
"value",
"from",
"an",
"element",
"s",
"property",
"."
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L202-L258 |
20,993 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._delete_unwanted_caracters | def _delete_unwanted_caracters(self, chain):
"""Remove not wanted char from chain
unwanted char are illegal_macro_output_chars attribute
:param chain: chain to remove char from
:type chain: str
:return: chain cleaned
:rtype: str
"""
try:
chain = chain.decode('utf8', 'replace')
except UnicodeEncodeError:
# If it is still encoded correctly, ignore...
pass
except AttributeError:
# Python 3 will raise an exception because the line is still unicode
pass
for char in self.illegal_macro_output_chars:
chain = chain.replace(char, '')
return chain | python | def _delete_unwanted_caracters(self, chain):
try:
chain = chain.decode('utf8', 'replace')
except UnicodeEncodeError:
# If it is still encoded correctly, ignore...
pass
except AttributeError:
# Python 3 will raise an exception because the line is still unicode
pass
for char in self.illegal_macro_output_chars:
chain = chain.replace(char, '')
return chain | [
"def",
"_delete_unwanted_caracters",
"(",
"self",
",",
"chain",
")",
":",
"try",
":",
"chain",
"=",
"chain",
".",
"decode",
"(",
"'utf8'",
",",
"'replace'",
")",
"except",
"UnicodeEncodeError",
":",
"# If it is still encoded correctly, ignore...",
"pass",
"except",
... | Remove not wanted char from chain
unwanted char are illegal_macro_output_chars attribute
:param chain: chain to remove char from
:type chain: str
:return: chain cleaned
:rtype: str | [
"Remove",
"not",
"wanted",
"char",
"from",
"chain",
"unwanted",
"char",
"are",
"illegal_macro_output_chars",
"attribute"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L260-L279 |
20,994 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver.resolve_command | def resolve_command(self, com, data, macromodulations, timeperiods):
"""Resolve command macros with data
:param com: check / event handler or command call object
:type com: object
:param data: objects list, used to search for a specific macro (custom or object related)
:type data:
:return: command line with '$MACRO$' replaced with values
:param macromodulations: the available macro modulations
:type macromodulations: dict
:param timeperiods: the available timeperiods
:type timeperiods: dict
:rtype: str
"""
logger.debug("Resolving: macros in: %s, arguments: %s",
com.command.command_line, com.args)
return self.resolve_simple_macros_in_string(com.command.command_line, data,
macromodulations, timeperiods,
args=com.args) | python | def resolve_command(self, com, data, macromodulations, timeperiods):
logger.debug("Resolving: macros in: %s, arguments: %s",
com.command.command_line, com.args)
return self.resolve_simple_macros_in_string(com.command.command_line, data,
macromodulations, timeperiods,
args=com.args) | [
"def",
"resolve_command",
"(",
"self",
",",
"com",
",",
"data",
",",
"macromodulations",
",",
"timeperiods",
")",
":",
"logger",
".",
"debug",
"(",
"\"Resolving: macros in: %s, arguments: %s\"",
",",
"com",
".",
"command",
".",
"command_line",
",",
"com",
".",
... | Resolve command macros with data
:param com: check / event handler or command call object
:type com: object
:param data: objects list, used to search for a specific macro (custom or object related)
:type data:
:return: command line with '$MACRO$' replaced with values
:param macromodulations: the available macro modulations
:type macromodulations: dict
:param timeperiods: the available timeperiods
:type timeperiods: dict
:rtype: str | [
"Resolve",
"command",
"macros",
"with",
"data"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L429-L447 |
20,995 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._get_type_of_macro | def _get_type_of_macro(macros, objs):
r"""Set macros types
Example::
ARG\d -> ARGN,
HOSTBLABLA -> class one and set Host in class)
_HOSTTOTO -> HOST CUSTOM MACRO TOTO
SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1
:param macros: macros list in a dictionary
:type macros: dict
:param objs: objects list, used to tag object macros
:type objs: list
:return: None
"""
for macro in macros:
# ARGN Macros
if re.match(r'ARG\d', macro):
macros[macro]['type'] = 'ARGN'
continue
# USERN macros
# are managed in the Config class, so no
# need to look that here
elif re.match(r'_HOST\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'HOST'
continue
elif re.match(r'_SERVICE\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'SERVICE'
# value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1]
continue
elif re.match(r'_CONTACT\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'CONTACT'
continue
# On demand macro
elif len(macro.split(':')) > 1:
macros[macro]['type'] = 'ONDEMAND'
continue
# OK, classical macro...
for obj in objs:
if macro in obj.macros:
macros[macro]['type'] = 'object'
macros[macro]['object'] = obj
continue | python | def _get_type_of_macro(macros, objs):
r"""Set macros types
Example::
ARG\d -> ARGN,
HOSTBLABLA -> class one and set Host in class)
_HOSTTOTO -> HOST CUSTOM MACRO TOTO
SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1
:param macros: macros list in a dictionary
:type macros: dict
:param objs: objects list, used to tag object macros
:type objs: list
:return: None
"""
for macro in macros:
# ARGN Macros
if re.match(r'ARG\d', macro):
macros[macro]['type'] = 'ARGN'
continue
# USERN macros
# are managed in the Config class, so no
# need to look that here
elif re.match(r'_HOST\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'HOST'
continue
elif re.match(r'_SERVICE\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'SERVICE'
# value of macro: re.split('_HOST', '_HOSTMAC_ADDRESS')[1]
continue
elif re.match(r'_CONTACT\w', macro):
macros[macro]['type'] = 'CUSTOM'
macros[macro]['class'] = 'CONTACT'
continue
# On demand macro
elif len(macro.split(':')) > 1:
macros[macro]['type'] = 'ONDEMAND'
continue
# OK, classical macro...
for obj in objs:
if macro in obj.macros:
macros[macro]['type'] = 'object'
macros[macro]['object'] = obj
continue | [
"def",
"_get_type_of_macro",
"(",
"macros",
",",
"objs",
")",
":",
"for",
"macro",
"in",
"macros",
":",
"# ARGN Macros",
"if",
"re",
".",
"match",
"(",
"r'ARG\\d'",
",",
"macro",
")",
":",
"macros",
"[",
"macro",
"]",
"[",
"'type'",
"]",
"=",
"'ARGN'",... | r"""Set macros types
Example::
ARG\d -> ARGN,
HOSTBLABLA -> class one and set Host in class)
_HOSTTOTO -> HOST CUSTOM MACRO TOTO
SERVICESTATEID:srv-1:Load$ -> MACRO SERVICESTATEID of the service Load of host srv-1
:param macros: macros list in a dictionary
:type macros: dict
:param objs: objects list, used to tag object macros
:type objs: list
:return: None | [
"r",
"Set",
"macros",
"types"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L450-L496 |
20,996 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._resolve_ondemand | def _resolve_ondemand(self, macro, data):
# pylint: disable=too-many-locals
"""Get on demand macro value
If the macro cannot be resolved, this function will return 'n/a' rather than
an empty string, this to alert the caller of a potential problem.
:param macro: macro to parse
:type macro:
:param data: data to get value from
:type data:
:return: macro value
:rtype: str
"""
elts = macro.split(':')
nb_parts = len(elts)
macro_name = elts[0]
# 3 parts for a service, 2 for all others types...
if nb_parts == 3:
val = ''
(host_name, service_description) = (elts[1], elts[2])
# host_name can be void, so it's the host in data
# that is important. We use our self.host_class to
# find the host in the data :)
if host_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
host_name = elt.host_name
# Ok now we get service
serv = self.services.find_srv_by_name_and_hostname(host_name, service_description)
if serv is not None:
cls = serv.__class__
prop = cls.macros[macro_name]
val = self._get_value_from_element(serv, prop)
return val
# Ok, service was easy, now hard part
else:
val = ''
elt_name = elts[1]
# Special case: elt_name can be void
# so it's the host where it apply
if elt_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
elt_name = elt.host_name
for od_list in self.lists_on_demand:
cls = od_list.inner_class
# We search our type by looking at the macro
if macro_name in cls.macros:
prop = cls.macros[macro_name]
i = od_list.find_by_name(elt_name)
if i is not None:
val = self._get_value_from_element(i, prop)
# Ok we got our value :)
break
return val
# Return a strange value in this case rather than an empty string
return 'n/a' | python | def _resolve_ondemand(self, macro, data):
# pylint: disable=too-many-locals
elts = macro.split(':')
nb_parts = len(elts)
macro_name = elts[0]
# 3 parts for a service, 2 for all others types...
if nb_parts == 3:
val = ''
(host_name, service_description) = (elts[1], elts[2])
# host_name can be void, so it's the host in data
# that is important. We use our self.host_class to
# find the host in the data :)
if host_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
host_name = elt.host_name
# Ok now we get service
serv = self.services.find_srv_by_name_and_hostname(host_name, service_description)
if serv is not None:
cls = serv.__class__
prop = cls.macros[macro_name]
val = self._get_value_from_element(serv, prop)
return val
# Ok, service was easy, now hard part
else:
val = ''
elt_name = elts[1]
# Special case: elt_name can be void
# so it's the host where it apply
if elt_name == '':
for elt in data:
if elt is not None and elt.__class__ == self.host_class:
elt_name = elt.host_name
for od_list in self.lists_on_demand:
cls = od_list.inner_class
# We search our type by looking at the macro
if macro_name in cls.macros:
prop = cls.macros[macro_name]
i = od_list.find_by_name(elt_name)
if i is not None:
val = self._get_value_from_element(i, prop)
# Ok we got our value :)
break
return val
# Return a strange value in this case rather than an empty string
return 'n/a' | [
"def",
"_resolve_ondemand",
"(",
"self",
",",
"macro",
",",
"data",
")",
":",
"# pylint: disable=too-many-locals",
"elts",
"=",
"macro",
".",
"split",
"(",
"':'",
")",
"nb_parts",
"=",
"len",
"(",
"elts",
")",
"macro_name",
"=",
"elts",
"[",
"0",
"]",
"#... | Get on demand macro value
If the macro cannot be resolved, this function will return 'n/a' rather than
an empty string, this to alert the caller of a potential problem.
:param macro: macro to parse
:type macro:
:param data: data to get value from
:type data:
:return: macro value
:rtype: str | [
"Get",
"on",
"demand",
"macro",
"value"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L523-L581 |
20,997 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._tot_hosts_by_state | def _tot_hosts_by_state(self, state=None, state_type=None):
"""Generic function to get the number of host in the specified state
:param state: state to filter on
:type state: str
:param state_type: state type to filter on (HARD, SOFT)
:type state_type: str
:return: number of host in state *state*
:rtype: int
"""
if state is None and state_type is None:
return len(self.hosts)
if state_type:
return sum(1 for h in self.hosts if h.state == state and h.state_type == state_type)
return sum(1 for h in self.hosts if h.state == state) | python | def _tot_hosts_by_state(self, state=None, state_type=None):
if state is None and state_type is None:
return len(self.hosts)
if state_type:
return sum(1 for h in self.hosts if h.state == state and h.state_type == state_type)
return sum(1 for h in self.hosts if h.state == state) | [
"def",
"_tot_hosts_by_state",
"(",
"self",
",",
"state",
"=",
"None",
",",
"state_type",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
"and",
"state_type",
"is",
"None",
":",
"return",
"len",
"(",
"self",
".",
"hosts",
")",
"if",
"state_type",
":... | Generic function to get the number of host in the specified state
:param state: state to filter on
:type state: str
:param state_type: state type to filter on (HARD, SOFT)
:type state_type: str
:return: number of host in state *state*
:rtype: int | [
"Generic",
"function",
"to",
"get",
"the",
"number",
"of",
"host",
"in",
"the",
"specified",
"state"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L648-L662 |
20,998 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._tot_unhandled_hosts_by_state | def _tot_unhandled_hosts_by_state(self, state):
"""Generic function to get the number of unhandled problem hosts in the specified state
:param state: state to filter on
:type state:
:return: number of host in state *state* and which are not acknowledged problems
:rtype: int
"""
return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and
h.is_problem and not h.problem_has_been_acknowledged) | python | def _tot_unhandled_hosts_by_state(self, state):
return sum(1 for h in self.hosts if h.state == state and h.state_type == u'HARD' and
h.is_problem and not h.problem_has_been_acknowledged) | [
"def",
"_tot_unhandled_hosts_by_state",
"(",
"self",
",",
"state",
")",
":",
"return",
"sum",
"(",
"1",
"for",
"h",
"in",
"self",
".",
"hosts",
"if",
"h",
".",
"state",
"==",
"state",
"and",
"h",
".",
"state_type",
"==",
"u'HARD'",
"and",
"h",
".",
"... | Generic function to get the number of unhandled problem hosts in the specified state
:param state: state to filter on
:type state:
:return: number of host in state *state* and which are not acknowledged problems
:rtype: int | [
"Generic",
"function",
"to",
"get",
"the",
"number",
"of",
"unhandled",
"problem",
"hosts",
"in",
"the",
"specified",
"state"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L664-L673 |
20,999 | Alignak-monitoring/alignak | alignak/macroresolver.py | MacroResolver._tot_services_by_state | def _tot_services_by_state(self, state=None, state_type=None):
"""Generic function to get the number of services in the specified state
:param state: state to filter on
:type state: str
:param state_type: state type to filter on (HARD, SOFT)
:type state_type: str
:return: number of host in state *state*
:rtype: int
TODO: Should be moved
"""
if state is None and state_type is None:
return len(self.services)
if state_type:
return sum(1 for s in self.services if s.state == state and s.state_type == state_type)
return sum(1 for s in self.services if s.state == state) | python | def _tot_services_by_state(self, state=None, state_type=None):
if state is None and state_type is None:
return len(self.services)
if state_type:
return sum(1 for s in self.services if s.state == state and s.state_type == state_type)
return sum(1 for s in self.services if s.state == state) | [
"def",
"_tot_services_by_state",
"(",
"self",
",",
"state",
"=",
"None",
",",
"state_type",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
"and",
"state_type",
"is",
"None",
":",
"return",
"len",
"(",
"self",
".",
"services",
")",
"if",
"state_type"... | Generic function to get the number of services in the specified state
:param state: state to filter on
:type state: str
:param state_type: state type to filter on (HARD, SOFT)
:type state_type: str
:return: number of host in state *state*
:rtype: int
TODO: Should be moved | [
"Generic",
"function",
"to",
"get",
"the",
"number",
"of",
"services",
"in",
"the",
"specified",
"state"
] | f3c145207e83159b799d3714e4241399c7740a64 | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/macroresolver.py#L783-L798 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.