repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.reload_configuration
|
def reload_configuration(self):
"""Ask to the arbiter to reload the monitored configuration
**Note** tha the arbiter will not reload its main configuration file (eg. alignak.ini)
but it will reload the monitored objects from the Nagios legacy files or from the
Alignak backend!
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
:return: True if configuration reload is accepted
"""
# If I'm not the master arbiter, ignore the command and raise a log
if not self.app.is_master:
message = u"I received a request to reload the monitored configuration. " \
u"I am not the Master arbiter, I ignore and continue to run."
logger.warning(message)
return {'_status': u'ERR', '_message': message}
message = "I received a request to reload the monitored configuration"
if self.app.loading_configuration:
message = message + "and I am still reloading the monitored configuration ;)"
else:
self.app.need_config_reload = True
logger.warning(message)
return {'_status': u'OK', '_message': message}
|
python
|
def reload_configuration(self):
"""Ask to the arbiter to reload the monitored configuration
**Note** tha the arbiter will not reload its main configuration file (eg. alignak.ini)
but it will reload the monitored objects from the Nagios legacy files or from the
Alignak backend!
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
:return: True if configuration reload is accepted
"""
# If I'm not the master arbiter, ignore the command and raise a log
if not self.app.is_master:
message = u"I received a request to reload the monitored configuration. " \
u"I am not the Master arbiter, I ignore and continue to run."
logger.warning(message)
return {'_status': u'ERR', '_message': message}
message = "I received a request to reload the monitored configuration"
if self.app.loading_configuration:
message = message + "and I am still reloading the monitored configuration ;)"
else:
self.app.need_config_reload = True
logger.warning(message)
return {'_status': u'OK', '_message': message}
|
[
"def",
"reload_configuration",
"(",
"self",
")",
":",
"# If I'm not the master arbiter, ignore the command and raise a log",
"if",
"not",
"self",
".",
"app",
".",
"is_master",
":",
"message",
"=",
"u\"I received a request to reload the monitored configuration. \"",
"u\"I am not the Master arbiter, I ignore and continue to run.\"",
"logger",
".",
"warning",
"(",
"message",
")",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"message",
"}",
"message",
"=",
"\"I received a request to reload the monitored configuration\"",
"if",
"self",
".",
"app",
".",
"loading_configuration",
":",
"message",
"=",
"message",
"+",
"\"and I am still reloading the monitored configuration ;)\"",
"else",
":",
"self",
".",
"app",
".",
"need_config_reload",
"=",
"True",
"logger",
".",
"warning",
"(",
"message",
")",
"return",
"{",
"'_status'",
":",
"u'OK'",
",",
"'_message'",
":",
"message",
"}"
] |
Ask to the arbiter to reload the monitored configuration
**Note** tha the arbiter will not reload its main configuration file (eg. alignak.ini)
but it will reload the monitored objects from the Nagios legacy files or from the
Alignak backend!
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
:return: True if configuration reload is accepted
|
[
"Ask",
"to",
"the",
"arbiter",
"to",
"reload",
"the",
"monitored",
"configuration"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L52-L79
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.command
|
def command(self, command=None,
timestamp=None, element=None, host=None, service=None, user=None, parameters=None):
# pylint: disable=too-many-branches
""" Request to execute an external command
Allowed parameters are:
`command`: mandatory parameter containing the whole command line or only the command name
`timestamp`: optional parameter containing the timestamp. If not present, the
current timestamp is added in the command line
`element`: the targeted element that will be appended after the command name (`command`).
If element contains a '/' character it is split to make an host and service.
`host`, `service` or `user`: the targeted host, service or user. Takes precedence over
the `element` to target a specific element
`parameters`: the parameter that will be appended after all the arguments
When using this endpoint with the HTTP GET method, the semi colons that are commonly used
to separate the parameters must be replace with %3B! This because the ; is an accepted
URL query parameters separator...
Indeed, the recommended way of using this endpoint is to use the HTTP POST method.
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
The `_status` field is 'OK' with an according `_message` to explain what the Arbiter
will do depending upon the notification. The `command` property contains the formatted
external command.
:return: dict
"""
if cherrypy.request.method in ["POST"]:
if not cherrypy.request.json:
return {'_status': u'ERR',
'_message': u'You must POST parameters on this endpoint.'}
if command is None:
try:
command = cherrypy.request.json.get('command', None)
timestamp = cherrypy.request.json.get('timestamp', None)
element = cherrypy.request.json.get('element', None)
host = cherrypy.request.json.get('host', None)
service = cherrypy.request.json.get('service', None)
user = cherrypy.request.json.get('user', None)
parameters = cherrypy.request.json.get('parameters', None)
except AttributeError:
return {'_status': u'ERR', '_message': u'Missing command parameters'}
if not command:
return {'_status': u'ERR', '_message': u'Missing command parameter'}
fields = split_semicolon(command)
command_line = command.replace(fields[0], fields[0].upper())
if timestamp:
try:
timestamp = int(timestamp)
except ValueError:
return {'_status': u'ERR', '_message': u'Timestamp must be an integer value'}
command_line = '[%d] %s' % (timestamp, command_line)
if host or service or user:
if host:
command_line = '%s;%s' % (command_line, host)
if service:
command_line = '%s;%s' % (command_line, service)
if user:
command_line = '%s;%s' % (command_line, user)
elif element:
if '/' in element:
# Replace only the first /
element = element.replace('/', ';', 1)
command_line = '%s;%s' % (command_line, element)
if parameters:
command_line = '%s;%s' % (command_line, parameters)
# Add a command to get managed
logger.warning("Got an external command: %s", command_line)
self.app.add(ExternalCommand(command_line))
return {'_status': u'OK',
'_message': u"Got command: %s" % command_line,
'command': command_line}
|
python
|
def command(self, command=None,
timestamp=None, element=None, host=None, service=None, user=None, parameters=None):
# pylint: disable=too-many-branches
""" Request to execute an external command
Allowed parameters are:
`command`: mandatory parameter containing the whole command line or only the command name
`timestamp`: optional parameter containing the timestamp. If not present, the
current timestamp is added in the command line
`element`: the targeted element that will be appended after the command name (`command`).
If element contains a '/' character it is split to make an host and service.
`host`, `service` or `user`: the targeted host, service or user. Takes precedence over
the `element` to target a specific element
`parameters`: the parameter that will be appended after all the arguments
When using this endpoint with the HTTP GET method, the semi colons that are commonly used
to separate the parameters must be replace with %3B! This because the ; is an accepted
URL query parameters separator...
Indeed, the recommended way of using this endpoint is to use the HTTP POST method.
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
The `_status` field is 'OK' with an according `_message` to explain what the Arbiter
will do depending upon the notification. The `command` property contains the formatted
external command.
:return: dict
"""
if cherrypy.request.method in ["POST"]:
if not cherrypy.request.json:
return {'_status': u'ERR',
'_message': u'You must POST parameters on this endpoint.'}
if command is None:
try:
command = cherrypy.request.json.get('command', None)
timestamp = cherrypy.request.json.get('timestamp', None)
element = cherrypy.request.json.get('element', None)
host = cherrypy.request.json.get('host', None)
service = cherrypy.request.json.get('service', None)
user = cherrypy.request.json.get('user', None)
parameters = cherrypy.request.json.get('parameters', None)
except AttributeError:
return {'_status': u'ERR', '_message': u'Missing command parameters'}
if not command:
return {'_status': u'ERR', '_message': u'Missing command parameter'}
fields = split_semicolon(command)
command_line = command.replace(fields[0], fields[0].upper())
if timestamp:
try:
timestamp = int(timestamp)
except ValueError:
return {'_status': u'ERR', '_message': u'Timestamp must be an integer value'}
command_line = '[%d] %s' % (timestamp, command_line)
if host or service or user:
if host:
command_line = '%s;%s' % (command_line, host)
if service:
command_line = '%s;%s' % (command_line, service)
if user:
command_line = '%s;%s' % (command_line, user)
elif element:
if '/' in element:
# Replace only the first /
element = element.replace('/', ';', 1)
command_line = '%s;%s' % (command_line, element)
if parameters:
command_line = '%s;%s' % (command_line, parameters)
# Add a command to get managed
logger.warning("Got an external command: %s", command_line)
self.app.add(ExternalCommand(command_line))
return {'_status': u'OK',
'_message': u"Got command: %s" % command_line,
'command': command_line}
|
[
"def",
"command",
"(",
"self",
",",
"command",
"=",
"None",
",",
"timestamp",
"=",
"None",
",",
"element",
"=",
"None",
",",
"host",
"=",
"None",
",",
"service",
"=",
"None",
",",
"user",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"cherrypy",
".",
"request",
".",
"method",
"in",
"[",
"\"POST\"",
"]",
":",
"if",
"not",
"cherrypy",
".",
"request",
".",
"json",
":",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"u'You must POST parameters on this endpoint.'",
"}",
"if",
"command",
"is",
"None",
":",
"try",
":",
"command",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'command'",
",",
"None",
")",
"timestamp",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'timestamp'",
",",
"None",
")",
"element",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'element'",
",",
"None",
")",
"host",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'host'",
",",
"None",
")",
"service",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'service'",
",",
"None",
")",
"user",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'user'",
",",
"None",
")",
"parameters",
"=",
"cherrypy",
".",
"request",
".",
"json",
".",
"get",
"(",
"'parameters'",
",",
"None",
")",
"except",
"AttributeError",
":",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"u'Missing command parameters'",
"}",
"if",
"not",
"command",
":",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"u'Missing command parameter'",
"}",
"fields",
"=",
"split_semicolon",
"(",
"command",
")",
"command_line",
"=",
"command",
".",
"replace",
"(",
"fields",
"[",
"0",
"]",
",",
"fields",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
"if",
"timestamp",
":",
"try",
":",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"except",
"ValueError",
":",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"u'Timestamp must be an integer value'",
"}",
"command_line",
"=",
"'[%d] %s'",
"%",
"(",
"timestamp",
",",
"command_line",
")",
"if",
"host",
"or",
"service",
"or",
"user",
":",
"if",
"host",
":",
"command_line",
"=",
"'%s;%s'",
"%",
"(",
"command_line",
",",
"host",
")",
"if",
"service",
":",
"command_line",
"=",
"'%s;%s'",
"%",
"(",
"command_line",
",",
"service",
")",
"if",
"user",
":",
"command_line",
"=",
"'%s;%s'",
"%",
"(",
"command_line",
",",
"user",
")",
"elif",
"element",
":",
"if",
"'/'",
"in",
"element",
":",
"# Replace only the first /",
"element",
"=",
"element",
".",
"replace",
"(",
"'/'",
",",
"';'",
",",
"1",
")",
"command_line",
"=",
"'%s;%s'",
"%",
"(",
"command_line",
",",
"element",
")",
"if",
"parameters",
":",
"command_line",
"=",
"'%s;%s'",
"%",
"(",
"command_line",
",",
"parameters",
")",
"# Add a command to get managed",
"logger",
".",
"warning",
"(",
"\"Got an external command: %s\"",
",",
"command_line",
")",
"self",
".",
"app",
".",
"add",
"(",
"ExternalCommand",
"(",
"command_line",
")",
")",
"return",
"{",
"'_status'",
":",
"u'OK'",
",",
"'_message'",
":",
"u\"Got command: %s\"",
"%",
"command_line",
",",
"'command'",
":",
"command_line",
"}"
] |
Request to execute an external command
Allowed parameters are:
`command`: mandatory parameter containing the whole command line or only the command name
`timestamp`: optional parameter containing the timestamp. If not present, the
current timestamp is added in the command line
`element`: the targeted element that will be appended after the command name (`command`).
If element contains a '/' character it is split to make an host and service.
`host`, `service` or `user`: the targeted host, service or user. Takes precedence over
the `element` to target a specific element
`parameters`: the parameter that will be appended after all the arguments
When using this endpoint with the HTTP GET method, the semi colons that are commonly used
to separate the parameters must be replace with %3B! This because the ; is an accepted
URL query parameters separator...
Indeed, the recommended way of using this endpoint is to use the HTTP POST method.
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
The `_status` field is 'OK' with an according `_message` to explain what the Arbiter
will do depending upon the notification. The `command` property contains the formatted
external command.
:return: dict
|
[
"Request",
"to",
"execute",
"an",
"external",
"command"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L138-L224
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.monitoring_problems
|
def monitoring_problems(self):
"""Get Alignak detailed monitoring status
This will return an object containing the properties of the `identity`, plus a `problems`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- problems, which is an object with the scheduler known problems:
{
...
"problems": {
"scheduler-master": {
"_freshness": 1528903945,
"problems": {
"fdfc986d-4ab4-4562-9d2f-4346832745e6": {
"last_state": "CRITICAL",
"service": "dummy_critical",
"last_state_type": "SOFT",
"last_state_update": 1528902442,
"last_hard_state": "CRITICAL",
"last_hard_state_change": 1528902442,
"last_state_change": 1528902381,
"state": "CRITICAL",
"state_type": "HARD",
"host": "host-all-8",
"output": "Hi, checking host-all-8/dummy_critical -> exit=2"
},
"2445f2a3-2a3b-4b13-96ed-4cfb60790e7e": {
"last_state": "WARNING",
"service": "dummy_warning",
"last_state_type": "SOFT",
"last_state_update": 1528902463,
"last_hard_state": "WARNING",
"last_hard_state_change": 1528902463,
"last_state_change": 1528902400,
"state": "WARNING",
"state_type": "HARD",
"host": "host-all-6",
"output": "Hi, checking host-all-6/dummy_warning -> exit=1"
},
...
}
}
}
}
:return: schedulers live synthesis list
:rtype: dict
"""
res = self.identity()
res['problems'] = {}
for scheduler_link in self.app.conf.schedulers:
sched_res = scheduler_link.con.get('monitoring_problems', wait=True)
res['problems'][scheduler_link.name] = {}
if '_freshness' in sched_res:
res['problems'][scheduler_link.name].update({'_freshness': sched_res['_freshness']})
if 'problems' in sched_res:
res['problems'][scheduler_link.name].update({'problems': sched_res['problems']})
res['_freshness'] = int(time.time())
return res
|
python
|
def monitoring_problems(self):
"""Get Alignak detailed monitoring status
This will return an object containing the properties of the `identity`, plus a `problems`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- problems, which is an object with the scheduler known problems:
{
...
"problems": {
"scheduler-master": {
"_freshness": 1528903945,
"problems": {
"fdfc986d-4ab4-4562-9d2f-4346832745e6": {
"last_state": "CRITICAL",
"service": "dummy_critical",
"last_state_type": "SOFT",
"last_state_update": 1528902442,
"last_hard_state": "CRITICAL",
"last_hard_state_change": 1528902442,
"last_state_change": 1528902381,
"state": "CRITICAL",
"state_type": "HARD",
"host": "host-all-8",
"output": "Hi, checking host-all-8/dummy_critical -> exit=2"
},
"2445f2a3-2a3b-4b13-96ed-4cfb60790e7e": {
"last_state": "WARNING",
"service": "dummy_warning",
"last_state_type": "SOFT",
"last_state_update": 1528902463,
"last_hard_state": "WARNING",
"last_hard_state_change": 1528902463,
"last_state_change": 1528902400,
"state": "WARNING",
"state_type": "HARD",
"host": "host-all-6",
"output": "Hi, checking host-all-6/dummy_warning -> exit=1"
},
...
}
}
}
}
:return: schedulers live synthesis list
:rtype: dict
"""
res = self.identity()
res['problems'] = {}
for scheduler_link in self.app.conf.schedulers:
sched_res = scheduler_link.con.get('monitoring_problems', wait=True)
res['problems'][scheduler_link.name] = {}
if '_freshness' in sched_res:
res['problems'][scheduler_link.name].update({'_freshness': sched_res['_freshness']})
if 'problems' in sched_res:
res['problems'][scheduler_link.name].update({'problems': sched_res['problems']})
res['_freshness'] = int(time.time())
return res
|
[
"def",
"monitoring_problems",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"identity",
"(",
")",
"res",
"[",
"'problems'",
"]",
"=",
"{",
"}",
"for",
"scheduler_link",
"in",
"self",
".",
"app",
".",
"conf",
".",
"schedulers",
":",
"sched_res",
"=",
"scheduler_link",
".",
"con",
".",
"get",
"(",
"'monitoring_problems'",
",",
"wait",
"=",
"True",
")",
"res",
"[",
"'problems'",
"]",
"[",
"scheduler_link",
".",
"name",
"]",
"=",
"{",
"}",
"if",
"'_freshness'",
"in",
"sched_res",
":",
"res",
"[",
"'problems'",
"]",
"[",
"scheduler_link",
".",
"name",
"]",
".",
"update",
"(",
"{",
"'_freshness'",
":",
"sched_res",
"[",
"'_freshness'",
"]",
"}",
")",
"if",
"'problems'",
"in",
"sched_res",
":",
"res",
"[",
"'problems'",
"]",
"[",
"scheduler_link",
".",
"name",
"]",
".",
"update",
"(",
"{",
"'problems'",
":",
"sched_res",
"[",
"'problems'",
"]",
"}",
")",
"res",
"[",
"'_freshness'",
"]",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"return",
"res"
] |
Get Alignak detailed monitoring status
This will return an object containing the properties of the `identity`, plus a `problems`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- problems, which is an object with the scheduler known problems:
{
...
"problems": {
"scheduler-master": {
"_freshness": 1528903945,
"problems": {
"fdfc986d-4ab4-4562-9d2f-4346832745e6": {
"last_state": "CRITICAL",
"service": "dummy_critical",
"last_state_type": "SOFT",
"last_state_update": 1528902442,
"last_hard_state": "CRITICAL",
"last_hard_state_change": 1528902442,
"last_state_change": 1528902381,
"state": "CRITICAL",
"state_type": "HARD",
"host": "host-all-8",
"output": "Hi, checking host-all-8/dummy_critical -> exit=2"
},
"2445f2a3-2a3b-4b13-96ed-4cfb60790e7e": {
"last_state": "WARNING",
"service": "dummy_warning",
"last_state_type": "SOFT",
"last_state_update": 1528902463,
"last_hard_state": "WARNING",
"last_hard_state_change": 1528902463,
"last_state_change": 1528902400,
"state": "WARNING",
"state_type": "HARD",
"host": "host-all-6",
"output": "Hi, checking host-all-6/dummy_warning -> exit=1"
},
...
}
}
}
}
:return: schedulers live synthesis list
:rtype: dict
|
[
"Get",
"Alignak",
"detailed",
"monitoring",
"status"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L234-L295
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.livesynthesis
|
def livesynthesis(self):
"""Get Alignak live synthesis
This will return an object containing the properties of the `identity`, plus a
`livesynthesis`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- livesynthesis, which is an object with the scheduler live synthesis.
An `_overall` fake scheduler is also contained in the schedulers list to provide the
cumulated live synthesis. Before sending the results, the arbiter sums-up all its
schedulers live synthesis counters in the `_overall` live synthesis.
{
...
"livesynthesis": {
"_overall": {
"_freshness": 1528947526,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
},
"scheduler-master": {
"_freshness": 1528947522,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
}
}
}
:return: scheduler live synthesis
:rtype: dict
"""
res = self.identity()
res.update(self.app.get_livesynthesis())
return res
|
python
|
def livesynthesis(self):
"""Get Alignak live synthesis
This will return an object containing the properties of the `identity`, plus a
`livesynthesis`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- livesynthesis, which is an object with the scheduler live synthesis.
An `_overall` fake scheduler is also contained in the schedulers list to provide the
cumulated live synthesis. Before sending the results, the arbiter sums-up all its
schedulers live synthesis counters in the `_overall` live synthesis.
{
...
"livesynthesis": {
"_overall": {
"_freshness": 1528947526,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
},
"scheduler-master": {
"_freshness": 1528947522,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
}
}
}
:return: scheduler live synthesis
:rtype: dict
"""
res = self.identity()
res.update(self.app.get_livesynthesis())
return res
|
[
"def",
"livesynthesis",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"identity",
"(",
")",
"res",
".",
"update",
"(",
"self",
".",
"app",
".",
"get_livesynthesis",
"(",
")",
")",
"return",
"res"
] |
Get Alignak live synthesis
This will return an object containing the properties of the `identity`, plus a
`livesynthesis`
object which contains 2 properties for each known scheduler:
- _freshness, which is the timestamp when the provided data were fetched
- livesynthesis, which is an object with the scheduler live synthesis.
An `_overall` fake scheduler is also contained in the schedulers list to provide the
cumulated live synthesis. Before sending the results, the arbiter sums-up all its
schedulers live synthesis counters in the `_overall` live synthesis.
{
...
"livesynthesis": {
"_overall": {
"_freshness": 1528947526,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
},
"scheduler-master": {
"_freshness": 1528947522,
"livesynthesis": {
"hosts_total": 11,
"hosts_not_monitored": 0,
"hosts_up_hard": 11,
"hosts_up_soft": 0,
"hosts_down_hard": 0,
"hosts_down_soft": 0,
"hosts_unreachable_hard": 0,
"hosts_unreachable_soft": 0,
"hosts_flapping": 0,
"hosts_problems": 0,
"hosts_acknowledged": 0,
"hosts_in_downtime": 0,
"services_total": 100,
"services_not_monitored": 0,
"services_ok_hard": 70,
"services_ok_soft": 0,
"services_warning_hard": 4,
"services_warning_soft": 6,
"services_critical_hard": 6,
"services_critical_soft": 4,
"services_unknown_hard": 3,
"services_unknown_soft": 7,
"services_unreachable_hard": 0,
"services_unreachable_soft": 0,
"services_flapping": 0,
"services_problems": 0,
"services_acknowledged": 0,
"services_in_downtime": 0
}
}
}
}
}
:return: scheduler live synthesis
:rtype: dict
|
[
"Get",
"Alignak",
"live",
"synthesis"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L299-L392
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.object
|
def object(self, o_type, o_name=None):
"""Get a monitored object from the arbiter.
Indeed, the arbiter requires the object from its schedulers. It will iterate in
its schedulers list until a matching object is found. Else it will return a Json
structure containing _status and _message properties.
When found, the result is a serialized object which is a Json structure containing:
- content: the serialized object content
- __sys_python_module__: the python class of the returned object
The Alignak unserialize function of the alignak.misc.serialization package allows
to restore the initial object.
.. code-block:: python
from alignak.misc.serialization import unserialize
from alignak.objects.hostgroup import Hostgroup
raw_data = req.get("http://127.0.0.1:7768/object/hostgroup/allhosts")
print("Got: %s / %s" % (raw_data.status_code, raw_data.content))
assert raw_data.status_code == 200
object = raw_data.json()
group = unserialize(object, True)
assert group.__class__ == Hostgroup
assert group.get_name() == 'allhosts'
As an example:
{
"__sys_python_module__": "alignak.objects.hostgroup.Hostgroup",
"content": {
"uuid": "32248642-97dd-4f39-aaa2-5120112a765d",
"name": "",
"hostgroup_name": "allhosts",
"use": [],
"tags": [],
"alias": "All Hosts",
"notes": "",
"definition_order": 100,
"register": true,
"unknown_members": [],
"notes_url": "",
"action_url": "",
"imported_from": "unknown",
"conf_is_correct": true,
"configuration_errors": [],
"configuration_warnings": [],
"realm": "",
"downtimes": {},
"hostgroup_members": [],
"members": [
"553d47bc-27aa-426c-a664-49c4c0c4a249",
"f88093ca-e61b-43ff-a41e-613f7ad2cea2",
"df1e2e13-552d-43de-ad2a-fe80ad4ba979",
"d3d667dd-f583-4668-9f44-22ef3dcb53ad"
]
}
}
:param o_type: searched object type
:type o_type: str
:param o_name: searched object name (or uuid)
:type o_name: str
:return: serialized object information
:rtype: str
"""
for scheduler_link in self.app.conf.schedulers:
sched_res = scheduler_link.con.get('object', {'o_type': o_type, 'o_name': o_name},
wait=True)
if isinstance(sched_res, dict) and 'content' in sched_res:
return sched_res
return {'_status': u'ERR', '_message': u'Required %s not found.' % o_type}
|
python
|
def object(self, o_type, o_name=None):
"""Get a monitored object from the arbiter.
Indeed, the arbiter requires the object from its schedulers. It will iterate in
its schedulers list until a matching object is found. Else it will return a Json
structure containing _status and _message properties.
When found, the result is a serialized object which is a Json structure containing:
- content: the serialized object content
- __sys_python_module__: the python class of the returned object
The Alignak unserialize function of the alignak.misc.serialization package allows
to restore the initial object.
.. code-block:: python
from alignak.misc.serialization import unserialize
from alignak.objects.hostgroup import Hostgroup
raw_data = req.get("http://127.0.0.1:7768/object/hostgroup/allhosts")
print("Got: %s / %s" % (raw_data.status_code, raw_data.content))
assert raw_data.status_code == 200
object = raw_data.json()
group = unserialize(object, True)
assert group.__class__ == Hostgroup
assert group.get_name() == 'allhosts'
As an example:
{
"__sys_python_module__": "alignak.objects.hostgroup.Hostgroup",
"content": {
"uuid": "32248642-97dd-4f39-aaa2-5120112a765d",
"name": "",
"hostgroup_name": "allhosts",
"use": [],
"tags": [],
"alias": "All Hosts",
"notes": "",
"definition_order": 100,
"register": true,
"unknown_members": [],
"notes_url": "",
"action_url": "",
"imported_from": "unknown",
"conf_is_correct": true,
"configuration_errors": [],
"configuration_warnings": [],
"realm": "",
"downtimes": {},
"hostgroup_members": [],
"members": [
"553d47bc-27aa-426c-a664-49c4c0c4a249",
"f88093ca-e61b-43ff-a41e-613f7ad2cea2",
"df1e2e13-552d-43de-ad2a-fe80ad4ba979",
"d3d667dd-f583-4668-9f44-22ef3dcb53ad"
]
}
}
:param o_type: searched object type
:type o_type: str
:param o_name: searched object name (or uuid)
:type o_name: str
:return: serialized object information
:rtype: str
"""
for scheduler_link in self.app.conf.schedulers:
sched_res = scheduler_link.con.get('object', {'o_type': o_type, 'o_name': o_name},
wait=True)
if isinstance(sched_res, dict) and 'content' in sched_res:
return sched_res
return {'_status': u'ERR', '_message': u'Required %s not found.' % o_type}
|
[
"def",
"object",
"(",
"self",
",",
"o_type",
",",
"o_name",
"=",
"None",
")",
":",
"for",
"scheduler_link",
"in",
"self",
".",
"app",
".",
"conf",
".",
"schedulers",
":",
"sched_res",
"=",
"scheduler_link",
".",
"con",
".",
"get",
"(",
"'object'",
",",
"{",
"'o_type'",
":",
"o_type",
",",
"'o_name'",
":",
"o_name",
"}",
",",
"wait",
"=",
"True",
")",
"if",
"isinstance",
"(",
"sched_res",
",",
"dict",
")",
"and",
"'content'",
"in",
"sched_res",
":",
"return",
"sched_res",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"u'Required %s not found.'",
"%",
"o_type",
"}"
] |
Get a monitored object from the arbiter.
Indeed, the arbiter requires the object from its schedulers. It will iterate in
its schedulers list until a matching object is found. Else it will return a Json
structure containing _status and _message properties.
When found, the result is a serialized object which is a Json structure containing:
- content: the serialized object content
- __sys_python_module__: the python class of the returned object
The Alignak unserialize function of the alignak.misc.serialization package allows
to restore the initial object.
.. code-block:: python
from alignak.misc.serialization import unserialize
from alignak.objects.hostgroup import Hostgroup
raw_data = req.get("http://127.0.0.1:7768/object/hostgroup/allhosts")
print("Got: %s / %s" % (raw_data.status_code, raw_data.content))
assert raw_data.status_code == 200
object = raw_data.json()
group = unserialize(object, True)
assert group.__class__ == Hostgroup
assert group.get_name() == 'allhosts'
As an example:
{
"__sys_python_module__": "alignak.objects.hostgroup.Hostgroup",
"content": {
"uuid": "32248642-97dd-4f39-aaa2-5120112a765d",
"name": "",
"hostgroup_name": "allhosts",
"use": [],
"tags": [],
"alias": "All Hosts",
"notes": "",
"definition_order": 100,
"register": true,
"unknown_members": [],
"notes_url": "",
"action_url": "",
"imported_from": "unknown",
"conf_is_correct": true,
"configuration_errors": [],
"configuration_warnings": [],
"realm": "",
"downtimes": {},
"hostgroup_members": [],
"members": [
"553d47bc-27aa-426c-a664-49c4c0c4a249",
"f88093ca-e61b-43ff-a41e-613f7ad2cea2",
"df1e2e13-552d-43de-ad2a-fe80ad4ba979",
"d3d667dd-f583-4668-9f44-22ef3dcb53ad"
]
}
}
:param o_type: searched object type
:type o_type: str
:param o_name: searched object name (or uuid)
:type o_name: str
:return: serialized object information
:rtype: str
|
[
"Get",
"a",
"monitored",
"object",
"from",
"the",
"arbiter",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L397-L468
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.status
|
def status(self, details=False):
"""Get the overall alignak status
Returns a list of the satellites as in:
{
services: [
{
livestate: {
perf_data: "",
timestamp: 1532106561,
state: "ok",
long_output: "",
output: "all daemons are up and running."
},
name: "arbiter-master"
},
{
livestate: {
name: "poller_poller-master",
timestamp: 1532106561,
long_output: "Realm: (True). Listening on: http://127.0.0.1:7771/",
state: "ok",
output: "daemon is alive and reachable.",
perf_data: "last_check=1532106560.17"
},
name: "poller-master"
},
...
...
],
variables: { },
livestate: {
timestamp: 1532106561,
long_output: "broker-master - daemon is alive and reachable.
poller-master - daemon is alive and reachable.
reactionner-master - daemon is alive and reachable.
receiver-master - daemon is alive and reachable.
receiver-nsca - daemon is alive and reachable.
scheduler-master - daemon is alive and reachable.
scheduler-master-2 - daemon is alive and reachable.
scheduler-master-3 - daemon is alive and reachable.",
state: "up",
output: "All my daemons are up and running.",
perf_data: "
'servicesextinfo'=0 'businessimpactmodulations'=0 'hostgroups'=2
'resultmodulations'=0 'escalations'=0 'schedulers'=3 'hostsextinfo'=0
'contacts'=2 'servicedependencies'=0 'servicegroups'=1 'pollers'=1
'arbiters'=1 'receivers'=2 'macromodulations'=0 'reactionners'=1
'contactgroups'=2 'brokers'=1 'realms'=3 'services'=32 'commands'=11
'notificationways'=2 'timeperiods'=4 'modules'=0 'checkmodulations'=0
'hosts'=6 'hostdependencies'=0"
},
name: "My Alignak",
template: {
notes: "",
alias: "My Alignak",
_templates: [
"alignak",
"important"
],
active_checks_enabled: false,
passive_checks_enabled: true
}
}
:param details: Details are required (different from 0)
:type details bool
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
"""
if details is not False:
details = bool(details)
return self.app.get_alignak_status(details=details)
|
python
|
def status(self, details=False):
"""Get the overall alignak status
Returns a list of the satellites as in:
{
services: [
{
livestate: {
perf_data: "",
timestamp: 1532106561,
state: "ok",
long_output: "",
output: "all daemons are up and running."
},
name: "arbiter-master"
},
{
livestate: {
name: "poller_poller-master",
timestamp: 1532106561,
long_output: "Realm: (True). Listening on: http://127.0.0.1:7771/",
state: "ok",
output: "daemon is alive and reachable.",
perf_data: "last_check=1532106560.17"
},
name: "poller-master"
},
...
...
],
variables: { },
livestate: {
timestamp: 1532106561,
long_output: "broker-master - daemon is alive and reachable.
poller-master - daemon is alive and reachable.
reactionner-master - daemon is alive and reachable.
receiver-master - daemon is alive and reachable.
receiver-nsca - daemon is alive and reachable.
scheduler-master - daemon is alive and reachable.
scheduler-master-2 - daemon is alive and reachable.
scheduler-master-3 - daemon is alive and reachable.",
state: "up",
output: "All my daemons are up and running.",
perf_data: "
'servicesextinfo'=0 'businessimpactmodulations'=0 'hostgroups'=2
'resultmodulations'=0 'escalations'=0 'schedulers'=3 'hostsextinfo'=0
'contacts'=2 'servicedependencies'=0 'servicegroups'=1 'pollers'=1
'arbiters'=1 'receivers'=2 'macromodulations'=0 'reactionners'=1
'contactgroups'=2 'brokers'=1 'realms'=3 'services'=32 'commands'=11
'notificationways'=2 'timeperiods'=4 'modules'=0 'checkmodulations'=0
'hosts'=6 'hostdependencies'=0"
},
name: "My Alignak",
template: {
notes: "",
alias: "My Alignak",
_templates: [
"alignak",
"important"
],
active_checks_enabled: false,
passive_checks_enabled: true
}
}
:param details: Details are required (different from 0)
:type details bool
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
"""
if details is not False:
details = bool(details)
return self.app.get_alignak_status(details=details)
|
[
"def",
"status",
"(",
"self",
",",
"details",
"=",
"False",
")",
":",
"if",
"details",
"is",
"not",
"False",
":",
"details",
"=",
"bool",
"(",
"details",
")",
"return",
"self",
".",
"app",
".",
"get_alignak_status",
"(",
"details",
"=",
"details",
")"
] |
Get the overall alignak status
Returns a list of the satellites as in:
{
services: [
{
livestate: {
perf_data: "",
timestamp: 1532106561,
state: "ok",
long_output: "",
output: "all daemons are up and running."
},
name: "arbiter-master"
},
{
livestate: {
name: "poller_poller-master",
timestamp: 1532106561,
long_output: "Realm: (True). Listening on: http://127.0.0.1:7771/",
state: "ok",
output: "daemon is alive and reachable.",
perf_data: "last_check=1532106560.17"
},
name: "poller-master"
},
...
...
],
variables: { },
livestate: {
timestamp: 1532106561,
long_output: "broker-master - daemon is alive and reachable.
poller-master - daemon is alive and reachable.
reactionner-master - daemon is alive and reachable.
receiver-master - daemon is alive and reachable.
receiver-nsca - daemon is alive and reachable.
scheduler-master - daemon is alive and reachable.
scheduler-master-2 - daemon is alive and reachable.
scheduler-master-3 - daemon is alive and reachable.",
state: "up",
output: "All my daemons are up and running.",
perf_data: "
'servicesextinfo'=0 'businessimpactmodulations'=0 'hostgroups'=2
'resultmodulations'=0 'escalations'=0 'schedulers'=3 'hostsextinfo'=0
'contacts'=2 'servicedependencies'=0 'servicegroups'=1 'pollers'=1
'arbiters'=1 'receivers'=2 'macromodulations'=0 'reactionners'=1
'contactgroups'=2 'brokers'=1 'realms'=3 'services'=32 'commands'=11
'notificationways'=2 'timeperiods'=4 'modules'=0 'checkmodulations'=0
'hosts'=6 'hostdependencies'=0"
},
name: "My Alignak",
template: {
notes: "",
alias: "My Alignak",
_templates: [
"alignak",
"important"
],
active_checks_enabled: false,
passive_checks_enabled: true
}
}
:param details: Details are required (different from 0)
:type details bool
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
|
[
"Get",
"the",
"overall",
"alignak",
"status"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L586-L660
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.events_log
|
def events_log(self, details=False, count=0, timestamp=0):
"""Get the most recent Alignak events
If count is specifies it is the maximum number of events to return.
If timestamp is specified, events older than this timestamp will not be returned
The arbiter maintains a list of the most recent Alignak events. This endpoint
provides this list.
The default format is:
[
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1;
host_0-dummy_critical-2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2;
Service internal check result: 2",
"2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2;
host_0-dummy_unknown-3"
]
If you request on this endpoint with the *details* parameter (whatever its value...),
you will get a detailed JSON output:
[
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:35",
message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:19",
message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
}
]
In this example, only the 5 most recent events are provided whereas the default value is
to provide the 100 last events. This default counter may be changed thanks to the
``events_log_count`` configuration variable or
``ALIGNAK_EVENTS_LOG_COUNT`` environment variable.
The date format may also be changed thanks to the ``events_date_format`` configuration
variable.
:return: list of the most recent events
:rtype: list
"""
if not count:
count = 1 + int(os.environ.get('ALIGNAK_EVENTS_LOG_COUNT',
self.app.conf.events_log_count))
count = int(count)
timestamp = float(timestamp)
logger.debug('Get max %d events, newer than %s out of %d',
count, timestamp, len(self.app.recent_events))
res = []
for log in reversed(self.app.recent_events):
if timestamp and timestamp > log['timestamp']:
break
if not count:
break
if details:
# Exposes the full object
res.append(log)
else:
res.append("%s - %s - %s"
% (log['date'], log['level'][0].upper(), log['message']))
logger.debug('Got %d events', len(res))
return res
|
python
|
def events_log(self, details=False, count=0, timestamp=0):
"""Get the most recent Alignak events
If count is specifies it is the maximum number of events to return.
If timestamp is specified, events older than this timestamp will not be returned
The arbiter maintains a list of the most recent Alignak events. This endpoint
provides this list.
The default format is:
[
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1;
host_0-dummy_critical-2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2;
Service internal check result: 2",
"2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2;
host_0-dummy_unknown-3"
]
If you request on this endpoint with the *details* parameter (whatever its value...),
you will get a detailed JSON output:
[
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:35",
message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:19",
message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
}
]
In this example, only the 5 most recent events are provided whereas the default value is
to provide the 100 last events. This default counter may be changed thanks to the
``events_log_count`` configuration variable or
``ALIGNAK_EVENTS_LOG_COUNT`` environment variable.
The date format may also be changed thanks to the ``events_date_format`` configuration
variable.
:return: list of the most recent events
:rtype: list
"""
if not count:
count = 1 + int(os.environ.get('ALIGNAK_EVENTS_LOG_COUNT',
self.app.conf.events_log_count))
count = int(count)
timestamp = float(timestamp)
logger.debug('Get max %d events, newer than %s out of %d',
count, timestamp, len(self.app.recent_events))
res = []
for log in reversed(self.app.recent_events):
if timestamp and timestamp > log['timestamp']:
break
if not count:
break
if details:
# Exposes the full object
res.append(log)
else:
res.append("%s - %s - %s"
% (log['date'], log['level'][0].upper(), log['message']))
logger.debug('Got %d events', len(res))
return res
|
[
"def",
"events_log",
"(",
"self",
",",
"details",
"=",
"False",
",",
"count",
"=",
"0",
",",
"timestamp",
"=",
"0",
")",
":",
"if",
"not",
"count",
":",
"count",
"=",
"1",
"+",
"int",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'ALIGNAK_EVENTS_LOG_COUNT'",
",",
"self",
".",
"app",
".",
"conf",
".",
"events_log_count",
")",
")",
"count",
"=",
"int",
"(",
"count",
")",
"timestamp",
"=",
"float",
"(",
"timestamp",
")",
"logger",
".",
"debug",
"(",
"'Get max %d events, newer than %s out of %d'",
",",
"count",
",",
"timestamp",
",",
"len",
"(",
"self",
".",
"app",
".",
"recent_events",
")",
")",
"res",
"=",
"[",
"]",
"for",
"log",
"in",
"reversed",
"(",
"self",
".",
"app",
".",
"recent_events",
")",
":",
"if",
"timestamp",
"and",
"timestamp",
">",
"log",
"[",
"'timestamp'",
"]",
":",
"break",
"if",
"not",
"count",
":",
"break",
"if",
"details",
":",
"# Exposes the full object",
"res",
".",
"append",
"(",
"log",
")",
"else",
":",
"res",
".",
"append",
"(",
"\"%s - %s - %s\"",
"%",
"(",
"log",
"[",
"'date'",
"]",
",",
"log",
"[",
"'level'",
"]",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"log",
"[",
"'message'",
"]",
")",
")",
"logger",
".",
"debug",
"(",
"'Got %d events'",
",",
"len",
"(",
"res",
")",
")",
"return",
"res"
] |
Get the most recent Alignak events
If count is specifies it is the maximum number of events to return.
If timestamp is specified, events older than this timestamp will not be returned
The arbiter maintains a list of the most recent Alignak events. This endpoint
provides this list.
The default format is:
[
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: guest;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:43 - E - SERVICE NOTIFICATION: admin;host_0;dummy_random;CRITICAL;1;
notify-service-by-log;Service internal check result: 2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_critical;CRITICAL;SOFT;1;
host_0-dummy_critical-2",
"2018-07-23 15:14:42 - E - SERVICE ALERT: host_0;dummy_random;CRITICAL;HARD;2;
Service internal check result: 2",
"2018-07-23 15:14:42 - I - SERVICE ALERT: host_0;dummy_unknown;UNKNOWN;HARD;2;
host_0-dummy_unknown-3"
]
If you request on this endpoint with the *details* parameter (whatever its value...),
you will get a detailed JSON output:
[
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:35",
message: "SERVICE ALERT: host_11;dummy_echo;UNREACHABLE;HARD;2;",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: guest;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE NOTIFICATION: admin;host_0;dummy_random;OK;0;
notify-service-by-log;Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:32",
message: "SERVICE ALERT: host_0;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
},
{
timestamp: 1535517701.1817362,
date: "2018-07-23 15:16:19",
message: "SERVICE ALERT: host_11;dummy_random;OK;HARD;2;
Service internal check result: 0",
level: "info"
}
]
In this example, only the 5 most recent events are provided whereas the default value is
to provide the 100 last events. This default counter may be changed thanks to the
``events_log_count`` configuration variable or
``ALIGNAK_EVENTS_LOG_COUNT`` environment variable.
The date format may also be changed thanks to the ``events_date_format`` configuration
variable.
:return: list of the most recent events
:rtype: list
|
[
"Get",
"the",
"most",
"recent",
"Alignak",
"events"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L664-L760
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.satellites_list
|
def satellites_list(self, daemon_type=''):
"""Get the arbiter satellite names sorted by type
Returns a list of the satellites as in:
{
reactionner: [
"reactionner-master"
],
broker: [
"broker-master"
],
arbiter: [
"arbiter-master"
],
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
],
receiver: [
"receiver-nsca",
"receiver-master"
],
poller: [
"poller-master"
]
}
If a specific daemon type is requested, the list is reduced to this unique daemon type:
{
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
]
}
:param daemon_type: daemon type to filter
:type daemon_type: str
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
"""
with self.app.conf_lock:
res = {}
for s_type in ['arbiter', 'scheduler', 'poller', 'reactionner', 'receiver', 'broker']:
if daemon_type and daemon_type != s_type:
continue
satellite_list = []
res[s_type] = satellite_list
for daemon_link in getattr(self.app.conf, s_type + 's', []):
satellite_list.append(daemon_link.name)
return res
|
python
|
def satellites_list(self, daemon_type=''):
"""Get the arbiter satellite names sorted by type
Returns a list of the satellites as in:
{
reactionner: [
"reactionner-master"
],
broker: [
"broker-master"
],
arbiter: [
"arbiter-master"
],
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
],
receiver: [
"receiver-nsca",
"receiver-master"
],
poller: [
"poller-master"
]
}
If a specific daemon type is requested, the list is reduced to this unique daemon type:
{
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
]
}
:param daemon_type: daemon type to filter
:type daemon_type: str
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
"""
with self.app.conf_lock:
res = {}
for s_type in ['arbiter', 'scheduler', 'poller', 'reactionner', 'receiver', 'broker']:
if daemon_type and daemon_type != s_type:
continue
satellite_list = []
res[s_type] = satellite_list
for daemon_link in getattr(self.app.conf, s_type + 's', []):
satellite_list.append(daemon_link.name)
return res
|
[
"def",
"satellites_list",
"(",
"self",
",",
"daemon_type",
"=",
"''",
")",
":",
"with",
"self",
".",
"app",
".",
"conf_lock",
":",
"res",
"=",
"{",
"}",
"for",
"s_type",
"in",
"[",
"'arbiter'",
",",
"'scheduler'",
",",
"'poller'",
",",
"'reactionner'",
",",
"'receiver'",
",",
"'broker'",
"]",
":",
"if",
"daemon_type",
"and",
"daemon_type",
"!=",
"s_type",
":",
"continue",
"satellite_list",
"=",
"[",
"]",
"res",
"[",
"s_type",
"]",
"=",
"satellite_list",
"for",
"daemon_link",
"in",
"getattr",
"(",
"self",
".",
"app",
".",
"conf",
",",
"s_type",
"+",
"'s'",
",",
"[",
"]",
")",
":",
"satellite_list",
".",
"append",
"(",
"daemon_link",
".",
"name",
")",
"return",
"res"
] |
Get the arbiter satellite names sorted by type
Returns a list of the satellites as in:
{
reactionner: [
"reactionner-master"
],
broker: [
"broker-master"
],
arbiter: [
"arbiter-master"
],
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
],
receiver: [
"receiver-nsca",
"receiver-master"
],
poller: [
"poller-master"
]
}
If a specific daemon type is requested, the list is reduced to this unique daemon type:
{
scheduler: [
"scheduler-master-3",
"scheduler-master",
"scheduler-master-2"
]
}
:param daemon_type: daemon type to filter
:type daemon_type: str
:return: dict with key *daemon_type* and value list of daemon name
:rtype: dict
|
[
"Get",
"the",
"arbiter",
"satellite",
"names",
"sorted",
"by",
"type"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L764-L816
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.satellites_configuration
|
def satellites_configuration(self):
"""Return all the configuration data of satellites
:return: dict containing satellites data
Output looks like this ::
{'arbiter' : [{'property1':'value1' ..}, {'property2', 'value11' ..}, ..],
'scheduler': [..],
'poller': [..],
'reactionner': [..],
'receiver': [..],
'broker: [..]'
}
:rtype: dict
"""
res = {}
for s_type in ['arbiter', 'scheduler', 'poller', 'reactionner', 'receiver',
'broker']:
lst = []
res[s_type] = lst
for daemon in getattr(self.app.conf, s_type + 's'):
cls = daemon.__class__
env = {}
all_props = [cls.properties, cls.running_properties]
for props in all_props:
for prop in props:
if not hasattr(daemon, prop):
continue
if prop in ["realms", "conf", "con", "tags", "modules", "cfg",
"broks", "cfg_to_manage"]:
continue
val = getattr(daemon, prop)
# give a try to a json able object
try:
json.dumps(val)
env[prop] = val
except TypeError as exp:
logger.warning('satellites_configuration, %s: %s', prop, str(exp))
lst.append(env)
return res
|
python
|
def satellites_configuration(self):
"""Return all the configuration data of satellites
:return: dict containing satellites data
Output looks like this ::
{'arbiter' : [{'property1':'value1' ..}, {'property2', 'value11' ..}, ..],
'scheduler': [..],
'poller': [..],
'reactionner': [..],
'receiver': [..],
'broker: [..]'
}
:rtype: dict
"""
res = {}
for s_type in ['arbiter', 'scheduler', 'poller', 'reactionner', 'receiver',
'broker']:
lst = []
res[s_type] = lst
for daemon in getattr(self.app.conf, s_type + 's'):
cls = daemon.__class__
env = {}
all_props = [cls.properties, cls.running_properties]
for props in all_props:
for prop in props:
if not hasattr(daemon, prop):
continue
if prop in ["realms", "conf", "con", "tags", "modules", "cfg",
"broks", "cfg_to_manage"]:
continue
val = getattr(daemon, prop)
# give a try to a json able object
try:
json.dumps(val)
env[prop] = val
except TypeError as exp:
logger.warning('satellites_configuration, %s: %s', prop, str(exp))
lst.append(env)
return res
|
[
"def",
"satellites_configuration",
"(",
"self",
")",
":",
"res",
"=",
"{",
"}",
"for",
"s_type",
"in",
"[",
"'arbiter'",
",",
"'scheduler'",
",",
"'poller'",
",",
"'reactionner'",
",",
"'receiver'",
",",
"'broker'",
"]",
":",
"lst",
"=",
"[",
"]",
"res",
"[",
"s_type",
"]",
"=",
"lst",
"for",
"daemon",
"in",
"getattr",
"(",
"self",
".",
"app",
".",
"conf",
",",
"s_type",
"+",
"'s'",
")",
":",
"cls",
"=",
"daemon",
".",
"__class__",
"env",
"=",
"{",
"}",
"all_props",
"=",
"[",
"cls",
".",
"properties",
",",
"cls",
".",
"running_properties",
"]",
"for",
"props",
"in",
"all_props",
":",
"for",
"prop",
"in",
"props",
":",
"if",
"not",
"hasattr",
"(",
"daemon",
",",
"prop",
")",
":",
"continue",
"if",
"prop",
"in",
"[",
"\"realms\"",
",",
"\"conf\"",
",",
"\"con\"",
",",
"\"tags\"",
",",
"\"modules\"",
",",
"\"cfg\"",
",",
"\"broks\"",
",",
"\"cfg_to_manage\"",
"]",
":",
"continue",
"val",
"=",
"getattr",
"(",
"daemon",
",",
"prop",
")",
"# give a try to a json able object",
"try",
":",
"json",
".",
"dumps",
"(",
"val",
")",
"env",
"[",
"prop",
"]",
"=",
"val",
"except",
"TypeError",
"as",
"exp",
":",
"logger",
".",
"warning",
"(",
"'satellites_configuration, %s: %s'",
",",
"prop",
",",
"str",
"(",
"exp",
")",
")",
"lst",
".",
"append",
"(",
"env",
")",
"return",
"res"
] |
Return all the configuration data of satellites
:return: dict containing satellites data
Output looks like this ::
{'arbiter' : [{'property1':'value1' ..}, {'property2', 'value11' ..}, ..],
'scheduler': [..],
'poller': [..],
'reactionner': [..],
'receiver': [..],
'broker: [..]'
}
:rtype: dict
|
[
"Return",
"all",
"the",
"configuration",
"data",
"of",
"satellites"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1098-L1139
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.external_commands
|
def external_commands(self):
"""Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str
"""
res = []
with self.app.external_commands_lock:
for cmd in self.app.get_external_commands():
res.append(cmd.serialize())
return res
|
python
|
def external_commands(self):
"""Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str
"""
res = []
with self.app.external_commands_lock:
for cmd in self.app.get_external_commands():
res.append(cmd.serialize())
return res
|
[
"def",
"external_commands",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"with",
"self",
".",
"app",
".",
"external_commands_lock",
":",
"for",
"cmd",
"in",
"self",
".",
"app",
".",
"get_external_commands",
"(",
")",
":",
"res",
".",
"append",
"(",
"cmd",
".",
"serialize",
"(",
")",
")",
"return",
"res"
] |
Get the external commands from the daemon
Use a lock for this function to protect
:return: serialized external command list
:rtype: str
|
[
"Get",
"the",
"external",
"commands",
"from",
"the",
"daemon"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1143-L1155
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface.search
|
def search(self): # pylint: disable=no-self-use
"""
Request available queries
Posted data: {u'target': u''}
Return the list of available target queries
:return: See upper comment
:rtype: list
"""
logger.debug("Grafana search... %s", cherrypy.request.method)
if cherrypy.request.method == 'OPTIONS':
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.request.handler = None
return {}
if getattr(cherrypy.request, 'json', None):
logger.debug("Posted data: %s", cherrypy.request.json)
logger.debug("Grafana search returns: %s", GRAFANA_TARGETS)
return GRAFANA_TARGETS
|
python
|
def search(self): # pylint: disable=no-self-use
"""
Request available queries
Posted data: {u'target': u''}
Return the list of available target queries
:return: See upper comment
:rtype: list
"""
logger.debug("Grafana search... %s", cherrypy.request.method)
if cherrypy.request.method == 'OPTIONS':
cherrypy.response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE'
cherrypy.response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization'
cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
cherrypy.request.handler = None
return {}
if getattr(cherrypy.request, 'json', None):
logger.debug("Posted data: %s", cherrypy.request.json)
logger.debug("Grafana search returns: %s", GRAFANA_TARGETS)
return GRAFANA_TARGETS
|
[
"def",
"search",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"logger",
".",
"debug",
"(",
"\"Grafana search... %s\"",
",",
"cherrypy",
".",
"request",
".",
"method",
")",
"if",
"cherrypy",
".",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"cherrypy",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Methods'",
"]",
"=",
"'GET,POST,PATCH,PUT,DELETE'",
"cherrypy",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Headers'",
"]",
"=",
"'Content-Type,Authorization'",
"cherrypy",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Origin'",
"]",
"=",
"'*'",
"cherrypy",
".",
"request",
".",
"handler",
"=",
"None",
"return",
"{",
"}",
"if",
"getattr",
"(",
"cherrypy",
".",
"request",
",",
"'json'",
",",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"\"Posted data: %s\"",
",",
"cherrypy",
".",
"request",
".",
"json",
")",
"logger",
".",
"debug",
"(",
"\"Grafana search returns: %s\"",
",",
"GRAFANA_TARGETS",
")",
"return",
"GRAFANA_TARGETS"
] |
Request available queries
Posted data: {u'target': u''}
Return the list of available target queries
:return: See upper comment
:rtype: list
|
[
"Request",
"available",
"queries"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1169-L1192
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface._build_host_livestate
|
def _build_host_livestate(self, host_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:param livestate: livestate dictionary
:return: external command line
"""
state = livestate.get('state', 'UP').upper()
output = livestate.get('output', '')
long_output = livestate.get('long_output', '')
perf_data = livestate.get('perf_data', '')
try:
timestamp = int(livestate.get('timestamp', 'ABC'))
except ValueError:
timestamp = None
host_state_to_id = {
"UP": 0,
"DOWN": 1,
"UNREACHABLE": 2
}
parameters = '%s;%s' % (host_state_to_id.get(state, 3), output)
if long_output and perf_data:
parameters = '%s|%s\n%s' % (parameters, perf_data, long_output)
elif long_output:
parameters = '%s\n%s' % (parameters, long_output)
elif perf_data:
parameters = '%s|%s' % (parameters, perf_data)
command_line = 'PROCESS_HOST_CHECK_RESULT;%s;%s' % (host_name, parameters)
if timestamp is not None:
command_line = '[%d] %s' % (timestamp, command_line)
else:
command_line = '[%d] %s' % (int(time.time()), command_line)
return command_line
|
python
|
def _build_host_livestate(self, host_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:param livestate: livestate dictionary
:return: external command line
"""
state = livestate.get('state', 'UP').upper()
output = livestate.get('output', '')
long_output = livestate.get('long_output', '')
perf_data = livestate.get('perf_data', '')
try:
timestamp = int(livestate.get('timestamp', 'ABC'))
except ValueError:
timestamp = None
host_state_to_id = {
"UP": 0,
"DOWN": 1,
"UNREACHABLE": 2
}
parameters = '%s;%s' % (host_state_to_id.get(state, 3), output)
if long_output and perf_data:
parameters = '%s|%s\n%s' % (parameters, perf_data, long_output)
elif long_output:
parameters = '%s\n%s' % (parameters, long_output)
elif perf_data:
parameters = '%s|%s' % (parameters, perf_data)
command_line = 'PROCESS_HOST_CHECK_RESULT;%s;%s' % (host_name, parameters)
if timestamp is not None:
command_line = '[%d] %s' % (timestamp, command_line)
else:
command_line = '[%d] %s' % (int(time.time()), command_line)
return command_line
|
[
"def",
"_build_host_livestate",
"(",
"self",
",",
"host_name",
",",
"livestate",
")",
":",
"# pylint: disable=no-self-use, too-many-locals",
"state",
"=",
"livestate",
".",
"get",
"(",
"'state'",
",",
"'UP'",
")",
".",
"upper",
"(",
")",
"output",
"=",
"livestate",
".",
"get",
"(",
"'output'",
",",
"''",
")",
"long_output",
"=",
"livestate",
".",
"get",
"(",
"'long_output'",
",",
"''",
")",
"perf_data",
"=",
"livestate",
".",
"get",
"(",
"'perf_data'",
",",
"''",
")",
"try",
":",
"timestamp",
"=",
"int",
"(",
"livestate",
".",
"get",
"(",
"'timestamp'",
",",
"'ABC'",
")",
")",
"except",
"ValueError",
":",
"timestamp",
"=",
"None",
"host_state_to_id",
"=",
"{",
"\"UP\"",
":",
"0",
",",
"\"DOWN\"",
":",
"1",
",",
"\"UNREACHABLE\"",
":",
"2",
"}",
"parameters",
"=",
"'%s;%s'",
"%",
"(",
"host_state_to_id",
".",
"get",
"(",
"state",
",",
"3",
")",
",",
"output",
")",
"if",
"long_output",
"and",
"perf_data",
":",
"parameters",
"=",
"'%s|%s\\n%s'",
"%",
"(",
"parameters",
",",
"perf_data",
",",
"long_output",
")",
"elif",
"long_output",
":",
"parameters",
"=",
"'%s\\n%s'",
"%",
"(",
"parameters",
",",
"long_output",
")",
"elif",
"perf_data",
":",
"parameters",
"=",
"'%s|%s'",
"%",
"(",
"parameters",
",",
"perf_data",
")",
"command_line",
"=",
"'PROCESS_HOST_CHECK_RESULT;%s;%s'",
"%",
"(",
"host_name",
",",
"parameters",
")",
"if",
"timestamp",
"is",
"not",
"None",
":",
"command_line",
"=",
"'[%d] %s'",
"%",
"(",
"timestamp",
",",
"command_line",
")",
"else",
":",
"command_line",
"=",
"'[%d] %s'",
"%",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"command_line",
")",
"return",
"command_line"
] |
Build and notify the external command for an host livestate
PROCESS_HOST_CHECK_RESULT;<host_name>;<status_code>;<plugin_output>
:param host_name: the concerned host name
:param livestate: livestate dictionary
:return: external command line
|
[
"Build",
"and",
"notify",
"the",
"external",
"command",
"for",
"an",
"host",
"livestate"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1390-L1428
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface._build_service_livestate
|
def _build_service_livestate(self, host_name, service_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for a service livestate
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
Create and post a logcheckresult to the backend for the livestate
:param host_name: the concerned host name
:param service_name: the concerned service name
:param livestate: livestate dictionary
:return: external command line
"""
state = livestate.get('state', 'OK').upper()
output = livestate.get('output', '')
long_output = livestate.get('long_output', '')
perf_data = livestate.get('perf_data', '')
try:
timestamp = int(livestate.get('timestamp', 'ABC'))
except ValueError:
timestamp = None
service_state_to_id = {
"OK": 0,
"WARNING": 1,
"CRITICAL": 2,
"UNKNOWN": 3,
"UNREACHABLE": 4
}
parameters = '%s;%s' % (service_state_to_id.get(state, 3), output)
if long_output and perf_data:
parameters = '%s|%s\n%s' % (parameters, perf_data, long_output)
elif long_output:
parameters = '%s\n%s' % (parameters, long_output)
elif perf_data:
parameters = '%s|%s' % (parameters, perf_data)
command_line = 'PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s' % \
(host_name, service_name, parameters)
if timestamp is not None:
command_line = '[%d] %s' % (timestamp, command_line)
else:
command_line = '[%d] %s' % (int(time.time()), command_line)
return command_line
|
python
|
def _build_service_livestate(self, host_name, service_name, livestate):
# pylint: disable=no-self-use, too-many-locals
"""Build and notify the external command for a service livestate
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
Create and post a logcheckresult to the backend for the livestate
:param host_name: the concerned host name
:param service_name: the concerned service name
:param livestate: livestate dictionary
:return: external command line
"""
state = livestate.get('state', 'OK').upper()
output = livestate.get('output', '')
long_output = livestate.get('long_output', '')
perf_data = livestate.get('perf_data', '')
try:
timestamp = int(livestate.get('timestamp', 'ABC'))
except ValueError:
timestamp = None
service_state_to_id = {
"OK": 0,
"WARNING": 1,
"CRITICAL": 2,
"UNKNOWN": 3,
"UNREACHABLE": 4
}
parameters = '%s;%s' % (service_state_to_id.get(state, 3), output)
if long_output and perf_data:
parameters = '%s|%s\n%s' % (parameters, perf_data, long_output)
elif long_output:
parameters = '%s\n%s' % (parameters, long_output)
elif perf_data:
parameters = '%s|%s' % (parameters, perf_data)
command_line = 'PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s' % \
(host_name, service_name, parameters)
if timestamp is not None:
command_line = '[%d] %s' % (timestamp, command_line)
else:
command_line = '[%d] %s' % (int(time.time()), command_line)
return command_line
|
[
"def",
"_build_service_livestate",
"(",
"self",
",",
"host_name",
",",
"service_name",
",",
"livestate",
")",
":",
"# pylint: disable=no-self-use, too-many-locals",
"state",
"=",
"livestate",
".",
"get",
"(",
"'state'",
",",
"'OK'",
")",
".",
"upper",
"(",
")",
"output",
"=",
"livestate",
".",
"get",
"(",
"'output'",
",",
"''",
")",
"long_output",
"=",
"livestate",
".",
"get",
"(",
"'long_output'",
",",
"''",
")",
"perf_data",
"=",
"livestate",
".",
"get",
"(",
"'perf_data'",
",",
"''",
")",
"try",
":",
"timestamp",
"=",
"int",
"(",
"livestate",
".",
"get",
"(",
"'timestamp'",
",",
"'ABC'",
")",
")",
"except",
"ValueError",
":",
"timestamp",
"=",
"None",
"service_state_to_id",
"=",
"{",
"\"OK\"",
":",
"0",
",",
"\"WARNING\"",
":",
"1",
",",
"\"CRITICAL\"",
":",
"2",
",",
"\"UNKNOWN\"",
":",
"3",
",",
"\"UNREACHABLE\"",
":",
"4",
"}",
"parameters",
"=",
"'%s;%s'",
"%",
"(",
"service_state_to_id",
".",
"get",
"(",
"state",
",",
"3",
")",
",",
"output",
")",
"if",
"long_output",
"and",
"perf_data",
":",
"parameters",
"=",
"'%s|%s\\n%s'",
"%",
"(",
"parameters",
",",
"perf_data",
",",
"long_output",
")",
"elif",
"long_output",
":",
"parameters",
"=",
"'%s\\n%s'",
"%",
"(",
"parameters",
",",
"long_output",
")",
"elif",
"perf_data",
":",
"parameters",
"=",
"'%s|%s'",
"%",
"(",
"parameters",
",",
"perf_data",
")",
"command_line",
"=",
"'PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s'",
"%",
"(",
"host_name",
",",
"service_name",
",",
"parameters",
")",
"if",
"timestamp",
"is",
"not",
"None",
":",
"command_line",
"=",
"'[%d] %s'",
"%",
"(",
"timestamp",
",",
"command_line",
")",
"else",
":",
"command_line",
"=",
"'[%d] %s'",
"%",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"command_line",
")",
"return",
"command_line"
] |
Build and notify the external command for a service livestate
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
Create and post a logcheckresult to the backend for the livestate
:param host_name: the concerned host name
:param service_name: the concerned service name
:param livestate: livestate dictionary
:return: external command line
|
[
"Build",
"and",
"notify",
"the",
"external",
"command",
"for",
"a",
"service",
"livestate"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1430-L1474
|
train
|
Alignak-monitoring/alignak
|
alignak/http/arbiter_interface.py
|
ArbiterInterface._do_not_run
|
def _do_not_run(self):
"""The master arbiter tells to its spare arbiters to not run.
A master arbiter will ignore this request and it will return an object
containing some properties:
'_status': 'ERR' because of the error
`_message`: some more explanations about the error
:return: None
"""
# If I'm the master, ignore the command and raise a log
if self.app.is_master:
message = "Received message to not run. " \
"I am the Master arbiter, ignore and continue to run."
logger.warning(message)
return {'_status': u'ERR', '_message': message}
# Else, I'm just a spare, so I listen to my master
logger.debug("Received message to not run. I am the spare, stopping.")
self.app.last_master_speak = time.time()
self.app.must_run = False
return {'_status': u'OK', '_message': message}
|
python
|
def _do_not_run(self):
"""The master arbiter tells to its spare arbiters to not run.
A master arbiter will ignore this request and it will return an object
containing some properties:
'_status': 'ERR' because of the error
`_message`: some more explanations about the error
:return: None
"""
# If I'm the master, ignore the command and raise a log
if self.app.is_master:
message = "Received message to not run. " \
"I am the Master arbiter, ignore and continue to run."
logger.warning(message)
return {'_status': u'ERR', '_message': message}
# Else, I'm just a spare, so I listen to my master
logger.debug("Received message to not run. I am the spare, stopping.")
self.app.last_master_speak = time.time()
self.app.must_run = False
return {'_status': u'OK', '_message': message}
|
[
"def",
"_do_not_run",
"(",
"self",
")",
":",
"# If I'm the master, ignore the command and raise a log",
"if",
"self",
".",
"app",
".",
"is_master",
":",
"message",
"=",
"\"Received message to not run. \"",
"\"I am the Master arbiter, ignore and continue to run.\"",
"logger",
".",
"warning",
"(",
"message",
")",
"return",
"{",
"'_status'",
":",
"u'ERR'",
",",
"'_message'",
":",
"message",
"}",
"# Else, I'm just a spare, so I listen to my master",
"logger",
".",
"debug",
"(",
"\"Received message to not run. I am the spare, stopping.\"",
")",
"self",
".",
"app",
".",
"last_master_speak",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"app",
".",
"must_run",
"=",
"False",
"return",
"{",
"'_status'",
":",
"u'OK'",
",",
"'_message'",
":",
"message",
"}"
] |
The master arbiter tells to its spare arbiters to not run.
A master arbiter will ignore this request and it will return an object
containing some properties:
'_status': 'ERR' because of the error
`_message`: some more explanations about the error
:return: None
|
[
"The",
"master",
"arbiter",
"tells",
"to",
"its",
"spare",
"arbiters",
"to",
"not",
"run",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1663-L1684
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/commandcallitem.py
|
CommandCallItems.create_commandcall
|
def create_commandcall(prop, commands, command):
"""
Create CommandCall object with command
:param prop: property
:type prop: str
:param commands: all commands
:type commands: alignak.objects.command.Commands
:param command: a command object
:type command: str
:return: a commandCall object
:rtype: alignak.objects.commandcallitem.CommandCall
"""
cc = {
'commands': commands,
'call': command
}
if hasattr(prop, 'enable_environment_macros'):
cc['enable_environment_macros'] = prop.enable_environment_macros
if hasattr(prop, 'poller_tag'):
cc['poller_tag'] = prop.poller_tag
elif hasattr(prop, 'reactionner_tag'):
cc['reactionner_tag'] = prop.reactionner_tag
return CommandCall(cc)
|
python
|
def create_commandcall(prop, commands, command):
"""
Create CommandCall object with command
:param prop: property
:type prop: str
:param commands: all commands
:type commands: alignak.objects.command.Commands
:param command: a command object
:type command: str
:return: a commandCall object
:rtype: alignak.objects.commandcallitem.CommandCall
"""
cc = {
'commands': commands,
'call': command
}
if hasattr(prop, 'enable_environment_macros'):
cc['enable_environment_macros'] = prop.enable_environment_macros
if hasattr(prop, 'poller_tag'):
cc['poller_tag'] = prop.poller_tag
elif hasattr(prop, 'reactionner_tag'):
cc['reactionner_tag'] = prop.reactionner_tag
return CommandCall(cc)
|
[
"def",
"create_commandcall",
"(",
"prop",
",",
"commands",
",",
"command",
")",
":",
"cc",
"=",
"{",
"'commands'",
":",
"commands",
",",
"'call'",
":",
"command",
"}",
"if",
"hasattr",
"(",
"prop",
",",
"'enable_environment_macros'",
")",
":",
"cc",
"[",
"'enable_environment_macros'",
"]",
"=",
"prop",
".",
"enable_environment_macros",
"if",
"hasattr",
"(",
"prop",
",",
"'poller_tag'",
")",
":",
"cc",
"[",
"'poller_tag'",
"]",
"=",
"prop",
".",
"poller_tag",
"elif",
"hasattr",
"(",
"prop",
",",
"'reactionner_tag'",
")",
":",
"cc",
"[",
"'reactionner_tag'",
"]",
"=",
"prop",
".",
"reactionner_tag",
"return",
"CommandCall",
"(",
"cc",
")"
] |
Create CommandCall object with command
:param prop: property
:type prop: str
:param commands: all commands
:type commands: alignak.objects.command.Commands
:param command: a command object
:type command: str
:return: a commandCall object
:rtype: alignak.objects.commandcallitem.CommandCall
|
[
"Create",
"CommandCall",
"object",
"with",
"command"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/commandcallitem.py#L79-L105
|
train
|
Alignak-monitoring/alignak
|
alignak/http/broker_interface.py
|
BrokerInterface._push_broks
|
def _push_broks(self):
"""Push the provided broks objects to the broker daemon
Only used on a Broker daemon by the Arbiter
:param: broks
:type: list
:return: None
"""
data = cherrypy.request.json
with self.app.arbiter_broks_lock:
logger.debug("Pushing %d broks", len(data['broks']))
self.app.arbiter_broks.extend([unserialize(elem, True) for elem in data['broks']])
|
python
|
def _push_broks(self):
"""Push the provided broks objects to the broker daemon
Only used on a Broker daemon by the Arbiter
:param: broks
:type: list
:return: None
"""
data = cherrypy.request.json
with self.app.arbiter_broks_lock:
logger.debug("Pushing %d broks", len(data['broks']))
self.app.arbiter_broks.extend([unserialize(elem, True) for elem in data['broks']])
|
[
"def",
"_push_broks",
"(",
"self",
")",
":",
"data",
"=",
"cherrypy",
".",
"request",
".",
"json",
"with",
"self",
".",
"app",
".",
"arbiter_broks_lock",
":",
"logger",
".",
"debug",
"(",
"\"Pushing %d broks\"",
",",
"len",
"(",
"data",
"[",
"'broks'",
"]",
")",
")",
"self",
".",
"app",
".",
"arbiter_broks",
".",
"extend",
"(",
"[",
"unserialize",
"(",
"elem",
",",
"True",
")",
"for",
"elem",
"in",
"data",
"[",
"'broks'",
"]",
"]",
")"
] |
Push the provided broks objects to the broker daemon
Only used on a Broker daemon by the Arbiter
:param: broks
:type: list
:return: None
|
[
"Push",
"the",
"provided",
"broks",
"objects",
"to",
"the",
"broker",
"daemon"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/broker_interface.py#L44-L56
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.load_params
|
def load_params(self, params):
"""Load parameters from main configuration file
:param params: parameters list (converted right at the beginning)
:type params:
:return: None
"""
logger.debug("Alignak parameters:")
for key, value in sorted(self.clean_params(params).items()):
update_attribute = None
# Maybe it's a variable as $USER$ or $ANOTHERVARIABLE$
# so look at the first character. If it's a $, it is a macro variable
# if it ends with $ too
if key[0] == '$' and key[-1] == '$':
key = key[1:-1]
# Update the macros list
if key not in self.__class__.macros:
logger.debug("New macro %s: %s - %s", self, key, value)
self.__class__.macros[key] = '$%s$' % key
key = '$%s$' % key
logger.debug("- macro %s", key)
update_attribute = value
# Create a new property to store the macro value
if isinstance(value, list):
self.__class__.properties[key] = ListProp(default=value)
else:
self.__class__.properties[key] = StringProp(default=value)
elif key in self.properties:
update_attribute = self.properties[key].pythonize(value)
elif key in self.running_properties:
logger.warning("using a the running property %s in a config file", key)
update_attribute = self.running_properties[key].pythonize(value)
elif key.startswith('$') or key in ['cfg_file', 'cfg_dir']:
# it's a macro or a useless now param, we don't touch this
update_attribute = value
else:
logger.debug("Guessing the property '%s' type because it "
"is not in %s object properties", key, self.__class__.__name__)
update_attribute = ToGuessProp().pythonize(value)
if update_attribute is not None:
setattr(self, key, update_attribute)
logger.debug("- update %s = %s", key, update_attribute)
# Change Nagios2 names to Nagios3 ones (before using them)
self.old_properties_names_to_new()
# Fill default for myself - new properties entry becomes a self attribute
self.fill_default()
|
python
|
def load_params(self, params):
"""Load parameters from main configuration file
:param params: parameters list (converted right at the beginning)
:type params:
:return: None
"""
logger.debug("Alignak parameters:")
for key, value in sorted(self.clean_params(params).items()):
update_attribute = None
# Maybe it's a variable as $USER$ or $ANOTHERVARIABLE$
# so look at the first character. If it's a $, it is a macro variable
# if it ends with $ too
if key[0] == '$' and key[-1] == '$':
key = key[1:-1]
# Update the macros list
if key not in self.__class__.macros:
logger.debug("New macro %s: %s - %s", self, key, value)
self.__class__.macros[key] = '$%s$' % key
key = '$%s$' % key
logger.debug("- macro %s", key)
update_attribute = value
# Create a new property to store the macro value
if isinstance(value, list):
self.__class__.properties[key] = ListProp(default=value)
else:
self.__class__.properties[key] = StringProp(default=value)
elif key in self.properties:
update_attribute = self.properties[key].pythonize(value)
elif key in self.running_properties:
logger.warning("using a the running property %s in a config file", key)
update_attribute = self.running_properties[key].pythonize(value)
elif key.startswith('$') or key in ['cfg_file', 'cfg_dir']:
# it's a macro or a useless now param, we don't touch this
update_attribute = value
else:
logger.debug("Guessing the property '%s' type because it "
"is not in %s object properties", key, self.__class__.__name__)
update_attribute = ToGuessProp().pythonize(value)
if update_attribute is not None:
setattr(self, key, update_attribute)
logger.debug("- update %s = %s", key, update_attribute)
# Change Nagios2 names to Nagios3 ones (before using them)
self.old_properties_names_to_new()
# Fill default for myself - new properties entry becomes a self attribute
self.fill_default()
|
[
"def",
"load_params",
"(",
"self",
",",
"params",
")",
":",
"logger",
".",
"debug",
"(",
"\"Alignak parameters:\"",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"self",
".",
"clean_params",
"(",
"params",
")",
".",
"items",
"(",
")",
")",
":",
"update_attribute",
"=",
"None",
"# Maybe it's a variable as $USER$ or $ANOTHERVARIABLE$",
"# so look at the first character. If it's a $, it is a macro variable",
"# if it ends with $ too",
"if",
"key",
"[",
"0",
"]",
"==",
"'$'",
"and",
"key",
"[",
"-",
"1",
"]",
"==",
"'$'",
":",
"key",
"=",
"key",
"[",
"1",
":",
"-",
"1",
"]",
"# Update the macros list",
"if",
"key",
"not",
"in",
"self",
".",
"__class__",
".",
"macros",
":",
"logger",
".",
"debug",
"(",
"\"New macro %s: %s - %s\"",
",",
"self",
",",
"key",
",",
"value",
")",
"self",
".",
"__class__",
".",
"macros",
"[",
"key",
"]",
"=",
"'$%s$'",
"%",
"key",
"key",
"=",
"'$%s$'",
"%",
"key",
"logger",
".",
"debug",
"(",
"\"- macro %s\"",
",",
"key",
")",
"update_attribute",
"=",
"value",
"# Create a new property to store the macro value",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"self",
".",
"__class__",
".",
"properties",
"[",
"key",
"]",
"=",
"ListProp",
"(",
"default",
"=",
"value",
")",
"else",
":",
"self",
".",
"__class__",
".",
"properties",
"[",
"key",
"]",
"=",
"StringProp",
"(",
"default",
"=",
"value",
")",
"elif",
"key",
"in",
"self",
".",
"properties",
":",
"update_attribute",
"=",
"self",
".",
"properties",
"[",
"key",
"]",
".",
"pythonize",
"(",
"value",
")",
"elif",
"key",
"in",
"self",
".",
"running_properties",
":",
"logger",
".",
"warning",
"(",
"\"using a the running property %s in a config file\"",
",",
"key",
")",
"update_attribute",
"=",
"self",
".",
"running_properties",
"[",
"key",
"]",
".",
"pythonize",
"(",
"value",
")",
"elif",
"key",
".",
"startswith",
"(",
"'$'",
")",
"or",
"key",
"in",
"[",
"'cfg_file'",
",",
"'cfg_dir'",
"]",
":",
"# it's a macro or a useless now param, we don't touch this",
"update_attribute",
"=",
"value",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Guessing the property '%s' type because it \"",
"\"is not in %s object properties\"",
",",
"key",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"update_attribute",
"=",
"ToGuessProp",
"(",
")",
".",
"pythonize",
"(",
"value",
")",
"if",
"update_attribute",
"is",
"not",
"None",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"update_attribute",
")",
"logger",
".",
"debug",
"(",
"\"- update %s = %s\"",
",",
"key",
",",
"update_attribute",
")",
"# Change Nagios2 names to Nagios3 ones (before using them)",
"self",
".",
"old_properties_names_to_new",
"(",
")",
"# Fill default for myself - new properties entry becomes a self attribute",
"self",
".",
"fill_default",
"(",
")"
] |
Load parameters from main configuration file
:param params: parameters list (converted right at the beginning)
:type params:
:return: None
|
[
"Load",
"parameters",
"from",
"main",
"configuration",
"file"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1000-L1050
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config._cut_line
|
def _cut_line(line):
"""Split the line on whitespaces and remove empty chunks
:param line: the line to split
:type line: str
:return: list of strings
:rtype: list
"""
# punct = '"#$%&\'()*+/<=>?@[\\]^`{|}~'
if re.search("([\t\n\r]+|[\x0b\x0c ]{3,})+", line):
tmp = re.split("([\t\n\r]+|[\x0b\x0c ]{3,})+", line, 1)
else:
tmp = re.split("[" + string.whitespace + "]+", line, 1)
res = [elt.strip() for elt in tmp if elt.strip() != '']
return res
|
python
|
def _cut_line(line):
"""Split the line on whitespaces and remove empty chunks
:param line: the line to split
:type line: str
:return: list of strings
:rtype: list
"""
# punct = '"#$%&\'()*+/<=>?@[\\]^`{|}~'
if re.search("([\t\n\r]+|[\x0b\x0c ]{3,})+", line):
tmp = re.split("([\t\n\r]+|[\x0b\x0c ]{3,})+", line, 1)
else:
tmp = re.split("[" + string.whitespace + "]+", line, 1)
res = [elt.strip() for elt in tmp if elt.strip() != '']
return res
|
[
"def",
"_cut_line",
"(",
"line",
")",
":",
"# punct = '\"#$%&\\'()*+/<=>?@[\\\\]^`{|}~'",
"if",
"re",
".",
"search",
"(",
"\"([\\t\\n\\r]+|[\\x0b\\x0c ]{3,})+\"",
",",
"line",
")",
":",
"tmp",
"=",
"re",
".",
"split",
"(",
"\"([\\t\\n\\r]+|[\\x0b\\x0c ]{3,})+\"",
",",
"line",
",",
"1",
")",
"else",
":",
"tmp",
"=",
"re",
".",
"split",
"(",
"\"[\"",
"+",
"string",
".",
"whitespace",
"+",
"\"]+\"",
",",
"line",
",",
"1",
")",
"res",
"=",
"[",
"elt",
".",
"strip",
"(",
")",
"for",
"elt",
"in",
"tmp",
"if",
"elt",
".",
"strip",
"(",
")",
"!=",
"''",
"]",
"return",
"res"
] |
Split the line on whitespaces and remove empty chunks
:param line: the line to split
:type line: str
:return: list of strings
:rtype: list
|
[
"Split",
"the",
"line",
"on",
"whitespaces",
"and",
"remove",
"empty",
"chunks"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1053-L1067
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.add_self_defined_objects
|
def add_self_defined_objects(raw_objects):
"""Add self defined command objects for internal processing ;
bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check
:param raw_objects: Raw config objects dict
:type raw_objects: dict
:return: raw_objects with some more commands
:rtype: dict
"""
logger.info("- creating internally defined commands...")
if 'command' not in raw_objects:
raw_objects['command'] = []
# Business rule
raw_objects['command'].append({
'command_name': 'bp_rule',
'command_line': 'bp_rule',
'imported_from': 'alignak-self'
})
# Internal host checks
raw_objects['command'].append({
'command_name': '_internal_host_up',
'command_line': '_internal_host_up',
'imported_from': 'alignak-self'
})
raw_objects['command'].append({
'command_name': '_internal_host_check',
# Command line must contain: state_id;output
'command_line': '_internal_host_check;$ARG1$;$ARG2$',
'imported_from': 'alignak-self'
})
# Internal service check
raw_objects['command'].append({
'command_name': '_echo',
'command_line': '_echo',
'imported_from': 'alignak-self'
})
raw_objects['command'].append({
'command_name': '_internal_service_check',
# Command line must contain: state_id;output
'command_line': '_internal_service_check;$ARG1$;$ARG2$',
'imported_from': 'alignak-self'
})
|
python
|
def add_self_defined_objects(raw_objects):
"""Add self defined command objects for internal processing ;
bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check
:param raw_objects: Raw config objects dict
:type raw_objects: dict
:return: raw_objects with some more commands
:rtype: dict
"""
logger.info("- creating internally defined commands...")
if 'command' not in raw_objects:
raw_objects['command'] = []
# Business rule
raw_objects['command'].append({
'command_name': 'bp_rule',
'command_line': 'bp_rule',
'imported_from': 'alignak-self'
})
# Internal host checks
raw_objects['command'].append({
'command_name': '_internal_host_up',
'command_line': '_internal_host_up',
'imported_from': 'alignak-self'
})
raw_objects['command'].append({
'command_name': '_internal_host_check',
# Command line must contain: state_id;output
'command_line': '_internal_host_check;$ARG1$;$ARG2$',
'imported_from': 'alignak-self'
})
# Internal service check
raw_objects['command'].append({
'command_name': '_echo',
'command_line': '_echo',
'imported_from': 'alignak-self'
})
raw_objects['command'].append({
'command_name': '_internal_service_check',
# Command line must contain: state_id;output
'command_line': '_internal_service_check;$ARG1$;$ARG2$',
'imported_from': 'alignak-self'
})
|
[
"def",
"add_self_defined_objects",
"(",
"raw_objects",
")",
":",
"logger",
".",
"info",
"(",
"\"- creating internally defined commands...\"",
")",
"if",
"'command'",
"not",
"in",
"raw_objects",
":",
"raw_objects",
"[",
"'command'",
"]",
"=",
"[",
"]",
"# Business rule",
"raw_objects",
"[",
"'command'",
"]",
".",
"append",
"(",
"{",
"'command_name'",
":",
"'bp_rule'",
",",
"'command_line'",
":",
"'bp_rule'",
",",
"'imported_from'",
":",
"'alignak-self'",
"}",
")",
"# Internal host checks",
"raw_objects",
"[",
"'command'",
"]",
".",
"append",
"(",
"{",
"'command_name'",
":",
"'_internal_host_up'",
",",
"'command_line'",
":",
"'_internal_host_up'",
",",
"'imported_from'",
":",
"'alignak-self'",
"}",
")",
"raw_objects",
"[",
"'command'",
"]",
".",
"append",
"(",
"{",
"'command_name'",
":",
"'_internal_host_check'",
",",
"# Command line must contain: state_id;output",
"'command_line'",
":",
"'_internal_host_check;$ARG1$;$ARG2$'",
",",
"'imported_from'",
":",
"'alignak-self'",
"}",
")",
"# Internal service check",
"raw_objects",
"[",
"'command'",
"]",
".",
"append",
"(",
"{",
"'command_name'",
":",
"'_echo'",
",",
"'command_line'",
":",
"'_echo'",
",",
"'imported_from'",
":",
"'alignak-self'",
"}",
")",
"raw_objects",
"[",
"'command'",
"]",
".",
"append",
"(",
"{",
"'command_name'",
":",
"'_internal_service_check'",
",",
"# Command line must contain: state_id;output",
"'command_line'",
":",
"'_internal_service_check;$ARG1$;$ARG2$'",
",",
"'imported_from'",
":",
"'alignak-self'",
"}",
")"
] |
Add self defined command objects for internal processing ;
bp_rule, _internal_host_up, _echo, _internal_host_check, _interna_service_check
:param raw_objects: Raw config objects dict
:type raw_objects: dict
:return: raw_objects with some more commands
:rtype: dict
|
[
"Add",
"self",
"defined",
"command",
"objects",
"for",
"internal",
"processing",
";",
"bp_rule",
"_internal_host_up",
"_echo",
"_internal_host_check",
"_interna_service_check"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1374-L1415
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.early_create_objects
|
def early_create_objects(self, raw_objects):
"""Create the objects needed for the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
"""
types_creations = self.__class__.types_creations
early_created_types = self.__class__.early_created_types
logger.info("Creating objects...")
for o_type in sorted(types_creations):
if o_type in early_created_types:
self.create_objects_for_type(raw_objects, o_type)
logger.info("Done")
|
python
|
def early_create_objects(self, raw_objects):
"""Create the objects needed for the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
"""
types_creations = self.__class__.types_creations
early_created_types = self.__class__.early_created_types
logger.info("Creating objects...")
for o_type in sorted(types_creations):
if o_type in early_created_types:
self.create_objects_for_type(raw_objects, o_type)
logger.info("Done")
|
[
"def",
"early_create_objects",
"(",
"self",
",",
"raw_objects",
")",
":",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"early_created_types",
"=",
"self",
".",
"__class__",
".",
"early_created_types",
"logger",
".",
"info",
"(",
"\"Creating objects...\"",
")",
"for",
"o_type",
"in",
"sorted",
"(",
"types_creations",
")",
":",
"if",
"o_type",
"in",
"early_created_types",
":",
"self",
".",
"create_objects_for_type",
"(",
"raw_objects",
",",
"o_type",
")",
"logger",
".",
"info",
"(",
"\"Done\"",
")"
] |
Create the objects needed for the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
|
[
"Create",
"the",
"objects",
"needed",
"for",
"the",
"post",
"configuration",
"file",
"initialization"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1417-L1431
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.create_objects
|
def create_objects(self, raw_objects):
"""Create all the objects got after the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
"""
types_creations = self.__class__.types_creations
early_created_types = self.__class__.early_created_types
logger.info("Creating objects...")
# Before really creating the objects, we add some ghost
# ones like the bp_rule for correlation
self.add_self_defined_objects(raw_objects)
for o_type in sorted(types_creations):
if o_type not in early_created_types:
self.create_objects_for_type(raw_objects, o_type)
logger.info("Done")
|
python
|
def create_objects(self, raw_objects):
"""Create all the objects got after the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
"""
types_creations = self.__class__.types_creations
early_created_types = self.__class__.early_created_types
logger.info("Creating objects...")
# Before really creating the objects, we add some ghost
# ones like the bp_rule for correlation
self.add_self_defined_objects(raw_objects)
for o_type in sorted(types_creations):
if o_type not in early_created_types:
self.create_objects_for_type(raw_objects, o_type)
logger.info("Done")
|
[
"def",
"create_objects",
"(",
"self",
",",
"raw_objects",
")",
":",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"early_created_types",
"=",
"self",
".",
"__class__",
".",
"early_created_types",
"logger",
".",
"info",
"(",
"\"Creating objects...\"",
")",
"# Before really creating the objects, we add some ghost",
"# ones like the bp_rule for correlation",
"self",
".",
"add_self_defined_objects",
"(",
"raw_objects",
")",
"for",
"o_type",
"in",
"sorted",
"(",
"types_creations",
")",
":",
"if",
"o_type",
"not",
"in",
"early_created_types",
":",
"self",
".",
"create_objects_for_type",
"(",
"raw_objects",
",",
"o_type",
")",
"logger",
".",
"info",
"(",
"\"Done\"",
")"
] |
Create all the objects got after the post configuration file initialization
:param raw_objects: dict with all object with str values
:type raw_objects: dict
:return: None
|
[
"Create",
"all",
"the",
"objects",
"got",
"after",
"the",
"post",
"configuration",
"file",
"initialization"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1433-L1452
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.create_objects_for_type
|
def create_objects_for_type(self, raw_objects, o_type):
"""Generic function to create objects regarding the o_type
This function create real Alignak objects from the raw data got from the configuration.
:param raw_objects: Raw objects
:type raw_objects: dict
:param o_type: the object type we want to create
:type o_type: object
:return: None
"""
# Ex: the above code do for timeperiods:
# timeperiods = []
# for timeperiodcfg in objects['timeperiod']:
# t = Timeperiod(timeperiodcfg)
# timeperiods.append(t)
# self.timeperiods = Timeperiods(timeperiods)
types_creations = self.__class__.types_creations
(cls, clss, prop, initial_index, _) = types_creations[o_type]
# List to store the created objects
lst = []
try:
logger.info("- creating '%s' objects", o_type)
for obj_cfg in raw_objects[o_type]:
# We create the object
my_object = cls(obj_cfg)
# and append it to the list
lst.append(my_object)
if not lst:
logger.info(" none.")
except KeyError:
logger.info(" no %s objects in the configuration", o_type)
# Create the objects list and set it in our properties
setattr(self, prop, clss(lst, initial_index))
|
python
|
def create_objects_for_type(self, raw_objects, o_type):
"""Generic function to create objects regarding the o_type
This function create real Alignak objects from the raw data got from the configuration.
:param raw_objects: Raw objects
:type raw_objects: dict
:param o_type: the object type we want to create
:type o_type: object
:return: None
"""
# Ex: the above code do for timeperiods:
# timeperiods = []
# for timeperiodcfg in objects['timeperiod']:
# t = Timeperiod(timeperiodcfg)
# timeperiods.append(t)
# self.timeperiods = Timeperiods(timeperiods)
types_creations = self.__class__.types_creations
(cls, clss, prop, initial_index, _) = types_creations[o_type]
# List to store the created objects
lst = []
try:
logger.info("- creating '%s' objects", o_type)
for obj_cfg in raw_objects[o_type]:
# We create the object
my_object = cls(obj_cfg)
# and append it to the list
lst.append(my_object)
if not lst:
logger.info(" none.")
except KeyError:
logger.info(" no %s objects in the configuration", o_type)
# Create the objects list and set it in our properties
setattr(self, prop, clss(lst, initial_index))
|
[
"def",
"create_objects_for_type",
"(",
"self",
",",
"raw_objects",
",",
"o_type",
")",
":",
"# Ex: the above code do for timeperiods:",
"# timeperiods = []",
"# for timeperiodcfg in objects['timeperiod']:",
"# t = Timeperiod(timeperiodcfg)",
"# timeperiods.append(t)",
"# self.timeperiods = Timeperiods(timeperiods)",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"(",
"cls",
",",
"clss",
",",
"prop",
",",
"initial_index",
",",
"_",
")",
"=",
"types_creations",
"[",
"o_type",
"]",
"# List to store the created objects",
"lst",
"=",
"[",
"]",
"try",
":",
"logger",
".",
"info",
"(",
"\"- creating '%s' objects\"",
",",
"o_type",
")",
"for",
"obj_cfg",
"in",
"raw_objects",
"[",
"o_type",
"]",
":",
"# We create the object",
"my_object",
"=",
"cls",
"(",
"obj_cfg",
")",
"# and append it to the list",
"lst",
".",
"append",
"(",
"my_object",
")",
"if",
"not",
"lst",
":",
"logger",
".",
"info",
"(",
"\" none.\"",
")",
"except",
"KeyError",
":",
"logger",
".",
"info",
"(",
"\" no %s objects in the configuration\"",
",",
"o_type",
")",
"# Create the objects list and set it in our properties",
"setattr",
"(",
"self",
",",
"prop",
",",
"clss",
"(",
"lst",
",",
"initial_index",
")",
")"
] |
Generic function to create objects regarding the o_type
This function create real Alignak objects from the raw data got from the configuration.
:param raw_objects: Raw objects
:type raw_objects: dict
:param o_type: the object type we want to create
:type o_type: object
:return: None
|
[
"Generic",
"function",
"to",
"create",
"objects",
"regarding",
"the",
"o_type"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1454-L1491
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.early_arbiter_linking
|
def early_arbiter_linking(self, arbiter_name, params):
""" Prepare the arbiter for early operations
:param arbiter_name: default arbiter name if no arbiter exist in the configuration
:type arbiter_name: str
:return: None
"""
if not self.arbiters:
params.update({
'name': arbiter_name, 'arbiter_name': arbiter_name,
'host_name': socket.gethostname(),
'address': '127.0.0.1', 'port': 7770,
'spare': '0'
})
logger.warning("There is no arbiter, I add myself (%s) reachable on %s:%d",
arbiter_name, params['address'], params['port'])
arb = ArbiterLink(params, parsing=True)
self.arbiters = ArbiterLinks([arb])
# First fill default
self.arbiters.fill_default()
self.modules.fill_default()
self.arbiters.linkify(modules=self.modules)
self.modules.linkify()
|
python
|
def early_arbiter_linking(self, arbiter_name, params):
""" Prepare the arbiter for early operations
:param arbiter_name: default arbiter name if no arbiter exist in the configuration
:type arbiter_name: str
:return: None
"""
if not self.arbiters:
params.update({
'name': arbiter_name, 'arbiter_name': arbiter_name,
'host_name': socket.gethostname(),
'address': '127.0.0.1', 'port': 7770,
'spare': '0'
})
logger.warning("There is no arbiter, I add myself (%s) reachable on %s:%d",
arbiter_name, params['address'], params['port'])
arb = ArbiterLink(params, parsing=True)
self.arbiters = ArbiterLinks([arb])
# First fill default
self.arbiters.fill_default()
self.modules.fill_default()
self.arbiters.linkify(modules=self.modules)
self.modules.linkify()
|
[
"def",
"early_arbiter_linking",
"(",
"self",
",",
"arbiter_name",
",",
"params",
")",
":",
"if",
"not",
"self",
".",
"arbiters",
":",
"params",
".",
"update",
"(",
"{",
"'name'",
":",
"arbiter_name",
",",
"'arbiter_name'",
":",
"arbiter_name",
",",
"'host_name'",
":",
"socket",
".",
"gethostname",
"(",
")",
",",
"'address'",
":",
"'127.0.0.1'",
",",
"'port'",
":",
"7770",
",",
"'spare'",
":",
"'0'",
"}",
")",
"logger",
".",
"warning",
"(",
"\"There is no arbiter, I add myself (%s) reachable on %s:%d\"",
",",
"arbiter_name",
",",
"params",
"[",
"'address'",
"]",
",",
"params",
"[",
"'port'",
"]",
")",
"arb",
"=",
"ArbiterLink",
"(",
"params",
",",
"parsing",
"=",
"True",
")",
"self",
".",
"arbiters",
"=",
"ArbiterLinks",
"(",
"[",
"arb",
"]",
")",
"# First fill default",
"self",
".",
"arbiters",
".",
"fill_default",
"(",
")",
"self",
".",
"modules",
".",
"fill_default",
"(",
")",
"self",
".",
"arbiters",
".",
"linkify",
"(",
"modules",
"=",
"self",
".",
"modules",
")",
"self",
".",
"modules",
".",
"linkify",
"(",
")"
] |
Prepare the arbiter for early operations
:param arbiter_name: default arbiter name if no arbiter exist in the configuration
:type arbiter_name: str
:return: None
|
[
"Prepare",
"the",
"arbiter",
"for",
"early",
"operations"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1493-L1518
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.linkify_one_command_with_commands
|
def linkify_one_command_with_commands(self, commands, prop):
"""
Link a command
:param commands: object commands
:type commands: object
:param prop: property name
:type prop: str
:return: None
"""
if not hasattr(self, prop):
return
command = getattr(self, prop).strip()
if not command:
setattr(self, prop, None)
return
data = {"commands": commands, "call": command}
if hasattr(self, 'poller_tag'):
data.update({"poller_tag": self.poller_tag})
if hasattr(self, 'reactionner_tag'):
data.update({"reactionner_tag": self.reactionner_tag})
setattr(self, prop, CommandCall(data))
|
python
|
def linkify_one_command_with_commands(self, commands, prop):
"""
Link a command
:param commands: object commands
:type commands: object
:param prop: property name
:type prop: str
:return: None
"""
if not hasattr(self, prop):
return
command = getattr(self, prop).strip()
if not command:
setattr(self, prop, None)
return
data = {"commands": commands, "call": command}
if hasattr(self, 'poller_tag'):
data.update({"poller_tag": self.poller_tag})
if hasattr(self, 'reactionner_tag'):
data.update({"reactionner_tag": self.reactionner_tag})
setattr(self, prop, CommandCall(data))
|
[
"def",
"linkify_one_command_with_commands",
"(",
"self",
",",
"commands",
",",
"prop",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"prop",
")",
":",
"return",
"command",
"=",
"getattr",
"(",
"self",
",",
"prop",
")",
".",
"strip",
"(",
")",
"if",
"not",
"command",
":",
"setattr",
"(",
"self",
",",
"prop",
",",
"None",
")",
"return",
"data",
"=",
"{",
"\"commands\"",
":",
"commands",
",",
"\"call\"",
":",
"command",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'poller_tag'",
")",
":",
"data",
".",
"update",
"(",
"{",
"\"poller_tag\"",
":",
"self",
".",
"poller_tag",
"}",
")",
"if",
"hasattr",
"(",
"self",
",",
"'reactionner_tag'",
")",
":",
"data",
".",
"update",
"(",
"{",
"\"reactionner_tag\"",
":",
"self",
".",
"reactionner_tag",
"}",
")",
"setattr",
"(",
"self",
",",
"prop",
",",
"CommandCall",
"(",
"data",
")",
")"
] |
Link a command
:param commands: object commands
:type commands: object
:param prop: property name
:type prop: str
:return: None
|
[
"Link",
"a",
"command"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1520-L1545
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.linkify
|
def linkify(self):
""" Make 'links' between elements, like a host got a services list
with all its services in it
:return: None
"""
self.services.optimize_service_search(self.hosts)
# First linkify myself like for some global commands
self.linkify_one_command_with_commands(self.commands, 'host_perfdata_command')
self.linkify_one_command_with_commands(self.commands, 'service_perfdata_command')
self.linkify_one_command_with_commands(self.commands, 'global_host_event_handler')
self.linkify_one_command_with_commands(self.commands, 'global_service_event_handler')
# link hosts with timeperiods and commands
self.hosts.linkify(self.timeperiods, self.commands,
self.contacts, self.realms,
self.resultmodulations, self.businessimpactmodulations,
self.escalations, self.hostgroups,
self.checkmodulations, self.macromodulations)
self.hostsextinfo.merge(self.hosts)
# Do the simplify AFTER explode groups
# link hostgroups with hosts
self.hostgroups.linkify(self.hosts, self.realms, self.forced_realms_hostgroups)
# link services with other objects
self.services.linkify(self.hosts, self.commands,
self.timeperiods, self.contacts,
self.resultmodulations, self.businessimpactmodulations,
self.escalations, self.servicegroups,
self.checkmodulations, self.macromodulations)
self.servicesextinfo.merge(self.services)
# link servicegroups members with services
self.servicegroups.linkify(self.hosts, self.services)
# link notificationways with timeperiods and commands
self.notificationways.linkify(self.timeperiods, self.commands)
# link notificationways with timeperiods and commands
self.checkmodulations.linkify(self.timeperiods, self.commands)
# Link with timeperiods
self.macromodulations.linkify(self.timeperiods)
# link contacgroups with contacts
self.contactgroups.linkify(self.contacts)
# link contacts with timeperiods and commands
self.contacts.linkify(self.commands, self.notificationways)
# link timeperiods with timeperiods (exclude part)
self.timeperiods.linkify()
self.servicedependencies.linkify(self.hosts, self.services,
self.timeperiods)
self.hostdependencies.linkify(self.hosts, self.timeperiods)
self.resultmodulations.linkify(self.timeperiods)
self.businessimpactmodulations.linkify(self.timeperiods)
self.escalations.linkify(self.timeperiods, self.contacts,
self.services, self.hosts)
# Link all satellite links with modules
self.schedulers.linkify(self.modules)
self.brokers.linkify(self.modules)
self.receivers.linkify(self.modules)
self.reactionners.linkify(self.modules)
self.pollers.linkify(self.modules)
# Ok, now update all realms with back links of satellites
satellites = {}
for sat in self.schedulers:
satellites[sat.uuid] = sat
for sat in self.pollers:
satellites[sat.uuid] = sat
for sat in self.reactionners:
satellites[sat.uuid] = sat
for sat in self.receivers:
satellites[sat.uuid] = sat
for sat in self.brokers:
satellites[sat.uuid] = sat
self.realms.prepare_satellites(satellites)
|
python
|
def linkify(self):
""" Make 'links' between elements, like a host got a services list
with all its services in it
:return: None
"""
self.services.optimize_service_search(self.hosts)
# First linkify myself like for some global commands
self.linkify_one_command_with_commands(self.commands, 'host_perfdata_command')
self.linkify_one_command_with_commands(self.commands, 'service_perfdata_command')
self.linkify_one_command_with_commands(self.commands, 'global_host_event_handler')
self.linkify_one_command_with_commands(self.commands, 'global_service_event_handler')
# link hosts with timeperiods and commands
self.hosts.linkify(self.timeperiods, self.commands,
self.contacts, self.realms,
self.resultmodulations, self.businessimpactmodulations,
self.escalations, self.hostgroups,
self.checkmodulations, self.macromodulations)
self.hostsextinfo.merge(self.hosts)
# Do the simplify AFTER explode groups
# link hostgroups with hosts
self.hostgroups.linkify(self.hosts, self.realms, self.forced_realms_hostgroups)
# link services with other objects
self.services.linkify(self.hosts, self.commands,
self.timeperiods, self.contacts,
self.resultmodulations, self.businessimpactmodulations,
self.escalations, self.servicegroups,
self.checkmodulations, self.macromodulations)
self.servicesextinfo.merge(self.services)
# link servicegroups members with services
self.servicegroups.linkify(self.hosts, self.services)
# link notificationways with timeperiods and commands
self.notificationways.linkify(self.timeperiods, self.commands)
# link notificationways with timeperiods and commands
self.checkmodulations.linkify(self.timeperiods, self.commands)
# Link with timeperiods
self.macromodulations.linkify(self.timeperiods)
# link contacgroups with contacts
self.contactgroups.linkify(self.contacts)
# link contacts with timeperiods and commands
self.contacts.linkify(self.commands, self.notificationways)
# link timeperiods with timeperiods (exclude part)
self.timeperiods.linkify()
self.servicedependencies.linkify(self.hosts, self.services,
self.timeperiods)
self.hostdependencies.linkify(self.hosts, self.timeperiods)
self.resultmodulations.linkify(self.timeperiods)
self.businessimpactmodulations.linkify(self.timeperiods)
self.escalations.linkify(self.timeperiods, self.contacts,
self.services, self.hosts)
# Link all satellite links with modules
self.schedulers.linkify(self.modules)
self.brokers.linkify(self.modules)
self.receivers.linkify(self.modules)
self.reactionners.linkify(self.modules)
self.pollers.linkify(self.modules)
# Ok, now update all realms with back links of satellites
satellites = {}
for sat in self.schedulers:
satellites[sat.uuid] = sat
for sat in self.pollers:
satellites[sat.uuid] = sat
for sat in self.reactionners:
satellites[sat.uuid] = sat
for sat in self.receivers:
satellites[sat.uuid] = sat
for sat in self.brokers:
satellites[sat.uuid] = sat
self.realms.prepare_satellites(satellites)
|
[
"def",
"linkify",
"(",
"self",
")",
":",
"self",
".",
"services",
".",
"optimize_service_search",
"(",
"self",
".",
"hosts",
")",
"# First linkify myself like for some global commands",
"self",
".",
"linkify_one_command_with_commands",
"(",
"self",
".",
"commands",
",",
"'host_perfdata_command'",
")",
"self",
".",
"linkify_one_command_with_commands",
"(",
"self",
".",
"commands",
",",
"'service_perfdata_command'",
")",
"self",
".",
"linkify_one_command_with_commands",
"(",
"self",
".",
"commands",
",",
"'global_host_event_handler'",
")",
"self",
".",
"linkify_one_command_with_commands",
"(",
"self",
".",
"commands",
",",
"'global_service_event_handler'",
")",
"# link hosts with timeperiods and commands",
"self",
".",
"hosts",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
",",
"self",
".",
"commands",
",",
"self",
".",
"contacts",
",",
"self",
".",
"realms",
",",
"self",
".",
"resultmodulations",
",",
"self",
".",
"businessimpactmodulations",
",",
"self",
".",
"escalations",
",",
"self",
".",
"hostgroups",
",",
"self",
".",
"checkmodulations",
",",
"self",
".",
"macromodulations",
")",
"self",
".",
"hostsextinfo",
".",
"merge",
"(",
"self",
".",
"hosts",
")",
"# Do the simplify AFTER explode groups",
"# link hostgroups with hosts",
"self",
".",
"hostgroups",
".",
"linkify",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"realms",
",",
"self",
".",
"forced_realms_hostgroups",
")",
"# link services with other objects",
"self",
".",
"services",
".",
"linkify",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"commands",
",",
"self",
".",
"timeperiods",
",",
"self",
".",
"contacts",
",",
"self",
".",
"resultmodulations",
",",
"self",
".",
"businessimpactmodulations",
",",
"self",
".",
"escalations",
",",
"self",
".",
"servicegroups",
",",
"self",
".",
"checkmodulations",
",",
"self",
".",
"macromodulations",
")",
"self",
".",
"servicesextinfo",
".",
"merge",
"(",
"self",
".",
"services",
")",
"# link servicegroups members with services",
"self",
".",
"servicegroups",
".",
"linkify",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
")",
"# link notificationways with timeperiods and commands",
"self",
".",
"notificationways",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
",",
"self",
".",
"commands",
")",
"# link notificationways with timeperiods and commands",
"self",
".",
"checkmodulations",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
",",
"self",
".",
"commands",
")",
"# Link with timeperiods",
"self",
".",
"macromodulations",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
")",
"# link contacgroups with contacts",
"self",
".",
"contactgroups",
".",
"linkify",
"(",
"self",
".",
"contacts",
")",
"# link contacts with timeperiods and commands",
"self",
".",
"contacts",
".",
"linkify",
"(",
"self",
".",
"commands",
",",
"self",
".",
"notificationways",
")",
"# link timeperiods with timeperiods (exclude part)",
"self",
".",
"timeperiods",
".",
"linkify",
"(",
")",
"self",
".",
"servicedependencies",
".",
"linkify",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
",",
"self",
".",
"timeperiods",
")",
"self",
".",
"hostdependencies",
".",
"linkify",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"timeperiods",
")",
"self",
".",
"resultmodulations",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
")",
"self",
".",
"businessimpactmodulations",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
")",
"self",
".",
"escalations",
".",
"linkify",
"(",
"self",
".",
"timeperiods",
",",
"self",
".",
"contacts",
",",
"self",
".",
"services",
",",
"self",
".",
"hosts",
")",
"# Link all satellite links with modules",
"self",
".",
"schedulers",
".",
"linkify",
"(",
"self",
".",
"modules",
")",
"self",
".",
"brokers",
".",
"linkify",
"(",
"self",
".",
"modules",
")",
"self",
".",
"receivers",
".",
"linkify",
"(",
"self",
".",
"modules",
")",
"self",
".",
"reactionners",
".",
"linkify",
"(",
"self",
".",
"modules",
")",
"self",
".",
"pollers",
".",
"linkify",
"(",
"self",
".",
"modules",
")",
"# Ok, now update all realms with back links of satellites",
"satellites",
"=",
"{",
"}",
"for",
"sat",
"in",
"self",
".",
"schedulers",
":",
"satellites",
"[",
"sat",
".",
"uuid",
"]",
"=",
"sat",
"for",
"sat",
"in",
"self",
".",
"pollers",
":",
"satellites",
"[",
"sat",
".",
"uuid",
"]",
"=",
"sat",
"for",
"sat",
"in",
"self",
".",
"reactionners",
":",
"satellites",
"[",
"sat",
".",
"uuid",
"]",
"=",
"sat",
"for",
"sat",
"in",
"self",
".",
"receivers",
":",
"satellites",
"[",
"sat",
".",
"uuid",
"]",
"=",
"sat",
"for",
"sat",
"in",
"self",
".",
"brokers",
":",
"satellites",
"[",
"sat",
".",
"uuid",
"]",
"=",
"sat",
"self",
".",
"realms",
".",
"prepare_satellites",
"(",
"satellites",
")"
] |
Make 'links' between elements, like a host got a services list
with all its services in it
:return: None
|
[
"Make",
"links",
"between",
"elements",
"like",
"a",
"host",
"got",
"a",
"services",
"list",
"with",
"all",
"its",
"services",
"in",
"it"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1547-L1635
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.clean
|
def clean(self):
"""Wrapper for calling the clean method of services attribute
:return: None
"""
logger.debug("Cleaning configuration objects before configuration sending:")
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
logger.debug(" . for %s", inner_property, )
inner_object = getattr(self, inner_property)
inner_object.clean()
|
python
|
def clean(self):
"""Wrapper for calling the clean method of services attribute
:return: None
"""
logger.debug("Cleaning configuration objects before configuration sending:")
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
logger.debug(" . for %s", inner_property, )
inner_object = getattr(self, inner_property)
inner_object.clean()
|
[
"def",
"clean",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Cleaning configuration objects before configuration sending:\"",
")",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"for",
"o_type",
"in",
"types_creations",
":",
"(",
"_",
",",
"_",
",",
"inner_property",
",",
"_",
",",
"_",
")",
"=",
"types_creations",
"[",
"o_type",
"]",
"logger",
".",
"debug",
"(",
"\" . for %s\"",
",",
"inner_property",
",",
")",
"inner_object",
"=",
"getattr",
"(",
"self",
",",
"inner_property",
")",
"inner_object",
".",
"clean",
"(",
")"
] |
Wrapper for calling the clean method of services attribute
:return: None
|
[
"Wrapper",
"for",
"calling",
"the",
"clean",
"method",
"of",
"services",
"attribute"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1637-L1648
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.warn_about_unmanaged_parameters
|
def warn_about_unmanaged_parameters(self):
"""used to raise warning if the user got parameter
that we do not manage from now
:return: None
"""
properties = self.__class__.properties
unmanaged = []
for prop, entry in list(properties.items()):
if not entry.managed and hasattr(self, prop):
if entry.help:
line = "%s: %s" % (prop, entry.help)
else:
line = prop
unmanaged.append(line)
if unmanaged:
logger.warning("The following Nagios legacy parameter(s) are not currently "
"managed by Alignak:")
for line in unmanaged:
logger.warning('- %s', line)
logger.warning("Those are unmanaged configuration statements, do you really need it? "
"Create an issue on the Alignak repository or submit a pull "
"request: http://www.github.com/Alignak-monitoring/alignak")
|
python
|
def warn_about_unmanaged_parameters(self):
"""used to raise warning if the user got parameter
that we do not manage from now
:return: None
"""
properties = self.__class__.properties
unmanaged = []
for prop, entry in list(properties.items()):
if not entry.managed and hasattr(self, prop):
if entry.help:
line = "%s: %s" % (prop, entry.help)
else:
line = prop
unmanaged.append(line)
if unmanaged:
logger.warning("The following Nagios legacy parameter(s) are not currently "
"managed by Alignak:")
for line in unmanaged:
logger.warning('- %s', line)
logger.warning("Those are unmanaged configuration statements, do you really need it? "
"Create an issue on the Alignak repository or submit a pull "
"request: http://www.github.com/Alignak-monitoring/alignak")
|
[
"def",
"warn_about_unmanaged_parameters",
"(",
"self",
")",
":",
"properties",
"=",
"self",
".",
"__class__",
".",
"properties",
"unmanaged",
"=",
"[",
"]",
"for",
"prop",
",",
"entry",
"in",
"list",
"(",
"properties",
".",
"items",
"(",
")",
")",
":",
"if",
"not",
"entry",
".",
"managed",
"and",
"hasattr",
"(",
"self",
",",
"prop",
")",
":",
"if",
"entry",
".",
"help",
":",
"line",
"=",
"\"%s: %s\"",
"%",
"(",
"prop",
",",
"entry",
".",
"help",
")",
"else",
":",
"line",
"=",
"prop",
"unmanaged",
".",
"append",
"(",
"line",
")",
"if",
"unmanaged",
":",
"logger",
".",
"warning",
"(",
"\"The following Nagios legacy parameter(s) are not currently \"",
"\"managed by Alignak:\"",
")",
"for",
"line",
"in",
"unmanaged",
":",
"logger",
".",
"warning",
"(",
"'- %s'",
",",
"line",
")",
"logger",
".",
"warning",
"(",
"\"Those are unmanaged configuration statements, do you really need it? \"",
"\"Create an issue on the Alignak repository or submit a pull \"",
"\"request: http://www.github.com/Alignak-monitoring/alignak\"",
")"
] |
used to raise warning if the user got parameter
that we do not manage from now
:return: None
|
[
"used",
"to",
"raise",
"warning",
"if",
"the",
"user",
"got",
"parameter",
"that",
"we",
"do",
"not",
"manage",
"from",
"now"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1650-L1674
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.apply_dependencies
|
def apply_dependencies(self):
"""Creates dependencies links between elements.
:return: None
"""
self.hosts.apply_dependencies()
self.services.apply_dependencies(self.hosts)
|
python
|
def apply_dependencies(self):
"""Creates dependencies links between elements.
:return: None
"""
self.hosts.apply_dependencies()
self.services.apply_dependencies(self.hosts)
|
[
"def",
"apply_dependencies",
"(",
"self",
")",
":",
"self",
".",
"hosts",
".",
"apply_dependencies",
"(",
")",
"self",
".",
"services",
".",
"apply_dependencies",
"(",
"self",
".",
"hosts",
")"
] |
Creates dependencies links between elements.
:return: None
|
[
"Creates",
"dependencies",
"links",
"between",
"elements",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1715-L1721
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.fill_default_configuration
|
def fill_default_configuration(self):
"""Fill objects properties with default value if necessary
:return: None
"""
logger.debug("Filling the unset properties with their default value:")
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
# Not yet for the realms and daemons links
if inner_property in ['realms', 'arbiters', 'schedulers', 'reactionners',
'pollers', 'brokers', 'receivers']:
continue
logger.debug(" . for %s", inner_property,)
inner_object = getattr(self, inner_property, None)
if inner_object is None:
logger.debug("No %s to fill with default values", inner_property)
continue
inner_object.fill_default()
# We have all monitored elements, we can create a default realm if none is defined
if getattr(self, 'realms', None) is not None:
self.fill_default_realm()
self.realms.fill_default()
# Then we create missing satellites, so no other satellites will be created after
self.fill_default_satellites(self.launch_missing_daemons)
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
if getattr(self, inner_property, None) is None:
logger.debug("No %s to fill with default values", inner_property)
continue
# Only for the daemons links
if inner_property in ['schedulers', 'reactionners', 'pollers', 'brokers', 'receivers']:
logger.debug(" . for %s", inner_property,)
inner_object = getattr(self, inner_property)
inner_object.fill_default()
# Now fill some fields we can predict (like address for hosts)
self.hosts.fill_predictive_missing_parameters()
self.services.fill_predictive_missing_parameters()
|
python
|
def fill_default_configuration(self):
"""Fill objects properties with default value if necessary
:return: None
"""
logger.debug("Filling the unset properties with their default value:")
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
# Not yet for the realms and daemons links
if inner_property in ['realms', 'arbiters', 'schedulers', 'reactionners',
'pollers', 'brokers', 'receivers']:
continue
logger.debug(" . for %s", inner_property,)
inner_object = getattr(self, inner_property, None)
if inner_object is None:
logger.debug("No %s to fill with default values", inner_property)
continue
inner_object.fill_default()
# We have all monitored elements, we can create a default realm if none is defined
if getattr(self, 'realms', None) is not None:
self.fill_default_realm()
self.realms.fill_default()
# Then we create missing satellites, so no other satellites will be created after
self.fill_default_satellites(self.launch_missing_daemons)
types_creations = self.__class__.types_creations
for o_type in types_creations:
(_, _, inner_property, _, _) = types_creations[o_type]
if getattr(self, inner_property, None) is None:
logger.debug("No %s to fill with default values", inner_property)
continue
# Only for the daemons links
if inner_property in ['schedulers', 'reactionners', 'pollers', 'brokers', 'receivers']:
logger.debug(" . for %s", inner_property,)
inner_object = getattr(self, inner_property)
inner_object.fill_default()
# Now fill some fields we can predict (like address for hosts)
self.hosts.fill_predictive_missing_parameters()
self.services.fill_predictive_missing_parameters()
|
[
"def",
"fill_default_configuration",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Filling the unset properties with their default value:\"",
")",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"for",
"o_type",
"in",
"types_creations",
":",
"(",
"_",
",",
"_",
",",
"inner_property",
",",
"_",
",",
"_",
")",
"=",
"types_creations",
"[",
"o_type",
"]",
"# Not yet for the realms and daemons links",
"if",
"inner_property",
"in",
"[",
"'realms'",
",",
"'arbiters'",
",",
"'schedulers'",
",",
"'reactionners'",
",",
"'pollers'",
",",
"'brokers'",
",",
"'receivers'",
"]",
":",
"continue",
"logger",
".",
"debug",
"(",
"\" . for %s\"",
",",
"inner_property",
",",
")",
"inner_object",
"=",
"getattr",
"(",
"self",
",",
"inner_property",
",",
"None",
")",
"if",
"inner_object",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"No %s to fill with default values\"",
",",
"inner_property",
")",
"continue",
"inner_object",
".",
"fill_default",
"(",
")",
"# We have all monitored elements, we can create a default realm if none is defined",
"if",
"getattr",
"(",
"self",
",",
"'realms'",
",",
"None",
")",
"is",
"not",
"None",
":",
"self",
".",
"fill_default_realm",
"(",
")",
"self",
".",
"realms",
".",
"fill_default",
"(",
")",
"# Then we create missing satellites, so no other satellites will be created after",
"self",
".",
"fill_default_satellites",
"(",
"self",
".",
"launch_missing_daemons",
")",
"types_creations",
"=",
"self",
".",
"__class__",
".",
"types_creations",
"for",
"o_type",
"in",
"types_creations",
":",
"(",
"_",
",",
"_",
",",
"inner_property",
",",
"_",
",",
"_",
")",
"=",
"types_creations",
"[",
"o_type",
"]",
"if",
"getattr",
"(",
"self",
",",
"inner_property",
",",
"None",
")",
"is",
"None",
":",
"logger",
".",
"debug",
"(",
"\"No %s to fill with default values\"",
",",
"inner_property",
")",
"continue",
"# Only for the daemons links",
"if",
"inner_property",
"in",
"[",
"'schedulers'",
",",
"'reactionners'",
",",
"'pollers'",
",",
"'brokers'",
",",
"'receivers'",
"]",
":",
"logger",
".",
"debug",
"(",
"\" . for %s\"",
",",
"inner_property",
",",
")",
"inner_object",
"=",
"getattr",
"(",
"self",
",",
"inner_property",
")",
"inner_object",
".",
"fill_default",
"(",
")",
"# Now fill some fields we can predict (like address for hosts)",
"self",
".",
"hosts",
".",
"fill_predictive_missing_parameters",
"(",
")",
"self",
".",
"services",
".",
"fill_predictive_missing_parameters",
"(",
")"
] |
Fill objects properties with default value if necessary
:return: None
|
[
"Fill",
"objects",
"properties",
"with",
"default",
"value",
"if",
"necessary"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1767-L1810
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.log_daemons_list
|
def log_daemons_list(self):
"""Log Alignak daemons list
:return:
"""
daemons = [self.arbiters, self.schedulers, self.pollers,
self.brokers, self.reactionners, self.receivers]
for daemons_list in daemons:
if not daemons_list:
logger.debug("- %ss: None", daemons_list.inner_class.my_type)
else:
logger.debug("- %ss: %s", daemons_list.inner_class.my_type,
','.join([daemon.get_name() for daemon in daemons_list]))
|
python
|
def log_daemons_list(self):
"""Log Alignak daemons list
:return:
"""
daemons = [self.arbiters, self.schedulers, self.pollers,
self.brokers, self.reactionners, self.receivers]
for daemons_list in daemons:
if not daemons_list:
logger.debug("- %ss: None", daemons_list.inner_class.my_type)
else:
logger.debug("- %ss: %s", daemons_list.inner_class.my_type,
','.join([daemon.get_name() for daemon in daemons_list]))
|
[
"def",
"log_daemons_list",
"(",
"self",
")",
":",
"daemons",
"=",
"[",
"self",
".",
"arbiters",
",",
"self",
".",
"schedulers",
",",
"self",
".",
"pollers",
",",
"self",
".",
"brokers",
",",
"self",
".",
"reactionners",
",",
"self",
".",
"receivers",
"]",
"for",
"daemons_list",
"in",
"daemons",
":",
"if",
"not",
"daemons_list",
":",
"logger",
".",
"debug",
"(",
"\"- %ss: None\"",
",",
"daemons_list",
".",
"inner_class",
".",
"my_type",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"- %ss: %s\"",
",",
"daemons_list",
".",
"inner_class",
".",
"my_type",
",",
"','",
".",
"join",
"(",
"[",
"daemon",
".",
"get_name",
"(",
")",
"for",
"daemon",
"in",
"daemons_list",
"]",
")",
")"
] |
Log Alignak daemons list
:return:
|
[
"Log",
"Alignak",
"daemons",
"list"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L1830-L1842
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.got_broker_module_type_defined
|
def got_broker_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the brokers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
"""
for broker_link in self.brokers:
for module in broker_link.modules:
if module.is_a_module(module_type):
return True
return False
|
python
|
def got_broker_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the brokers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
"""
for broker_link in self.brokers:
for module in broker_link.modules:
if module.is_a_module(module_type):
return True
return False
|
[
"def",
"got_broker_module_type_defined",
"(",
"self",
",",
"module_type",
")",
":",
"for",
"broker_link",
"in",
"self",
".",
"brokers",
":",
"for",
"module",
"in",
"broker_link",
".",
"modules",
":",
"if",
"module",
".",
"is_a_module",
"(",
"module_type",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if a module type is defined in one of the brokers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
|
[
"Check",
"if",
"a",
"module",
"type",
"is",
"defined",
"in",
"one",
"of",
"the",
"brokers"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2083-L2095
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.got_scheduler_module_type_defined
|
def got_scheduler_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the schedulers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined
"""
for scheduler_link in self.schedulers:
for module in scheduler_link.modules:
if module.is_a_module(module_type):
return True
return False
|
python
|
def got_scheduler_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the schedulers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined
"""
for scheduler_link in self.schedulers:
for module in scheduler_link.modules:
if module.is_a_module(module_type):
return True
return False
|
[
"def",
"got_scheduler_module_type_defined",
"(",
"self",
",",
"module_type",
")",
":",
"for",
"scheduler_link",
"in",
"self",
".",
"schedulers",
":",
"for",
"module",
"in",
"scheduler_link",
".",
"modules",
":",
"if",
"module",
".",
"is_a_module",
"(",
"module_type",
")",
":",
"return",
"True",
"return",
"False"
] |
Check if a module type is defined in one of the schedulers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined
|
[
"Check",
"if",
"a",
"module",
"type",
"is",
"defined",
"in",
"one",
"of",
"the",
"schedulers"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2097-L2110
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.got_arbiter_module_type_defined
|
def got_arbiter_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined:
"""
for arbiter in self.arbiters:
# Do like the linkify will do after....
for module in getattr(arbiter, 'modules', []):
# So look at what the arbiter try to call as module
module_name = module.get_name()
# Ok, now look in modules...
for mod in self.modules:
# try to see if this module is the good type
if getattr(mod, 'python_name', '').strip() == module_type.strip():
# if so, the good name?
if getattr(mod, 'name', '').strip() == module_name:
return True
return False
|
python
|
def got_arbiter_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined:
"""
for arbiter in self.arbiters:
# Do like the linkify will do after....
for module in getattr(arbiter, 'modules', []):
# So look at what the arbiter try to call as module
module_name = module.get_name()
# Ok, now look in modules...
for mod in self.modules:
# try to see if this module is the good type
if getattr(mod, 'python_name', '').strip() == module_type.strip():
# if so, the good name?
if getattr(mod, 'name', '').strip() == module_name:
return True
return False
|
[
"def",
"got_arbiter_module_type_defined",
"(",
"self",
",",
"module_type",
")",
":",
"for",
"arbiter",
"in",
"self",
".",
"arbiters",
":",
"# Do like the linkify will do after....",
"for",
"module",
"in",
"getattr",
"(",
"arbiter",
",",
"'modules'",
",",
"[",
"]",
")",
":",
"# So look at what the arbiter try to call as module",
"module_name",
"=",
"module",
".",
"get_name",
"(",
")",
"# Ok, now look in modules...",
"for",
"mod",
"in",
"self",
".",
"modules",
":",
"# try to see if this module is the good type",
"if",
"getattr",
"(",
"mod",
",",
"'python_name'",
",",
"''",
")",
".",
"strip",
"(",
")",
"==",
"module_type",
".",
"strip",
"(",
")",
":",
"# if so, the good name?",
"if",
"getattr",
"(",
"mod",
",",
"'name'",
",",
"''",
")",
".",
"strip",
"(",
")",
"==",
"module_name",
":",
"return",
"True",
"return",
"False"
] |
Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined:
|
[
"Check",
"if",
"a",
"module",
"type",
"is",
"defined",
"in",
"one",
"of",
"the",
"arbiters",
"Also",
"check",
"the",
"module",
"name"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2112-L2134
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.create_business_rules
|
def create_business_rules(self):
"""Create business rules for hosts and services
:return: None
"""
self.hosts.create_business_rules(self.hosts, self.services,
self.hostgroups, self.servicegroups,
self.macromodulations, self.timeperiods)
self.services.create_business_rules(self.hosts, self.services,
self.hostgroups, self.servicegroups,
self.macromodulations, self.timeperiods)
|
python
|
def create_business_rules(self):
"""Create business rules for hosts and services
:return: None
"""
self.hosts.create_business_rules(self.hosts, self.services,
self.hostgroups, self.servicegroups,
self.macromodulations, self.timeperiods)
self.services.create_business_rules(self.hosts, self.services,
self.hostgroups, self.servicegroups,
self.macromodulations, self.timeperiods)
|
[
"def",
"create_business_rules",
"(",
"self",
")",
":",
"self",
".",
"hosts",
".",
"create_business_rules",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
",",
"self",
".",
"hostgroups",
",",
"self",
".",
"servicegroups",
",",
"self",
".",
"macromodulations",
",",
"self",
".",
"timeperiods",
")",
"self",
".",
"services",
".",
"create_business_rules",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
",",
"self",
".",
"hostgroups",
",",
"self",
".",
"servicegroups",
",",
"self",
".",
"macromodulations",
",",
"self",
".",
"timeperiods",
")"
] |
Create business rules for hosts and services
:return: None
|
[
"Create",
"business",
"rules",
"for",
"hosts",
"and",
"services"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2136-L2146
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.create_business_rules_dependencies
|
def create_business_rules_dependencies(self):
"""Create business rules dependencies for hosts and services
:return: None
"""
for item in itertools.chain(self.hosts, self.services):
if not item.got_business_rule:
continue
bp_items = item.business_rule.list_all_elements()
for bp_item_uuid in bp_items:
if bp_item_uuid in self.hosts:
bp_item = self.hosts[bp_item_uuid]
notif_options = item.business_rule_host_notification_options
else: # We have a service
bp_item = self.services[bp_item_uuid]
notif_options = item.business_rule_service_notification_options
if notif_options:
bp_item.notification_options = notif_options
bp_item.act_depend_of_me.append((item.uuid, ['d', 'u', 's', 'f', 'c', 'w', 'x'],
'', True))
# TODO: Is it necessary? We already have this info in act_depend_* attributes
item.parent_dependencies.add(bp_item.uuid)
bp_item.child_dependencies.add(item.uuid)
|
python
|
def create_business_rules_dependencies(self):
"""Create business rules dependencies for hosts and services
:return: None
"""
for item in itertools.chain(self.hosts, self.services):
if not item.got_business_rule:
continue
bp_items = item.business_rule.list_all_elements()
for bp_item_uuid in bp_items:
if bp_item_uuid in self.hosts:
bp_item = self.hosts[bp_item_uuid]
notif_options = item.business_rule_host_notification_options
else: # We have a service
bp_item = self.services[bp_item_uuid]
notif_options = item.business_rule_service_notification_options
if notif_options:
bp_item.notification_options = notif_options
bp_item.act_depend_of_me.append((item.uuid, ['d', 'u', 's', 'f', 'c', 'w', 'x'],
'', True))
# TODO: Is it necessary? We already have this info in act_depend_* attributes
item.parent_dependencies.add(bp_item.uuid)
bp_item.child_dependencies.add(item.uuid)
|
[
"def",
"create_business_rules_dependencies",
"(",
"self",
")",
":",
"for",
"item",
"in",
"itertools",
".",
"chain",
"(",
"self",
".",
"hosts",
",",
"self",
".",
"services",
")",
":",
"if",
"not",
"item",
".",
"got_business_rule",
":",
"continue",
"bp_items",
"=",
"item",
".",
"business_rule",
".",
"list_all_elements",
"(",
")",
"for",
"bp_item_uuid",
"in",
"bp_items",
":",
"if",
"bp_item_uuid",
"in",
"self",
".",
"hosts",
":",
"bp_item",
"=",
"self",
".",
"hosts",
"[",
"bp_item_uuid",
"]",
"notif_options",
"=",
"item",
".",
"business_rule_host_notification_options",
"else",
":",
"# We have a service",
"bp_item",
"=",
"self",
".",
"services",
"[",
"bp_item_uuid",
"]",
"notif_options",
"=",
"item",
".",
"business_rule_service_notification_options",
"if",
"notif_options",
":",
"bp_item",
".",
"notification_options",
"=",
"notif_options",
"bp_item",
".",
"act_depend_of_me",
".",
"append",
"(",
"(",
"item",
".",
"uuid",
",",
"[",
"'d'",
",",
"'u'",
",",
"'s'",
",",
"'f'",
",",
"'c'",
",",
"'w'",
",",
"'x'",
"]",
",",
"''",
",",
"True",
")",
")",
"# TODO: Is it necessary? We already have this info in act_depend_* attributes",
"item",
".",
"parent_dependencies",
".",
"add",
"(",
"bp_item",
".",
"uuid",
")",
"bp_item",
".",
"child_dependencies",
".",
"add",
"(",
"item",
".",
"uuid",
")"
] |
Create business rules dependencies for hosts and services
:return: None
|
[
"Create",
"business",
"rules",
"dependencies",
"for",
"hosts",
"and",
"services"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2148-L2175
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.propagate_timezone_option
|
def propagate_timezone_option(self):
"""Set our timezone value and give it too to unset satellites
:return: None
"""
if self.use_timezone:
# first apply myself
os.environ['TZ'] = self.use_timezone
time.tzset()
tab = [self.schedulers, self.pollers, self.brokers, self.receivers, self.reactionners]
for sat_list in tab:
for sat in sat_list:
if sat.use_timezone == 'NOTSET':
setattr(sat, 'use_timezone', self.use_timezone)
|
python
|
def propagate_timezone_option(self):
"""Set our timezone value and give it too to unset satellites
:return: None
"""
if self.use_timezone:
# first apply myself
os.environ['TZ'] = self.use_timezone
time.tzset()
tab = [self.schedulers, self.pollers, self.brokers, self.receivers, self.reactionners]
for sat_list in tab:
for sat in sat_list:
if sat.use_timezone == 'NOTSET':
setattr(sat, 'use_timezone', self.use_timezone)
|
[
"def",
"propagate_timezone_option",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_timezone",
":",
"# first apply myself",
"os",
".",
"environ",
"[",
"'TZ'",
"]",
"=",
"self",
".",
"use_timezone",
"time",
".",
"tzset",
"(",
")",
"tab",
"=",
"[",
"self",
".",
"schedulers",
",",
"self",
".",
"pollers",
",",
"self",
".",
"brokers",
",",
"self",
".",
"receivers",
",",
"self",
".",
"reactionners",
"]",
"for",
"sat_list",
"in",
"tab",
":",
"for",
"sat",
"in",
"sat_list",
":",
"if",
"sat",
".",
"use_timezone",
"==",
"'NOTSET'",
":",
"setattr",
"(",
"sat",
",",
"'use_timezone'",
",",
"self",
".",
"use_timezone",
")"
] |
Set our timezone value and give it too to unset satellites
:return: None
|
[
"Set",
"our",
"timezone",
"value",
"and",
"give",
"it",
"too",
"to",
"unset",
"satellites"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2291-L2305
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.linkify_templates
|
def linkify_templates(self):
""" Like for normal object, we link templates with each others
:return: None
"""
self.hosts.linkify_templates()
self.contacts.linkify_templates()
self.services.linkify_templates()
self.servicedependencies.linkify_templates()
self.hostdependencies.linkify_templates()
self.timeperiods.linkify_templates()
self.hostsextinfo.linkify_templates()
self.servicesextinfo.linkify_templates()
self.escalations.linkify_templates()
# But also old srv and host escalations
self.serviceescalations.linkify_templates()
self.hostescalations.linkify_templates()
|
python
|
def linkify_templates(self):
""" Like for normal object, we link templates with each others
:return: None
"""
self.hosts.linkify_templates()
self.contacts.linkify_templates()
self.services.linkify_templates()
self.servicedependencies.linkify_templates()
self.hostdependencies.linkify_templates()
self.timeperiods.linkify_templates()
self.hostsextinfo.linkify_templates()
self.servicesextinfo.linkify_templates()
self.escalations.linkify_templates()
# But also old srv and host escalations
self.serviceescalations.linkify_templates()
self.hostescalations.linkify_templates()
|
[
"def",
"linkify_templates",
"(",
"self",
")",
":",
"self",
".",
"hosts",
".",
"linkify_templates",
"(",
")",
"self",
".",
"contacts",
".",
"linkify_templates",
"(",
")",
"self",
".",
"services",
".",
"linkify_templates",
"(",
")",
"self",
".",
"servicedependencies",
".",
"linkify_templates",
"(",
")",
"self",
".",
"hostdependencies",
".",
"linkify_templates",
"(",
")",
"self",
".",
"timeperiods",
".",
"linkify_templates",
"(",
")",
"self",
".",
"hostsextinfo",
".",
"linkify_templates",
"(",
")",
"self",
".",
"servicesextinfo",
".",
"linkify_templates",
"(",
")",
"self",
".",
"escalations",
".",
"linkify_templates",
"(",
")",
"# But also old srv and host escalations",
"self",
".",
"serviceescalations",
".",
"linkify_templates",
"(",
")",
"self",
".",
"hostescalations",
".",
"linkify_templates",
"(",
")"
] |
Like for normal object, we link templates with each others
:return: None
|
[
"Like",
"for",
"normal",
"object",
"we",
"link",
"templates",
"with",
"each",
"others"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2307-L2323
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.remove_templates
|
def remove_templates(self):
"""Clean useless elements like templates because they are not needed anymore
:return: None
"""
self.hosts.remove_templates()
self.contacts.remove_templates()
self.services.remove_templates()
self.servicedependencies.remove_templates()
self.hostdependencies.remove_templates()
self.timeperiods.remove_templates()
|
python
|
def remove_templates(self):
"""Clean useless elements like templates because they are not needed anymore
:return: None
"""
self.hosts.remove_templates()
self.contacts.remove_templates()
self.services.remove_templates()
self.servicedependencies.remove_templates()
self.hostdependencies.remove_templates()
self.timeperiods.remove_templates()
|
[
"def",
"remove_templates",
"(",
"self",
")",
":",
"self",
".",
"hosts",
".",
"remove_templates",
"(",
")",
"self",
".",
"contacts",
".",
"remove_templates",
"(",
")",
"self",
".",
"services",
".",
"remove_templates",
"(",
")",
"self",
".",
"servicedependencies",
".",
"remove_templates",
"(",
")",
"self",
".",
"hostdependencies",
".",
"remove_templates",
"(",
")",
"self",
".",
"timeperiods",
".",
"remove_templates",
"(",
")"
] |
Clean useless elements like templates because they are not needed anymore
:return: None
|
[
"Clean",
"useless",
"elements",
"like",
"templates",
"because",
"they",
"are",
"not",
"needed",
"anymore"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2566-L2576
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.show_errors
|
def show_errors(self):
"""
Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to log as WARNING and ERROR in this function which is used as a sum-up
on the end of configuration parsing when an error has been detected.
:return: None
"""
if self.configuration_warnings:
logger.warning("Configuration warnings:")
for msg in self.configuration_warnings:
logger.warning(msg)
if self.configuration_errors:
logger.warning("Configuration errors:")
for msg in self.configuration_errors:
logger.warning(msg)
|
python
|
def show_errors(self):
"""
Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to log as WARNING and ERROR in this function which is used as a sum-up
on the end of configuration parsing when an error has been detected.
:return: None
"""
if self.configuration_warnings:
logger.warning("Configuration warnings:")
for msg in self.configuration_warnings:
logger.warning(msg)
if self.configuration_errors:
logger.warning("Configuration errors:")
for msg in self.configuration_errors:
logger.warning(msg)
|
[
"def",
"show_errors",
"(",
"self",
")",
":",
"if",
"self",
".",
"configuration_warnings",
":",
"logger",
".",
"warning",
"(",
"\"Configuration warnings:\"",
")",
"for",
"msg",
"in",
"self",
".",
"configuration_warnings",
":",
"logger",
".",
"warning",
"(",
"msg",
")",
"if",
"self",
".",
"configuration_errors",
":",
"logger",
".",
"warning",
"(",
"\"Configuration errors:\"",
")",
"for",
"msg",
"in",
"self",
".",
"configuration_errors",
":",
"logger",
".",
"warning",
"(",
"msg",
")"
] |
Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing.
It is not necessary to log as WARNING and ERROR in this function which is used as a sum-up
on the end of configuration parsing when an error has been detected.
:return: None
|
[
"Loop",
"over",
"configuration",
"warnings",
"and",
"log",
"them",
"as",
"INFO",
"log",
"Loop",
"over",
"configuration",
"errors",
"and",
"log",
"them",
"as",
"INFO",
"log"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L2578-L2596
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.prepare_for_sending
|
def prepare_for_sending(self):
"""The configuration needs to be serialized before being sent to a spare arbiter
:return: None
"""
if [arbiter_link for arbiter_link in self.arbiters if arbiter_link.spare]:
logger.info('Serializing the configuration for my spare arbiter...')
# Now serialize the whole configuration, for sending to spare arbiters
self.spare_arbiter_conf = serialize(self)
|
python
|
def prepare_for_sending(self):
"""The configuration needs to be serialized before being sent to a spare arbiter
:return: None
"""
if [arbiter_link for arbiter_link in self.arbiters if arbiter_link.spare]:
logger.info('Serializing the configuration for my spare arbiter...')
# Now serialize the whole configuration, for sending to spare arbiters
self.spare_arbiter_conf = serialize(self)
|
[
"def",
"prepare_for_sending",
"(",
"self",
")",
":",
"if",
"[",
"arbiter_link",
"for",
"arbiter_link",
"in",
"self",
".",
"arbiters",
"if",
"arbiter_link",
".",
"spare",
"]",
":",
"logger",
".",
"info",
"(",
"'Serializing the configuration for my spare arbiter...'",
")",
"# Now serialize the whole configuration, for sending to spare arbiters",
"self",
".",
"spare_arbiter_conf",
"=",
"serialize",
"(",
"self",
")"
] |
The configuration needs to be serialized before being sent to a spare arbiter
:return: None
|
[
"The",
"configuration",
"needs",
"to",
"be",
"serialized",
"before",
"being",
"sent",
"to",
"a",
"spare",
"arbiter"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L3042-L3051
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/config.py
|
Config.dump
|
def dump(self, dump_file_name=None):
"""Dump configuration to a file in a JSON format
:param dump_file_name: the file to dump configuration to
:type dump_file_name: str
:return: None
"""
config_dump = {}
for _, _, category, _, _ in list(self.types_creations.values()):
try:
objs = [jsonify_r(i) for i in getattr(self, category)]
except (TypeError, AttributeError): # pragma: no cover, simple protection
logger.warning("Dumping configuration, '%s' not present in the configuration",
category)
continue
container = getattr(self, category)
if category == "services":
objs = sorted(objs,
key=lambda o: "%s/%s" % (o["host_name"], o["service_description"]))
elif hasattr(container, "name_property"):
name_prop = container.name_property
objs = sorted(objs, key=lambda o, prop=name_prop: getattr(o, prop, ''))
config_dump[category] = objs
if not dump_file_name:
dump_file_name = os.path.join(tempfile.gettempdir(),
'alignak-%s-cfg-dump-%d.json'
% (self.name, int(time.time())))
try:
logger.info('Dumping configuration to: %s', dump_file_name)
fd = open(dump_file_name, "w")
fd.write(json.dumps(config_dump, indent=4, separators=(',', ': '), sort_keys=True))
fd.close()
logger.info('Dumped')
except (OSError, IndexError) as exp: # pragma: no cover, should never happen...
logger.critical("Error when dumping configuration to %s: %s", dump_file_name, str(exp))
|
python
|
def dump(self, dump_file_name=None):
"""Dump configuration to a file in a JSON format
:param dump_file_name: the file to dump configuration to
:type dump_file_name: str
:return: None
"""
config_dump = {}
for _, _, category, _, _ in list(self.types_creations.values()):
try:
objs = [jsonify_r(i) for i in getattr(self, category)]
except (TypeError, AttributeError): # pragma: no cover, simple protection
logger.warning("Dumping configuration, '%s' not present in the configuration",
category)
continue
container = getattr(self, category)
if category == "services":
objs = sorted(objs,
key=lambda o: "%s/%s" % (o["host_name"], o["service_description"]))
elif hasattr(container, "name_property"):
name_prop = container.name_property
objs = sorted(objs, key=lambda o, prop=name_prop: getattr(o, prop, ''))
config_dump[category] = objs
if not dump_file_name:
dump_file_name = os.path.join(tempfile.gettempdir(),
'alignak-%s-cfg-dump-%d.json'
% (self.name, int(time.time())))
try:
logger.info('Dumping configuration to: %s', dump_file_name)
fd = open(dump_file_name, "w")
fd.write(json.dumps(config_dump, indent=4, separators=(',', ': '), sort_keys=True))
fd.close()
logger.info('Dumped')
except (OSError, IndexError) as exp: # pragma: no cover, should never happen...
logger.critical("Error when dumping configuration to %s: %s", dump_file_name, str(exp))
|
[
"def",
"dump",
"(",
"self",
",",
"dump_file_name",
"=",
"None",
")",
":",
"config_dump",
"=",
"{",
"}",
"for",
"_",
",",
"_",
",",
"category",
",",
"_",
",",
"_",
"in",
"list",
"(",
"self",
".",
"types_creations",
".",
"values",
"(",
")",
")",
":",
"try",
":",
"objs",
"=",
"[",
"jsonify_r",
"(",
"i",
")",
"for",
"i",
"in",
"getattr",
"(",
"self",
",",
"category",
")",
"]",
"except",
"(",
"TypeError",
",",
"AttributeError",
")",
":",
"# pragma: no cover, simple protection",
"logger",
".",
"warning",
"(",
"\"Dumping configuration, '%s' not present in the configuration\"",
",",
"category",
")",
"continue",
"container",
"=",
"getattr",
"(",
"self",
",",
"category",
")",
"if",
"category",
"==",
"\"services\"",
":",
"objs",
"=",
"sorted",
"(",
"objs",
",",
"key",
"=",
"lambda",
"o",
":",
"\"%s/%s\"",
"%",
"(",
"o",
"[",
"\"host_name\"",
"]",
",",
"o",
"[",
"\"service_description\"",
"]",
")",
")",
"elif",
"hasattr",
"(",
"container",
",",
"\"name_property\"",
")",
":",
"name_prop",
"=",
"container",
".",
"name_property",
"objs",
"=",
"sorted",
"(",
"objs",
",",
"key",
"=",
"lambda",
"o",
",",
"prop",
"=",
"name_prop",
":",
"getattr",
"(",
"o",
",",
"prop",
",",
"''",
")",
")",
"config_dump",
"[",
"category",
"]",
"=",
"objs",
"if",
"not",
"dump_file_name",
":",
"dump_file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'alignak-%s-cfg-dump-%d.json'",
"%",
"(",
"self",
".",
"name",
",",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
")",
"try",
":",
"logger",
".",
"info",
"(",
"'Dumping configuration to: %s'",
",",
"dump_file_name",
")",
"fd",
"=",
"open",
"(",
"dump_file_name",
",",
"\"w\"",
")",
"fd",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"config_dump",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
",",
"sort_keys",
"=",
"True",
")",
")",
"fd",
".",
"close",
"(",
")",
"logger",
".",
"info",
"(",
"'Dumped'",
")",
"except",
"(",
"OSError",
",",
"IndexError",
")",
"as",
"exp",
":",
"# pragma: no cover, should never happen...",
"logger",
".",
"critical",
"(",
"\"Error when dumping configuration to %s: %s\"",
",",
"dump_file_name",
",",
"str",
"(",
"exp",
")",
")"
] |
Dump configuration to a file in a JSON format
:param dump_file_name: the file to dump configuration to
:type dump_file_name: str
:return: None
|
[
"Dump",
"configuration",
"to",
"a",
"file",
"in",
"a",
"JSON",
"format"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/config.py#L3053-L3090
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.push_broks_to_broker
|
def push_broks_to_broker(self): # pragma: no cover - not used!
"""Send all broks from arbiter internal list to broker
The arbiter get some broks and then pushes them to all the brokers.
:return: None
"""
someone_is_concerned = False
sent = False
for broker_link in self.conf.brokers:
# Send only if the broker is concerned...
if not broker_link.manage_arbiters:
continue
someone_is_concerned = True
if broker_link.reachable:
logger.debug("Sending %d broks to the broker %s", len(self.broks), broker_link.name)
if broker_link.push_broks(self.broks):
statsmgr.counter('broks.pushed.count', len(self.broks))
sent = True
if not someone_is_concerned or sent:
# No one is anymore interested with...
del self.broks[:]
|
python
|
def push_broks_to_broker(self): # pragma: no cover - not used!
"""Send all broks from arbiter internal list to broker
The arbiter get some broks and then pushes them to all the brokers.
:return: None
"""
someone_is_concerned = False
sent = False
for broker_link in self.conf.brokers:
# Send only if the broker is concerned...
if not broker_link.manage_arbiters:
continue
someone_is_concerned = True
if broker_link.reachable:
logger.debug("Sending %d broks to the broker %s", len(self.broks), broker_link.name)
if broker_link.push_broks(self.broks):
statsmgr.counter('broks.pushed.count', len(self.broks))
sent = True
if not someone_is_concerned or sent:
# No one is anymore interested with...
del self.broks[:]
|
[
"def",
"push_broks_to_broker",
"(",
"self",
")",
":",
"# pragma: no cover - not used!",
"someone_is_concerned",
"=",
"False",
"sent",
"=",
"False",
"for",
"broker_link",
"in",
"self",
".",
"conf",
".",
"brokers",
":",
"# Send only if the broker is concerned...",
"if",
"not",
"broker_link",
".",
"manage_arbiters",
":",
"continue",
"someone_is_concerned",
"=",
"True",
"if",
"broker_link",
".",
"reachable",
":",
"logger",
".",
"debug",
"(",
"\"Sending %d broks to the broker %s\"",
",",
"len",
"(",
"self",
".",
"broks",
")",
",",
"broker_link",
".",
"name",
")",
"if",
"broker_link",
".",
"push_broks",
"(",
"self",
".",
"broks",
")",
":",
"statsmgr",
".",
"counter",
"(",
"'broks.pushed.count'",
",",
"len",
"(",
"self",
".",
"broks",
")",
")",
"sent",
"=",
"True",
"if",
"not",
"someone_is_concerned",
"or",
"sent",
":",
"# No one is anymore interested with...",
"del",
"self",
".",
"broks",
"[",
":",
"]"
] |
Send all broks from arbiter internal list to broker
The arbiter get some broks and then pushes them to all the brokers.
:return: None
|
[
"Send",
"all",
"broks",
"from",
"arbiter",
"internal",
"list",
"to",
"broker"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L268-L291
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.push_external_commands_to_schedulers
|
def push_external_commands_to_schedulers(self): # pragma: no cover - not used!
"""Send external commands to schedulers
:return: None
"""
# Now get all external commands and push them to the schedulers
for external_command in self.external_commands:
self.external_commands_manager.resolve_command(external_command)
# Now for all reachable schedulers, send the commands
sent = False
for scheduler_link in self.conf.schedulers:
ext_cmds = scheduler_link.external_commands
if ext_cmds and scheduler_link.reachable:
logger.debug("Sending %d commands to the scheduler %s",
len(ext_cmds), scheduler_link.name)
if scheduler_link.push_external_commands(ext_cmds):
statsmgr.counter('external-commands.pushed.count', len(ext_cmds))
sent = True
if sent:
# Clean the pushed commands
scheduler_link.external_commands.clear()
|
python
|
def push_external_commands_to_schedulers(self): # pragma: no cover - not used!
"""Send external commands to schedulers
:return: None
"""
# Now get all external commands and push them to the schedulers
for external_command in self.external_commands:
self.external_commands_manager.resolve_command(external_command)
# Now for all reachable schedulers, send the commands
sent = False
for scheduler_link in self.conf.schedulers:
ext_cmds = scheduler_link.external_commands
if ext_cmds and scheduler_link.reachable:
logger.debug("Sending %d commands to the scheduler %s",
len(ext_cmds), scheduler_link.name)
if scheduler_link.push_external_commands(ext_cmds):
statsmgr.counter('external-commands.pushed.count', len(ext_cmds))
sent = True
if sent:
# Clean the pushed commands
scheduler_link.external_commands.clear()
|
[
"def",
"push_external_commands_to_schedulers",
"(",
"self",
")",
":",
"# pragma: no cover - not used!",
"# Now get all external commands and push them to the schedulers",
"for",
"external_command",
"in",
"self",
".",
"external_commands",
":",
"self",
".",
"external_commands_manager",
".",
"resolve_command",
"(",
"external_command",
")",
"# Now for all reachable schedulers, send the commands",
"sent",
"=",
"False",
"for",
"scheduler_link",
"in",
"self",
".",
"conf",
".",
"schedulers",
":",
"ext_cmds",
"=",
"scheduler_link",
".",
"external_commands",
"if",
"ext_cmds",
"and",
"scheduler_link",
".",
"reachable",
":",
"logger",
".",
"debug",
"(",
"\"Sending %d commands to the scheduler %s\"",
",",
"len",
"(",
"ext_cmds",
")",
",",
"scheduler_link",
".",
"name",
")",
"if",
"scheduler_link",
".",
"push_external_commands",
"(",
"ext_cmds",
")",
":",
"statsmgr",
".",
"counter",
"(",
"'external-commands.pushed.count'",
",",
"len",
"(",
"ext_cmds",
")",
")",
"sent",
"=",
"True",
"if",
"sent",
":",
"# Clean the pushed commands",
"scheduler_link",
".",
"external_commands",
".",
"clear",
"(",
")"
] |
Send external commands to schedulers
:return: None
|
[
"Send",
"external",
"commands",
"to",
"schedulers"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L293-L314
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.get_broks_from_satellites
|
def get_broks_from_satellites(self): # pragma: no cover - not used!
"""Get broks from my all internal satellite links
The arbiter get the broks from ALL the known satellites
:return: None
"""
for satellites in [self.conf.brokers, self.conf.schedulers,
self.conf.pollers, self.conf.reactionners, self.conf.receivers]:
for satellite in satellites:
# Get only if reachable...
if not satellite.reachable:
continue
logger.debug("Getting broks from: %s", satellite.name)
new_broks = satellite.get_and_clear_broks()
if new_broks:
logger.debug("Got %d broks from: %s", len(new_broks), satellite.name)
for brok in new_broks:
self.add(brok)
|
python
|
def get_broks_from_satellites(self): # pragma: no cover - not used!
"""Get broks from my all internal satellite links
The arbiter get the broks from ALL the known satellites
:return: None
"""
for satellites in [self.conf.brokers, self.conf.schedulers,
self.conf.pollers, self.conf.reactionners, self.conf.receivers]:
for satellite in satellites:
# Get only if reachable...
if not satellite.reachable:
continue
logger.debug("Getting broks from: %s", satellite.name)
new_broks = satellite.get_and_clear_broks()
if new_broks:
logger.debug("Got %d broks from: %s", len(new_broks), satellite.name)
for brok in new_broks:
self.add(brok)
|
[
"def",
"get_broks_from_satellites",
"(",
"self",
")",
":",
"# pragma: no cover - not used!",
"for",
"satellites",
"in",
"[",
"self",
".",
"conf",
".",
"brokers",
",",
"self",
".",
"conf",
".",
"schedulers",
",",
"self",
".",
"conf",
".",
"pollers",
",",
"self",
".",
"conf",
".",
"reactionners",
",",
"self",
".",
"conf",
".",
"receivers",
"]",
":",
"for",
"satellite",
"in",
"satellites",
":",
"# Get only if reachable...",
"if",
"not",
"satellite",
".",
"reachable",
":",
"continue",
"logger",
".",
"debug",
"(",
"\"Getting broks from: %s\"",
",",
"satellite",
".",
"name",
")",
"new_broks",
"=",
"satellite",
".",
"get_and_clear_broks",
"(",
")",
"if",
"new_broks",
":",
"logger",
".",
"debug",
"(",
"\"Got %d broks from: %s\"",
",",
"len",
"(",
"new_broks",
")",
",",
"satellite",
".",
"name",
")",
"for",
"brok",
"in",
"new_broks",
":",
"self",
".",
"add",
"(",
"brok",
")"
] |
Get broks from my all internal satellite links
The arbiter get the broks from ALL the known satellites
:return: None
|
[
"Get",
"broks",
"from",
"my",
"all",
"internal",
"satellite",
"links"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L327-L345
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.get_initial_broks_from_satellites
|
def get_initial_broks_from_satellites(self):
"""Get initial broks from my internal satellite links
:return: None
"""
for satellites in [self.conf.brokers, self.conf.schedulers,
self.conf.pollers, self.conf.reactionners, self.conf.receivers]:
for satellite in satellites:
# Get only if reachable...
if not satellite.reachable:
continue
logger.debug("Getting initial brok from: %s", satellite.name)
brok = satellite.get_initial_status_brok()
logger.debug("Satellite '%s' initial brok: %s", satellite.name, brok)
self.add(brok)
|
python
|
def get_initial_broks_from_satellites(self):
"""Get initial broks from my internal satellite links
:return: None
"""
for satellites in [self.conf.brokers, self.conf.schedulers,
self.conf.pollers, self.conf.reactionners, self.conf.receivers]:
for satellite in satellites:
# Get only if reachable...
if not satellite.reachable:
continue
logger.debug("Getting initial brok from: %s", satellite.name)
brok = satellite.get_initial_status_brok()
logger.debug("Satellite '%s' initial brok: %s", satellite.name, brok)
self.add(brok)
|
[
"def",
"get_initial_broks_from_satellites",
"(",
"self",
")",
":",
"for",
"satellites",
"in",
"[",
"self",
".",
"conf",
".",
"brokers",
",",
"self",
".",
"conf",
".",
"schedulers",
",",
"self",
".",
"conf",
".",
"pollers",
",",
"self",
".",
"conf",
".",
"reactionners",
",",
"self",
".",
"conf",
".",
"receivers",
"]",
":",
"for",
"satellite",
"in",
"satellites",
":",
"# Get only if reachable...",
"if",
"not",
"satellite",
".",
"reachable",
":",
"continue",
"logger",
".",
"debug",
"(",
"\"Getting initial brok from: %s\"",
",",
"satellite",
".",
"name",
")",
"brok",
"=",
"satellite",
".",
"get_initial_status_brok",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Satellite '%s' initial brok: %s\"",
",",
"satellite",
".",
"name",
",",
"brok",
")",
"self",
".",
"add",
"(",
"brok",
")"
] |
Get initial broks from my internal satellite links
:return: None
|
[
"Get",
"initial",
"broks",
"from",
"my",
"internal",
"satellite",
"links"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L347-L361
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.load_modules_configuration_objects
|
def load_modules_configuration_objects(self, raw_objects): # pragma: no cover,
# not yet with unit tests.
"""Load configuration objects from arbiter modules
If module implements get_objects arbiter will call it and add create
objects
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
"""
# Now we ask for configuration modules if they
# got items for us
for instance in self.modules_manager.instances:
logger.debug("Getting objects from the module: %s", instance.name)
if not hasattr(instance, 'get_objects'):
logger.debug("The module '%s' do not provide any objects.", instance.name)
return
try:
logger.info("Getting Alignak monitored configuration objects from module '%s'",
instance.name)
got_objects = instance.get_objects()
except Exception as exp: # pylint: disable=broad-except
logger.exception("Module %s get_objects raised an exception %s. "
"Log and continue to run.", instance.name, exp)
continue
if not got_objects:
logger.warning("The module '%s' did not provided any objects.", instance.name)
return
types_creations = self.conf.types_creations
for o_type in types_creations:
(_, _, prop, _, _) = types_creations[o_type]
if prop in ['arbiters', 'brokers', 'schedulers',
'pollers', 'reactionners', 'receivers', 'modules']:
continue
if prop not in got_objects:
logger.warning("Did not get any '%s' objects from %s", prop, instance.name)
continue
for obj in got_objects[prop]:
# test if raw_objects[k] are already set - if not, add empty array
if o_type not in raw_objects:
raw_objects[o_type] = []
# Update the imported_from property if the module did not set
if 'imported_from' not in obj:
obj['imported_from'] = 'module:%s' % instance.name
# Append to the raw objects
raw_objects[o_type].append(obj)
logger.debug("Added %i %s objects from %s",
len(got_objects[prop]), o_type, instance.name)
|
python
|
def load_modules_configuration_objects(self, raw_objects): # pragma: no cover,
# not yet with unit tests.
"""Load configuration objects from arbiter modules
If module implements get_objects arbiter will call it and add create
objects
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
"""
# Now we ask for configuration modules if they
# got items for us
for instance in self.modules_manager.instances:
logger.debug("Getting objects from the module: %s", instance.name)
if not hasattr(instance, 'get_objects'):
logger.debug("The module '%s' do not provide any objects.", instance.name)
return
try:
logger.info("Getting Alignak monitored configuration objects from module '%s'",
instance.name)
got_objects = instance.get_objects()
except Exception as exp: # pylint: disable=broad-except
logger.exception("Module %s get_objects raised an exception %s. "
"Log and continue to run.", instance.name, exp)
continue
if not got_objects:
logger.warning("The module '%s' did not provided any objects.", instance.name)
return
types_creations = self.conf.types_creations
for o_type in types_creations:
(_, _, prop, _, _) = types_creations[o_type]
if prop in ['arbiters', 'brokers', 'schedulers',
'pollers', 'reactionners', 'receivers', 'modules']:
continue
if prop not in got_objects:
logger.warning("Did not get any '%s' objects from %s", prop, instance.name)
continue
for obj in got_objects[prop]:
# test if raw_objects[k] are already set - if not, add empty array
if o_type not in raw_objects:
raw_objects[o_type] = []
# Update the imported_from property if the module did not set
if 'imported_from' not in obj:
obj['imported_from'] = 'module:%s' % instance.name
# Append to the raw objects
raw_objects[o_type].append(obj)
logger.debug("Added %i %s objects from %s",
len(got_objects[prop]), o_type, instance.name)
|
[
"def",
"load_modules_configuration_objects",
"(",
"self",
",",
"raw_objects",
")",
":",
"# pragma: no cover,",
"# not yet with unit tests.",
"# Now we ask for configuration modules if they",
"# got items for us",
"for",
"instance",
"in",
"self",
".",
"modules_manager",
".",
"instances",
":",
"logger",
".",
"debug",
"(",
"\"Getting objects from the module: %s\"",
",",
"instance",
".",
"name",
")",
"if",
"not",
"hasattr",
"(",
"instance",
",",
"'get_objects'",
")",
":",
"logger",
".",
"debug",
"(",
"\"The module '%s' do not provide any objects.\"",
",",
"instance",
".",
"name",
")",
"return",
"try",
":",
"logger",
".",
"info",
"(",
"\"Getting Alignak monitored configuration objects from module '%s'\"",
",",
"instance",
".",
"name",
")",
"got_objects",
"=",
"instance",
".",
"get_objects",
"(",
")",
"except",
"Exception",
"as",
"exp",
":",
"# pylint: disable=broad-except",
"logger",
".",
"exception",
"(",
"\"Module %s get_objects raised an exception %s. \"",
"\"Log and continue to run.\"",
",",
"instance",
".",
"name",
",",
"exp",
")",
"continue",
"if",
"not",
"got_objects",
":",
"logger",
".",
"warning",
"(",
"\"The module '%s' did not provided any objects.\"",
",",
"instance",
".",
"name",
")",
"return",
"types_creations",
"=",
"self",
".",
"conf",
".",
"types_creations",
"for",
"o_type",
"in",
"types_creations",
":",
"(",
"_",
",",
"_",
",",
"prop",
",",
"_",
",",
"_",
")",
"=",
"types_creations",
"[",
"o_type",
"]",
"if",
"prop",
"in",
"[",
"'arbiters'",
",",
"'brokers'",
",",
"'schedulers'",
",",
"'pollers'",
",",
"'reactionners'",
",",
"'receivers'",
",",
"'modules'",
"]",
":",
"continue",
"if",
"prop",
"not",
"in",
"got_objects",
":",
"logger",
".",
"warning",
"(",
"\"Did not get any '%s' objects from %s\"",
",",
"prop",
",",
"instance",
".",
"name",
")",
"continue",
"for",
"obj",
"in",
"got_objects",
"[",
"prop",
"]",
":",
"# test if raw_objects[k] are already set - if not, add empty array",
"if",
"o_type",
"not",
"in",
"raw_objects",
":",
"raw_objects",
"[",
"o_type",
"]",
"=",
"[",
"]",
"# Update the imported_from property if the module did not set",
"if",
"'imported_from'",
"not",
"in",
"obj",
":",
"obj",
"[",
"'imported_from'",
"]",
"=",
"'module:%s'",
"%",
"instance",
".",
"name",
"# Append to the raw objects",
"raw_objects",
"[",
"o_type",
"]",
".",
"append",
"(",
"obj",
")",
"logger",
".",
"debug",
"(",
"\"Added %i %s objects from %s\"",
",",
"len",
"(",
"got_objects",
"[",
"prop",
"]",
")",
",",
"o_type",
",",
"instance",
".",
"name",
")"
] |
Load configuration objects from arbiter modules
If module implements get_objects arbiter will call it and add create
objects
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
|
[
"Load",
"configuration",
"objects",
"from",
"arbiter",
"modules",
"If",
"module",
"implements",
"get_objects",
"arbiter",
"will",
"call",
"it",
"and",
"add",
"create",
"objects"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L821-L871
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.load_modules_alignak_configuration
|
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests.
"""Load Alignak configuration from the arbiter modules
If module implements get_alignak_configuration, call this function
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
"""
alignak_cfg = {}
# Ask configured modules if they got configuration for us
for instance in self.modules_manager.instances:
if not hasattr(instance, 'get_alignak_configuration'):
return
try:
logger.info("Getting Alignak global configuration from module '%s'", instance.name)
cfg = instance.get_alignak_configuration()
alignak_cfg.update(cfg)
except Exception as exp: # pylint: disable=broad-except
logger.error("Module %s get_alignak_configuration raised an exception %s. "
"Log and continue to run", instance.name, str(exp))
output = io.StringIO()
traceback.print_exc(file=output)
logger.error("Back trace of this remove: %s", output.getvalue())
output.close()
continue
params = []
if alignak_cfg:
logger.info("Got Alignak global configuration:")
for key, value in sorted(alignak_cfg.items()):
logger.info("- %s = %s", key, value)
# properties starting with an _ character are "transformed" to macro variables
if key.startswith('_'):
key = '$' + key[1:].upper() + '$'
# properties valued as None are filtered
if value is None:
continue
# properties valued as None string are filtered
if value == 'None':
continue
# properties valued as empty strings are filtered
if value == '':
continue
# set properties as legacy Shinken configuration files
params.append("%s=%s" % (key, value))
self.conf.load_params(params)
|
python
|
def load_modules_alignak_configuration(self): # pragma: no cover, not yet with unit tests.
"""Load Alignak configuration from the arbiter modules
If module implements get_alignak_configuration, call this function
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
"""
alignak_cfg = {}
# Ask configured modules if they got configuration for us
for instance in self.modules_manager.instances:
if not hasattr(instance, 'get_alignak_configuration'):
return
try:
logger.info("Getting Alignak global configuration from module '%s'", instance.name)
cfg = instance.get_alignak_configuration()
alignak_cfg.update(cfg)
except Exception as exp: # pylint: disable=broad-except
logger.error("Module %s get_alignak_configuration raised an exception %s. "
"Log and continue to run", instance.name, str(exp))
output = io.StringIO()
traceback.print_exc(file=output)
logger.error("Back trace of this remove: %s", output.getvalue())
output.close()
continue
params = []
if alignak_cfg:
logger.info("Got Alignak global configuration:")
for key, value in sorted(alignak_cfg.items()):
logger.info("- %s = %s", key, value)
# properties starting with an _ character are "transformed" to macro variables
if key.startswith('_'):
key = '$' + key[1:].upper() + '$'
# properties valued as None are filtered
if value is None:
continue
# properties valued as None string are filtered
if value == 'None':
continue
# properties valued as empty strings are filtered
if value == '':
continue
# set properties as legacy Shinken configuration files
params.append("%s=%s" % (key, value))
self.conf.load_params(params)
|
[
"def",
"load_modules_alignak_configuration",
"(",
"self",
")",
":",
"# pragma: no cover, not yet with unit tests.",
"alignak_cfg",
"=",
"{",
"}",
"# Ask configured modules if they got configuration for us",
"for",
"instance",
"in",
"self",
".",
"modules_manager",
".",
"instances",
":",
"if",
"not",
"hasattr",
"(",
"instance",
",",
"'get_alignak_configuration'",
")",
":",
"return",
"try",
":",
"logger",
".",
"info",
"(",
"\"Getting Alignak global configuration from module '%s'\"",
",",
"instance",
".",
"name",
")",
"cfg",
"=",
"instance",
".",
"get_alignak_configuration",
"(",
")",
"alignak_cfg",
".",
"update",
"(",
"cfg",
")",
"except",
"Exception",
"as",
"exp",
":",
"# pylint: disable=broad-except",
"logger",
".",
"error",
"(",
"\"Module %s get_alignak_configuration raised an exception %s. \"",
"\"Log and continue to run\"",
",",
"instance",
".",
"name",
",",
"str",
"(",
"exp",
")",
")",
"output",
"=",
"io",
".",
"StringIO",
"(",
")",
"traceback",
".",
"print_exc",
"(",
"file",
"=",
"output",
")",
"logger",
".",
"error",
"(",
"\"Back trace of this remove: %s\"",
",",
"output",
".",
"getvalue",
"(",
")",
")",
"output",
".",
"close",
"(",
")",
"continue",
"params",
"=",
"[",
"]",
"if",
"alignak_cfg",
":",
"logger",
".",
"info",
"(",
"\"Got Alignak global configuration:\"",
")",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"alignak_cfg",
".",
"items",
"(",
")",
")",
":",
"logger",
".",
"info",
"(",
"\"- %s = %s\"",
",",
"key",
",",
"value",
")",
"# properties starting with an _ character are \"transformed\" to macro variables",
"if",
"key",
".",
"startswith",
"(",
"'_'",
")",
":",
"key",
"=",
"'$'",
"+",
"key",
"[",
"1",
":",
"]",
".",
"upper",
"(",
")",
"+",
"'$'",
"# properties valued as None are filtered",
"if",
"value",
"is",
"None",
":",
"continue",
"# properties valued as None string are filtered",
"if",
"value",
"==",
"'None'",
":",
"continue",
"# properties valued as empty strings are filtered",
"if",
"value",
"==",
"''",
":",
"continue",
"# set properties as legacy Shinken configuration files",
"params",
".",
"append",
"(",
"\"%s=%s\"",
"%",
"(",
"key",
",",
"value",
")",
")",
"self",
".",
"conf",
".",
"load_params",
"(",
"params",
")"
] |
Load Alignak configuration from the arbiter modules
If module implements get_alignak_configuration, call this function
:param raw_objects: raw objects we got from reading config files
:type raw_objects: dict
:return: None
|
[
"Load",
"Alignak",
"configuration",
"from",
"the",
"arbiter",
"modules",
"If",
"module",
"implements",
"get_alignak_configuration",
"call",
"this",
"function"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L873-L919
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.request_stop
|
def request_stop(self, message='', exit_code=0):
"""Stop the Arbiter daemon
:return: None
"""
# Only a master arbiter can stop the daemons
if self.is_master:
# Stop the daemons
self.daemons_stop(timeout=self.conf.daemons_stop_timeout)
# Request the daemon stop
super(Arbiter, self).request_stop(message, exit_code)
|
python
|
def request_stop(self, message='', exit_code=0):
"""Stop the Arbiter daemon
:return: None
"""
# Only a master arbiter can stop the daemons
if self.is_master:
# Stop the daemons
self.daemons_stop(timeout=self.conf.daemons_stop_timeout)
# Request the daemon stop
super(Arbiter, self).request_stop(message, exit_code)
|
[
"def",
"request_stop",
"(",
"self",
",",
"message",
"=",
"''",
",",
"exit_code",
"=",
"0",
")",
":",
"# Only a master arbiter can stop the daemons",
"if",
"self",
".",
"is_master",
":",
"# Stop the daemons",
"self",
".",
"daemons_stop",
"(",
"timeout",
"=",
"self",
".",
"conf",
".",
"daemons_stop_timeout",
")",
"# Request the daemon stop",
"super",
"(",
"Arbiter",
",",
"self",
")",
".",
"request_stop",
"(",
"message",
",",
"exit_code",
")"
] |
Stop the Arbiter daemon
:return: None
|
[
"Stop",
"the",
"Arbiter",
"daemon"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L921-L932
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.start_daemon
|
def start_daemon(self, satellite):
"""Manage the list of detected missing daemons
If the daemon does not in exist `my_daemons`, then:
- prepare daemon start arguments (port, name and log file)
- start the daemon
- make sure it started correctly
:param satellite: the satellite for which a daemon is to be started
:type satellite: SatelliteLink
:return: True if the daemon started correctly
"""
logger.info(" launching a daemon for: %s/%s...", satellite.type, satellite.name)
# The daemon startup script location may be defined in the configuration
daemon_script_location = getattr(self.conf, 'daemons_script_location', self.bindir)
if not daemon_script_location:
daemon_script_location = "alignak-%s" % satellite.type
else:
daemon_script_location = "%s/alignak-%s" % (daemon_script_location, satellite.type)
# Some extra arguments may be defined in the Alignak configuration
daemon_arguments = getattr(self.conf, 'daemons_arguments', '')
args = [daemon_script_location,
"--name", satellite.name,
"--environment", self.env_filename,
"--host", str(satellite.host),
"--port", str(satellite.port)]
if daemon_arguments:
args.append(daemon_arguments)
logger.info(" ... with some arguments: %s", args)
try:
process = psutil.Popen(args, stdin=None, stdout=None, stderr=None)
# A brief pause...
time.sleep(0.1)
except Exception as exp: # pylint: disable=broad-except
logger.error("Error when launching %s: %s", satellite.name, exp)
logger.error("Command: %s", args)
return False
logger.info(" %s launched (pid=%d, gids=%s)",
satellite.name, process.pid, process.gids())
# My satellites/daemons map
self.my_daemons[satellite.name] = {
'satellite': satellite,
'process': process
}
return True
|
python
|
def start_daemon(self, satellite):
"""Manage the list of detected missing daemons
If the daemon does not in exist `my_daemons`, then:
- prepare daemon start arguments (port, name and log file)
- start the daemon
- make sure it started correctly
:param satellite: the satellite for which a daemon is to be started
:type satellite: SatelliteLink
:return: True if the daemon started correctly
"""
logger.info(" launching a daemon for: %s/%s...", satellite.type, satellite.name)
# The daemon startup script location may be defined in the configuration
daemon_script_location = getattr(self.conf, 'daemons_script_location', self.bindir)
if not daemon_script_location:
daemon_script_location = "alignak-%s" % satellite.type
else:
daemon_script_location = "%s/alignak-%s" % (daemon_script_location, satellite.type)
# Some extra arguments may be defined in the Alignak configuration
daemon_arguments = getattr(self.conf, 'daemons_arguments', '')
args = [daemon_script_location,
"--name", satellite.name,
"--environment", self.env_filename,
"--host", str(satellite.host),
"--port", str(satellite.port)]
if daemon_arguments:
args.append(daemon_arguments)
logger.info(" ... with some arguments: %s", args)
try:
process = psutil.Popen(args, stdin=None, stdout=None, stderr=None)
# A brief pause...
time.sleep(0.1)
except Exception as exp: # pylint: disable=broad-except
logger.error("Error when launching %s: %s", satellite.name, exp)
logger.error("Command: %s", args)
return False
logger.info(" %s launched (pid=%d, gids=%s)",
satellite.name, process.pid, process.gids())
# My satellites/daemons map
self.my_daemons[satellite.name] = {
'satellite': satellite,
'process': process
}
return True
|
[
"def",
"start_daemon",
"(",
"self",
",",
"satellite",
")",
":",
"logger",
".",
"info",
"(",
"\" launching a daemon for: %s/%s...\"",
",",
"satellite",
".",
"type",
",",
"satellite",
".",
"name",
")",
"# The daemon startup script location may be defined in the configuration",
"daemon_script_location",
"=",
"getattr",
"(",
"self",
".",
"conf",
",",
"'daemons_script_location'",
",",
"self",
".",
"bindir",
")",
"if",
"not",
"daemon_script_location",
":",
"daemon_script_location",
"=",
"\"alignak-%s\"",
"%",
"satellite",
".",
"type",
"else",
":",
"daemon_script_location",
"=",
"\"%s/alignak-%s\"",
"%",
"(",
"daemon_script_location",
",",
"satellite",
".",
"type",
")",
"# Some extra arguments may be defined in the Alignak configuration",
"daemon_arguments",
"=",
"getattr",
"(",
"self",
".",
"conf",
",",
"'daemons_arguments'",
",",
"''",
")",
"args",
"=",
"[",
"daemon_script_location",
",",
"\"--name\"",
",",
"satellite",
".",
"name",
",",
"\"--environment\"",
",",
"self",
".",
"env_filename",
",",
"\"--host\"",
",",
"str",
"(",
"satellite",
".",
"host",
")",
",",
"\"--port\"",
",",
"str",
"(",
"satellite",
".",
"port",
")",
"]",
"if",
"daemon_arguments",
":",
"args",
".",
"append",
"(",
"daemon_arguments",
")",
"logger",
".",
"info",
"(",
"\" ... with some arguments: %s\"",
",",
"args",
")",
"try",
":",
"process",
"=",
"psutil",
".",
"Popen",
"(",
"args",
",",
"stdin",
"=",
"None",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
"# A brief pause...",
"time",
".",
"sleep",
"(",
"0.1",
")",
"except",
"Exception",
"as",
"exp",
":",
"# pylint: disable=broad-except",
"logger",
".",
"error",
"(",
"\"Error when launching %s: %s\"",
",",
"satellite",
".",
"name",
",",
"exp",
")",
"logger",
".",
"error",
"(",
"\"Command: %s\"",
",",
"args",
")",
"return",
"False",
"logger",
".",
"info",
"(",
"\" %s launched (pid=%d, gids=%s)\"",
",",
"satellite",
".",
"name",
",",
"process",
".",
"pid",
",",
"process",
".",
"gids",
"(",
")",
")",
"# My satellites/daemons map",
"self",
".",
"my_daemons",
"[",
"satellite",
".",
"name",
"]",
"=",
"{",
"'satellite'",
":",
"satellite",
",",
"'process'",
":",
"process",
"}",
"return",
"True"
] |
Manage the list of detected missing daemons
If the daemon does not in exist `my_daemons`, then:
- prepare daemon start arguments (port, name and log file)
- start the daemon
- make sure it started correctly
:param satellite: the satellite for which a daemon is to be started
:type satellite: SatelliteLink
:return: True if the daemon started correctly
|
[
"Manage",
"the",
"list",
"of",
"detected",
"missing",
"daemons"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L934-L984
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.daemons_start
|
def daemons_start(self, run_daemons=True):
"""Manage the list of the daemons in the configuration
Check if the daemon needs to be started by the Arbiter.
If so, starts the daemon if `run_daemons` is True
:param run_daemons: run the daemons or make a simple check
:type run_daemons: bool
:return: True if all daemons are running, else False. always True for a simple check
"""
result = True
if run_daemons:
logger.info("Alignak configured daemons start:")
else:
logger.info("Alignak configured daemons check:")
# Parse the list of the missing daemons and try to run the corresponding processes
for satellites_list in [self.conf.arbiters, self.conf.receivers, self.conf.reactionners,
self.conf.pollers, self.conf.brokers, self.conf.schedulers]:
for satellite in satellites_list:
logger.info("- found %s, to be launched: %s, address: %s",
satellite.name, satellite.alignak_launched, satellite.uri)
if satellite == self.link_to_myself:
# Ignore myself ;)
continue
if satellite.alignak_launched and \
satellite.address not in ['127.0.0.1', 'localhost']:
logger.error("Alignak is required to launch a daemon for %s %s "
"but the satelitte is defined on an external address: %s",
satellite.type, satellite.name, satellite.address)
result = False
continue
if not run_daemons:
# When checking, ignore the daemon launch part...
continue
if not satellite.alignak_launched:
logger.debug("Alignak will not launch '%s'")
continue
if not satellite.active:
logger.warning("- daemon '%s' is declared but not set as active, "
"do not start...", satellite.name)
continue
if satellite.name in self.my_daemons:
logger.warning("- daemon '%s' is already running", satellite.name)
continue
started = self.start_daemon(satellite)
result = result and started
return result
|
python
|
def daemons_start(self, run_daemons=True):
"""Manage the list of the daemons in the configuration
Check if the daemon needs to be started by the Arbiter.
If so, starts the daemon if `run_daemons` is True
:param run_daemons: run the daemons or make a simple check
:type run_daemons: bool
:return: True if all daemons are running, else False. always True for a simple check
"""
result = True
if run_daemons:
logger.info("Alignak configured daemons start:")
else:
logger.info("Alignak configured daemons check:")
# Parse the list of the missing daemons and try to run the corresponding processes
for satellites_list in [self.conf.arbiters, self.conf.receivers, self.conf.reactionners,
self.conf.pollers, self.conf.brokers, self.conf.schedulers]:
for satellite in satellites_list:
logger.info("- found %s, to be launched: %s, address: %s",
satellite.name, satellite.alignak_launched, satellite.uri)
if satellite == self.link_to_myself:
# Ignore myself ;)
continue
if satellite.alignak_launched and \
satellite.address not in ['127.0.0.1', 'localhost']:
logger.error("Alignak is required to launch a daemon for %s %s "
"but the satelitte is defined on an external address: %s",
satellite.type, satellite.name, satellite.address)
result = False
continue
if not run_daemons:
# When checking, ignore the daemon launch part...
continue
if not satellite.alignak_launched:
logger.debug("Alignak will not launch '%s'")
continue
if not satellite.active:
logger.warning("- daemon '%s' is declared but not set as active, "
"do not start...", satellite.name)
continue
if satellite.name in self.my_daemons:
logger.warning("- daemon '%s' is already running", satellite.name)
continue
started = self.start_daemon(satellite)
result = result and started
return result
|
[
"def",
"daemons_start",
"(",
"self",
",",
"run_daemons",
"=",
"True",
")",
":",
"result",
"=",
"True",
"if",
"run_daemons",
":",
"logger",
".",
"info",
"(",
"\"Alignak configured daemons start:\"",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Alignak configured daemons check:\"",
")",
"# Parse the list of the missing daemons and try to run the corresponding processes",
"for",
"satellites_list",
"in",
"[",
"self",
".",
"conf",
".",
"arbiters",
",",
"self",
".",
"conf",
".",
"receivers",
",",
"self",
".",
"conf",
".",
"reactionners",
",",
"self",
".",
"conf",
".",
"pollers",
",",
"self",
".",
"conf",
".",
"brokers",
",",
"self",
".",
"conf",
".",
"schedulers",
"]",
":",
"for",
"satellite",
"in",
"satellites_list",
":",
"logger",
".",
"info",
"(",
"\"- found %s, to be launched: %s, address: %s\"",
",",
"satellite",
".",
"name",
",",
"satellite",
".",
"alignak_launched",
",",
"satellite",
".",
"uri",
")",
"if",
"satellite",
"==",
"self",
".",
"link_to_myself",
":",
"# Ignore myself ;)",
"continue",
"if",
"satellite",
".",
"alignak_launched",
"and",
"satellite",
".",
"address",
"not",
"in",
"[",
"'127.0.0.1'",
",",
"'localhost'",
"]",
":",
"logger",
".",
"error",
"(",
"\"Alignak is required to launch a daemon for %s %s \"",
"\"but the satelitte is defined on an external address: %s\"",
",",
"satellite",
".",
"type",
",",
"satellite",
".",
"name",
",",
"satellite",
".",
"address",
")",
"result",
"=",
"False",
"continue",
"if",
"not",
"run_daemons",
":",
"# When checking, ignore the daemon launch part...",
"continue",
"if",
"not",
"satellite",
".",
"alignak_launched",
":",
"logger",
".",
"debug",
"(",
"\"Alignak will not launch '%s'\"",
")",
"continue",
"if",
"not",
"satellite",
".",
"active",
":",
"logger",
".",
"warning",
"(",
"\"- daemon '%s' is declared but not set as active, \"",
"\"do not start...\"",
",",
"satellite",
".",
"name",
")",
"continue",
"if",
"satellite",
".",
"name",
"in",
"self",
".",
"my_daemons",
":",
"logger",
".",
"warning",
"(",
"\"- daemon '%s' is already running\"",
",",
"satellite",
".",
"name",
")",
"continue",
"started",
"=",
"self",
".",
"start_daemon",
"(",
"satellite",
")",
"result",
"=",
"result",
"and",
"started",
"return",
"result"
] |
Manage the list of the daemons in the configuration
Check if the daemon needs to be started by the Arbiter.
If so, starts the daemon if `run_daemons` is True
:param run_daemons: run the daemons or make a simple check
:type run_daemons: bool
:return: True if all daemons are running, else False. always True for a simple check
|
[
"Manage",
"the",
"list",
"of",
"the",
"daemons",
"in",
"the",
"configuration"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L986-L1043
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.daemons_stop
|
def daemons_stop(self, timeout=30, kill_children=False):
"""Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default behavior, only the launched daemons are killed, not their children.
Each daemon will manage its children killing
:param timeout: delay to wait before killing a daemon
:type timeout: int
:param kill_children: also kill the children (defaults to False)
:type kill_children: bool
:return: True if all daemons stopped
"""
def on_terminate(proc):
"""Process termination callback function"""
logger.debug("process %s terminated with exit code %s", proc.pid, proc.returncode)
result = True
if self.my_daemons:
logger.info("Alignak self-launched daemons stop:")
start = time.time()
for daemon in list(self.my_daemons.values()):
# Terminate the daemon and its children process
procs = []
if kill_children:
procs = daemon['process'].children()
procs.append(daemon['process'])
for process in procs:
try:
logger.info("- terminating process %s", process.name())
process.terminate()
except psutil.AccessDenied:
logger.warning("Process %s is %s", process.name(), process.status())
procs = []
for daemon in list(self.my_daemons.values()):
# Stop the daemon and its children process
if kill_children:
procs = daemon['process'].children()
procs.append(daemon['process'])
_, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
if alive:
# Kill processes
for process in alive:
logger.warning("Process %s did not stopped, trying to kill", process.name())
process.kill()
_, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
if alive:
# give up
for process in alive:
logger.warning("process %s survived SIGKILL; giving up", process.name())
result = False
logger.debug("Stopping daemons duration: %.2f seconds", time.time() - start)
return result
|
python
|
def daemons_stop(self, timeout=30, kill_children=False):
"""Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default behavior, only the launched daemons are killed, not their children.
Each daemon will manage its children killing
:param timeout: delay to wait before killing a daemon
:type timeout: int
:param kill_children: also kill the children (defaults to False)
:type kill_children: bool
:return: True if all daemons stopped
"""
def on_terminate(proc):
"""Process termination callback function"""
logger.debug("process %s terminated with exit code %s", proc.pid, proc.returncode)
result = True
if self.my_daemons:
logger.info("Alignak self-launched daemons stop:")
start = time.time()
for daemon in list(self.my_daemons.values()):
# Terminate the daemon and its children process
procs = []
if kill_children:
procs = daemon['process'].children()
procs.append(daemon['process'])
for process in procs:
try:
logger.info("- terminating process %s", process.name())
process.terminate()
except psutil.AccessDenied:
logger.warning("Process %s is %s", process.name(), process.status())
procs = []
for daemon in list(self.my_daemons.values()):
# Stop the daemon and its children process
if kill_children:
procs = daemon['process'].children()
procs.append(daemon['process'])
_, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
if alive:
# Kill processes
for process in alive:
logger.warning("Process %s did not stopped, trying to kill", process.name())
process.kill()
_, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
if alive:
# give up
for process in alive:
logger.warning("process %s survived SIGKILL; giving up", process.name())
result = False
logger.debug("Stopping daemons duration: %.2f seconds", time.time() - start)
return result
|
[
"def",
"daemons_stop",
"(",
"self",
",",
"timeout",
"=",
"30",
",",
"kill_children",
"=",
"False",
")",
":",
"def",
"on_terminate",
"(",
"proc",
")",
":",
"\"\"\"Process termination callback function\"\"\"",
"logger",
".",
"debug",
"(",
"\"process %s terminated with exit code %s\"",
",",
"proc",
".",
"pid",
",",
"proc",
".",
"returncode",
")",
"result",
"=",
"True",
"if",
"self",
".",
"my_daemons",
":",
"logger",
".",
"info",
"(",
"\"Alignak self-launched daemons stop:\"",
")",
"start",
"=",
"time",
".",
"time",
"(",
")",
"for",
"daemon",
"in",
"list",
"(",
"self",
".",
"my_daemons",
".",
"values",
"(",
")",
")",
":",
"# Terminate the daemon and its children process",
"procs",
"=",
"[",
"]",
"if",
"kill_children",
":",
"procs",
"=",
"daemon",
"[",
"'process'",
"]",
".",
"children",
"(",
")",
"procs",
".",
"append",
"(",
"daemon",
"[",
"'process'",
"]",
")",
"for",
"process",
"in",
"procs",
":",
"try",
":",
"logger",
".",
"info",
"(",
"\"- terminating process %s\"",
",",
"process",
".",
"name",
"(",
")",
")",
"process",
".",
"terminate",
"(",
")",
"except",
"psutil",
".",
"AccessDenied",
":",
"logger",
".",
"warning",
"(",
"\"Process %s is %s\"",
",",
"process",
".",
"name",
"(",
")",
",",
"process",
".",
"status",
"(",
")",
")",
"procs",
"=",
"[",
"]",
"for",
"daemon",
"in",
"list",
"(",
"self",
".",
"my_daemons",
".",
"values",
"(",
")",
")",
":",
"# Stop the daemon and its children process",
"if",
"kill_children",
":",
"procs",
"=",
"daemon",
"[",
"'process'",
"]",
".",
"children",
"(",
")",
"procs",
".",
"append",
"(",
"daemon",
"[",
"'process'",
"]",
")",
"_",
",",
"alive",
"=",
"psutil",
".",
"wait_procs",
"(",
"procs",
",",
"timeout",
"=",
"timeout",
",",
"callback",
"=",
"on_terminate",
")",
"if",
"alive",
":",
"# Kill processes",
"for",
"process",
"in",
"alive",
":",
"logger",
".",
"warning",
"(",
"\"Process %s did not stopped, trying to kill\"",
",",
"process",
".",
"name",
"(",
")",
")",
"process",
".",
"kill",
"(",
")",
"_",
",",
"alive",
"=",
"psutil",
".",
"wait_procs",
"(",
"alive",
",",
"timeout",
"=",
"timeout",
",",
"callback",
"=",
"on_terminate",
")",
"if",
"alive",
":",
"# give up",
"for",
"process",
"in",
"alive",
":",
"logger",
".",
"warning",
"(",
"\"process %s survived SIGKILL; giving up\"",
",",
"process",
".",
"name",
"(",
")",
")",
"result",
"=",
"False",
"logger",
".",
"debug",
"(",
"\"Stopping daemons duration: %.2f seconds\"",
",",
"time",
".",
"time",
"(",
")",
"-",
"start",
")",
"return",
"result"
] |
Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default behavior, only the launched daemons are killed, not their children.
Each daemon will manage its children killing
:param timeout: delay to wait before killing a daemon
:type timeout: int
:param kill_children: also kill the children (defaults to False)
:type kill_children: bool
:return: True if all daemons stopped
|
[
"Stop",
"the",
"Alignak",
"daemons"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1109-L1170
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.setup_new_conf
|
def setup_new_conf(self):
# pylint: disable=too-many-locals
""" Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
:return: None
"""
# Execute the base class treatment...
super(Arbiter, self).setup_new_conf()
with self.conf_lock:
logger.info("I received a new configuration from my master")
# Get the new configuration
self.cur_conf = self.new_conf
# self_conf is our own configuration from the alignak environment
# Arbiters do not have this property in the received configuration because
# they already loaded a configuration on daemon load
self_conf = self.cur_conf.get('self_conf', None)
if not self_conf:
self_conf = self.conf
# whole_conf contains the full configuration load by my master
whole_conf = self.cur_conf['whole_conf']
logger.debug("Received a new configuration, containing:")
for key in self.cur_conf:
logger.debug("- %s: %s", key, self.cur_conf[key])
logger.debug("satellite self configuration part: %s", self_conf)
# Update Alignak name
self.alignak_name = self.cur_conf['alignak_name']
logger.info("My Alignak instance: %s", self.alignak_name)
# This to indicate that the new configuration got managed...
self.new_conf = {}
# Get the whole monitored objects configuration
t00 = time.time()
try:
received_conf_part = unserialize(whole_conf)
except AlignakClassLookupException as exp: # pragma: no cover, simple protection
# This to indicate that the new configuration is not managed...
self.new_conf = {
"_status": "Cannot un-serialize configuration received from arbiter"
}
logger.error(self.new_conf['_status'])
logger.error("Back trace of the error:\n%s", traceback.format_exc())
return
except Exception as exp: # pylint: disable=broad-except
# This to indicate that the new configuration is not managed...
self.new_conf = {
"_status": "Cannot un-serialize configuration received from arbiter"
}
logger.error(self.new_conf['_status'])
logger.error(self.new_conf)
self.exit_on_exception(exp, self.new_conf)
logger.info("Monitored configuration %s received at %d. Un-serialized in %d secs",
received_conf_part, t00, time.time() - t00)
# Now we create our arbiters and schedulers links
my_satellites = getattr(self, 'arbiters', {})
received_satellites = self.cur_conf['arbiters']
for link_uuid in received_satellites:
rs_conf = received_satellites[link_uuid]
logger.debug("- received %s - %s: %s", rs_conf['instance_id'],
rs_conf['type'], rs_conf['name'])
# Must look if we already had a configuration and save our broks
already_got = rs_conf['instance_id'] in my_satellites
broks = []
actions = {}
wait_homerun = {}
external_commands = {}
running_id = 0
if already_got:
logger.warning("I already got: %s", rs_conf['instance_id'])
# Save some information
running_id = my_satellites[link_uuid].running_id
(broks, actions,
wait_homerun, external_commands) = \
my_satellites[link_uuid].get_and_clear_context()
# Delete the former link
del my_satellites[link_uuid]
# My new satellite link...
new_link = SatelliteLink.get_a_satellite_link('arbiter', rs_conf)
my_satellites[new_link.uuid] = new_link
logger.info("I got a new arbiter satellite: %s", new_link)
new_link.running_id = running_id
new_link.external_commands = external_commands
new_link.broks = broks
new_link.wait_homerun = wait_homerun
new_link.actions = actions
# # replacing satellite address and port by those defined in satellite_map
# if new_link.name in self_conf.satellite_map:
# overriding = self_conf.satellite_map[new_link.name]
# # satellite = dict(satellite) # make a copy
# # new_link.update(self_conf.get('satellite_map', {})[new_link.name])
# logger.warning("Do not override the configuration for: %s, with: %s. "
# "Please check whether this is necessary!",
# new_link.name, overriding)
# for arbiter_link in received_conf_part.arbiters:
# logger.info("I have arbiter links in my configuration: %s", arbiter_link.name)
# if arbiter_link.name != self.name and not arbiter_link.spare:
# # Arbiter is not me!
# logger.info("I found my master arbiter in the configuration: %s",
# arbiter_link.name)
# continue
#
# logger.info("I found myself in the received configuration: %s", arbiter_link.name)
# self.link_to_myself = arbiter_link
# # We received a configuration s we are not a master !
# self.is_master = False
# self.link_to_myself.spare = True
# # Set myself as alive ;)
# self.link_to_myself.set_alive()
# Now I have a configuration!
self.have_conf = True
|
python
|
def setup_new_conf(self):
# pylint: disable=too-many-locals
""" Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
:return: None
"""
# Execute the base class treatment...
super(Arbiter, self).setup_new_conf()
with self.conf_lock:
logger.info("I received a new configuration from my master")
# Get the new configuration
self.cur_conf = self.new_conf
# self_conf is our own configuration from the alignak environment
# Arbiters do not have this property in the received configuration because
# they already loaded a configuration on daemon load
self_conf = self.cur_conf.get('self_conf', None)
if not self_conf:
self_conf = self.conf
# whole_conf contains the full configuration load by my master
whole_conf = self.cur_conf['whole_conf']
logger.debug("Received a new configuration, containing:")
for key in self.cur_conf:
logger.debug("- %s: %s", key, self.cur_conf[key])
logger.debug("satellite self configuration part: %s", self_conf)
# Update Alignak name
self.alignak_name = self.cur_conf['alignak_name']
logger.info("My Alignak instance: %s", self.alignak_name)
# This to indicate that the new configuration got managed...
self.new_conf = {}
# Get the whole monitored objects configuration
t00 = time.time()
try:
received_conf_part = unserialize(whole_conf)
except AlignakClassLookupException as exp: # pragma: no cover, simple protection
# This to indicate that the new configuration is not managed...
self.new_conf = {
"_status": "Cannot un-serialize configuration received from arbiter"
}
logger.error(self.new_conf['_status'])
logger.error("Back trace of the error:\n%s", traceback.format_exc())
return
except Exception as exp: # pylint: disable=broad-except
# This to indicate that the new configuration is not managed...
self.new_conf = {
"_status": "Cannot un-serialize configuration received from arbiter"
}
logger.error(self.new_conf['_status'])
logger.error(self.new_conf)
self.exit_on_exception(exp, self.new_conf)
logger.info("Monitored configuration %s received at %d. Un-serialized in %d secs",
received_conf_part, t00, time.time() - t00)
# Now we create our arbiters and schedulers links
my_satellites = getattr(self, 'arbiters', {})
received_satellites = self.cur_conf['arbiters']
for link_uuid in received_satellites:
rs_conf = received_satellites[link_uuid]
logger.debug("- received %s - %s: %s", rs_conf['instance_id'],
rs_conf['type'], rs_conf['name'])
# Must look if we already had a configuration and save our broks
already_got = rs_conf['instance_id'] in my_satellites
broks = []
actions = {}
wait_homerun = {}
external_commands = {}
running_id = 0
if already_got:
logger.warning("I already got: %s", rs_conf['instance_id'])
# Save some information
running_id = my_satellites[link_uuid].running_id
(broks, actions,
wait_homerun, external_commands) = \
my_satellites[link_uuid].get_and_clear_context()
# Delete the former link
del my_satellites[link_uuid]
# My new satellite link...
new_link = SatelliteLink.get_a_satellite_link('arbiter', rs_conf)
my_satellites[new_link.uuid] = new_link
logger.info("I got a new arbiter satellite: %s", new_link)
new_link.running_id = running_id
new_link.external_commands = external_commands
new_link.broks = broks
new_link.wait_homerun = wait_homerun
new_link.actions = actions
# # replacing satellite address and port by those defined in satellite_map
# if new_link.name in self_conf.satellite_map:
# overriding = self_conf.satellite_map[new_link.name]
# # satellite = dict(satellite) # make a copy
# # new_link.update(self_conf.get('satellite_map', {})[new_link.name])
# logger.warning("Do not override the configuration for: %s, with: %s. "
# "Please check whether this is necessary!",
# new_link.name, overriding)
# for arbiter_link in received_conf_part.arbiters:
# logger.info("I have arbiter links in my configuration: %s", arbiter_link.name)
# if arbiter_link.name != self.name and not arbiter_link.spare:
# # Arbiter is not me!
# logger.info("I found my master arbiter in the configuration: %s",
# arbiter_link.name)
# continue
#
# logger.info("I found myself in the received configuration: %s", arbiter_link.name)
# self.link_to_myself = arbiter_link
# # We received a configuration s we are not a master !
# self.is_master = False
# self.link_to_myself.spare = True
# # Set myself as alive ;)
# self.link_to_myself.set_alive()
# Now I have a configuration!
self.have_conf = True
|
[
"def",
"setup_new_conf",
"(",
"self",
")",
":",
"# pylint: disable=too-many-locals",
"# Execute the base class treatment...",
"super",
"(",
"Arbiter",
",",
"self",
")",
".",
"setup_new_conf",
"(",
")",
"with",
"self",
".",
"conf_lock",
":",
"logger",
".",
"info",
"(",
"\"I received a new configuration from my master\"",
")",
"# Get the new configuration",
"self",
".",
"cur_conf",
"=",
"self",
".",
"new_conf",
"# self_conf is our own configuration from the alignak environment",
"# Arbiters do not have this property in the received configuration because",
"# they already loaded a configuration on daemon load",
"self_conf",
"=",
"self",
".",
"cur_conf",
".",
"get",
"(",
"'self_conf'",
",",
"None",
")",
"if",
"not",
"self_conf",
":",
"self_conf",
"=",
"self",
".",
"conf",
"# whole_conf contains the full configuration load by my master",
"whole_conf",
"=",
"self",
".",
"cur_conf",
"[",
"'whole_conf'",
"]",
"logger",
".",
"debug",
"(",
"\"Received a new configuration, containing:\"",
")",
"for",
"key",
"in",
"self",
".",
"cur_conf",
":",
"logger",
".",
"debug",
"(",
"\"- %s: %s\"",
",",
"key",
",",
"self",
".",
"cur_conf",
"[",
"key",
"]",
")",
"logger",
".",
"debug",
"(",
"\"satellite self configuration part: %s\"",
",",
"self_conf",
")",
"# Update Alignak name",
"self",
".",
"alignak_name",
"=",
"self",
".",
"cur_conf",
"[",
"'alignak_name'",
"]",
"logger",
".",
"info",
"(",
"\"My Alignak instance: %s\"",
",",
"self",
".",
"alignak_name",
")",
"# This to indicate that the new configuration got managed...",
"self",
".",
"new_conf",
"=",
"{",
"}",
"# Get the whole monitored objects configuration",
"t00",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"received_conf_part",
"=",
"unserialize",
"(",
"whole_conf",
")",
"except",
"AlignakClassLookupException",
"as",
"exp",
":",
"# pragma: no cover, simple protection",
"# This to indicate that the new configuration is not managed...",
"self",
".",
"new_conf",
"=",
"{",
"\"_status\"",
":",
"\"Cannot un-serialize configuration received from arbiter\"",
"}",
"logger",
".",
"error",
"(",
"self",
".",
"new_conf",
"[",
"'_status'",
"]",
")",
"logger",
".",
"error",
"(",
"\"Back trace of the error:\\n%s\"",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"except",
"Exception",
"as",
"exp",
":",
"# pylint: disable=broad-except",
"# This to indicate that the new configuration is not managed...",
"self",
".",
"new_conf",
"=",
"{",
"\"_status\"",
":",
"\"Cannot un-serialize configuration received from arbiter\"",
"}",
"logger",
".",
"error",
"(",
"self",
".",
"new_conf",
"[",
"'_status'",
"]",
")",
"logger",
".",
"error",
"(",
"self",
".",
"new_conf",
")",
"self",
".",
"exit_on_exception",
"(",
"exp",
",",
"self",
".",
"new_conf",
")",
"logger",
".",
"info",
"(",
"\"Monitored configuration %s received at %d. Un-serialized in %d secs\"",
",",
"received_conf_part",
",",
"t00",
",",
"time",
".",
"time",
"(",
")",
"-",
"t00",
")",
"# Now we create our arbiters and schedulers links",
"my_satellites",
"=",
"getattr",
"(",
"self",
",",
"'arbiters'",
",",
"{",
"}",
")",
"received_satellites",
"=",
"self",
".",
"cur_conf",
"[",
"'arbiters'",
"]",
"for",
"link_uuid",
"in",
"received_satellites",
":",
"rs_conf",
"=",
"received_satellites",
"[",
"link_uuid",
"]",
"logger",
".",
"debug",
"(",
"\"- received %s - %s: %s\"",
",",
"rs_conf",
"[",
"'instance_id'",
"]",
",",
"rs_conf",
"[",
"'type'",
"]",
",",
"rs_conf",
"[",
"'name'",
"]",
")",
"# Must look if we already had a configuration and save our broks",
"already_got",
"=",
"rs_conf",
"[",
"'instance_id'",
"]",
"in",
"my_satellites",
"broks",
"=",
"[",
"]",
"actions",
"=",
"{",
"}",
"wait_homerun",
"=",
"{",
"}",
"external_commands",
"=",
"{",
"}",
"running_id",
"=",
"0",
"if",
"already_got",
":",
"logger",
".",
"warning",
"(",
"\"I already got: %s\"",
",",
"rs_conf",
"[",
"'instance_id'",
"]",
")",
"# Save some information",
"running_id",
"=",
"my_satellites",
"[",
"link_uuid",
"]",
".",
"running_id",
"(",
"broks",
",",
"actions",
",",
"wait_homerun",
",",
"external_commands",
")",
"=",
"my_satellites",
"[",
"link_uuid",
"]",
".",
"get_and_clear_context",
"(",
")",
"# Delete the former link",
"del",
"my_satellites",
"[",
"link_uuid",
"]",
"# My new satellite link...",
"new_link",
"=",
"SatelliteLink",
".",
"get_a_satellite_link",
"(",
"'arbiter'",
",",
"rs_conf",
")",
"my_satellites",
"[",
"new_link",
".",
"uuid",
"]",
"=",
"new_link",
"logger",
".",
"info",
"(",
"\"I got a new arbiter satellite: %s\"",
",",
"new_link",
")",
"new_link",
".",
"running_id",
"=",
"running_id",
"new_link",
".",
"external_commands",
"=",
"external_commands",
"new_link",
".",
"broks",
"=",
"broks",
"new_link",
".",
"wait_homerun",
"=",
"wait_homerun",
"new_link",
".",
"actions",
"=",
"actions",
"# # replacing satellite address and port by those defined in satellite_map",
"# if new_link.name in self_conf.satellite_map:",
"# overriding = self_conf.satellite_map[new_link.name]",
"# # satellite = dict(satellite) # make a copy",
"# # new_link.update(self_conf.get('satellite_map', {})[new_link.name])",
"# logger.warning(\"Do not override the configuration for: %s, with: %s. \"",
"# \"Please check whether this is necessary!\",",
"# new_link.name, overriding)",
"# for arbiter_link in received_conf_part.arbiters:",
"# logger.info(\"I have arbiter links in my configuration: %s\", arbiter_link.name)",
"# if arbiter_link.name != self.name and not arbiter_link.spare:",
"# # Arbiter is not me!",
"# logger.info(\"I found my master arbiter in the configuration: %s\",",
"# arbiter_link.name)",
"# continue",
"#",
"# logger.info(\"I found myself in the received configuration: %s\", arbiter_link.name)",
"# self.link_to_myself = arbiter_link",
"# # We received a configuration s we are not a master !",
"# self.is_master = False",
"# self.link_to_myself.spare = True",
"# # Set myself as alive ;)",
"# self.link_to_myself.set_alive()",
"# Now I have a configuration!",
"self",
".",
"have_conf",
"=",
"True"
] |
Setup a new configuration received from a Master arbiter.
TODO: perharps we should not accept the configuration or raise an error if we do not
find our own configuration data in the data. Thus this should never happen...
:return: None
|
[
"Setup",
"a",
"new",
"configuration",
"received",
"from",
"a",
"Master",
"arbiter",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1219-L1342
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.wait_for_master_death
|
def wait_for_master_death(self):
"""Wait for a master timeout and take the lead if necessary
:return: None
"""
logger.info("Waiting for master death")
timeout = 1.0
self.last_master_ping = time.time()
master_timeout = 300
for arbiter_link in self.conf.arbiters:
if not arbiter_link.spare:
master_timeout = \
arbiter_link.spare_check_interval * arbiter_link.spare_max_check_attempts
logger.info("I'll wait master death for %d seconds", master_timeout)
while not self.interrupted:
# Make a pause and check if the system time changed
_, tcdiff = self.make_a_pause(timeout)
# If there was a system time change then we have to adapt last_master_ping:
if tcdiff:
self.last_master_ping += tcdiff
if self.new_conf:
self.setup_new_conf()
sys.stdout.write(".")
sys.stdout.flush()
# Now check if master is dead or not
now = time.time()
if now - self.last_master_ping > master_timeout:
logger.info("Arbiter Master is dead. The arbiter %s takes the lead!",
self.link_to_myself.name)
for arbiter_link in self.conf.arbiters:
if not arbiter_link.spare:
arbiter_link.alive = False
self.must_run = True
break
|
python
|
def wait_for_master_death(self):
"""Wait for a master timeout and take the lead if necessary
:return: None
"""
logger.info("Waiting for master death")
timeout = 1.0
self.last_master_ping = time.time()
master_timeout = 300
for arbiter_link in self.conf.arbiters:
if not arbiter_link.spare:
master_timeout = \
arbiter_link.spare_check_interval * arbiter_link.spare_max_check_attempts
logger.info("I'll wait master death for %d seconds", master_timeout)
while not self.interrupted:
# Make a pause and check if the system time changed
_, tcdiff = self.make_a_pause(timeout)
# If there was a system time change then we have to adapt last_master_ping:
if tcdiff:
self.last_master_ping += tcdiff
if self.new_conf:
self.setup_new_conf()
sys.stdout.write(".")
sys.stdout.flush()
# Now check if master is dead or not
now = time.time()
if now - self.last_master_ping > master_timeout:
logger.info("Arbiter Master is dead. The arbiter %s takes the lead!",
self.link_to_myself.name)
for arbiter_link in self.conf.arbiters:
if not arbiter_link.spare:
arbiter_link.alive = False
self.must_run = True
break
|
[
"def",
"wait_for_master_death",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Waiting for master death\"",
")",
"timeout",
"=",
"1.0",
"self",
".",
"last_master_ping",
"=",
"time",
".",
"time",
"(",
")",
"master_timeout",
"=",
"300",
"for",
"arbiter_link",
"in",
"self",
".",
"conf",
".",
"arbiters",
":",
"if",
"not",
"arbiter_link",
".",
"spare",
":",
"master_timeout",
"=",
"arbiter_link",
".",
"spare_check_interval",
"*",
"arbiter_link",
".",
"spare_max_check_attempts",
"logger",
".",
"info",
"(",
"\"I'll wait master death for %d seconds\"",
",",
"master_timeout",
")",
"while",
"not",
"self",
".",
"interrupted",
":",
"# Make a pause and check if the system time changed",
"_",
",",
"tcdiff",
"=",
"self",
".",
"make_a_pause",
"(",
"timeout",
")",
"# If there was a system time change then we have to adapt last_master_ping:",
"if",
"tcdiff",
":",
"self",
".",
"last_master_ping",
"+=",
"tcdiff",
"if",
"self",
".",
"new_conf",
":",
"self",
".",
"setup_new_conf",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\".\"",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"# Now check if master is dead or not",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_master_ping",
">",
"master_timeout",
":",
"logger",
".",
"info",
"(",
"\"Arbiter Master is dead. The arbiter %s takes the lead!\"",
",",
"self",
".",
"link_to_myself",
".",
"name",
")",
"for",
"arbiter_link",
"in",
"self",
".",
"conf",
".",
"arbiters",
":",
"if",
"not",
"arbiter_link",
".",
"spare",
":",
"arbiter_link",
".",
"alive",
"=",
"False",
"self",
".",
"must_run",
"=",
"True",
"break"
] |
Wait for a master timeout and take the lead if necessary
:return: None
|
[
"Wait",
"for",
"a",
"master",
"timeout",
"and",
"take",
"the",
"lead",
"if",
"necessary"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1344-L1382
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.manage_signal
|
def manage_signal(self, sig, frame):
"""Manage signals caught by the process
Specific behavior for the arbiter when it receives a sigkill or sigterm
:param sig: signal caught by the process
:type sig: str
:param frame: current stack frame
:type frame:
:return: None
"""
# Request the arbiter to stop
if sig in [signal.SIGINT, signal.SIGTERM]:
logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig])
self.kill_request = True
self.kill_timestamp = time.time()
logger.info("request to stop in progress")
else:
Daemon.manage_signal(self, sig, frame)
|
python
|
def manage_signal(self, sig, frame):
"""Manage signals caught by the process
Specific behavior for the arbiter when it receives a sigkill or sigterm
:param sig: signal caught by the process
:type sig: str
:param frame: current stack frame
:type frame:
:return: None
"""
# Request the arbiter to stop
if sig in [signal.SIGINT, signal.SIGTERM]:
logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig])
self.kill_request = True
self.kill_timestamp = time.time()
logger.info("request to stop in progress")
else:
Daemon.manage_signal(self, sig, frame)
|
[
"def",
"manage_signal",
"(",
"self",
",",
"sig",
",",
"frame",
")",
":",
"# Request the arbiter to stop",
"if",
"sig",
"in",
"[",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGTERM",
"]",
":",
"logger",
".",
"info",
"(",
"\"received a signal: %s\"",
",",
"SIGNALS_TO_NAMES_DICT",
"[",
"sig",
"]",
")",
"self",
".",
"kill_request",
"=",
"True",
"self",
".",
"kill_timestamp",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"info",
"(",
"\"request to stop in progress\"",
")",
"else",
":",
"Daemon",
".",
"manage_signal",
"(",
"self",
",",
"sig",
",",
"frame",
")"
] |
Manage signals caught by the process
Specific behavior for the arbiter when it receives a sigkill or sigterm
:param sig: signal caught by the process
:type sig: str
:param frame: current stack frame
:type frame:
:return: None
|
[
"Manage",
"signals",
"caught",
"by",
"the",
"process",
"Specific",
"behavior",
"for",
"the",
"arbiter",
"when",
"it",
"receives",
"a",
"sigkill",
"or",
"sigterm"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1394-L1411
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.configuration_dispatch
|
def configuration_dispatch(self, not_configured=None):
"""Monitored configuration preparation and dispatch
:return: None
"""
if not not_configured:
self.dispatcher = Dispatcher(self.conf, self.link_to_myself)
# I set my own dispatched configuration as the provided one...
# because I will not push a configuration to myself :)
self.cur_conf = self.conf
# Loop for the first configuration dispatching, if the first dispatch fails, bail out!
# Without a correct configuration, Alignak daemons will not run correctly
first_connection_try_count = 0
logger.info("Connecting to my satellites...")
while True:
first_connection_try_count += 1
# Initialize connection with all our satellites
self.all_connected = True
for satellite in self.dispatcher.all_daemons_links:
if satellite == self.link_to_myself:
continue
if not satellite.active:
continue
connected = self.daemon_connection_init(satellite, set_wait_new_conf=True)
logger.debug(" %s is %s", satellite, connected)
self.all_connected = self.all_connected and connected
if self.all_connected:
logger.info("- satellites connection #%s is ok", first_connection_try_count)
break
else:
logger.warning("- satellites connection #%s is not correct; "
"let's give another chance after %d seconds...",
first_connection_try_count,
self.link_to_myself.polling_interval)
if first_connection_try_count >= 3:
self.request_stop("All the daemons connections could not be established "
"despite %d tries! "
"Sorry, I bail out!" % first_connection_try_count,
exit_code=4)
time.sleep(self.link_to_myself.polling_interval)
# Now I have a connection with all the daemons I need to contact them,
# check they are alive and ready to run
_t0 = time.time()
self.all_connected = self.dispatcher.check_reachable()
statsmgr.timer('dispatcher.check-alive', time.time() - _t0)
_t0 = time.time()
# Preparing the configuration for dispatching
logger.info("Preparing the configuration for dispatching...")
self.dispatcher.prepare_dispatch()
statsmgr.timer('dispatcher.prepare-dispatch', time.time() - _t0)
logger.info("- configuration is ready to dispatch")
# Loop for the first configuration dispatching, if the first dispatch fails, bail out!
# Without a correct configuration, Alignak daemons will not run correctly
first_dispatch_try_count = 0
logger.info("Dispatching the configuration to my satellites...")
while True:
first_dispatch_try_count += 1
# Check reachable - if a configuration is prepared, this will force the
# daemons communication, and the dispatching will be launched
_t0 = time.time()
logger.info("- configuration dispatching #%s...", first_dispatch_try_count)
self.dispatcher.check_reachable(forced=True)
statsmgr.timer('dispatcher.dispatch', time.time() - _t0)
# Make a pause to let our satellites get ready...
pause = max(1, max(self.conf.daemons_dispatch_timeout, len(self.my_daemons) * 0.5))
# pause = len(self.my_daemons) * 0.2
logger.info("- pausing %d seconds...", pause)
time.sleep(pause)
_t0 = time.time()
logger.info("- checking configuration dispatch...")
# Checking the dispatch is accepted
self.dispatcher.check_dispatch()
statsmgr.timer('dispatcher.check-dispatch', time.time() - _t0)
if self.dispatcher.dispatch_ok:
logger.info("- configuration dispatching #%s is ok", first_dispatch_try_count)
break
else:
logger.warning("- configuration dispatching #%s is not correct; "
"let's give another chance...", first_dispatch_try_count)
if first_dispatch_try_count >= 3:
self.request_stop("The configuration could not be dispatched despite %d tries! "
"Sorry, I bail out!" % first_connection_try_count,
exit_code=4)
|
python
|
def configuration_dispatch(self, not_configured=None):
"""Monitored configuration preparation and dispatch
:return: None
"""
if not not_configured:
self.dispatcher = Dispatcher(self.conf, self.link_to_myself)
# I set my own dispatched configuration as the provided one...
# because I will not push a configuration to myself :)
self.cur_conf = self.conf
# Loop for the first configuration dispatching, if the first dispatch fails, bail out!
# Without a correct configuration, Alignak daemons will not run correctly
first_connection_try_count = 0
logger.info("Connecting to my satellites...")
while True:
first_connection_try_count += 1
# Initialize connection with all our satellites
self.all_connected = True
for satellite in self.dispatcher.all_daemons_links:
if satellite == self.link_to_myself:
continue
if not satellite.active:
continue
connected = self.daemon_connection_init(satellite, set_wait_new_conf=True)
logger.debug(" %s is %s", satellite, connected)
self.all_connected = self.all_connected and connected
if self.all_connected:
logger.info("- satellites connection #%s is ok", first_connection_try_count)
break
else:
logger.warning("- satellites connection #%s is not correct; "
"let's give another chance after %d seconds...",
first_connection_try_count,
self.link_to_myself.polling_interval)
if first_connection_try_count >= 3:
self.request_stop("All the daemons connections could not be established "
"despite %d tries! "
"Sorry, I bail out!" % first_connection_try_count,
exit_code=4)
time.sleep(self.link_to_myself.polling_interval)
# Now I have a connection with all the daemons I need to contact them,
# check they are alive and ready to run
_t0 = time.time()
self.all_connected = self.dispatcher.check_reachable()
statsmgr.timer('dispatcher.check-alive', time.time() - _t0)
_t0 = time.time()
# Preparing the configuration for dispatching
logger.info("Preparing the configuration for dispatching...")
self.dispatcher.prepare_dispatch()
statsmgr.timer('dispatcher.prepare-dispatch', time.time() - _t0)
logger.info("- configuration is ready to dispatch")
# Loop for the first configuration dispatching, if the first dispatch fails, bail out!
# Without a correct configuration, Alignak daemons will not run correctly
first_dispatch_try_count = 0
logger.info("Dispatching the configuration to my satellites...")
while True:
first_dispatch_try_count += 1
# Check reachable - if a configuration is prepared, this will force the
# daemons communication, and the dispatching will be launched
_t0 = time.time()
logger.info("- configuration dispatching #%s...", first_dispatch_try_count)
self.dispatcher.check_reachable(forced=True)
statsmgr.timer('dispatcher.dispatch', time.time() - _t0)
# Make a pause to let our satellites get ready...
pause = max(1, max(self.conf.daemons_dispatch_timeout, len(self.my_daemons) * 0.5))
# pause = len(self.my_daemons) * 0.2
logger.info("- pausing %d seconds...", pause)
time.sleep(pause)
_t0 = time.time()
logger.info("- checking configuration dispatch...")
# Checking the dispatch is accepted
self.dispatcher.check_dispatch()
statsmgr.timer('dispatcher.check-dispatch', time.time() - _t0)
if self.dispatcher.dispatch_ok:
logger.info("- configuration dispatching #%s is ok", first_dispatch_try_count)
break
else:
logger.warning("- configuration dispatching #%s is not correct; "
"let's give another chance...", first_dispatch_try_count)
if first_dispatch_try_count >= 3:
self.request_stop("The configuration could not be dispatched despite %d tries! "
"Sorry, I bail out!" % first_connection_try_count,
exit_code=4)
|
[
"def",
"configuration_dispatch",
"(",
"self",
",",
"not_configured",
"=",
"None",
")",
":",
"if",
"not",
"not_configured",
":",
"self",
".",
"dispatcher",
"=",
"Dispatcher",
"(",
"self",
".",
"conf",
",",
"self",
".",
"link_to_myself",
")",
"# I set my own dispatched configuration as the provided one...",
"# because I will not push a configuration to myself :)",
"self",
".",
"cur_conf",
"=",
"self",
".",
"conf",
"# Loop for the first configuration dispatching, if the first dispatch fails, bail out!",
"# Without a correct configuration, Alignak daemons will not run correctly",
"first_connection_try_count",
"=",
"0",
"logger",
".",
"info",
"(",
"\"Connecting to my satellites...\"",
")",
"while",
"True",
":",
"first_connection_try_count",
"+=",
"1",
"# Initialize connection with all our satellites",
"self",
".",
"all_connected",
"=",
"True",
"for",
"satellite",
"in",
"self",
".",
"dispatcher",
".",
"all_daemons_links",
":",
"if",
"satellite",
"==",
"self",
".",
"link_to_myself",
":",
"continue",
"if",
"not",
"satellite",
".",
"active",
":",
"continue",
"connected",
"=",
"self",
".",
"daemon_connection_init",
"(",
"satellite",
",",
"set_wait_new_conf",
"=",
"True",
")",
"logger",
".",
"debug",
"(",
"\" %s is %s\"",
",",
"satellite",
",",
"connected",
")",
"self",
".",
"all_connected",
"=",
"self",
".",
"all_connected",
"and",
"connected",
"if",
"self",
".",
"all_connected",
":",
"logger",
".",
"info",
"(",
"\"- satellites connection #%s is ok\"",
",",
"first_connection_try_count",
")",
"break",
"else",
":",
"logger",
".",
"warning",
"(",
"\"- satellites connection #%s is not correct; \"",
"\"let's give another chance after %d seconds...\"",
",",
"first_connection_try_count",
",",
"self",
".",
"link_to_myself",
".",
"polling_interval",
")",
"if",
"first_connection_try_count",
">=",
"3",
":",
"self",
".",
"request_stop",
"(",
"\"All the daemons connections could not be established \"",
"\"despite %d tries! \"",
"\"Sorry, I bail out!\"",
"%",
"first_connection_try_count",
",",
"exit_code",
"=",
"4",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"link_to_myself",
".",
"polling_interval",
")",
"# Now I have a connection with all the daemons I need to contact them,",
"# check they are alive and ready to run",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"all_connected",
"=",
"self",
".",
"dispatcher",
".",
"check_reachable",
"(",
")",
"statsmgr",
".",
"timer",
"(",
"'dispatcher.check-alive'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",
")",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"# Preparing the configuration for dispatching",
"logger",
".",
"info",
"(",
"\"Preparing the configuration for dispatching...\"",
")",
"self",
".",
"dispatcher",
".",
"prepare_dispatch",
"(",
")",
"statsmgr",
".",
"timer",
"(",
"'dispatcher.prepare-dispatch'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",
")",
"logger",
".",
"info",
"(",
"\"- configuration is ready to dispatch\"",
")",
"# Loop for the first configuration dispatching, if the first dispatch fails, bail out!",
"# Without a correct configuration, Alignak daemons will not run correctly",
"first_dispatch_try_count",
"=",
"0",
"logger",
".",
"info",
"(",
"\"Dispatching the configuration to my satellites...\"",
")",
"while",
"True",
":",
"first_dispatch_try_count",
"+=",
"1",
"# Check reachable - if a configuration is prepared, this will force the",
"# daemons communication, and the dispatching will be launched",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"info",
"(",
"\"- configuration dispatching #%s...\"",
",",
"first_dispatch_try_count",
")",
"self",
".",
"dispatcher",
".",
"check_reachable",
"(",
"forced",
"=",
"True",
")",
"statsmgr",
".",
"timer",
"(",
"'dispatcher.dispatch'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",
")",
"# Make a pause to let our satellites get ready...",
"pause",
"=",
"max",
"(",
"1",
",",
"max",
"(",
"self",
".",
"conf",
".",
"daemons_dispatch_timeout",
",",
"len",
"(",
"self",
".",
"my_daemons",
")",
"*",
"0.5",
")",
")",
"# pause = len(self.my_daemons) * 0.2",
"logger",
".",
"info",
"(",
"\"- pausing %d seconds...\"",
",",
"pause",
")",
"time",
".",
"sleep",
"(",
"pause",
")",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"info",
"(",
"\"- checking configuration dispatch...\"",
")",
"# Checking the dispatch is accepted",
"self",
".",
"dispatcher",
".",
"check_dispatch",
"(",
")",
"statsmgr",
".",
"timer",
"(",
"'dispatcher.check-dispatch'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",
")",
"if",
"self",
".",
"dispatcher",
".",
"dispatch_ok",
":",
"logger",
".",
"info",
"(",
"\"- configuration dispatching #%s is ok\"",
",",
"first_dispatch_try_count",
")",
"break",
"else",
":",
"logger",
".",
"warning",
"(",
"\"- configuration dispatching #%s is not correct; \"",
"\"let's give another chance...\"",
",",
"first_dispatch_try_count",
")",
"if",
"first_dispatch_try_count",
">=",
"3",
":",
"self",
".",
"request_stop",
"(",
"\"The configuration could not be dispatched despite %d tries! \"",
"\"Sorry, I bail out!\"",
"%",
"first_connection_try_count",
",",
"exit_code",
"=",
"4",
")"
] |
Monitored configuration preparation and dispatch
:return: None
|
[
"Monitored",
"configuration",
"preparation",
"and",
"dispatch"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1413-L1504
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.do_before_loop
|
def do_before_loop(self):
"""Called before the main daemon loop.
:return: None
"""
logger.info("I am the arbiter: %s", self.link_to_myself.name)
# If I am a spare, I do not have anything to do here...
if not self.is_master:
logger.debug("Waiting for my master death...")
return
# Arbiter check if some daemons need to be started
if not self.daemons_start(run_daemons=True):
self.request_stop(message="Some Alignak daemons did not started correctly.",
exit_code=4)
if not self.daemons_check():
self.request_stop(message="Some Alignak daemons cannot be checked.",
exit_code=4)
# Make a pause to let our started daemons get ready...
pause = max(1, max(self.conf.daemons_start_timeout, len(self.my_daemons) * 0.5))
if pause:
logger.info("Pausing %.2f seconds...", pause)
time.sleep(pause)
# Prepare and dispatch the monitored configuration
self.configuration_dispatch()
# Now we can get all initial broks for our satellites
_t0 = time.time()
self.get_initial_broks_from_satellites()
statsmgr.timer('broks.get-initial', time.time() - _t0)
# Now create the external commands manager
# We are a dispatcher: our role is to dispatch commands to the schedulers
self.external_commands_manager = ExternalCommandManager(
self.conf, 'dispatcher', self, self.conf.accept_passive_unknown_check_results,
self.conf.log_external_commands)
|
python
|
def do_before_loop(self):
"""Called before the main daemon loop.
:return: None
"""
logger.info("I am the arbiter: %s", self.link_to_myself.name)
# If I am a spare, I do not have anything to do here...
if not self.is_master:
logger.debug("Waiting for my master death...")
return
# Arbiter check if some daemons need to be started
if not self.daemons_start(run_daemons=True):
self.request_stop(message="Some Alignak daemons did not started correctly.",
exit_code=4)
if not self.daemons_check():
self.request_stop(message="Some Alignak daemons cannot be checked.",
exit_code=4)
# Make a pause to let our started daemons get ready...
pause = max(1, max(self.conf.daemons_start_timeout, len(self.my_daemons) * 0.5))
if pause:
logger.info("Pausing %.2f seconds...", pause)
time.sleep(pause)
# Prepare and dispatch the monitored configuration
self.configuration_dispatch()
# Now we can get all initial broks for our satellites
_t0 = time.time()
self.get_initial_broks_from_satellites()
statsmgr.timer('broks.get-initial', time.time() - _t0)
# Now create the external commands manager
# We are a dispatcher: our role is to dispatch commands to the schedulers
self.external_commands_manager = ExternalCommandManager(
self.conf, 'dispatcher', self, self.conf.accept_passive_unknown_check_results,
self.conf.log_external_commands)
|
[
"def",
"do_before_loop",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"I am the arbiter: %s\"",
",",
"self",
".",
"link_to_myself",
".",
"name",
")",
"# If I am a spare, I do not have anything to do here...",
"if",
"not",
"self",
".",
"is_master",
":",
"logger",
".",
"debug",
"(",
"\"Waiting for my master death...\"",
")",
"return",
"# Arbiter check if some daemons need to be started",
"if",
"not",
"self",
".",
"daemons_start",
"(",
"run_daemons",
"=",
"True",
")",
":",
"self",
".",
"request_stop",
"(",
"message",
"=",
"\"Some Alignak daemons did not started correctly.\"",
",",
"exit_code",
"=",
"4",
")",
"if",
"not",
"self",
".",
"daemons_check",
"(",
")",
":",
"self",
".",
"request_stop",
"(",
"message",
"=",
"\"Some Alignak daemons cannot be checked.\"",
",",
"exit_code",
"=",
"4",
")",
"# Make a pause to let our started daemons get ready...",
"pause",
"=",
"max",
"(",
"1",
",",
"max",
"(",
"self",
".",
"conf",
".",
"daemons_start_timeout",
",",
"len",
"(",
"self",
".",
"my_daemons",
")",
"*",
"0.5",
")",
")",
"if",
"pause",
":",
"logger",
".",
"info",
"(",
"\"Pausing %.2f seconds...\"",
",",
"pause",
")",
"time",
".",
"sleep",
"(",
"pause",
")",
"# Prepare and dispatch the monitored configuration",
"self",
".",
"configuration_dispatch",
"(",
")",
"# Now we can get all initial broks for our satellites",
"_t0",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"get_initial_broks_from_satellites",
"(",
")",
"statsmgr",
".",
"timer",
"(",
"'broks.get-initial'",
",",
"time",
".",
"time",
"(",
")",
"-",
"_t0",
")",
"# Now create the external commands manager",
"# We are a dispatcher: our role is to dispatch commands to the schedulers",
"self",
".",
"external_commands_manager",
"=",
"ExternalCommandManager",
"(",
"self",
".",
"conf",
",",
"'dispatcher'",
",",
"self",
",",
"self",
".",
"conf",
".",
"accept_passive_unknown_check_results",
",",
"self",
".",
"conf",
".",
"log_external_commands",
")"
] |
Called before the main daemon loop.
:return: None
|
[
"Called",
"before",
"the",
"main",
"daemon",
"loop",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1506-L1545
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.get_monitoring_problems
|
def get_monitoring_problems(self):
"""Get the schedulers satellites problems list
:return: problems dictionary
:rtype: dict
"""
res = self.get_id()
res['problems'] = {}
# Report our schedulers information, but only if a dispatcher exists
if getattr(self, 'dispatcher', None) is None:
return res
for satellite in self.dispatcher.all_daemons_links:
if satellite.type not in ['scheduler']:
continue
if not satellite.active:
continue
if satellite.statistics and 'problems' in satellite.statistics:
res['problems'][satellite.name] = {
'_freshness': satellite.statistics['_freshness'],
'problems': satellite.statistics['problems']
}
return res
|
python
|
def get_monitoring_problems(self):
"""Get the schedulers satellites problems list
:return: problems dictionary
:rtype: dict
"""
res = self.get_id()
res['problems'] = {}
# Report our schedulers information, but only if a dispatcher exists
if getattr(self, 'dispatcher', None) is None:
return res
for satellite in self.dispatcher.all_daemons_links:
if satellite.type not in ['scheduler']:
continue
if not satellite.active:
continue
if satellite.statistics and 'problems' in satellite.statistics:
res['problems'][satellite.name] = {
'_freshness': satellite.statistics['_freshness'],
'problems': satellite.statistics['problems']
}
return res
|
[
"def",
"get_monitoring_problems",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"get_id",
"(",
")",
"res",
"[",
"'problems'",
"]",
"=",
"{",
"}",
"# Report our schedulers information, but only if a dispatcher exists",
"if",
"getattr",
"(",
"self",
",",
"'dispatcher'",
",",
"None",
")",
"is",
"None",
":",
"return",
"res",
"for",
"satellite",
"in",
"self",
".",
"dispatcher",
".",
"all_daemons_links",
":",
"if",
"satellite",
".",
"type",
"not",
"in",
"[",
"'scheduler'",
"]",
":",
"continue",
"if",
"not",
"satellite",
".",
"active",
":",
"continue",
"if",
"satellite",
".",
"statistics",
"and",
"'problems'",
"in",
"satellite",
".",
"statistics",
":",
"res",
"[",
"'problems'",
"]",
"[",
"satellite",
".",
"name",
"]",
"=",
"{",
"'_freshness'",
":",
"satellite",
".",
"statistics",
"[",
"'_freshness'",
"]",
",",
"'problems'",
":",
"satellite",
".",
"statistics",
"[",
"'problems'",
"]",
"}",
"return",
"res"
] |
Get the schedulers satellites problems list
:return: problems dictionary
:rtype: dict
|
[
"Get",
"the",
"schedulers",
"satellites",
"problems",
"list"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1801-L1826
|
train
|
Alignak-monitoring/alignak
|
alignak/daemons/arbiterdaemon.py
|
Arbiter.get_livesynthesis
|
def get_livesynthesis(self):
"""Get the schedulers satellites live synthesis
:return: compiled livesynthesis dictionary
:rtype: dict
"""
res = self.get_id()
res['livesynthesis'] = {
'_overall': {
'_freshness': int(time.time()),
'livesynthesis': {
'hosts_total': 0,
'hosts_not_monitored': 0,
'hosts_up_hard': 0,
'hosts_up_soft': 0,
'hosts_down_hard': 0,
'hosts_down_soft': 0,
'hosts_unreachable_hard': 0,
'hosts_unreachable_soft': 0,
'hosts_problems': 0,
'hosts_acknowledged': 0,
'hosts_in_downtime': 0,
'hosts_flapping': 0,
'services_total': 0,
'services_not_monitored': 0,
'services_ok_hard': 0,
'services_ok_soft': 0,
'services_warning_hard': 0,
'services_warning_soft': 0,
'services_critical_hard': 0,
'services_critical_soft': 0,
'services_unknown_hard': 0,
'services_unknown_soft': 0,
'services_unreachable_hard': 0,
'services_unreachable_soft': 0,
'services_problems': 0,
'services_acknowledged': 0,
'services_in_downtime': 0,
'services_flapping': 0,
}
}
}
# Report our schedulers information, but only if a dispatcher exists
if getattr(self, 'dispatcher', None) is None:
return res
for satellite in self.dispatcher.all_daemons_links:
if satellite.type not in ['scheduler']:
continue
if not satellite.active:
continue
if 'livesynthesis' in satellite.statistics:
# Scheduler detailed live synthesis
res['livesynthesis'][satellite.name] = {
'_freshness': satellite.statistics['_freshness'],
'livesynthesis': satellite.statistics['livesynthesis']
}
# Cumulated live synthesis
for prop in res['livesynthesis']['_overall']['livesynthesis']:
if prop in satellite.statistics['livesynthesis']:
res['livesynthesis']['_overall']['livesynthesis'][prop] += \
satellite.statistics['livesynthesis'][prop]
return res
|
python
|
def get_livesynthesis(self):
"""Get the schedulers satellites live synthesis
:return: compiled livesynthesis dictionary
:rtype: dict
"""
res = self.get_id()
res['livesynthesis'] = {
'_overall': {
'_freshness': int(time.time()),
'livesynthesis': {
'hosts_total': 0,
'hosts_not_monitored': 0,
'hosts_up_hard': 0,
'hosts_up_soft': 0,
'hosts_down_hard': 0,
'hosts_down_soft': 0,
'hosts_unreachable_hard': 0,
'hosts_unreachable_soft': 0,
'hosts_problems': 0,
'hosts_acknowledged': 0,
'hosts_in_downtime': 0,
'hosts_flapping': 0,
'services_total': 0,
'services_not_monitored': 0,
'services_ok_hard': 0,
'services_ok_soft': 0,
'services_warning_hard': 0,
'services_warning_soft': 0,
'services_critical_hard': 0,
'services_critical_soft': 0,
'services_unknown_hard': 0,
'services_unknown_soft': 0,
'services_unreachable_hard': 0,
'services_unreachable_soft': 0,
'services_problems': 0,
'services_acknowledged': 0,
'services_in_downtime': 0,
'services_flapping': 0,
}
}
}
# Report our schedulers information, but only if a dispatcher exists
if getattr(self, 'dispatcher', None) is None:
return res
for satellite in self.dispatcher.all_daemons_links:
if satellite.type not in ['scheduler']:
continue
if not satellite.active:
continue
if 'livesynthesis' in satellite.statistics:
# Scheduler detailed live synthesis
res['livesynthesis'][satellite.name] = {
'_freshness': satellite.statistics['_freshness'],
'livesynthesis': satellite.statistics['livesynthesis']
}
# Cumulated live synthesis
for prop in res['livesynthesis']['_overall']['livesynthesis']:
if prop in satellite.statistics['livesynthesis']:
res['livesynthesis']['_overall']['livesynthesis'][prop] += \
satellite.statistics['livesynthesis'][prop]
return res
|
[
"def",
"get_livesynthesis",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"get_id",
"(",
")",
"res",
"[",
"'livesynthesis'",
"]",
"=",
"{",
"'_overall'",
":",
"{",
"'_freshness'",
":",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"'livesynthesis'",
":",
"{",
"'hosts_total'",
":",
"0",
",",
"'hosts_not_monitored'",
":",
"0",
",",
"'hosts_up_hard'",
":",
"0",
",",
"'hosts_up_soft'",
":",
"0",
",",
"'hosts_down_hard'",
":",
"0",
",",
"'hosts_down_soft'",
":",
"0",
",",
"'hosts_unreachable_hard'",
":",
"0",
",",
"'hosts_unreachable_soft'",
":",
"0",
",",
"'hosts_problems'",
":",
"0",
",",
"'hosts_acknowledged'",
":",
"0",
",",
"'hosts_in_downtime'",
":",
"0",
",",
"'hosts_flapping'",
":",
"0",
",",
"'services_total'",
":",
"0",
",",
"'services_not_monitored'",
":",
"0",
",",
"'services_ok_hard'",
":",
"0",
",",
"'services_ok_soft'",
":",
"0",
",",
"'services_warning_hard'",
":",
"0",
",",
"'services_warning_soft'",
":",
"0",
",",
"'services_critical_hard'",
":",
"0",
",",
"'services_critical_soft'",
":",
"0",
",",
"'services_unknown_hard'",
":",
"0",
",",
"'services_unknown_soft'",
":",
"0",
",",
"'services_unreachable_hard'",
":",
"0",
",",
"'services_unreachable_soft'",
":",
"0",
",",
"'services_problems'",
":",
"0",
",",
"'services_acknowledged'",
":",
"0",
",",
"'services_in_downtime'",
":",
"0",
",",
"'services_flapping'",
":",
"0",
",",
"}",
"}",
"}",
"# Report our schedulers information, but only if a dispatcher exists",
"if",
"getattr",
"(",
"self",
",",
"'dispatcher'",
",",
"None",
")",
"is",
"None",
":",
"return",
"res",
"for",
"satellite",
"in",
"self",
".",
"dispatcher",
".",
"all_daemons_links",
":",
"if",
"satellite",
".",
"type",
"not",
"in",
"[",
"'scheduler'",
"]",
":",
"continue",
"if",
"not",
"satellite",
".",
"active",
":",
"continue",
"if",
"'livesynthesis'",
"in",
"satellite",
".",
"statistics",
":",
"# Scheduler detailed live synthesis",
"res",
"[",
"'livesynthesis'",
"]",
"[",
"satellite",
".",
"name",
"]",
"=",
"{",
"'_freshness'",
":",
"satellite",
".",
"statistics",
"[",
"'_freshness'",
"]",
",",
"'livesynthesis'",
":",
"satellite",
".",
"statistics",
"[",
"'livesynthesis'",
"]",
"}",
"# Cumulated live synthesis",
"for",
"prop",
"in",
"res",
"[",
"'livesynthesis'",
"]",
"[",
"'_overall'",
"]",
"[",
"'livesynthesis'",
"]",
":",
"if",
"prop",
"in",
"satellite",
".",
"statistics",
"[",
"'livesynthesis'",
"]",
":",
"res",
"[",
"'livesynthesis'",
"]",
"[",
"'_overall'",
"]",
"[",
"'livesynthesis'",
"]",
"[",
"prop",
"]",
"+=",
"satellite",
".",
"statistics",
"[",
"'livesynthesis'",
"]",
"[",
"prop",
"]",
"return",
"res"
] |
Get the schedulers satellites live synthesis
:return: compiled livesynthesis dictionary
:rtype: dict
|
[
"Get",
"the",
"schedulers",
"satellites",
"live",
"synthesis"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/arbiterdaemon.py#L1828-L1893
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.overall_state_id
|
def overall_state_id(self):
"""Get the service overall state.
The service overall state identifier is the service status including:
- the monitored state
- the acknowledged state
- the downtime state
The overall state is (prioritized):
- a service is not monitored (5)
- a service critical or unreachable (4)
- a service warning or unknown (3)
- a service downtimed (2)
- a service acknowledged (1)
- a service ok (0)
*Note* that services in unknown state are considered as warning, and unreachable ones
are considered as critical!
Also note that the service state is considered only for HARD state type!
"""
overall_state = 0
if not self.monitored:
overall_state = 5
elif self.acknowledged:
overall_state = 1
elif self.downtimed:
overall_state = 2
elif self.state_type == 'HARD':
if self.state == 'WARNING':
overall_state = 3
elif self.state == 'CRITICAL':
overall_state = 4
elif self.state == 'UNKNOWN':
overall_state = 3
elif self.state == 'UNREACHABLE':
overall_state = 4
return overall_state
|
python
|
def overall_state_id(self):
"""Get the service overall state.
The service overall state identifier is the service status including:
- the monitored state
- the acknowledged state
- the downtime state
The overall state is (prioritized):
- a service is not monitored (5)
- a service critical or unreachable (4)
- a service warning or unknown (3)
- a service downtimed (2)
- a service acknowledged (1)
- a service ok (0)
*Note* that services in unknown state are considered as warning, and unreachable ones
are considered as critical!
Also note that the service state is considered only for HARD state type!
"""
overall_state = 0
if not self.monitored:
overall_state = 5
elif self.acknowledged:
overall_state = 1
elif self.downtimed:
overall_state = 2
elif self.state_type == 'HARD':
if self.state == 'WARNING':
overall_state = 3
elif self.state == 'CRITICAL':
overall_state = 4
elif self.state == 'UNKNOWN':
overall_state = 3
elif self.state == 'UNREACHABLE':
overall_state = 4
return overall_state
|
[
"def",
"overall_state_id",
"(",
"self",
")",
":",
"overall_state",
"=",
"0",
"if",
"not",
"self",
".",
"monitored",
":",
"overall_state",
"=",
"5",
"elif",
"self",
".",
"acknowledged",
":",
"overall_state",
"=",
"1",
"elif",
"self",
".",
"downtimed",
":",
"overall_state",
"=",
"2",
"elif",
"self",
".",
"state_type",
"==",
"'HARD'",
":",
"if",
"self",
".",
"state",
"==",
"'WARNING'",
":",
"overall_state",
"=",
"3",
"elif",
"self",
".",
"state",
"==",
"'CRITICAL'",
":",
"overall_state",
"=",
"4",
"elif",
"self",
".",
"state",
"==",
"'UNKNOWN'",
":",
"overall_state",
"=",
"3",
"elif",
"self",
".",
"state",
"==",
"'UNREACHABLE'",
":",
"overall_state",
"=",
"4",
"return",
"overall_state"
] |
Get the service overall state.
The service overall state identifier is the service status including:
- the monitored state
- the acknowledged state
- the downtime state
The overall state is (prioritized):
- a service is not monitored (5)
- a service critical or unreachable (4)
- a service warning or unknown (3)
- a service downtimed (2)
- a service acknowledged (1)
- a service ok (0)
*Note* that services in unknown state are considered as warning, and unreachable ones
are considered as critical!
Also note that the service state is considered only for HARD state type!
|
[
"Get",
"the",
"service",
"overall",
"state",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L255-L294
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.fill_predictive_missing_parameters
|
def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.state = u'WARNING'
elif self.initial_state == 'u':
self.state = u'UNKNOWN'
elif self.initial_state == 'c':
self.state = u'CRITICAL'
elif self.initial_state == 'x':
self.state = u'UNREACHABLE'
|
python
|
def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.state = u'WARNING'
elif self.initial_state == 'u':
self.state = u'UNKNOWN'
elif self.initial_state == 'c':
self.state = u'CRITICAL'
elif self.initial_state == 'x':
self.state = u'UNREACHABLE'
|
[
"def",
"fill_predictive_missing_parameters",
"(",
"self",
")",
":",
"if",
"self",
".",
"initial_state",
"==",
"'w'",
":",
"self",
".",
"state",
"=",
"u'WARNING'",
"elif",
"self",
".",
"initial_state",
"==",
"'u'",
":",
"self",
".",
"state",
"=",
"u'UNKNOWN'",
"elif",
"self",
".",
"initial_state",
"==",
"'c'",
":",
"self",
".",
"state",
"=",
"u'CRITICAL'",
"elif",
"self",
".",
"initial_state",
"==",
"'x'",
":",
"self",
".",
"state",
"=",
"u'UNREACHABLE'"
] |
define state with initial_state
:return: None
|
[
"define",
"state",
"with",
"initial_state"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L307-L319
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.get_name
|
def get_name(self):
"""Accessor to service_description attribute or name if first not defined
:return: service name
:rtype: str
"""
if hasattr(self, 'service_description'):
return self.service_description
if hasattr(self, 'name'):
return self.name
return 'SERVICE-DESCRIPTION-MISSING'
|
python
|
def get_name(self):
"""Accessor to service_description attribute or name if first not defined
:return: service name
:rtype: str
"""
if hasattr(self, 'service_description'):
return self.service_description
if hasattr(self, 'name'):
return self.name
return 'SERVICE-DESCRIPTION-MISSING'
|
[
"def",
"get_name",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'service_description'",
")",
":",
"return",
"self",
".",
"service_description",
"if",
"hasattr",
"(",
"self",
",",
"'name'",
")",
":",
"return",
"self",
".",
"name",
"return",
"'SERVICE-DESCRIPTION-MISSING'"
] |
Accessor to service_description attribute or name if first not defined
:return: service name
:rtype: str
|
[
"Accessor",
"to",
"service_description",
"attribute",
"or",
"name",
"if",
"first",
"not",
"defined"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L351-L361
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.get_groupnames
|
def get_groupnames(self, sgs):
"""Get servicegroups list
:return: comma separated list of servicegroups
:rtype: str
"""
return ','.join([sgs[sg].get_name() for sg in self.servicegroups])
|
python
|
def get_groupnames(self, sgs):
"""Get servicegroups list
:return: comma separated list of servicegroups
:rtype: str
"""
return ','.join([sgs[sg].get_name() for sg in self.servicegroups])
|
[
"def",
"get_groupnames",
"(",
"self",
",",
"sgs",
")",
":",
"return",
"','",
".",
"join",
"(",
"[",
"sgs",
"[",
"sg",
"]",
".",
"get_name",
"(",
")",
"for",
"sg",
"in",
"self",
".",
"servicegroups",
"]",
")"
] |
Get servicegroups list
:return: comma separated list of servicegroups
:rtype: str
|
[
"Get",
"servicegroups",
"list"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L383-L389
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.duplicate
|
def duplicate(self, host):
# pylint: disable=too-many-locals
"""For a given host, look for all copy we must create for for_each property
:param host: alignak host object
:type host: alignak.objects.host.Host
:return: list
:rtype: list
"""
duplicates = []
# In macro, it's all in UPPER case
prop = self.duplicate_foreach.strip().upper()
if prop not in host.customs: # If I do not have the property, we bail out
return duplicates
# Get the list entry, and the not one if there is one
entry = host.customs[prop]
# Look at the list of the key we do NOT want maybe,
# for _disks it will be _!disks
not_entry = host.customs.get('_' + '!' + prop[1:], '').split(',')
not_keys = strip_and_uniq(not_entry)
default_value = getattr(self, 'default_value', '')
# Transform the generator string to a list
# Missing values are filled with the default value
try:
key_values = tuple(generate_key_value_sequences(entry, default_value))
except KeyValueSyntaxError as exc:
fmt_dict = {
'prop': self.duplicate_foreach,
'host': host.get_name(),
'svc': self.service_description,
'entry': entry,
'exc': exc,
}
err = (
"The custom property %(prop)r of the "
"host %(host)r is not a valid entry for a service generator: %(exc)s, "
"with entry=%(entry)r") % fmt_dict
logger.warning(err)
host.add_error(err)
return duplicates
for key_value in key_values:
key = key_value['KEY']
# Maybe this key is in the NOT list, if so, skip it
if key in not_keys:
continue
new_s = self.copy()
new_s.host_name = host.get_name()
if self.is_tpl(): # if template, the new one is not
new_s.register = 1
for key in key_value:
if key == 'KEY':
if hasattr(self, 'service_description'):
# We want to change all illegal chars to a _ sign.
# We can't use class.illegal_obj_char
# because in the "explode" phase, we do not have access to this data! :(
safe_key_value = re.sub(r'[' + "`~!$%^&*\"|'<>?,()=" + ']+', '_',
key_value[key])
new_s.service_description = self.service_description.replace(
'$' + key + '$', safe_key_value
)
# Here is a list of property where we will expand the $KEY$ by the value
_the_expandables = ['check_command', 'aggregation', 'event_handler']
for prop in _the_expandables:
if hasattr(self, prop):
# here we can replace VALUE, VALUE1, VALUE2,...
setattr(new_s, prop, getattr(new_s, prop).replace('$' + key + '$',
key_value[key]))
if hasattr(self, 'service_dependencies'):
for i, servicedep in enumerate(new_s.service_dependencies):
new_s.service_dependencies[i] = servicedep.replace(
'$' + key + '$', key_value[key]
)
# And then add in our list this new service
duplicates.append(new_s)
return duplicates
|
python
|
def duplicate(self, host):
# pylint: disable=too-many-locals
"""For a given host, look for all copy we must create for for_each property
:param host: alignak host object
:type host: alignak.objects.host.Host
:return: list
:rtype: list
"""
duplicates = []
# In macro, it's all in UPPER case
prop = self.duplicate_foreach.strip().upper()
if prop not in host.customs: # If I do not have the property, we bail out
return duplicates
# Get the list entry, and the not one if there is one
entry = host.customs[prop]
# Look at the list of the key we do NOT want maybe,
# for _disks it will be _!disks
not_entry = host.customs.get('_' + '!' + prop[1:], '').split(',')
not_keys = strip_and_uniq(not_entry)
default_value = getattr(self, 'default_value', '')
# Transform the generator string to a list
# Missing values are filled with the default value
try:
key_values = tuple(generate_key_value_sequences(entry, default_value))
except KeyValueSyntaxError as exc:
fmt_dict = {
'prop': self.duplicate_foreach,
'host': host.get_name(),
'svc': self.service_description,
'entry': entry,
'exc': exc,
}
err = (
"The custom property %(prop)r of the "
"host %(host)r is not a valid entry for a service generator: %(exc)s, "
"with entry=%(entry)r") % fmt_dict
logger.warning(err)
host.add_error(err)
return duplicates
for key_value in key_values:
key = key_value['KEY']
# Maybe this key is in the NOT list, if so, skip it
if key in not_keys:
continue
new_s = self.copy()
new_s.host_name = host.get_name()
if self.is_tpl(): # if template, the new one is not
new_s.register = 1
for key in key_value:
if key == 'KEY':
if hasattr(self, 'service_description'):
# We want to change all illegal chars to a _ sign.
# We can't use class.illegal_obj_char
# because in the "explode" phase, we do not have access to this data! :(
safe_key_value = re.sub(r'[' + "`~!$%^&*\"|'<>?,()=" + ']+', '_',
key_value[key])
new_s.service_description = self.service_description.replace(
'$' + key + '$', safe_key_value
)
# Here is a list of property where we will expand the $KEY$ by the value
_the_expandables = ['check_command', 'aggregation', 'event_handler']
for prop in _the_expandables:
if hasattr(self, prop):
# here we can replace VALUE, VALUE1, VALUE2,...
setattr(new_s, prop, getattr(new_s, prop).replace('$' + key + '$',
key_value[key]))
if hasattr(self, 'service_dependencies'):
for i, servicedep in enumerate(new_s.service_dependencies):
new_s.service_dependencies[i] = servicedep.replace(
'$' + key + '$', key_value[key]
)
# And then add in our list this new service
duplicates.append(new_s)
return duplicates
|
[
"def",
"duplicate",
"(",
"self",
",",
"host",
")",
":",
"# pylint: disable=too-many-locals",
"duplicates",
"=",
"[",
"]",
"# In macro, it's all in UPPER case",
"prop",
"=",
"self",
".",
"duplicate_foreach",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
"if",
"prop",
"not",
"in",
"host",
".",
"customs",
":",
"# If I do not have the property, we bail out",
"return",
"duplicates",
"# Get the list entry, and the not one if there is one",
"entry",
"=",
"host",
".",
"customs",
"[",
"prop",
"]",
"# Look at the list of the key we do NOT want maybe,",
"# for _disks it will be _!disks",
"not_entry",
"=",
"host",
".",
"customs",
".",
"get",
"(",
"'_'",
"+",
"'!'",
"+",
"prop",
"[",
"1",
":",
"]",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"not_keys",
"=",
"strip_and_uniq",
"(",
"not_entry",
")",
"default_value",
"=",
"getattr",
"(",
"self",
",",
"'default_value'",
",",
"''",
")",
"# Transform the generator string to a list",
"# Missing values are filled with the default value",
"try",
":",
"key_values",
"=",
"tuple",
"(",
"generate_key_value_sequences",
"(",
"entry",
",",
"default_value",
")",
")",
"except",
"KeyValueSyntaxError",
"as",
"exc",
":",
"fmt_dict",
"=",
"{",
"'prop'",
":",
"self",
".",
"duplicate_foreach",
",",
"'host'",
":",
"host",
".",
"get_name",
"(",
")",
",",
"'svc'",
":",
"self",
".",
"service_description",
",",
"'entry'",
":",
"entry",
",",
"'exc'",
":",
"exc",
",",
"}",
"err",
"=",
"(",
"\"The custom property %(prop)r of the \"",
"\"host %(host)r is not a valid entry for a service generator: %(exc)s, \"",
"\"with entry=%(entry)r\"",
")",
"%",
"fmt_dict",
"logger",
".",
"warning",
"(",
"err",
")",
"host",
".",
"add_error",
"(",
"err",
")",
"return",
"duplicates",
"for",
"key_value",
"in",
"key_values",
":",
"key",
"=",
"key_value",
"[",
"'KEY'",
"]",
"# Maybe this key is in the NOT list, if so, skip it",
"if",
"key",
"in",
"not_keys",
":",
"continue",
"new_s",
"=",
"self",
".",
"copy",
"(",
")",
"new_s",
".",
"host_name",
"=",
"host",
".",
"get_name",
"(",
")",
"if",
"self",
".",
"is_tpl",
"(",
")",
":",
"# if template, the new one is not",
"new_s",
".",
"register",
"=",
"1",
"for",
"key",
"in",
"key_value",
":",
"if",
"key",
"==",
"'KEY'",
":",
"if",
"hasattr",
"(",
"self",
",",
"'service_description'",
")",
":",
"# We want to change all illegal chars to a _ sign.",
"# We can't use class.illegal_obj_char",
"# because in the \"explode\" phase, we do not have access to this data! :(",
"safe_key_value",
"=",
"re",
".",
"sub",
"(",
"r'['",
"+",
"\"`~!$%^&*\\\"|'<>?,()=\"",
"+",
"']+'",
",",
"'_'",
",",
"key_value",
"[",
"key",
"]",
")",
"new_s",
".",
"service_description",
"=",
"self",
".",
"service_description",
".",
"replace",
"(",
"'$'",
"+",
"key",
"+",
"'$'",
",",
"safe_key_value",
")",
"# Here is a list of property where we will expand the $KEY$ by the value",
"_the_expandables",
"=",
"[",
"'check_command'",
",",
"'aggregation'",
",",
"'event_handler'",
"]",
"for",
"prop",
"in",
"_the_expandables",
":",
"if",
"hasattr",
"(",
"self",
",",
"prop",
")",
":",
"# here we can replace VALUE, VALUE1, VALUE2,...",
"setattr",
"(",
"new_s",
",",
"prop",
",",
"getattr",
"(",
"new_s",
",",
"prop",
")",
".",
"replace",
"(",
"'$'",
"+",
"key",
"+",
"'$'",
",",
"key_value",
"[",
"key",
"]",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'service_dependencies'",
")",
":",
"for",
"i",
",",
"servicedep",
"in",
"enumerate",
"(",
"new_s",
".",
"service_dependencies",
")",
":",
"new_s",
".",
"service_dependencies",
"[",
"i",
"]",
"=",
"servicedep",
".",
"replace",
"(",
"'$'",
"+",
"key",
"+",
"'$'",
",",
"key_value",
"[",
"key",
"]",
")",
"# And then add in our list this new service",
"duplicates",
".",
"append",
"(",
"new_s",
")",
"return",
"duplicates"
] |
For a given host, look for all copy we must create for for_each property
:param host: alignak host object
:type host: alignak.objects.host.Host
:return: list
:rtype: list
|
[
"For",
"a",
"given",
"host",
"look",
"for",
"all",
"copy",
"we",
"must",
"create",
"for",
"for_each",
"property"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L457-L537
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.set_state_from_exit_status
|
def set_state_from_exit_status(self, status, notif_period, hosts, services):
"""Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE
according to the status of a check result.
:param status: integer between 0 and 4
:type status: int
:return: None
"""
now = time.time()
# we should put in last_state the good last state:
# if not just change the state by an problem/impact
# we can take current state. But if it's the case, the
# real old state is self.state_before_impact (it's the TRUE
# state in fact)
# but only if the global conf have enable the impact state change
cls = self.__class__
if cls.enable_problem_impacts_states_change \
and self.is_impact \
and not self.state_changed_since_impact:
self.last_state = self.state_before_impact
else: # standard case
self.last_state = self.state
# The last times are kept as integer values rather than float... no need for ms!
if status == 0:
self.state = u'OK'
self.state_id = 0
self.last_time_ok = int(self.last_state_update)
# self.last_time_ok = self.last_state_update
state_code = 'o'
elif status == 1:
self.state = u'WARNING'
self.state_id = 1
self.last_time_warning = int(self.last_state_update)
# self.last_time_warning = self.last_state_update
state_code = 'w'
elif status == 2:
self.state = u'CRITICAL'
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
elif status == 3:
self.state = u'UNKNOWN'
self.state_id = 3
self.last_time_unknown = int(self.last_state_update)
# self.last_time_unknown = self.last_state_update
state_code = 'u'
elif status == 4:
self.state = u'UNREACHABLE'
self.state_id = 4
self.last_time_unreachable = int(self.last_state_update)
# self.last_time_unreachable = self.last_state_update
state_code = 'x'
else:
self.state = u'CRITICAL' # exit code UNDETERMINED
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
if state_code in self.flap_detection_options:
self.add_flapping_change(self.state != self.last_state)
# Now we add a value, we update the is_flapping prop
self.update_flapping(notif_period, hosts, services)
if self.state != self.last_state:
self.last_state_change = self.last_state_update
self.duration_sec = now - self.last_state_change
|
python
|
def set_state_from_exit_status(self, status, notif_period, hosts, services):
"""Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE
according to the status of a check result.
:param status: integer between 0 and 4
:type status: int
:return: None
"""
now = time.time()
# we should put in last_state the good last state:
# if not just change the state by an problem/impact
# we can take current state. But if it's the case, the
# real old state is self.state_before_impact (it's the TRUE
# state in fact)
# but only if the global conf have enable the impact state change
cls = self.__class__
if cls.enable_problem_impacts_states_change \
and self.is_impact \
and not self.state_changed_since_impact:
self.last_state = self.state_before_impact
else: # standard case
self.last_state = self.state
# The last times are kept as integer values rather than float... no need for ms!
if status == 0:
self.state = u'OK'
self.state_id = 0
self.last_time_ok = int(self.last_state_update)
# self.last_time_ok = self.last_state_update
state_code = 'o'
elif status == 1:
self.state = u'WARNING'
self.state_id = 1
self.last_time_warning = int(self.last_state_update)
# self.last_time_warning = self.last_state_update
state_code = 'w'
elif status == 2:
self.state = u'CRITICAL'
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
elif status == 3:
self.state = u'UNKNOWN'
self.state_id = 3
self.last_time_unknown = int(self.last_state_update)
# self.last_time_unknown = self.last_state_update
state_code = 'u'
elif status == 4:
self.state = u'UNREACHABLE'
self.state_id = 4
self.last_time_unreachable = int(self.last_state_update)
# self.last_time_unreachable = self.last_state_update
state_code = 'x'
else:
self.state = u'CRITICAL' # exit code UNDETERMINED
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
if state_code in self.flap_detection_options:
self.add_flapping_change(self.state != self.last_state)
# Now we add a value, we update the is_flapping prop
self.update_flapping(notif_period, hosts, services)
if self.state != self.last_state:
self.last_state_change = self.last_state_update
self.duration_sec = now - self.last_state_change
|
[
"def",
"set_state_from_exit_status",
"(",
"self",
",",
"status",
",",
"notif_period",
",",
"hosts",
",",
"services",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# we should put in last_state the good last state:",
"# if not just change the state by an problem/impact",
"# we can take current state. But if it's the case, the",
"# real old state is self.state_before_impact (it's the TRUE",
"# state in fact)",
"# but only if the global conf have enable the impact state change",
"cls",
"=",
"self",
".",
"__class__",
"if",
"cls",
".",
"enable_problem_impacts_states_change",
"and",
"self",
".",
"is_impact",
"and",
"not",
"self",
".",
"state_changed_since_impact",
":",
"self",
".",
"last_state",
"=",
"self",
".",
"state_before_impact",
"else",
":",
"# standard case",
"self",
".",
"last_state",
"=",
"self",
".",
"state",
"# The last times are kept as integer values rather than float... no need for ms!",
"if",
"status",
"==",
"0",
":",
"self",
".",
"state",
"=",
"u'OK'",
"self",
".",
"state_id",
"=",
"0",
"self",
".",
"last_time_ok",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_ok = self.last_state_update",
"state_code",
"=",
"'o'",
"elif",
"status",
"==",
"1",
":",
"self",
".",
"state",
"=",
"u'WARNING'",
"self",
".",
"state_id",
"=",
"1",
"self",
".",
"last_time_warning",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_warning = self.last_state_update",
"state_code",
"=",
"'w'",
"elif",
"status",
"==",
"2",
":",
"self",
".",
"state",
"=",
"u'CRITICAL'",
"self",
".",
"state_id",
"=",
"2",
"self",
".",
"last_time_critical",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_critical = self.last_state_update",
"state_code",
"=",
"'c'",
"elif",
"status",
"==",
"3",
":",
"self",
".",
"state",
"=",
"u'UNKNOWN'",
"self",
".",
"state_id",
"=",
"3",
"self",
".",
"last_time_unknown",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_unknown = self.last_state_update",
"state_code",
"=",
"'u'",
"elif",
"status",
"==",
"4",
":",
"self",
".",
"state",
"=",
"u'UNREACHABLE'",
"self",
".",
"state_id",
"=",
"4",
"self",
".",
"last_time_unreachable",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_unreachable = self.last_state_update",
"state_code",
"=",
"'x'",
"else",
":",
"self",
".",
"state",
"=",
"u'CRITICAL'",
"# exit code UNDETERMINED",
"self",
".",
"state_id",
"=",
"2",
"self",
".",
"last_time_critical",
"=",
"int",
"(",
"self",
".",
"last_state_update",
")",
"# self.last_time_critical = self.last_state_update",
"state_code",
"=",
"'c'",
"if",
"state_code",
"in",
"self",
".",
"flap_detection_options",
":",
"self",
".",
"add_flapping_change",
"(",
"self",
".",
"state",
"!=",
"self",
".",
"last_state",
")",
"# Now we add a value, we update the is_flapping prop",
"self",
".",
"update_flapping",
"(",
"notif_period",
",",
"hosts",
",",
"services",
")",
"if",
"self",
".",
"state",
"!=",
"self",
".",
"last_state",
":",
"self",
".",
"last_state_change",
"=",
"self",
".",
"last_state_update",
"self",
".",
"duration_sec",
"=",
"now",
"-",
"self",
".",
"last_state_change"
] |
Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE
according to the status of a check result.
:param status: integer between 0 and 4
:type status: int
:return: None
|
[
"Set",
"the",
"state",
"in",
"UP",
"WARNING",
"CRITICAL",
"UNKNOWN",
"or",
"UNREACHABLE",
"according",
"to",
"the",
"status",
"of",
"a",
"check",
"result",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L550-L619
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.is_state
|
def is_state(self, status):
# pylint: disable=too-many-return-statements
"""Return True if status match the current service status
:param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files
:type status: str
:return: True if status <=> self.status, otherwise False
:rtype: bool
"""
if status == self.state:
return True
# Now low status
if status == 'o' and self.state == u'OK':
return True
if status == 'c' and self.state == u'CRITICAL':
return True
if status == 'w' and self.state == u'WARNING':
return True
if status == 'u' and self.state == u'UNKNOWN':
return True
if status == 'x' and self.state == u'UNREACHABLE':
return True
return False
|
python
|
def is_state(self, status):
# pylint: disable=too-many-return-statements
"""Return True if status match the current service status
:param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files
:type status: str
:return: True if status <=> self.status, otherwise False
:rtype: bool
"""
if status == self.state:
return True
# Now low status
if status == 'o' and self.state == u'OK':
return True
if status == 'c' and self.state == u'CRITICAL':
return True
if status == 'w' and self.state == u'WARNING':
return True
if status == 'u' and self.state == u'UNKNOWN':
return True
if status == 'x' and self.state == u'UNREACHABLE':
return True
return False
|
[
"def",
"is_state",
"(",
"self",
",",
"status",
")",
":",
"# pylint: disable=too-many-return-statements",
"if",
"status",
"==",
"self",
".",
"state",
":",
"return",
"True",
"# Now low status",
"if",
"status",
"==",
"'o'",
"and",
"self",
".",
"state",
"==",
"u'OK'",
":",
"return",
"True",
"if",
"status",
"==",
"'c'",
"and",
"self",
".",
"state",
"==",
"u'CRITICAL'",
":",
"return",
"True",
"if",
"status",
"==",
"'w'",
"and",
"self",
".",
"state",
"==",
"u'WARNING'",
":",
"return",
"True",
"if",
"status",
"==",
"'u'",
"and",
"self",
".",
"state",
"==",
"u'UNKNOWN'",
":",
"return",
"True",
"if",
"status",
"==",
"'x'",
"and",
"self",
".",
"state",
"==",
"u'UNREACHABLE'",
":",
"return",
"True",
"return",
"False"
] |
Return True if status match the current service status
:param status: status to compare ( "o", "c", "w", "u", "x"). Usually comes from config files
:type status: str
:return: True if status <=> self.status, otherwise False
:rtype: bool
|
[
"Return",
"True",
"if",
"status",
"match",
"the",
"current",
"service",
"status"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L621-L643
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.last_time_non_ok_or_up
|
def last_time_non_ok_or_up(self):
"""Get the last time the service was in a non-OK state
:return: the nearest last time the service was not ok
:rtype: int
"""
non_ok_times = [x for x in [self.last_time_warning,
self.last_time_critical,
self.last_time_unknown]
if x > self.last_time_ok]
if not non_ok_times:
last_time_non_ok = 0 # todo: program_start would be better?
else:
last_time_non_ok = min(non_ok_times)
return last_time_non_ok
|
python
|
def last_time_non_ok_or_up(self):
"""Get the last time the service was in a non-OK state
:return: the nearest last time the service was not ok
:rtype: int
"""
non_ok_times = [x for x in [self.last_time_warning,
self.last_time_critical,
self.last_time_unknown]
if x > self.last_time_ok]
if not non_ok_times:
last_time_non_ok = 0 # todo: program_start would be better?
else:
last_time_non_ok = min(non_ok_times)
return last_time_non_ok
|
[
"def",
"last_time_non_ok_or_up",
"(",
"self",
")",
":",
"non_ok_times",
"=",
"[",
"x",
"for",
"x",
"in",
"[",
"self",
".",
"last_time_warning",
",",
"self",
".",
"last_time_critical",
",",
"self",
".",
"last_time_unknown",
"]",
"if",
"x",
">",
"self",
".",
"last_time_ok",
"]",
"if",
"not",
"non_ok_times",
":",
"last_time_non_ok",
"=",
"0",
"# todo: program_start would be better?",
"else",
":",
"last_time_non_ok",
"=",
"min",
"(",
"non_ok_times",
")",
"return",
"last_time_non_ok"
] |
Get the last time the service was in a non-OK state
:return: the nearest last time the service was not ok
:rtype: int
|
[
"Get",
"the",
"last",
"time",
"the",
"service",
"was",
"in",
"a",
"non",
"-",
"OK",
"state"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L645-L659
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.get_data_for_notifications
|
def get_data_for_notifications(self, contact, notif, host_ref):
"""Get data for a notification
:param contact: The contact to return
:type contact:
:param notif: the notification to return
:type notif:
:return: list containing the service, the host and the given parameters
:rtype: list
"""
if not host_ref:
return [self, contact, notif]
return [host_ref, self, contact, notif]
|
python
|
def get_data_for_notifications(self, contact, notif, host_ref):
"""Get data for a notification
:param contact: The contact to return
:type contact:
:param notif: the notification to return
:type notif:
:return: list containing the service, the host and the given parameters
:rtype: list
"""
if not host_ref:
return [self, contact, notif]
return [host_ref, self, contact, notif]
|
[
"def",
"get_data_for_notifications",
"(",
"self",
",",
"contact",
",",
"notif",
",",
"host_ref",
")",
":",
"if",
"not",
"host_ref",
":",
"return",
"[",
"self",
",",
"contact",
",",
"notif",
"]",
"return",
"[",
"host_ref",
",",
"self",
",",
"contact",
",",
"notif",
"]"
] |
Get data for a notification
:param contact: The contact to return
:type contact:
:param notif: the notification to return
:type notif:
:return: list containing the service, the host and the given parameters
:rtype: list
|
[
"Get",
"data",
"for",
"a",
"notification"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1028-L1040
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Service.get_short_status
|
def get_short_status(self, hosts, services):
"""Get the short status of this host
:return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state
:rtype: str
"""
mapping = {
0: "O",
1: "W",
2: "C",
3: "U",
4: "N",
}
if self.got_business_rule:
return mapping.get(self.business_rule.get_state(hosts, services), "n/a")
return mapping.get(self.state_id, "n/a")
|
python
|
def get_short_status(self, hosts, services):
"""Get the short status of this host
:return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state
:rtype: str
"""
mapping = {
0: "O",
1: "W",
2: "C",
3: "U",
4: "N",
}
if self.got_business_rule:
return mapping.get(self.business_rule.get_state(hosts, services), "n/a")
return mapping.get(self.state_id, "n/a")
|
[
"def",
"get_short_status",
"(",
"self",
",",
"hosts",
",",
"services",
")",
":",
"mapping",
"=",
"{",
"0",
":",
"\"O\"",
",",
"1",
":",
"\"W\"",
",",
"2",
":",
"\"C\"",
",",
"3",
":",
"\"U\"",
",",
"4",
":",
"\"N\"",
",",
"}",
"if",
"self",
".",
"got_business_rule",
":",
"return",
"mapping",
".",
"get",
"(",
"self",
".",
"business_rule",
".",
"get_state",
"(",
"hosts",
",",
"services",
")",
",",
"\"n/a\"",
")",
"return",
"mapping",
".",
"get",
"(",
"self",
".",
"state_id",
",",
"\"n/a\"",
")"
] |
Get the short status of this host
:return: "O", "W", "C", "U', or "n/a" based on service state_id or business_rule state
:rtype: str
|
[
"Get",
"the",
"short",
"status",
"of",
"this",
"host"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1257-L1273
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.add_template
|
def add_template(self, tpl):
"""
Adds and index a template into the `templates` container.
This implementation takes into account that a service has two naming
attribute: `host_name` and `service_description`.
:param tpl: The template to add
:type tpl:
:return: None
"""
objcls = self.inner_class.my_type
name = getattr(tpl, 'name', '')
sdesc = getattr(tpl, 'service_description', '')
hname = getattr(tpl, 'host_name', '')
logger.debug("Adding a %s template: host_name: %s, name: %s, service_description: %s",
objcls, hname, name, sdesc)
if not name and not hname:
msg = "a %s template has been defined without name nor host_name. from: %s" \
% (objcls, tpl.imported_from)
tpl.add_error(msg)
elif not name and not sdesc:
msg = "a %s template has been defined without name nor service_description. from: %s" \
% (objcls, tpl.imported_from)
tpl.add_error(msg)
elif not name:
# If name is not defined, use the host_name_service_description as name (fix #791)
setattr(tpl, 'name', "%s_%s" % (hname, sdesc))
tpl = self.index_template(tpl)
elif name:
tpl = self.index_template(tpl)
self.templates[tpl.uuid] = tpl
logger.debug('\tAdded service template #%d %s', len(self.templates), tpl)
|
python
|
def add_template(self, tpl):
"""
Adds and index a template into the `templates` container.
This implementation takes into account that a service has two naming
attribute: `host_name` and `service_description`.
:param tpl: The template to add
:type tpl:
:return: None
"""
objcls = self.inner_class.my_type
name = getattr(tpl, 'name', '')
sdesc = getattr(tpl, 'service_description', '')
hname = getattr(tpl, 'host_name', '')
logger.debug("Adding a %s template: host_name: %s, name: %s, service_description: %s",
objcls, hname, name, sdesc)
if not name and not hname:
msg = "a %s template has been defined without name nor host_name. from: %s" \
% (objcls, tpl.imported_from)
tpl.add_error(msg)
elif not name and not sdesc:
msg = "a %s template has been defined without name nor service_description. from: %s" \
% (objcls, tpl.imported_from)
tpl.add_error(msg)
elif not name:
# If name is not defined, use the host_name_service_description as name (fix #791)
setattr(tpl, 'name', "%s_%s" % (hname, sdesc))
tpl = self.index_template(tpl)
elif name:
tpl = self.index_template(tpl)
self.templates[tpl.uuid] = tpl
logger.debug('\tAdded service template #%d %s', len(self.templates), tpl)
|
[
"def",
"add_template",
"(",
"self",
",",
"tpl",
")",
":",
"objcls",
"=",
"self",
".",
"inner_class",
".",
"my_type",
"name",
"=",
"getattr",
"(",
"tpl",
",",
"'name'",
",",
"''",
")",
"sdesc",
"=",
"getattr",
"(",
"tpl",
",",
"'service_description'",
",",
"''",
")",
"hname",
"=",
"getattr",
"(",
"tpl",
",",
"'host_name'",
",",
"''",
")",
"logger",
".",
"debug",
"(",
"\"Adding a %s template: host_name: %s, name: %s, service_description: %s\"",
",",
"objcls",
",",
"hname",
",",
"name",
",",
"sdesc",
")",
"if",
"not",
"name",
"and",
"not",
"hname",
":",
"msg",
"=",
"\"a %s template has been defined without name nor host_name. from: %s\"",
"%",
"(",
"objcls",
",",
"tpl",
".",
"imported_from",
")",
"tpl",
".",
"add_error",
"(",
"msg",
")",
"elif",
"not",
"name",
"and",
"not",
"sdesc",
":",
"msg",
"=",
"\"a %s template has been defined without name nor service_description. from: %s\"",
"%",
"(",
"objcls",
",",
"tpl",
".",
"imported_from",
")",
"tpl",
".",
"add_error",
"(",
"msg",
")",
"elif",
"not",
"name",
":",
"# If name is not defined, use the host_name_service_description as name (fix #791)",
"setattr",
"(",
"tpl",
",",
"'name'",
",",
"\"%s_%s\"",
"%",
"(",
"hname",
",",
"sdesc",
")",
")",
"tpl",
"=",
"self",
".",
"index_template",
"(",
"tpl",
")",
"elif",
"name",
":",
"tpl",
"=",
"self",
".",
"index_template",
"(",
"tpl",
")",
"self",
".",
"templates",
"[",
"tpl",
".",
"uuid",
"]",
"=",
"tpl",
"logger",
".",
"debug",
"(",
"'\\tAdded service template #%d %s'",
",",
"len",
"(",
"self",
".",
"templates",
")",
",",
"tpl",
")"
] |
Adds and index a template into the `templates` container.
This implementation takes into account that a service has two naming
attribute: `host_name` and `service_description`.
:param tpl: The template to add
:type tpl:
:return: None
|
[
"Adds",
"and",
"index",
"a",
"template",
"into",
"the",
"templates",
"container",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1312-L1344
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.find_srvs_by_hostname
|
def find_srvs_by_hostname(self, host_name):
"""Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
"""
if hasattr(self, 'hosts'):
host = self.hosts.find_by_name(host_name)
if host is None:
return None
return host.get_services()
return None
|
python
|
def find_srvs_by_hostname(self, host_name):
"""Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
"""
if hasattr(self, 'hosts'):
host = self.hosts.find_by_name(host_name)
if host is None:
return None
return host.get_services()
return None
|
[
"def",
"find_srvs_by_hostname",
"(",
"self",
",",
"host_name",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'hosts'",
")",
":",
"host",
"=",
"self",
".",
"hosts",
".",
"find_by_name",
"(",
"host_name",
")",
"if",
"host",
"is",
"None",
":",
"return",
"None",
"return",
"host",
".",
"get_services",
"(",
")",
"return",
"None"
] |
Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
|
[
"Get",
"all",
"services",
"from",
"a",
"host",
"based",
"on",
"a",
"host_name"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1358-L1371
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.find_srv_by_name_and_hostname
|
def find_srv_by_name_and_hostname(self, host_name, sdescr):
"""Get a specific service based on a host_name and service_description
:param host_name: host name linked to needed service
:type host_name: str
:param sdescr: service name we need
:type sdescr: str
:return: the service found or None
:rtype: alignak.objects.service.Service
"""
key = (host_name, sdescr)
return self.name_to_item.get(key, None)
|
python
|
def find_srv_by_name_and_hostname(self, host_name, sdescr):
"""Get a specific service based on a host_name and service_description
:param host_name: host name linked to needed service
:type host_name: str
:param sdescr: service name we need
:type sdescr: str
:return: the service found or None
:rtype: alignak.objects.service.Service
"""
key = (host_name, sdescr)
return self.name_to_item.get(key, None)
|
[
"def",
"find_srv_by_name_and_hostname",
"(",
"self",
",",
"host_name",
",",
"sdescr",
")",
":",
"key",
"=",
"(",
"host_name",
",",
"sdescr",
")",
"return",
"self",
".",
"name_to_item",
".",
"get",
"(",
"key",
",",
"None",
")"
] |
Get a specific service based on a host_name and service_description
:param host_name: host name linked to needed service
:type host_name: str
:param sdescr: service name we need
:type sdescr: str
:return: the service found or None
:rtype: alignak.objects.service.Service
|
[
"Get",
"a",
"specific",
"service",
"based",
"on",
"a",
"host_name",
"and",
"service_description"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1373-L1384
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.linkify_s_by_hst
|
def linkify_s_by_hst(self, hosts):
"""Link services with their parent host
:param hosts: Hosts to look for simple host
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for serv in self:
# If we do not have a host_name, we set it as
# a template element to delete. (like Nagios)
if not hasattr(serv, 'host_name'):
serv.host = None
continue
try:
hst_name = serv.host_name
# The new member list, in id
hst = hosts.find_by_name(hst_name)
# Let the host know we are his service
if hst is not None:
serv.host = hst.uuid
hst.add_service_link(serv.uuid)
else: # Ok, the host do not exists!
err = "Warning: the service '%s' got an invalid host_name '%s'" % \
(serv.get_name(), hst_name)
serv.configuration_warnings.append(err)
continue
except AttributeError:
pass
|
python
|
def linkify_s_by_hst(self, hosts):
"""Link services with their parent host
:param hosts: Hosts to look for simple host
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for serv in self:
# If we do not have a host_name, we set it as
# a template element to delete. (like Nagios)
if not hasattr(serv, 'host_name'):
serv.host = None
continue
try:
hst_name = serv.host_name
# The new member list, in id
hst = hosts.find_by_name(hst_name)
# Let the host know we are his service
if hst is not None:
serv.host = hst.uuid
hst.add_service_link(serv.uuid)
else: # Ok, the host do not exists!
err = "Warning: the service '%s' got an invalid host_name '%s'" % \
(serv.get_name(), hst_name)
serv.configuration_warnings.append(err)
continue
except AttributeError:
pass
|
[
"def",
"linkify_s_by_hst",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"serv",
"in",
"self",
":",
"# If we do not have a host_name, we set it as",
"# a template element to delete. (like Nagios)",
"if",
"not",
"hasattr",
"(",
"serv",
",",
"'host_name'",
")",
":",
"serv",
".",
"host",
"=",
"None",
"continue",
"try",
":",
"hst_name",
"=",
"serv",
".",
"host_name",
"# The new member list, in id",
"hst",
"=",
"hosts",
".",
"find_by_name",
"(",
"hst_name",
")",
"# Let the host know we are his service",
"if",
"hst",
"is",
"not",
"None",
":",
"serv",
".",
"host",
"=",
"hst",
".",
"uuid",
"hst",
".",
"add_service_link",
"(",
"serv",
".",
"uuid",
")",
"else",
":",
"# Ok, the host do not exists!",
"err",
"=",
"\"Warning: the service '%s' got an invalid host_name '%s'\"",
"%",
"(",
"serv",
".",
"get_name",
"(",
")",
",",
"hst_name",
")",
"serv",
".",
"configuration_warnings",
".",
"append",
"(",
"err",
")",
"continue",
"except",
"AttributeError",
":",
"pass"
] |
Link services with their parent host
:param hosts: Hosts to look for simple host
:type hosts: alignak.objects.host.Hosts
:return: None
|
[
"Link",
"services",
"with",
"their",
"parent",
"host"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1487-L1514
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.linkify_s_by_sg
|
def linkify_s_by_sg(self, servicegroups):
"""Link services with servicegroups
:param servicegroups: Servicegroups
:type servicegroups: alignak.objects.servicegroup.Servicegroups
:return: None
"""
for serv in self:
new_servicegroups = []
if hasattr(serv, 'servicegroups') and serv.servicegroups != '':
for sg_name in serv.servicegroups:
sg_name = sg_name.strip()
servicegroup = servicegroups.find_by_name(sg_name)
if servicegroup is not None:
new_servicegroups.append(servicegroup.uuid)
else:
err = "Error: the servicegroup '%s' of the service '%s' is unknown" %\
(sg_name, serv.get_dbg_name())
serv.add_error(err)
serv.servicegroups = new_servicegroups
|
python
|
def linkify_s_by_sg(self, servicegroups):
"""Link services with servicegroups
:param servicegroups: Servicegroups
:type servicegroups: alignak.objects.servicegroup.Servicegroups
:return: None
"""
for serv in self:
new_servicegroups = []
if hasattr(serv, 'servicegroups') and serv.servicegroups != '':
for sg_name in serv.servicegroups:
sg_name = sg_name.strip()
servicegroup = servicegroups.find_by_name(sg_name)
if servicegroup is not None:
new_servicegroups.append(servicegroup.uuid)
else:
err = "Error: the servicegroup '%s' of the service '%s' is unknown" %\
(sg_name, serv.get_dbg_name())
serv.add_error(err)
serv.servicegroups = new_servicegroups
|
[
"def",
"linkify_s_by_sg",
"(",
"self",
",",
"servicegroups",
")",
":",
"for",
"serv",
"in",
"self",
":",
"new_servicegroups",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"serv",
",",
"'servicegroups'",
")",
"and",
"serv",
".",
"servicegroups",
"!=",
"''",
":",
"for",
"sg_name",
"in",
"serv",
".",
"servicegroups",
":",
"sg_name",
"=",
"sg_name",
".",
"strip",
"(",
")",
"servicegroup",
"=",
"servicegroups",
".",
"find_by_name",
"(",
"sg_name",
")",
"if",
"servicegroup",
"is",
"not",
"None",
":",
"new_servicegroups",
".",
"append",
"(",
"servicegroup",
".",
"uuid",
")",
"else",
":",
"err",
"=",
"\"Error: the servicegroup '%s' of the service '%s' is unknown\"",
"%",
"(",
"sg_name",
",",
"serv",
".",
"get_dbg_name",
"(",
")",
")",
"serv",
".",
"add_error",
"(",
"err",
")",
"serv",
".",
"servicegroups",
"=",
"new_servicegroups"
] |
Link services with servicegroups
:param servicegroups: Servicegroups
:type servicegroups: alignak.objects.servicegroup.Servicegroups
:return: None
|
[
"Link",
"services",
"with",
"servicegroups"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1516-L1535
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.clean
|
def clean(self):
"""Remove services without host object linked to
Note that this should not happen!
:return: None
"""
to_del = []
for serv in self:
if not serv.host:
to_del.append(serv.uuid)
for service_uuid in to_del:
del self.items[service_uuid]
|
python
|
def clean(self):
"""Remove services without host object linked to
Note that this should not happen!
:return: None
"""
to_del = []
for serv in self:
if not serv.host:
to_del.append(serv.uuid)
for service_uuid in to_del:
del self.items[service_uuid]
|
[
"def",
"clean",
"(",
"self",
")",
":",
"to_del",
"=",
"[",
"]",
"for",
"serv",
"in",
"self",
":",
"if",
"not",
"serv",
".",
"host",
":",
"to_del",
".",
"append",
"(",
"serv",
".",
"uuid",
")",
"for",
"service_uuid",
"in",
"to_del",
":",
"del",
"self",
".",
"items",
"[",
"service_uuid",
"]"
] |
Remove services without host object linked to
Note that this should not happen!
:return: None
|
[
"Remove",
"services",
"without",
"host",
"object",
"linked",
"to"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1586-L1598
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.explode_services_from_hosts
|
def explode_services_from_hosts(self, hosts, service, hnames):
"""
Explodes a service based on a list of hosts.
:param hosts: The hosts container
:type hosts:
:param service: The base service to explode
:type service:
:param hnames: The host_name list to explode service on
:type hnames: str
:return: None
"""
duplicate_for_hosts = [] # get the list of our host_names if more than 1
not_hosts = [] # the list of !host_name so we remove them after
for hname in hnames:
hname = hname.strip()
# If the name begin with a !, we put it in
# the not list
if hname.startswith('!'):
not_hosts.append(hname[1:])
else: # the standard list
duplicate_for_hosts.append(hname)
# remove duplicate items from duplicate_for_hosts:
duplicate_for_hosts = list(set(duplicate_for_hosts))
# Ok now we clean the duplicate_for_hosts with all hosts
# of the not
for hname in not_hosts:
try:
duplicate_for_hosts.remove(hname)
except IndexError:
pass
# Now we duplicate the service for all host_names
for hname in duplicate_for_hosts:
host = hosts.find_by_name(hname)
if host is None:
service.add_error("Error: The hostname %s is unknown for the service %s!"
% (hname, service.get_name()))
continue
if host.is_excluded_for(service):
continue
new_s = service.copy()
new_s.host_name = hname
self.add_item(new_s)
|
python
|
def explode_services_from_hosts(self, hosts, service, hnames):
"""
Explodes a service based on a list of hosts.
:param hosts: The hosts container
:type hosts:
:param service: The base service to explode
:type service:
:param hnames: The host_name list to explode service on
:type hnames: str
:return: None
"""
duplicate_for_hosts = [] # get the list of our host_names if more than 1
not_hosts = [] # the list of !host_name so we remove them after
for hname in hnames:
hname = hname.strip()
# If the name begin with a !, we put it in
# the not list
if hname.startswith('!'):
not_hosts.append(hname[1:])
else: # the standard list
duplicate_for_hosts.append(hname)
# remove duplicate items from duplicate_for_hosts:
duplicate_for_hosts = list(set(duplicate_for_hosts))
# Ok now we clean the duplicate_for_hosts with all hosts
# of the not
for hname in not_hosts:
try:
duplicate_for_hosts.remove(hname)
except IndexError:
pass
# Now we duplicate the service for all host_names
for hname in duplicate_for_hosts:
host = hosts.find_by_name(hname)
if host is None:
service.add_error("Error: The hostname %s is unknown for the service %s!"
% (hname, service.get_name()))
continue
if host.is_excluded_for(service):
continue
new_s = service.copy()
new_s.host_name = hname
self.add_item(new_s)
|
[
"def",
"explode_services_from_hosts",
"(",
"self",
",",
"hosts",
",",
"service",
",",
"hnames",
")",
":",
"duplicate_for_hosts",
"=",
"[",
"]",
"# get the list of our host_names if more than 1",
"not_hosts",
"=",
"[",
"]",
"# the list of !host_name so we remove them after",
"for",
"hname",
"in",
"hnames",
":",
"hname",
"=",
"hname",
".",
"strip",
"(",
")",
"# If the name begin with a !, we put it in",
"# the not list",
"if",
"hname",
".",
"startswith",
"(",
"'!'",
")",
":",
"not_hosts",
".",
"append",
"(",
"hname",
"[",
"1",
":",
"]",
")",
"else",
":",
"# the standard list",
"duplicate_for_hosts",
".",
"append",
"(",
"hname",
")",
"# remove duplicate items from duplicate_for_hosts:",
"duplicate_for_hosts",
"=",
"list",
"(",
"set",
"(",
"duplicate_for_hosts",
")",
")",
"# Ok now we clean the duplicate_for_hosts with all hosts",
"# of the not",
"for",
"hname",
"in",
"not_hosts",
":",
"try",
":",
"duplicate_for_hosts",
".",
"remove",
"(",
"hname",
")",
"except",
"IndexError",
":",
"pass",
"# Now we duplicate the service for all host_names",
"for",
"hname",
"in",
"duplicate_for_hosts",
":",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"hname",
")",
"if",
"host",
"is",
"None",
":",
"service",
".",
"add_error",
"(",
"\"Error: The hostname %s is unknown for the service %s!\"",
"%",
"(",
"hname",
",",
"service",
".",
"get_name",
"(",
")",
")",
")",
"continue",
"if",
"host",
".",
"is_excluded_for",
"(",
"service",
")",
":",
"continue",
"new_s",
"=",
"service",
".",
"copy",
"(",
")",
"new_s",
".",
"host_name",
"=",
"hname",
"self",
".",
"add_item",
"(",
"new_s",
")"
] |
Explodes a service based on a list of hosts.
:param hosts: The hosts container
:type hosts:
:param service: The base service to explode
:type service:
:param hnames: The host_name list to explode service on
:type hnames: str
:return: None
|
[
"Explodes",
"a",
"service",
"based",
"on",
"a",
"list",
"of",
"hosts",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1600-L1646
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services._local_create_service
|
def _local_create_service(self, hosts, host_name, service):
"""Create a new service based on a host_name and service instance.
:param hosts: The hosts items instance.
:type hosts: alignak.objects.host.Hosts
:param host_name: The host_name to create a new service.
:type host_name: str
:param service: The service to be used as template.
:type service: Service
:return: The new service created.
:rtype: alignak.objects.service.Service
"""
host = hosts.find_by_name(host_name.strip())
if host.is_excluded_for(service):
return None
# Creates a real service instance from the template
new_s = service.copy()
new_s.host_name = host_name
new_s.register = 1
self.add_item(new_s)
return new_s
|
python
|
def _local_create_service(self, hosts, host_name, service):
"""Create a new service based on a host_name and service instance.
:param hosts: The hosts items instance.
:type hosts: alignak.objects.host.Hosts
:param host_name: The host_name to create a new service.
:type host_name: str
:param service: The service to be used as template.
:type service: Service
:return: The new service created.
:rtype: alignak.objects.service.Service
"""
host = hosts.find_by_name(host_name.strip())
if host.is_excluded_for(service):
return None
# Creates a real service instance from the template
new_s = service.copy()
new_s.host_name = host_name
new_s.register = 1
self.add_item(new_s)
return new_s
|
[
"def",
"_local_create_service",
"(",
"self",
",",
"hosts",
",",
"host_name",
",",
"service",
")",
":",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"host_name",
".",
"strip",
"(",
")",
")",
"if",
"host",
".",
"is_excluded_for",
"(",
"service",
")",
":",
"return",
"None",
"# Creates a real service instance from the template",
"new_s",
"=",
"service",
".",
"copy",
"(",
")",
"new_s",
".",
"host_name",
"=",
"host_name",
"new_s",
".",
"register",
"=",
"1",
"self",
".",
"add_item",
"(",
"new_s",
")",
"return",
"new_s"
] |
Create a new service based on a host_name and service instance.
:param hosts: The hosts items instance.
:type hosts: alignak.objects.host.Hosts
:param host_name: The host_name to create a new service.
:type host_name: str
:param service: The service to be used as template.
:type service: Service
:return: The new service created.
:rtype: alignak.objects.service.Service
|
[
"Create",
"a",
"new",
"service",
"based",
"on",
"a",
"host_name",
"and",
"service",
"instance",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1649-L1670
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.explode_services_from_templates
|
def explode_services_from_templates(self, hosts, service_template):
"""
Explodes services from templates. All hosts holding the specified
templates are bound with the service.
:param hosts: The hosts container.
:type hosts: alignak.objects.host.Hosts
:param service_template: The service to explode.
:type service_template: alignak.objects.service.Service
:return: None
"""
hname = getattr(service_template, "host_name", None)
if not hname:
logger.debug("Service template %s is declared without an host_name",
service_template.get_name())
return
logger.debug("Explode services %s for the host: %s", service_template.get_name(), hname)
# Now really create the services
if is_complex_expr(hname):
hnames = self.evaluate_hostgroup_expression(
hname.strip(), hosts, hosts.templates, look_in='templates')
for name in hnames:
self._local_create_service(hosts, name, service_template)
else:
hnames = [n.strip() for n in hname.split(',') if n.strip()]
for hname in hnames:
for name in hosts.find_hosts_that_use_template(hname):
self._local_create_service(hosts, name, service_template)
|
python
|
def explode_services_from_templates(self, hosts, service_template):
"""
Explodes services from templates. All hosts holding the specified
templates are bound with the service.
:param hosts: The hosts container.
:type hosts: alignak.objects.host.Hosts
:param service_template: The service to explode.
:type service_template: alignak.objects.service.Service
:return: None
"""
hname = getattr(service_template, "host_name", None)
if not hname:
logger.debug("Service template %s is declared without an host_name",
service_template.get_name())
return
logger.debug("Explode services %s for the host: %s", service_template.get_name(), hname)
# Now really create the services
if is_complex_expr(hname):
hnames = self.evaluate_hostgroup_expression(
hname.strip(), hosts, hosts.templates, look_in='templates')
for name in hnames:
self._local_create_service(hosts, name, service_template)
else:
hnames = [n.strip() for n in hname.split(',') if n.strip()]
for hname in hnames:
for name in hosts.find_hosts_that_use_template(hname):
self._local_create_service(hosts, name, service_template)
|
[
"def",
"explode_services_from_templates",
"(",
"self",
",",
"hosts",
",",
"service_template",
")",
":",
"hname",
"=",
"getattr",
"(",
"service_template",
",",
"\"host_name\"",
",",
"None",
")",
"if",
"not",
"hname",
":",
"logger",
".",
"debug",
"(",
"\"Service template %s is declared without an host_name\"",
",",
"service_template",
".",
"get_name",
"(",
")",
")",
"return",
"logger",
".",
"debug",
"(",
"\"Explode services %s for the host: %s\"",
",",
"service_template",
".",
"get_name",
"(",
")",
",",
"hname",
")",
"# Now really create the services",
"if",
"is_complex_expr",
"(",
"hname",
")",
":",
"hnames",
"=",
"self",
".",
"evaluate_hostgroup_expression",
"(",
"hname",
".",
"strip",
"(",
")",
",",
"hosts",
",",
"hosts",
".",
"templates",
",",
"look_in",
"=",
"'templates'",
")",
"for",
"name",
"in",
"hnames",
":",
"self",
".",
"_local_create_service",
"(",
"hosts",
",",
"name",
",",
"service_template",
")",
"else",
":",
"hnames",
"=",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"hname",
".",
"split",
"(",
"','",
")",
"if",
"n",
".",
"strip",
"(",
")",
"]",
"for",
"hname",
"in",
"hnames",
":",
"for",
"name",
"in",
"hosts",
".",
"find_hosts_that_use_template",
"(",
"hname",
")",
":",
"self",
".",
"_local_create_service",
"(",
"hosts",
",",
"name",
",",
"service_template",
")"
] |
Explodes services from templates. All hosts holding the specified
templates are bound with the service.
:param hosts: The hosts container.
:type hosts: alignak.objects.host.Hosts
:param service_template: The service to explode.
:type service_template: alignak.objects.service.Service
:return: None
|
[
"Explodes",
"services",
"from",
"templates",
".",
"All",
"hosts",
"holding",
"the",
"specified",
"templates",
"are",
"bound",
"with",
"the",
"service",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1672-L1701
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.explode_services_duplicates
|
def explode_services_duplicates(self, hosts, service):
"""
Explodes services holding a `duplicate_foreach` clause.
:param hosts: The hosts container
:type hosts: alignak.objects.host.Hosts
:param service: The service to explode
:type service: alignak.objects.service.Service
"""
hname = getattr(service, "host_name", None)
if hname is None:
return
# the generator case, we must create several new services
# we must find our host, and get all key:value we need
host = hosts.find_by_name(hname.strip())
if host is None:
service.add_error('Error: The hostname %s is unknown for the service %s!'
% (hname, service.get_name()))
return
# Duplicate services
for new_s in service.duplicate(host):
if host.is_excluded_for(new_s):
continue
# Adds concrete instance
self.add_item(new_s)
|
python
|
def explode_services_duplicates(self, hosts, service):
"""
Explodes services holding a `duplicate_foreach` clause.
:param hosts: The hosts container
:type hosts: alignak.objects.host.Hosts
:param service: The service to explode
:type service: alignak.objects.service.Service
"""
hname = getattr(service, "host_name", None)
if hname is None:
return
# the generator case, we must create several new services
# we must find our host, and get all key:value we need
host = hosts.find_by_name(hname.strip())
if host is None:
service.add_error('Error: The hostname %s is unknown for the service %s!'
% (hname, service.get_name()))
return
# Duplicate services
for new_s in service.duplicate(host):
if host.is_excluded_for(new_s):
continue
# Adds concrete instance
self.add_item(new_s)
|
[
"def",
"explode_services_duplicates",
"(",
"self",
",",
"hosts",
",",
"service",
")",
":",
"hname",
"=",
"getattr",
"(",
"service",
",",
"\"host_name\"",
",",
"None",
")",
"if",
"hname",
"is",
"None",
":",
"return",
"# the generator case, we must create several new services",
"# we must find our host, and get all key:value we need",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"hname",
".",
"strip",
"(",
")",
")",
"if",
"host",
"is",
"None",
":",
"service",
".",
"add_error",
"(",
"'Error: The hostname %s is unknown for the service %s!'",
"%",
"(",
"hname",
",",
"service",
".",
"get_name",
"(",
")",
")",
")",
"return",
"# Duplicate services",
"for",
"new_s",
"in",
"service",
".",
"duplicate",
"(",
"host",
")",
":",
"if",
"host",
".",
"is_excluded_for",
"(",
"new_s",
")",
":",
"continue",
"# Adds concrete instance",
"self",
".",
"add_item",
"(",
"new_s",
")"
] |
Explodes services holding a `duplicate_foreach` clause.
:param hosts: The hosts container
:type hosts: alignak.objects.host.Hosts
:param service: The service to explode
:type service: alignak.objects.service.Service
|
[
"Explodes",
"services",
"holding",
"a",
"duplicate_foreach",
"clause",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1703-L1729
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.register_service_into_servicegroups
|
def register_service_into_servicegroups(service, servicegroups):
"""
Registers a service into the service groups declared in its
`servicegroups` attribute.
:param service: The service to register
:type service:
:param servicegroups: The servicegroups container
:type servicegroups:
:return: None
"""
if hasattr(service, 'service_description'):
sname = service.service_description
shname = getattr(service, 'host_name', '')
if hasattr(service, 'servicegroups'):
# Todo: See if we can remove this if
if isinstance(service.servicegroups, list):
sgs = service.servicegroups
else:
sgs = service.servicegroups.split(',')
for servicegroup in sgs:
servicegroups.add_member([shname, sname], servicegroup.strip())
|
python
|
def register_service_into_servicegroups(service, servicegroups):
"""
Registers a service into the service groups declared in its
`servicegroups` attribute.
:param service: The service to register
:type service:
:param servicegroups: The servicegroups container
:type servicegroups:
:return: None
"""
if hasattr(service, 'service_description'):
sname = service.service_description
shname = getattr(service, 'host_name', '')
if hasattr(service, 'servicegroups'):
# Todo: See if we can remove this if
if isinstance(service.servicegroups, list):
sgs = service.servicegroups
else:
sgs = service.servicegroups.split(',')
for servicegroup in sgs:
servicegroups.add_member([shname, sname], servicegroup.strip())
|
[
"def",
"register_service_into_servicegroups",
"(",
"service",
",",
"servicegroups",
")",
":",
"if",
"hasattr",
"(",
"service",
",",
"'service_description'",
")",
":",
"sname",
"=",
"service",
".",
"service_description",
"shname",
"=",
"getattr",
"(",
"service",
",",
"'host_name'",
",",
"''",
")",
"if",
"hasattr",
"(",
"service",
",",
"'servicegroups'",
")",
":",
"# Todo: See if we can remove this if",
"if",
"isinstance",
"(",
"service",
".",
"servicegroups",
",",
"list",
")",
":",
"sgs",
"=",
"service",
".",
"servicegroups",
"else",
":",
"sgs",
"=",
"service",
".",
"servicegroups",
".",
"split",
"(",
"','",
")",
"for",
"servicegroup",
"in",
"sgs",
":",
"servicegroups",
".",
"add_member",
"(",
"[",
"shname",
",",
"sname",
"]",
",",
"servicegroup",
".",
"strip",
"(",
")",
")"
] |
Registers a service into the service groups declared in its
`servicegroups` attribute.
:param service: The service to register
:type service:
:param servicegroups: The servicegroups container
:type servicegroups:
:return: None
|
[
"Registers",
"a",
"service",
"into",
"the",
"service",
"groups",
"declared",
"in",
"its",
"servicegroups",
"attribute",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1732-L1753
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.register_service_dependencies
|
def register_service_dependencies(service, servicedependencies):
"""
Registers a service dependencies.
:param service: The service to register
:type service:
:param servicedependencies: The servicedependencies container
:type servicedependencies:
:return: None
"""
# We explode service_dependencies into Servicedependency
# We just create serviceDep with goods values (as STRING!),
# the link pass will be done after
sdeps = [d.strip() for d in getattr(service, "service_dependencies", [])]
# %2=0 are for hosts, !=0 are for service_description
i = 0
hname = ''
for elt in sdeps:
if i % 2 == 0: # host
hname = elt
else: # description
desc = elt
# we can register it (service) (depend on) -> (hname, desc)
# If we do not have enough data for service, it'service no use
if hasattr(service, 'service_description') and hasattr(service, 'host_name'):
if hname == '':
hname = service.host_name
servicedependencies.add_service_dependency(
service.host_name, service.service_description, hname, desc)
i += 1
|
python
|
def register_service_dependencies(service, servicedependencies):
"""
Registers a service dependencies.
:param service: The service to register
:type service:
:param servicedependencies: The servicedependencies container
:type servicedependencies:
:return: None
"""
# We explode service_dependencies into Servicedependency
# We just create serviceDep with goods values (as STRING!),
# the link pass will be done after
sdeps = [d.strip() for d in getattr(service, "service_dependencies", [])]
# %2=0 are for hosts, !=0 are for service_description
i = 0
hname = ''
for elt in sdeps:
if i % 2 == 0: # host
hname = elt
else: # description
desc = elt
# we can register it (service) (depend on) -> (hname, desc)
# If we do not have enough data for service, it'service no use
if hasattr(service, 'service_description') and hasattr(service, 'host_name'):
if hname == '':
hname = service.host_name
servicedependencies.add_service_dependency(
service.host_name, service.service_description, hname, desc)
i += 1
|
[
"def",
"register_service_dependencies",
"(",
"service",
",",
"servicedependencies",
")",
":",
"# We explode service_dependencies into Servicedependency",
"# We just create serviceDep with goods values (as STRING!),",
"# the link pass will be done after",
"sdeps",
"=",
"[",
"d",
".",
"strip",
"(",
")",
"for",
"d",
"in",
"getattr",
"(",
"service",
",",
"\"service_dependencies\"",
",",
"[",
"]",
")",
"]",
"# %2=0 are for hosts, !=0 are for service_description",
"i",
"=",
"0",
"hname",
"=",
"''",
"for",
"elt",
"in",
"sdeps",
":",
"if",
"i",
"%",
"2",
"==",
"0",
":",
"# host",
"hname",
"=",
"elt",
"else",
":",
"# description",
"desc",
"=",
"elt",
"# we can register it (service) (depend on) -> (hname, desc)",
"# If we do not have enough data for service, it'service no use",
"if",
"hasattr",
"(",
"service",
",",
"'service_description'",
")",
"and",
"hasattr",
"(",
"service",
",",
"'host_name'",
")",
":",
"if",
"hname",
"==",
"''",
":",
"hname",
"=",
"service",
".",
"host_name",
"servicedependencies",
".",
"add_service_dependency",
"(",
"service",
".",
"host_name",
",",
"service",
".",
"service_description",
",",
"hname",
",",
"desc",
")",
"i",
"+=",
"1"
] |
Registers a service dependencies.
:param service: The service to register
:type service:
:param servicedependencies: The servicedependencies container
:type servicedependencies:
:return: None
|
[
"Registers",
"a",
"service",
"dependencies",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1756-L1785
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/service.py
|
Services.explode
|
def explode(self, hosts, hostgroups, contactgroups, servicegroups, servicedependencies):
# pylint: disable=too-many-locals
"""
Explodes services, from host, hostgroups, contactgroups, servicegroups and dependencies.
:param hosts: The hosts container
:type hosts: [alignak.object.host.Host]
:param hostgroups: The hosts goups container
:type hostgroups: [alignak.object.hostgroup.Hostgroup]
:param contactgroups: The contacts goups container
:type contactgroups: [alignak.object.contactgroup.Contactgroup]
:param servicegroups: The services goups container
:type servicegroups: [alignak.object.servicegroup.Servicegroup]
:param servicedependencies: The services dependencies container
:type servicedependencies: [alignak.object.servicedependency.Servicedependency]
:return: None
"""
# Then for every service create a copy of the service with just the host
# because we are adding services, we can't just loop in it
itemkeys = list(self.items.keys())
for s_id in itemkeys:
serv = self.items[s_id]
# items::explode_host_groups_into_hosts
# take all hosts from our hostgroup_name into our host_name property
self.explode_host_groups_into_hosts(serv, hosts, hostgroups)
# items::explode_contact_groups_into_contacts
# take all contacts from our contact_groups into our contact property
self.explode_contact_groups_into_contacts(serv, contactgroups)
hnames = getattr(serv, "host_name", '')
hnames = list(set([n.strip() for n in hnames.split(',') if n.strip()]))
# hnames = strip_and_uniq(hnames)
# We will duplicate if we have multiple host_name
# or if we are a template (so a clean service)
if len(hnames) == 1:
self.index_item(serv)
else:
if len(hnames) >= 2:
self.explode_services_from_hosts(hosts, serv, hnames)
# Delete expanded source service, even if some errors exist
self.remove_item(serv)
for s_id in self.templates:
template = self.templates[s_id]
self.explode_contact_groups_into_contacts(template, contactgroups)
self.explode_services_from_templates(hosts, template)
# Explode services that have a duplicate_foreach clause
duplicates = [serv.uuid for serv in self if getattr(serv, 'duplicate_foreach', '')]
for s_id in duplicates:
serv = self.items[s_id]
self.explode_services_duplicates(hosts, serv)
if not serv.configuration_errors:
self.remove_item(serv)
to_remove = []
for service in self:
host = hosts.find_by_name(service.host_name)
if host and host.is_excluded_for(service):
to_remove.append(service)
for service in to_remove:
self.remove_item(service)
# Servicegroups property need to be fulfill for got the information
# And then just register to this service_group
for serv in self:
self.register_service_into_servicegroups(serv, servicegroups)
self.register_service_dependencies(serv, servicedependencies)
|
python
|
def explode(self, hosts, hostgroups, contactgroups, servicegroups, servicedependencies):
# pylint: disable=too-many-locals
"""
Explodes services, from host, hostgroups, contactgroups, servicegroups and dependencies.
:param hosts: The hosts container
:type hosts: [alignak.object.host.Host]
:param hostgroups: The hosts goups container
:type hostgroups: [alignak.object.hostgroup.Hostgroup]
:param contactgroups: The contacts goups container
:type contactgroups: [alignak.object.contactgroup.Contactgroup]
:param servicegroups: The services goups container
:type servicegroups: [alignak.object.servicegroup.Servicegroup]
:param servicedependencies: The services dependencies container
:type servicedependencies: [alignak.object.servicedependency.Servicedependency]
:return: None
"""
# Then for every service create a copy of the service with just the host
# because we are adding services, we can't just loop in it
itemkeys = list(self.items.keys())
for s_id in itemkeys:
serv = self.items[s_id]
# items::explode_host_groups_into_hosts
# take all hosts from our hostgroup_name into our host_name property
self.explode_host_groups_into_hosts(serv, hosts, hostgroups)
# items::explode_contact_groups_into_contacts
# take all contacts from our contact_groups into our contact property
self.explode_contact_groups_into_contacts(serv, contactgroups)
hnames = getattr(serv, "host_name", '')
hnames = list(set([n.strip() for n in hnames.split(',') if n.strip()]))
# hnames = strip_and_uniq(hnames)
# We will duplicate if we have multiple host_name
# or if we are a template (so a clean service)
if len(hnames) == 1:
self.index_item(serv)
else:
if len(hnames) >= 2:
self.explode_services_from_hosts(hosts, serv, hnames)
# Delete expanded source service, even if some errors exist
self.remove_item(serv)
for s_id in self.templates:
template = self.templates[s_id]
self.explode_contact_groups_into_contacts(template, contactgroups)
self.explode_services_from_templates(hosts, template)
# Explode services that have a duplicate_foreach clause
duplicates = [serv.uuid for serv in self if getattr(serv, 'duplicate_foreach', '')]
for s_id in duplicates:
serv = self.items[s_id]
self.explode_services_duplicates(hosts, serv)
if not serv.configuration_errors:
self.remove_item(serv)
to_remove = []
for service in self:
host = hosts.find_by_name(service.host_name)
if host and host.is_excluded_for(service):
to_remove.append(service)
for service in to_remove:
self.remove_item(service)
# Servicegroups property need to be fulfill for got the information
# And then just register to this service_group
for serv in self:
self.register_service_into_servicegroups(serv, servicegroups)
self.register_service_dependencies(serv, servicedependencies)
|
[
"def",
"explode",
"(",
"self",
",",
"hosts",
",",
"hostgroups",
",",
"contactgroups",
",",
"servicegroups",
",",
"servicedependencies",
")",
":",
"# pylint: disable=too-many-locals",
"# Then for every service create a copy of the service with just the host",
"# because we are adding services, we can't just loop in it",
"itemkeys",
"=",
"list",
"(",
"self",
".",
"items",
".",
"keys",
"(",
")",
")",
"for",
"s_id",
"in",
"itemkeys",
":",
"serv",
"=",
"self",
".",
"items",
"[",
"s_id",
"]",
"# items::explode_host_groups_into_hosts",
"# take all hosts from our hostgroup_name into our host_name property",
"self",
".",
"explode_host_groups_into_hosts",
"(",
"serv",
",",
"hosts",
",",
"hostgroups",
")",
"# items::explode_contact_groups_into_contacts",
"# take all contacts from our contact_groups into our contact property",
"self",
".",
"explode_contact_groups_into_contacts",
"(",
"serv",
",",
"contactgroups",
")",
"hnames",
"=",
"getattr",
"(",
"serv",
",",
"\"host_name\"",
",",
"''",
")",
"hnames",
"=",
"list",
"(",
"set",
"(",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"hnames",
".",
"split",
"(",
"','",
")",
"if",
"n",
".",
"strip",
"(",
")",
"]",
")",
")",
"# hnames = strip_and_uniq(hnames)",
"# We will duplicate if we have multiple host_name",
"# or if we are a template (so a clean service)",
"if",
"len",
"(",
"hnames",
")",
"==",
"1",
":",
"self",
".",
"index_item",
"(",
"serv",
")",
"else",
":",
"if",
"len",
"(",
"hnames",
")",
">=",
"2",
":",
"self",
".",
"explode_services_from_hosts",
"(",
"hosts",
",",
"serv",
",",
"hnames",
")",
"# Delete expanded source service, even if some errors exist",
"self",
".",
"remove_item",
"(",
"serv",
")",
"for",
"s_id",
"in",
"self",
".",
"templates",
":",
"template",
"=",
"self",
".",
"templates",
"[",
"s_id",
"]",
"self",
".",
"explode_contact_groups_into_contacts",
"(",
"template",
",",
"contactgroups",
")",
"self",
".",
"explode_services_from_templates",
"(",
"hosts",
",",
"template",
")",
"# Explode services that have a duplicate_foreach clause",
"duplicates",
"=",
"[",
"serv",
".",
"uuid",
"for",
"serv",
"in",
"self",
"if",
"getattr",
"(",
"serv",
",",
"'duplicate_foreach'",
",",
"''",
")",
"]",
"for",
"s_id",
"in",
"duplicates",
":",
"serv",
"=",
"self",
".",
"items",
"[",
"s_id",
"]",
"self",
".",
"explode_services_duplicates",
"(",
"hosts",
",",
"serv",
")",
"if",
"not",
"serv",
".",
"configuration_errors",
":",
"self",
".",
"remove_item",
"(",
"serv",
")",
"to_remove",
"=",
"[",
"]",
"for",
"service",
"in",
"self",
":",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"service",
".",
"host_name",
")",
"if",
"host",
"and",
"host",
".",
"is_excluded_for",
"(",
"service",
")",
":",
"to_remove",
".",
"append",
"(",
"service",
")",
"for",
"service",
"in",
"to_remove",
":",
"self",
".",
"remove_item",
"(",
"service",
")",
"# Servicegroups property need to be fulfill for got the information",
"# And then just register to this service_group",
"for",
"serv",
"in",
"self",
":",
"self",
".",
"register_service_into_servicegroups",
"(",
"serv",
",",
"servicegroups",
")",
"self",
".",
"register_service_dependencies",
"(",
"serv",
",",
"servicedependencies",
")"
] |
Explodes services, from host, hostgroups, contactgroups, servicegroups and dependencies.
:param hosts: The hosts container
:type hosts: [alignak.object.host.Host]
:param hostgroups: The hosts goups container
:type hostgroups: [alignak.object.hostgroup.Hostgroup]
:param contactgroups: The contacts goups container
:type contactgroups: [alignak.object.contactgroup.Contactgroup]
:param servicegroups: The services goups container
:type servicegroups: [alignak.object.servicegroup.Servicegroup]
:param servicedependencies: The services dependencies container
:type servicedependencies: [alignak.object.servicedependency.Servicedependency]
:return: None
|
[
"Explodes",
"services",
"from",
"host",
"hostgroups",
"contactgroups",
"servicegroups",
"and",
"dependencies",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/service.py#L1788-L1856
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/escalation.py
|
Escalation.get_next_notif_time
|
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
"""
short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c',
u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's',
u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'}
# If we are not time based, we bail out!
if not self.time_based:
return None
# Check if we are valid
if status in short_states and short_states[status] not in self.escalation_options:
return None
# Look for the min of our future validity
start = self.first_notification_time * interval + creation_time
# If we are after the classic next time, we are not asking for a smaller interval
if start > t_wished:
return None
# Maybe the time we found is not a valid one....
if escal_period is not None and not escal_period.is_time_valid(start):
return None
# Ok so I ask for my start as a possibility for the next notification time
return start
|
python
|
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
"""
short_states = {u'WARNING': 'w', u'UNKNOWN': 'u', u'CRITICAL': 'c',
u'RECOVERY': 'r', u'FLAPPING': 'f', u'DOWNTIME': 's',
u'DOWN': 'd', u'UNREACHABLE': 'u', u'OK': 'o', u'UP': 'o'}
# If we are not time based, we bail out!
if not self.time_based:
return None
# Check if we are valid
if status in short_states and short_states[status] not in self.escalation_options:
return None
# Look for the min of our future validity
start = self.first_notification_time * interval + creation_time
# If we are after the classic next time, we are not asking for a smaller interval
if start > t_wished:
return None
# Maybe the time we found is not a valid one....
if escal_period is not None and not escal_period.is_time_valid(start):
return None
# Ok so I ask for my start as a possibility for the next notification time
return start
|
[
"def",
"get_next_notif_time",
"(",
"self",
",",
"t_wished",
",",
"status",
",",
"creation_time",
",",
"interval",
",",
"escal_period",
")",
":",
"short_states",
"=",
"{",
"u'WARNING'",
":",
"'w'",
",",
"u'UNKNOWN'",
":",
"'u'",
",",
"u'CRITICAL'",
":",
"'c'",
",",
"u'RECOVERY'",
":",
"'r'",
",",
"u'FLAPPING'",
":",
"'f'",
",",
"u'DOWNTIME'",
":",
"'s'",
",",
"u'DOWN'",
":",
"'d'",
",",
"u'UNREACHABLE'",
":",
"'u'",
",",
"u'OK'",
":",
"'o'",
",",
"u'UP'",
":",
"'o'",
"}",
"# If we are not time based, we bail out!",
"if",
"not",
"self",
".",
"time_based",
":",
"return",
"None",
"# Check if we are valid",
"if",
"status",
"in",
"short_states",
"and",
"short_states",
"[",
"status",
"]",
"not",
"in",
"self",
".",
"escalation_options",
":",
"return",
"None",
"# Look for the min of our future validity",
"start",
"=",
"self",
".",
"first_notification_time",
"*",
"interval",
"+",
"creation_time",
"# If we are after the classic next time, we are not asking for a smaller interval",
"if",
"start",
">",
"t_wished",
":",
"return",
"None",
"# Maybe the time we found is not a valid one....",
"if",
"escal_period",
"is",
"not",
"None",
"and",
"not",
"escal_period",
".",
"is_time_valid",
"(",
"start",
")",
":",
"return",
"None",
"# Ok so I ask for my start as a possibility for the next notification time",
"return",
"start"
] |
Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param status: status of the host or service
:type status:
:param creation_time: time the notification was created
:type creation_time:
:param interval: time interval length
:type interval: int
:return: timestamp for next notification or None
:rtype: int | None
|
[
"Get",
"the",
"next",
"notification",
"time",
"for",
"the",
"escalation",
"Only",
"legit",
"for",
"time",
"based",
"escalation"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L189-L228
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/escalation.py
|
Escalations.linkify_es_by_s
|
def linkify_es_by_s(self, services):
"""Add each escalation object into service.escalation attribute
:param services: service list, used to look for a specific service
:type services: alignak.objects.service.Services
:return: None
"""
for escalation in self:
# If no host, no hope of having a service
if not hasattr(escalation, 'host_name'):
continue
es_hname, sdesc = escalation.host_name, escalation.service_description
if not es_hname.strip() or not sdesc.strip():
continue
for hname in strip_and_uniq(es_hname.split(',')):
if sdesc.strip() == '*':
slist = services.find_srvs_by_hostname(hname)
if slist is not None:
slist = [services[serv] for serv in slist]
for serv in slist:
serv.escalations.append(escalation.uuid)
else:
for sname in strip_and_uniq(sdesc.split(',')):
serv = services.find_srv_by_name_and_hostname(hname, sname)
if serv is not None:
serv.escalations.append(escalation.uuid)
|
python
|
def linkify_es_by_s(self, services):
"""Add each escalation object into service.escalation attribute
:param services: service list, used to look for a specific service
:type services: alignak.objects.service.Services
:return: None
"""
for escalation in self:
# If no host, no hope of having a service
if not hasattr(escalation, 'host_name'):
continue
es_hname, sdesc = escalation.host_name, escalation.service_description
if not es_hname.strip() or not sdesc.strip():
continue
for hname in strip_and_uniq(es_hname.split(',')):
if sdesc.strip() == '*':
slist = services.find_srvs_by_hostname(hname)
if slist is not None:
slist = [services[serv] for serv in slist]
for serv in slist:
serv.escalations.append(escalation.uuid)
else:
for sname in strip_and_uniq(sdesc.split(',')):
serv = services.find_srv_by_name_and_hostname(hname, sname)
if serv is not None:
serv.escalations.append(escalation.uuid)
|
[
"def",
"linkify_es_by_s",
"(",
"self",
",",
"services",
")",
":",
"for",
"escalation",
"in",
"self",
":",
"# If no host, no hope of having a service",
"if",
"not",
"hasattr",
"(",
"escalation",
",",
"'host_name'",
")",
":",
"continue",
"es_hname",
",",
"sdesc",
"=",
"escalation",
".",
"host_name",
",",
"escalation",
".",
"service_description",
"if",
"not",
"es_hname",
".",
"strip",
"(",
")",
"or",
"not",
"sdesc",
".",
"strip",
"(",
")",
":",
"continue",
"for",
"hname",
"in",
"strip_and_uniq",
"(",
"es_hname",
".",
"split",
"(",
"','",
")",
")",
":",
"if",
"sdesc",
".",
"strip",
"(",
")",
"==",
"'*'",
":",
"slist",
"=",
"services",
".",
"find_srvs_by_hostname",
"(",
"hname",
")",
"if",
"slist",
"is",
"not",
"None",
":",
"slist",
"=",
"[",
"services",
"[",
"serv",
"]",
"for",
"serv",
"in",
"slist",
"]",
"for",
"serv",
"in",
"slist",
":",
"serv",
".",
"escalations",
".",
"append",
"(",
"escalation",
".",
"uuid",
")",
"else",
":",
"for",
"sname",
"in",
"strip_and_uniq",
"(",
"sdesc",
".",
"split",
"(",
"','",
")",
")",
":",
"serv",
"=",
"services",
".",
"find_srv_by_name_and_hostname",
"(",
"hname",
",",
"sname",
")",
"if",
"serv",
"is",
"not",
"None",
":",
"serv",
".",
"escalations",
".",
"append",
"(",
"escalation",
".",
"uuid",
")"
] |
Add each escalation object into service.escalation attribute
:param services: service list, used to look for a specific service
:type services: alignak.objects.service.Services
:return: None
|
[
"Add",
"each",
"escalation",
"object",
"into",
"service",
".",
"escalation",
"attribute"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L320-L347
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/escalation.py
|
Escalations.linkify_es_by_h
|
def linkify_es_by_h(self, hosts):
"""Add each escalation object into host.escalation attribute
:param hosts: host list, used to look for a specific host
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for escal in self:
# If no host, no hope of having a service
if (not hasattr(escal, 'host_name') or escal.host_name.strip() == '' or
(hasattr(escal, 'service_description')
and escal.service_description.strip() != '')):
continue
# I must be NOT a escalation on for service
for hname in strip_and_uniq(escal.host_name.split(',')):
host = hosts.find_by_name(hname)
if host is not None:
host.escalations.append(escal.uuid)
|
python
|
def linkify_es_by_h(self, hosts):
"""Add each escalation object into host.escalation attribute
:param hosts: host list, used to look for a specific host
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for escal in self:
# If no host, no hope of having a service
if (not hasattr(escal, 'host_name') or escal.host_name.strip() == '' or
(hasattr(escal, 'service_description')
and escal.service_description.strip() != '')):
continue
# I must be NOT a escalation on for service
for hname in strip_and_uniq(escal.host_name.split(',')):
host = hosts.find_by_name(hname)
if host is not None:
host.escalations.append(escal.uuid)
|
[
"def",
"linkify_es_by_h",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"escal",
"in",
"self",
":",
"# If no host, no hope of having a service",
"if",
"(",
"not",
"hasattr",
"(",
"escal",
",",
"'host_name'",
")",
"or",
"escal",
".",
"host_name",
".",
"strip",
"(",
")",
"==",
"''",
"or",
"(",
"hasattr",
"(",
"escal",
",",
"'service_description'",
")",
"and",
"escal",
".",
"service_description",
".",
"strip",
"(",
")",
"!=",
"''",
")",
")",
":",
"continue",
"# I must be NOT a escalation on for service",
"for",
"hname",
"in",
"strip_and_uniq",
"(",
"escal",
".",
"host_name",
".",
"split",
"(",
"','",
")",
")",
":",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"hname",
")",
"if",
"host",
"is",
"not",
"None",
":",
"host",
".",
"escalations",
".",
"append",
"(",
"escal",
".",
"uuid",
")"
] |
Add each escalation object into host.escalation attribute
:param hosts: host list, used to look for a specific host
:type hosts: alignak.objects.host.Hosts
:return: None
|
[
"Add",
"each",
"escalation",
"object",
"into",
"host",
".",
"escalation",
"attribute"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L349-L366
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/escalation.py
|
Escalations.explode
|
def explode(self, hosts, hostgroups, contactgroups):
"""Loop over all escalation and explode hostsgroups in host
and contactgroups in contacts
Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts
:param hosts: host list to explode
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroup list to explode
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:param contactgroups: contactgroup list to explode
:type contactgroups: alignak.objects.contactgroup.Contactgroups
:return: None
"""
for i in self:
# items::explode_host_groups_into_hosts
# take all hosts from our hostgroup_name into our host_name property
self.explode_host_groups_into_hosts(i, hosts, hostgroups)
# items::explode_contact_groups_into_contacts
# take all contacts from our contact_groups into our contact property
self.explode_contact_groups_into_contacts(i, contactgroups)
|
python
|
def explode(self, hosts, hostgroups, contactgroups):
"""Loop over all escalation and explode hostsgroups in host
and contactgroups in contacts
Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts
:param hosts: host list to explode
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroup list to explode
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:param contactgroups: contactgroup list to explode
:type contactgroups: alignak.objects.contactgroup.Contactgroups
:return: None
"""
for i in self:
# items::explode_host_groups_into_hosts
# take all hosts from our hostgroup_name into our host_name property
self.explode_host_groups_into_hosts(i, hosts, hostgroups)
# items::explode_contact_groups_into_contacts
# take all contacts from our contact_groups into our contact property
self.explode_contact_groups_into_contacts(i, contactgroups)
|
[
"def",
"explode",
"(",
"self",
",",
"hosts",
",",
"hostgroups",
",",
"contactgroups",
")",
":",
"for",
"i",
"in",
"self",
":",
"# items::explode_host_groups_into_hosts",
"# take all hosts from our hostgroup_name into our host_name property",
"self",
".",
"explode_host_groups_into_hosts",
"(",
"i",
",",
"hosts",
",",
"hostgroups",
")",
"# items::explode_contact_groups_into_contacts",
"# take all contacts from our contact_groups into our contact property",
"self",
".",
"explode_contact_groups_into_contacts",
"(",
"i",
",",
"contactgroups",
")"
] |
Loop over all escalation and explode hostsgroups in host
and contactgroups in contacts
Call Item.explode_host_groups_into_hosts and Item.explode_contact_groups_into_contacts
:param hosts: host list to explode
:type hosts: alignak.objects.host.Hosts
:param hostgroups: hostgroup list to explode
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:param contactgroups: contactgroup list to explode
:type contactgroups: alignak.objects.contactgroup.Contactgroups
:return: None
|
[
"Loop",
"over",
"all",
"escalation",
"and",
"explode",
"hostsgroups",
"in",
"host",
"and",
"contactgroups",
"in",
"contacts"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/escalation.py#L368-L389
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/hostgroup.py
|
Hostgroup.get_hosts_by_explosion
|
def get_hosts_by_explosion(self, hostgroups):
# pylint: disable=access-member-before-definition
"""
Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list
"""
# First we tag the hg so it will not be explode
# if a son of it already call it
self.already_exploded = True
# Now the recursive part
# rec_tag is set to False every HG we explode
# so if True here, it must be a loop in HG
# calls... not GOOD!
if self.rec_tag:
logger.error("[hostgroup::%s] got a loop in hostgroup definition", self.get_name())
return self.get_hosts()
# Ok, not a loop, we tag it and continue
self.rec_tag = True
hg_mbrs = self.get_hostgroup_members()
for hg_mbr in hg_mbrs:
hostgroup = hostgroups.find_by_name(hg_mbr.strip())
if hostgroup is not None:
value = hostgroup.get_hosts_by_explosion(hostgroups)
if value is not None:
self.add_members(value)
return self.get_hosts()
|
python
|
def get_hosts_by_explosion(self, hostgroups):
# pylint: disable=access-member-before-definition
"""
Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list
"""
# First we tag the hg so it will not be explode
# if a son of it already call it
self.already_exploded = True
# Now the recursive part
# rec_tag is set to False every HG we explode
# so if True here, it must be a loop in HG
# calls... not GOOD!
if self.rec_tag:
logger.error("[hostgroup::%s] got a loop in hostgroup definition", self.get_name())
return self.get_hosts()
# Ok, not a loop, we tag it and continue
self.rec_tag = True
hg_mbrs = self.get_hostgroup_members()
for hg_mbr in hg_mbrs:
hostgroup = hostgroups.find_by_name(hg_mbr.strip())
if hostgroup is not None:
value = hostgroup.get_hosts_by_explosion(hostgroups)
if value is not None:
self.add_members(value)
return self.get_hosts()
|
[
"def",
"get_hosts_by_explosion",
"(",
"self",
",",
"hostgroups",
")",
":",
"# pylint: disable=access-member-before-definition",
"# First we tag the hg so it will not be explode",
"# if a son of it already call it",
"self",
".",
"already_exploded",
"=",
"True",
"# Now the recursive part",
"# rec_tag is set to False every HG we explode",
"# so if True here, it must be a loop in HG",
"# calls... not GOOD!",
"if",
"self",
".",
"rec_tag",
":",
"logger",
".",
"error",
"(",
"\"[hostgroup::%s] got a loop in hostgroup definition\"",
",",
"self",
".",
"get_name",
"(",
")",
")",
"return",
"self",
".",
"get_hosts",
"(",
")",
"# Ok, not a loop, we tag it and continue",
"self",
".",
"rec_tag",
"=",
"True",
"hg_mbrs",
"=",
"self",
".",
"get_hostgroup_members",
"(",
")",
"for",
"hg_mbr",
"in",
"hg_mbrs",
":",
"hostgroup",
"=",
"hostgroups",
".",
"find_by_name",
"(",
"hg_mbr",
".",
"strip",
"(",
")",
")",
"if",
"hostgroup",
"is",
"not",
"None",
":",
"value",
"=",
"hostgroup",
".",
"get_hosts_by_explosion",
"(",
"hostgroups",
")",
"if",
"value",
"is",
"not",
"None",
":",
"self",
".",
"add_members",
"(",
"value",
")",
"return",
"self",
".",
"get_hosts",
"(",
")"
] |
Get hosts of this group
:param hostgroups: Hostgroup object
:type hostgroups: alignak.objects.hostgroup.Hostgroups
:return: list of hosts of this group
:rtype: list
|
[
"Get",
"hosts",
"of",
"this",
"group"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L134-L167
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/hostgroup.py
|
Hostgroups.add_member
|
def add_member(self, host_name, hostgroup_name):
"""Add a host string to a hostgroup member
if the host group do not exist, create it
:param host_name: host name
:type host_name: str
:param hostgroup_name:hostgroup name
:type hostgroup_name: str
:return: None
"""
hostgroup = self.find_by_name(hostgroup_name)
if not hostgroup:
hostgroup = Hostgroup({'hostgroup_name': hostgroup_name,
'alias': hostgroup_name,
'members': host_name})
self.add(hostgroup)
else:
hostgroup.add_members(host_name)
|
python
|
def add_member(self, host_name, hostgroup_name):
"""Add a host string to a hostgroup member
if the host group do not exist, create it
:param host_name: host name
:type host_name: str
:param hostgroup_name:hostgroup name
:type hostgroup_name: str
:return: None
"""
hostgroup = self.find_by_name(hostgroup_name)
if not hostgroup:
hostgroup = Hostgroup({'hostgroup_name': hostgroup_name,
'alias': hostgroup_name,
'members': host_name})
self.add(hostgroup)
else:
hostgroup.add_members(host_name)
|
[
"def",
"add_member",
"(",
"self",
",",
"host_name",
",",
"hostgroup_name",
")",
":",
"hostgroup",
"=",
"self",
".",
"find_by_name",
"(",
"hostgroup_name",
")",
"if",
"not",
"hostgroup",
":",
"hostgroup",
"=",
"Hostgroup",
"(",
"{",
"'hostgroup_name'",
":",
"hostgroup_name",
",",
"'alias'",
":",
"hostgroup_name",
",",
"'members'",
":",
"host_name",
"}",
")",
"self",
".",
"add",
"(",
"hostgroup",
")",
"else",
":",
"hostgroup",
".",
"add_members",
"(",
"host_name",
")"
] |
Add a host string to a hostgroup member
if the host group do not exist, create it
:param host_name: host name
:type host_name: str
:param hostgroup_name:hostgroup name
:type hostgroup_name: str
:return: None
|
[
"Add",
"a",
"host",
"string",
"to",
"a",
"hostgroup",
"member",
"if",
"the",
"host",
"group",
"do",
"not",
"exist",
"create",
"it"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L178-L195
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/hostgroup.py
|
Hostgroups.linkify
|
def linkify(self, hosts=None, realms=None, forced_realms_hostgroups=True):
"""Link hostgroups with hosts and realms
:param hosts: all Hosts
:type hosts: alignak.objects.host.Hosts
:param realms: all Realms
:type realms: alignak.objects.realm.Realms
:return: None
"""
self.linkify_hostgroups_hosts(hosts)
self.linkify_hostgroups_realms_hosts(realms, hosts, forced_realms_hostgroups)
|
python
|
def linkify(self, hosts=None, realms=None, forced_realms_hostgroups=True):
"""Link hostgroups with hosts and realms
:param hosts: all Hosts
:type hosts: alignak.objects.host.Hosts
:param realms: all Realms
:type realms: alignak.objects.realm.Realms
:return: None
"""
self.linkify_hostgroups_hosts(hosts)
self.linkify_hostgroups_realms_hosts(realms, hosts, forced_realms_hostgroups)
|
[
"def",
"linkify",
"(",
"self",
",",
"hosts",
"=",
"None",
",",
"realms",
"=",
"None",
",",
"forced_realms_hostgroups",
"=",
"True",
")",
":",
"self",
".",
"linkify_hostgroups_hosts",
"(",
"hosts",
")",
"self",
".",
"linkify_hostgroups_realms_hosts",
"(",
"realms",
",",
"hosts",
",",
"forced_realms_hostgroups",
")"
] |
Link hostgroups with hosts and realms
:param hosts: all Hosts
:type hosts: alignak.objects.host.Hosts
:param realms: all Realms
:type realms: alignak.objects.realm.Realms
:return: None
|
[
"Link",
"hostgroups",
"with",
"hosts",
"and",
"realms"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L210-L220
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/hostgroup.py
|
Hostgroups.linkify_hostgroups_hosts
|
def linkify_hostgroups_hosts(self, hosts):
"""We just search for each hostgroup the id of the hosts
and replace the names by the found identifiers
:param hosts: object Hosts
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for hostgroup in self:
members = hostgroup.get_hosts()
# The new members identifiers list
new_members = []
for member in members:
# member is an host name
member = member.strip()
if not member: # void entry, skip this
continue
if member == '*':
# All the hosts identifiers list
new_members.extend(list(hosts.items.keys()))
else:
host = hosts.find_by_name(member)
if host is not None:
new_members.append(host.uuid)
if hostgroup.uuid not in host.hostgroups:
host.hostgroups.append(hostgroup.uuid)
else:
hostgroup.add_unknown_members(member)
# Make members unique
new_members = list(set(new_members))
# We find the id, we replace the names
hostgroup.replace_members(new_members)
|
python
|
def linkify_hostgroups_hosts(self, hosts):
"""We just search for each hostgroup the id of the hosts
and replace the names by the found identifiers
:param hosts: object Hosts
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for hostgroup in self:
members = hostgroup.get_hosts()
# The new members identifiers list
new_members = []
for member in members:
# member is an host name
member = member.strip()
if not member: # void entry, skip this
continue
if member == '*':
# All the hosts identifiers list
new_members.extend(list(hosts.items.keys()))
else:
host = hosts.find_by_name(member)
if host is not None:
new_members.append(host.uuid)
if hostgroup.uuid not in host.hostgroups:
host.hostgroups.append(hostgroup.uuid)
else:
hostgroup.add_unknown_members(member)
# Make members unique
new_members = list(set(new_members))
# We find the id, we replace the names
hostgroup.replace_members(new_members)
|
[
"def",
"linkify_hostgroups_hosts",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"hostgroup",
"in",
"self",
":",
"members",
"=",
"hostgroup",
".",
"get_hosts",
"(",
")",
"# The new members identifiers list",
"new_members",
"=",
"[",
"]",
"for",
"member",
"in",
"members",
":",
"# member is an host name",
"member",
"=",
"member",
".",
"strip",
"(",
")",
"if",
"not",
"member",
":",
"# void entry, skip this",
"continue",
"if",
"member",
"==",
"'*'",
":",
"# All the hosts identifiers list",
"new_members",
".",
"extend",
"(",
"list",
"(",
"hosts",
".",
"items",
".",
"keys",
"(",
")",
")",
")",
"else",
":",
"host",
"=",
"hosts",
".",
"find_by_name",
"(",
"member",
")",
"if",
"host",
"is",
"not",
"None",
":",
"new_members",
".",
"append",
"(",
"host",
".",
"uuid",
")",
"if",
"hostgroup",
".",
"uuid",
"not",
"in",
"host",
".",
"hostgroups",
":",
"host",
".",
"hostgroups",
".",
"append",
"(",
"hostgroup",
".",
"uuid",
")",
"else",
":",
"hostgroup",
".",
"add_unknown_members",
"(",
"member",
")",
"# Make members unique",
"new_members",
"=",
"list",
"(",
"set",
"(",
"new_members",
")",
")",
"# We find the id, we replace the names",
"hostgroup",
".",
"replace_members",
"(",
"new_members",
")"
] |
We just search for each hostgroup the id of the hosts
and replace the names by the found identifiers
:param hosts: object Hosts
:type hosts: alignak.objects.host.Hosts
:return: None
|
[
"We",
"just",
"search",
"for",
"each",
"hostgroup",
"the",
"id",
"of",
"the",
"hosts",
"and",
"replace",
"the",
"names",
"by",
"the",
"found",
"identifiers"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L222-L256
|
train
|
Alignak-monitoring/alignak
|
alignak/objects/hostgroup.py
|
Hostgroups.explode
|
def explode(self):
"""
Fill members with hostgroup_members
:return: None
"""
# We do not want a same hostgroup to be exploded again and again
# so we tag it
for tmp_hg in list(self.items.values()):
tmp_hg.already_exploded = False
for hostgroup in list(self.items.values()):
if hostgroup.already_exploded:
continue
# get_hosts_by_explosion is a recursive
# function, so we must tag hg so we do not loop
for tmp_hg in list(self.items.values()):
tmp_hg.rec_tag = False
hostgroup.get_hosts_by_explosion(self)
# We clean the tags
for tmp_hg in list(self.items.values()):
if hasattr(tmp_hg, 'rec_tag'):
del tmp_hg.rec_tag
del tmp_hg.already_exploded
|
python
|
def explode(self):
"""
Fill members with hostgroup_members
:return: None
"""
# We do not want a same hostgroup to be exploded again and again
# so we tag it
for tmp_hg in list(self.items.values()):
tmp_hg.already_exploded = False
for hostgroup in list(self.items.values()):
if hostgroup.already_exploded:
continue
# get_hosts_by_explosion is a recursive
# function, so we must tag hg so we do not loop
for tmp_hg in list(self.items.values()):
tmp_hg.rec_tag = False
hostgroup.get_hosts_by_explosion(self)
# We clean the tags
for tmp_hg in list(self.items.values()):
if hasattr(tmp_hg, 'rec_tag'):
del tmp_hg.rec_tag
del tmp_hg.already_exploded
|
[
"def",
"explode",
"(",
"self",
")",
":",
"# We do not want a same hostgroup to be exploded again and again",
"# so we tag it",
"for",
"tmp_hg",
"in",
"list",
"(",
"self",
".",
"items",
".",
"values",
"(",
")",
")",
":",
"tmp_hg",
".",
"already_exploded",
"=",
"False",
"for",
"hostgroup",
"in",
"list",
"(",
"self",
".",
"items",
".",
"values",
"(",
")",
")",
":",
"if",
"hostgroup",
".",
"already_exploded",
":",
"continue",
"# get_hosts_by_explosion is a recursive",
"# function, so we must tag hg so we do not loop",
"for",
"tmp_hg",
"in",
"list",
"(",
"self",
".",
"items",
".",
"values",
"(",
")",
")",
":",
"tmp_hg",
".",
"rec_tag",
"=",
"False",
"hostgroup",
".",
"get_hosts_by_explosion",
"(",
"self",
")",
"# We clean the tags",
"for",
"tmp_hg",
"in",
"list",
"(",
"self",
".",
"items",
".",
"values",
"(",
")",
")",
":",
"if",
"hasattr",
"(",
"tmp_hg",
",",
"'rec_tag'",
")",
":",
"del",
"tmp_hg",
".",
"rec_tag",
"del",
"tmp_hg",
".",
"already_exploded"
] |
Fill members with hostgroup_members
:return: None
|
[
"Fill",
"members",
"with",
"hostgroup_members"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/objects/hostgroup.py#L380-L405
|
train
|
Alignak-monitoring/alignak
|
alignak/http/daemon.py
|
HTTPDaemon.run
|
def run(self):
"""Wrapper to start the CherryPy server
This function throws a PortNotFree exception if any socket error is raised.
:return: None
"""
def _started_callback():
"""Callback function when Cherrypy Engine is started"""
cherrypy.log("CherryPy engine started and listening...")
self.cherrypy_thread = None
try:
cherrypy.log("Starting CherryPy engine on %s" % (self.uri))
self.cherrypy_thread = cherrypy.engine.start_with_callback(_started_callback)
cherrypy.engine.block()
cherrypy.log("Exited from the engine block")
except socket.error as exp:
raise PortNotFree("Error: Sorry, the HTTP server did not started correctly: error: %s"
% (str(exp)))
|
python
|
def run(self):
"""Wrapper to start the CherryPy server
This function throws a PortNotFree exception if any socket error is raised.
:return: None
"""
def _started_callback():
"""Callback function when Cherrypy Engine is started"""
cherrypy.log("CherryPy engine started and listening...")
self.cherrypy_thread = None
try:
cherrypy.log("Starting CherryPy engine on %s" % (self.uri))
self.cherrypy_thread = cherrypy.engine.start_with_callback(_started_callback)
cherrypy.engine.block()
cherrypy.log("Exited from the engine block")
except socket.error as exp:
raise PortNotFree("Error: Sorry, the HTTP server did not started correctly: error: %s"
% (str(exp)))
|
[
"def",
"run",
"(",
"self",
")",
":",
"def",
"_started_callback",
"(",
")",
":",
"\"\"\"Callback function when Cherrypy Engine is started\"\"\"",
"cherrypy",
".",
"log",
"(",
"\"CherryPy engine started and listening...\"",
")",
"self",
".",
"cherrypy_thread",
"=",
"None",
"try",
":",
"cherrypy",
".",
"log",
"(",
"\"Starting CherryPy engine on %s\"",
"%",
"(",
"self",
".",
"uri",
")",
")",
"self",
".",
"cherrypy_thread",
"=",
"cherrypy",
".",
"engine",
".",
"start_with_callback",
"(",
"_started_callback",
")",
"cherrypy",
".",
"engine",
".",
"block",
"(",
")",
"cherrypy",
".",
"log",
"(",
"\"Exited from the engine block\"",
")",
"except",
"socket",
".",
"error",
"as",
"exp",
":",
"raise",
"PortNotFree",
"(",
"\"Error: Sorry, the HTTP server did not started correctly: error: %s\"",
"%",
"(",
"str",
"(",
"exp",
")",
")",
")"
] |
Wrapper to start the CherryPy server
This function throws a PortNotFree exception if any socket error is raised.
:return: None
|
[
"Wrapper",
"to",
"start",
"the",
"CherryPy",
"server"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/daemon.py#L163-L182
|
train
|
Alignak-monitoring/alignak
|
alignak/http/daemon.py
|
HTTPDaemon.stop
|
def stop(self): # pylint: disable=no-self-use
"""Wrapper to stop the CherryPy server
:return: None
"""
cherrypy.log("Stopping CherryPy engine (current state: %s)..." % cherrypy.engine.state)
try:
cherrypy.engine.exit()
except RuntimeWarning:
pass
except SystemExit:
cherrypy.log('SystemExit raised: shutting down bus')
cherrypy.log("Stopped")
|
python
|
def stop(self): # pylint: disable=no-self-use
"""Wrapper to stop the CherryPy server
:return: None
"""
cherrypy.log("Stopping CherryPy engine (current state: %s)..." % cherrypy.engine.state)
try:
cherrypy.engine.exit()
except RuntimeWarning:
pass
except SystemExit:
cherrypy.log('SystemExit raised: shutting down bus')
cherrypy.log("Stopped")
|
[
"def",
"stop",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"cherrypy",
".",
"log",
"(",
"\"Stopping CherryPy engine (current state: %s)...\"",
"%",
"cherrypy",
".",
"engine",
".",
"state",
")",
"try",
":",
"cherrypy",
".",
"engine",
".",
"exit",
"(",
")",
"except",
"RuntimeWarning",
":",
"pass",
"except",
"SystemExit",
":",
"cherrypy",
".",
"log",
"(",
"'SystemExit raised: shutting down bus'",
")",
"cherrypy",
".",
"log",
"(",
"\"Stopped\"",
")"
] |
Wrapper to stop the CherryPy server
:return: None
|
[
"Wrapper",
"to",
"stop",
"the",
"CherryPy",
"server"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/daemon.py#L184-L196
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.create_queues
|
def create_queues(self, manager=None):
"""
Create the shared queues that will be used by alignak daemon
process and this module process.
But clear queues if they were already set before recreating new one.
Note:
If manager is None, then we are running the unit tests for the modules and
we must create some queues for the external modules without a SyncManager
:param manager: Manager() object
:type manager: None | object
:return: None
"""
self.clear_queues(manager)
# If no Manager() object, go with classic Queue()
if not manager:
self.from_q = Queue()
self.to_q = Queue()
else:
self.from_q = manager.Queue()
self.to_q = manager.Queue()
|
python
|
def create_queues(self, manager=None):
"""
Create the shared queues that will be used by alignak daemon
process and this module process.
But clear queues if they were already set before recreating new one.
Note:
If manager is None, then we are running the unit tests for the modules and
we must create some queues for the external modules without a SyncManager
:param manager: Manager() object
:type manager: None | object
:return: None
"""
self.clear_queues(manager)
# If no Manager() object, go with classic Queue()
if not manager:
self.from_q = Queue()
self.to_q = Queue()
else:
self.from_q = manager.Queue()
self.to_q = manager.Queue()
|
[
"def",
"create_queues",
"(",
"self",
",",
"manager",
"=",
"None",
")",
":",
"self",
".",
"clear_queues",
"(",
"manager",
")",
"# If no Manager() object, go with classic Queue()",
"if",
"not",
"manager",
":",
"self",
".",
"from_q",
"=",
"Queue",
"(",
")",
"self",
".",
"to_q",
"=",
"Queue",
"(",
")",
"else",
":",
"self",
".",
"from_q",
"=",
"manager",
".",
"Queue",
"(",
")",
"self",
".",
"to_q",
"=",
"manager",
".",
"Queue",
"(",
")"
] |
Create the shared queues that will be used by alignak daemon
process and this module process.
But clear queues if they were already set before recreating new one.
Note:
If manager is None, then we are running the unit tests for the modules and
we must create some queues for the external modules without a SyncManager
:param manager: Manager() object
:type manager: None | object
:return: None
|
[
"Create",
"the",
"shared",
"queues",
"that",
"will",
"be",
"used",
"by",
"alignak",
"daemon",
"process",
"and",
"this",
"module",
"process",
".",
"But",
"clear",
"queues",
"if",
"they",
"were",
"already",
"set",
"before",
"recreating",
"new",
"one",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L189-L210
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.clear_queues
|
def clear_queues(self, manager):
"""Release the resources associated to the queues of this instance
:param manager: Manager() object
:type manager: None | object
:return: None
"""
for queue in (self.to_q, self.from_q):
if queue is None:
continue
# If we got no manager, we directly call the clean
if not manager:
try:
queue.close()
queue.join_thread()
except AttributeError:
pass
# else:
# q._callmethod('close')
# q._callmethod('join_thread')
self.to_q = self.from_q = None
|
python
|
def clear_queues(self, manager):
"""Release the resources associated to the queues of this instance
:param manager: Manager() object
:type manager: None | object
:return: None
"""
for queue in (self.to_q, self.from_q):
if queue is None:
continue
# If we got no manager, we directly call the clean
if not manager:
try:
queue.close()
queue.join_thread()
except AttributeError:
pass
# else:
# q._callmethod('close')
# q._callmethod('join_thread')
self.to_q = self.from_q = None
|
[
"def",
"clear_queues",
"(",
"self",
",",
"manager",
")",
":",
"for",
"queue",
"in",
"(",
"self",
".",
"to_q",
",",
"self",
".",
"from_q",
")",
":",
"if",
"queue",
"is",
"None",
":",
"continue",
"# If we got no manager, we directly call the clean",
"if",
"not",
"manager",
":",
"try",
":",
"queue",
".",
"close",
"(",
")",
"queue",
".",
"join_thread",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"# else:",
"# q._callmethod('close')",
"# q._callmethod('join_thread')",
"self",
".",
"to_q",
"=",
"self",
".",
"from_q",
"=",
"None"
] |
Release the resources associated to the queues of this instance
:param manager: Manager() object
:type manager: None | object
:return: None
|
[
"Release",
"the",
"resources",
"associated",
"to",
"the",
"queues",
"of",
"this",
"instance"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L212-L232
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.start_module
|
def start_module(self):
"""Wrapper for _main function.
Catch and raise any exception occurring in the main function
:return: None
"""
try:
self._main()
except Exception as exp:
logger.exception('%s', traceback.format_exc())
raise Exception(exp)
|
python
|
def start_module(self):
"""Wrapper for _main function.
Catch and raise any exception occurring in the main function
:return: None
"""
try:
self._main()
except Exception as exp:
logger.exception('%s', traceback.format_exc())
raise Exception(exp)
|
[
"def",
"start_module",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_main",
"(",
")",
"except",
"Exception",
"as",
"exp",
":",
"logger",
".",
"exception",
"(",
"'%s'",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",
"raise",
"Exception",
"(",
"exp",
")"
] |
Wrapper for _main function.
Catch and raise any exception occurring in the main function
:return: None
|
[
"Wrapper",
"for",
"_main",
"function",
".",
"Catch",
"and",
"raise",
"any",
"exception",
"occurring",
"in",
"the",
"main",
"function"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L234-L244
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.start
|
def start(self, http_daemon=None): # pylint: disable=unused-argument
"""Actually restart the process if the module is external
Try first to stop the process and create a new Process instance
with target start_module.
Finally start process.
:param http_daemon: Not used here but can be used in other modules
:type http_daemon: None | object
:return: None
"""
if not self.is_external:
return
if self.process:
self.stop_process()
logger.info("Starting external process for module %s...", self.name)
proc = Process(target=self.start_module, args=(), group=None)
# Under windows we should not call start() on an object that got its process
# as an object, so we remove it and we set it in a earlier start
try:
del self.properties['process']
except KeyError:
pass
proc.start()
# We save the process data AFTER the fork()
self.process = proc
self.properties['process'] = proc
logger.info("%s is now started (pid=%d)", self.name, proc.pid)
|
python
|
def start(self, http_daemon=None): # pylint: disable=unused-argument
"""Actually restart the process if the module is external
Try first to stop the process and create a new Process instance
with target start_module.
Finally start process.
:param http_daemon: Not used here but can be used in other modules
:type http_daemon: None | object
:return: None
"""
if not self.is_external:
return
if self.process:
self.stop_process()
logger.info("Starting external process for module %s...", self.name)
proc = Process(target=self.start_module, args=(), group=None)
# Under windows we should not call start() on an object that got its process
# as an object, so we remove it and we set it in a earlier start
try:
del self.properties['process']
except KeyError:
pass
proc.start()
# We save the process data AFTER the fork()
self.process = proc
self.properties['process'] = proc
logger.info("%s is now started (pid=%d)", self.name, proc.pid)
|
[
"def",
"start",
"(",
"self",
",",
"http_daemon",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"self",
".",
"is_external",
":",
"return",
"if",
"self",
".",
"process",
":",
"self",
".",
"stop_process",
"(",
")",
"logger",
".",
"info",
"(",
"\"Starting external process for module %s...\"",
",",
"self",
".",
"name",
")",
"proc",
"=",
"Process",
"(",
"target",
"=",
"self",
".",
"start_module",
",",
"args",
"=",
"(",
")",
",",
"group",
"=",
"None",
")",
"# Under windows we should not call start() on an object that got its process",
"# as an object, so we remove it and we set it in a earlier start",
"try",
":",
"del",
"self",
".",
"properties",
"[",
"'process'",
"]",
"except",
"KeyError",
":",
"pass",
"proc",
".",
"start",
"(",
")",
"# We save the process data AFTER the fork()",
"self",
".",
"process",
"=",
"proc",
"self",
".",
"properties",
"[",
"'process'",
"]",
"=",
"proc",
"logger",
".",
"info",
"(",
"\"%s is now started (pid=%d)\"",
",",
"self",
".",
"name",
",",
"proc",
".",
"pid",
")"
] |
Actually restart the process if the module is external
Try first to stop the process and create a new Process instance
with target start_module.
Finally start process.
:param http_daemon: Not used here but can be used in other modules
:type http_daemon: None | object
:return: None
|
[
"Actually",
"restart",
"the",
"process",
"if",
"the",
"module",
"is",
"external",
"Try",
"first",
"to",
"stop",
"the",
"process",
"and",
"create",
"a",
"new",
"Process",
"instance",
"with",
"target",
"start_module",
".",
"Finally",
"start",
"process",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L246-L276
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.stop_process
|
def stop_process(self):
"""Request the module process to stop and release it
:return: None
"""
if not self.process:
return
logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid)
self.kill()
# Clean inner process reference
self.process = None
|
python
|
def stop_process(self):
"""Request the module process to stop and release it
:return: None
"""
if not self.process:
return
logger.info("I'm stopping module %r (pid=%d)", self.name, self.process.pid)
self.kill()
# Clean inner process reference
self.process = None
|
[
"def",
"stop_process",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"process",
":",
"return",
"logger",
".",
"info",
"(",
"\"I'm stopping module %r (pid=%d)\"",
",",
"self",
".",
"name",
",",
"self",
".",
"process",
".",
"pid",
")",
"self",
".",
"kill",
"(",
")",
"# Clean inner process reference",
"self",
".",
"process",
"=",
"None"
] |
Request the module process to stop and release it
:return: None
|
[
"Request",
"the",
"module",
"process",
"to",
"stop",
"and",
"release",
"it"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L303-L314
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.manage_brok
|
def manage_brok(self, brok):
"""Request the module to manage the given brok.
There are a lot of different possible broks to manage. The list is defined
in the Brok class.
An internal module may redefine this function or, easier, define only the function
for the brok it is interested with. Hence a module interested in the `service_check_result`
broks will only need to define a function named as `manage_service_check_result_brok`
:param brok:
:type brok:
:return:
:rtype:
"""
manage = getattr(self, 'manage_' + brok.type + '_brok', None)
if not manage:
return False
# Be sure the brok is prepared before calling the function
brok.prepare()
return manage(brok)
|
python
|
def manage_brok(self, brok):
"""Request the module to manage the given brok.
There are a lot of different possible broks to manage. The list is defined
in the Brok class.
An internal module may redefine this function or, easier, define only the function
for the brok it is interested with. Hence a module interested in the `service_check_result`
broks will only need to define a function named as `manage_service_check_result_brok`
:param brok:
:type brok:
:return:
:rtype:
"""
manage = getattr(self, 'manage_' + brok.type + '_brok', None)
if not manage:
return False
# Be sure the brok is prepared before calling the function
brok.prepare()
return manage(brok)
|
[
"def",
"manage_brok",
"(",
"self",
",",
"brok",
")",
":",
"manage",
"=",
"getattr",
"(",
"self",
",",
"'manage_'",
"+",
"brok",
".",
"type",
"+",
"'_brok'",
",",
"None",
")",
"if",
"not",
"manage",
":",
"return",
"False",
"# Be sure the brok is prepared before calling the function",
"brok",
".",
"prepare",
"(",
")",
"return",
"manage",
"(",
"brok",
")"
] |
Request the module to manage the given brok.
There are a lot of different possible broks to manage. The list is defined
in the Brok class.
An internal module may redefine this function or, easier, define only the function
for the brok it is interested with. Hence a module interested in the `service_check_result`
broks will only need to define a function named as `manage_service_check_result_brok`
:param brok:
:type brok:
:return:
:rtype:
|
[
"Request",
"the",
"module",
"to",
"manage",
"the",
"given",
"brok",
".",
"There",
"are",
"a",
"lot",
"of",
"different",
"possible",
"broks",
"to",
"manage",
".",
"The",
"list",
"is",
"defined",
"in",
"the",
"Brok",
"class",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L327-L348
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule.manage_signal
|
def manage_signal(self, sig, frame): # pylint: disable=unused-argument
"""Generic function to handle signals
Only called when the module process received SIGINT or SIGKILL.
Set interrupted attribute to True, self.process to None and returns
:param sig: signal sent
:type sig:
:param frame: frame before catching signal
:type frame:
:return: None
"""
logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig])
if sig == signal.SIGHUP:
# if SIGHUP, reload configuration in arbiter
logger.info("Modules are not able to reload their configuration. "
"Stopping the module...")
logger.info("Request to stop the module")
self.interrupted = True
|
python
|
def manage_signal(self, sig, frame): # pylint: disable=unused-argument
"""Generic function to handle signals
Only called when the module process received SIGINT or SIGKILL.
Set interrupted attribute to True, self.process to None and returns
:param sig: signal sent
:type sig:
:param frame: frame before catching signal
:type frame:
:return: None
"""
logger.info("received a signal: %s", SIGNALS_TO_NAMES_DICT[sig])
if sig == signal.SIGHUP:
# if SIGHUP, reload configuration in arbiter
logger.info("Modules are not able to reload their configuration. "
"Stopping the module...")
logger.info("Request to stop the module")
self.interrupted = True
|
[
"def",
"manage_signal",
"(",
"self",
",",
"sig",
",",
"frame",
")",
":",
"# pylint: disable=unused-argument",
"logger",
".",
"info",
"(",
"\"received a signal: %s\"",
",",
"SIGNALS_TO_NAMES_DICT",
"[",
"sig",
"]",
")",
"if",
"sig",
"==",
"signal",
".",
"SIGHUP",
":",
"# if SIGHUP, reload configuration in arbiter",
"logger",
".",
"info",
"(",
"\"Modules are not able to reload their configuration. \"",
"\"Stopping the module...\"",
")",
"logger",
".",
"info",
"(",
"\"Request to stop the module\"",
")",
"self",
".",
"interrupted",
"=",
"True"
] |
Generic function to handle signals
Only called when the module process received SIGINT or SIGKILL.
Set interrupted attribute to True, self.process to None and returns
:param sig: signal sent
:type sig:
:param frame: frame before catching signal
:type frame:
:return: None
|
[
"Generic",
"function",
"to",
"handle",
"signals"
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L350-L371
|
train
|
Alignak-monitoring/alignak
|
alignak/basemodule.py
|
BaseModule._main
|
def _main(self):
"""module "main" method. Only used by external modules.
:return: None
"""
self.set_proctitle(self.name)
self.set_signal_handler()
logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid())
# Will block here!
try:
self.main()
except (IOError, EOFError):
pass
# logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc())
except Exception as exp: # pylint: disable=broad-except
logger.exception('main function exception: %s', exp)
self.do_stop()
logger.info("process for module %s is now exiting (pid=%d)", self.name, os.getpid())
exit()
|
python
|
def _main(self):
"""module "main" method. Only used by external modules.
:return: None
"""
self.set_proctitle(self.name)
self.set_signal_handler()
logger.info("process for module %s is now running (pid=%d)", self.name, os.getpid())
# Will block here!
try:
self.main()
except (IOError, EOFError):
pass
# logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc())
except Exception as exp: # pylint: disable=broad-except
logger.exception('main function exception: %s', exp)
self.do_stop()
logger.info("process for module %s is now exiting (pid=%d)", self.name, os.getpid())
exit()
|
[
"def",
"_main",
"(",
"self",
")",
":",
"self",
".",
"set_proctitle",
"(",
"self",
".",
"name",
")",
"self",
".",
"set_signal_handler",
"(",
")",
"logger",
".",
"info",
"(",
"\"process for module %s is now running (pid=%d)\"",
",",
"self",
".",
"name",
",",
"os",
".",
"getpid",
"(",
")",
")",
"# Will block here!",
"try",
":",
"self",
".",
"main",
"(",
")",
"except",
"(",
"IOError",
",",
"EOFError",
")",
":",
"pass",
"# logger.warning('[%s] EOF exception: %s', self.name, traceback.format_exc())",
"except",
"Exception",
"as",
"exp",
":",
"# pylint: disable=broad-except",
"logger",
".",
"exception",
"(",
"'main function exception: %s'",
",",
"exp",
")",
"self",
".",
"do_stop",
"(",
")",
"logger",
".",
"info",
"(",
"\"process for module %s is now exiting (pid=%d)\"",
",",
"self",
".",
"name",
",",
"os",
".",
"getpid",
"(",
")",
")",
"exit",
"(",
")"
] |
module "main" method. Only used by external modules.
:return: None
|
[
"module",
"main",
"method",
".",
"Only",
"used",
"by",
"external",
"modules",
"."
] |
f3c145207e83159b799d3714e4241399c7740a64
|
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/basemodule.py#L435-L457
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.