Debian Codegraph @

Nagstamon/servers/Centreon/CentreonAPI.py

raw
1 # encoding: utf-8
2
3 # Nagstamon - Nagios status monitor for your desktop
4 # Copyright (C) 2008-2026 Henri Wahl <[email protected]> et al.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19
20 import traceback
21 import urllib.request
22 import urllib.parse
23 import urllib.error
24 import sys
25 # API V2
26 import pprint
27 import json
28 import requests
29
30 from datetime import datetime, timedelta
31
32 from Nagstamon.objects import *
33 from Nagstamon.servers.Generic import GenericServer
34 from Nagstamon.config import conf
35 from Nagstamon.helpers import webbrowser_open
36
37
38 # This class support Centreon V2 API
39 # Things to do :
40 # - BROWSER_URLS -> move into define_url() to be consistent
41
42 class CentreonServer(GenericServer):
43
44 def __init__(self, **kwds):
45
46 GenericServer.__init__(self, **kwds)
47
48 self.TYPE = 'Centreon'
49
50 # Centreon API uses a token
51 self.token = None
52
53 # HARD/SOFT state mapping
54 self.HARD_SOFT = {'(H)': 'hard', '(S)': 'soft'}
55
56 # Entries for monitor default actions in context menu
57 # Removed Monitor, as I don’t know a way to show directly the service
58 # or host details page, so i show the main ressource page
59 # self.MENU_ACTIONS = ['Monitor', 'Recheck', 'Acknowledge', 'Submit check result', 'Downtime']
60 self.MENU_ACTIONS = ['Recheck', 'Acknowledge', 'Downtime']
61
62 # URLs of the Centreon pages
63 self.urls_centreon = None
64
65 # limit number of services retrived
66 self.limit_services_number = 9999
67
68 def init_config(self):
69 '''
70 init_config, called at thread start
71 '''
72 # Version check
73 result = self.fetch_url(f'{self.monitor_cgi_url}/api/latest/platform/versions', no_auth=True, giveback='raw')
74
75 data = json.loads(result.result)
76 error = result.error
77 status_code = result.status_code
78
79 # check if any error occured
80 errors_occured = self.check_for_error(data, error, status_code)
81 if errors_occured is not None:
82 return (errors_occured)
83
84 self.centreon_version_major = int(data["web"]["major"])
85 self.centreon_version_minor = int(data["web"]["minor"])
86 if conf.debug_mode is True:
87 self.debug(server='[' + self.get_name() + ']', debug='Centreon version detected : ' + str(self.centreon_version_major) + '.' + str(self.centreon_version_minor))
88
89 if self.centreon_version_major >= 21:
90 # URLs for browser shortlinks/buttons on popup window
91 self.BROWSER_URLS = {'monitor': '$MONITOR$/monitoring/resources',
92 'hosts': '$MONITOR$/monitoring/resources',
93 'services': '$MONITOR$/monitoring/resources',
94 'history': '$MONITOR$/main.php?p=20301'}
95 # RestAPI version
96 if self.centreon_version_major == 21:
97 self.restapi_version = "latest"
98 elif self.centreon_version_major == 22:
99 self.restapi_version = "v22.04"
100 elif self.centreon_version_major == 23 and self.centreon_version_minor == 4:
101 self.restapi_version = "v23.04"
102 elif self.centreon_version_major == 23 and self.centreon_version_minor == 10:
103 self.restapi_version = "v23.10"
104 elif self.centreon_version_major == 24:
105 self.restapi_version = "v24.04"
106 else:
107 self.restapi_version = "v24.04"
108 if conf.debug_mode is True:
109 self.debug(server='[' + self.get_name() + ']', debug='Centreon API version used : ' + self.restapi_version)
110
111 else:
112 if conf.debug_mode is True:
113 self.debug(server='[' + self.get_name() + ']', debug='Unsupported Centreon version, must be >= 21')
114
115 # Changed this because define_url was called 2 times
116 if not self.tls_error and self.urls_centreon is None:
117 self.define_url()
118
119 def init_http(self):
120 GenericServer.init_http(self)
121 if self.session is None:
122 self.session.headers.update({'Content-Type': 'application/json'})
123 self.token = self.get_token().result
124
125 def define_url(self):
126 urls_centreon_api_v2 = {
127 'resources': self.monitor_cgi_url + '/api/' + self.restapi_version + '/monitoring/resources',
128 'login': self.monitor_cgi_url + '/api/' + self.restapi_version + '/login',
129 'services': self.monitor_cgi_url + '/api/' + self.restapi_version + '/monitoring/resources',
130 'hosts': self.monitor_cgi_url + '/api/' + self.restapi_version + '/monitoring/resources'
131 }
132
133 self.urls_centreon = urls_centreon_api_v2
134
135 def open_monitor(self, host, service=''):
136 # Used for self.MENU_ACTIONS = ['Monitor']
137 # Autologin seems deprecated as admin must enable it globaly and use the old pages
138 # Ex : http://10.66.113.52/centreon/main.php?autologin=1&useralias=admin&token=xxxxxx
139 # if self.use_autologin is True:
140 # auth = '&autologin=1&useralias=' + self.username + '&token=' + self.autologin_key
141 # else:
142 # auth = ''
143 # webbrowser_open(self.urls_centreon['resources'] + auth )
144 webbrowser_open(self.monitor_cgi_url)
145
146 def get_token(self):
147 try:
148 cgi_data = {
149 "security": {
150 "credentials": {
151 "login": self.username,
152 "password": self.password
153 }
154 }
155 }
156
157 # Post json
158 json_string = json.dumps(cgi_data)
159 result = self.fetch_url(self.urls_centreon['login'], cgi_data=json_string, giveback='raw')
160
161 data = json.loads(result.result)
162 error = result.error
163 status_code = result.status_code
164
165 if conf.debug_mode:
166 self.debug(server=self.get_name(),
167 debug="Fetched JSON: " + pprint.pformat(data))
168
169 # check if any error occured
170 errors_occured = self.check_for_error(data, error, status_code)
171 if errors_occured is not None:
172 self.debug(server=self.get_name(), debug="Authentication failed")
173 return Result(result='ERROR', error="Authentication failed")
174
175 token = data["security"]["token"]
176 # ID of the user is needed by some requests
177 user_id = data["contact"]["id"]
178
179 if conf.debug_mode:
180 self.debug(server='[' + self.get_name() + ']',
181 debug='API login : ' + self.username + ' / ' + self.password + ' > Token : ' + token + ' > User ID : ' + str(
182 user_id))
183
184 self.user_id = user_id
185 self.session.headers.update({'X-Auth-Token': token})
186 return Result(result=token)
187
188 except:
189 traceback.print_exc(file=sys.stdout)
190 result, error = self.error(sys.exc_info())
191 return Result(result=result, error=error)
192
193 def get_host(self, host):
194 # https://demo.centreon.com/centreon/api/latest/monitoring/resources?page=1&limit=30&sort_by={"status_severity_code":"asc","last_status_change":"desc"}&types=["host"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]
195 url_hosts = self.urls_centreon['hosts'] + '?types=["host"]&search={"h.name":"' + host + '"}'
196
197 try:
198 # Get json
199 result = self.fetch_url(url_hosts, giveback='raw')
200
201 data = json.loads(result.result)
202 error = result.error
203 status_code = result.status_code
204
205 # check if any error occured
206 errors_occured = self.check_for_error(data, error, status_code)
207 if errors_occured is not None:
208 return (errors_occured)
209
210 fqdn = str(data["result"][0]["fqdn"])
211
212 if conf.debug_mode:
213 self.debug(server='[' + self.get_name() + ']',
214 debug='Get Host FQDN or address : ' + host + " / " + fqdn)
215
216 # Give back host or ip
217 return Result(result=fqdn)
218
219 except:
220 traceback.print_exc(file=sys.stdout)
221 # set checking flag back to False
222 self.isChecking = False
223 result, error = self.error(sys.exc_info())
224 return Result(result=result, error=error)
225
226 def get_host_and_service_id(self, host, service=''):
227 if service == "":
228 # Hosts only
229 # https://demo.centreon.com/centreon/api/latest/monitoring/resources?page=1&limit=30&sort_by={"status_severity_code":"asc","last_status_change":"desc"}&types=["host"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]
230 url_hosts = self.urls_centreon['hosts'] + '?types=["host"]&search={"h.name":"' + host + '"}'
231
232 try:
233 # Get json
234 result = self.fetch_url(url_hosts, giveback='raw')
235
236 data = json.loads(result.result)
237 error = result.error
238 status_code = result.status_code
239
240 # check if any error occured
241 errors_occured = self.check_for_error(data, error, status_code)
242 if errors_occured is not None:
243 return (errors_occured)
244
245 host_id = data["result"][0]["id"]
246
247 if conf.debug_mode:
248 self.debug(server='[' + self.get_name() + ']', debug='Get Host ID : ' + host + " / " + str(host_id))
249 return host_id
250
251 except:
252 traceback.print_exc(file=sys.stdout)
253 # set checking flag back to False
254 self.isChecking = False
255 result, error = self.error(sys.exc_info())
256 return Result(result=result, error=error)
257 else:
258 # Host + Service
259 if host == "Meta_Services":
260 url_service = self.urls_centreon[
261 'services'] + '?types=["metaservice"]&search={"s.name":"' + service + '"}'
262 else:
263 url_service = self.urls_centreon[
264 'services'] + '?types=["service"]&search={"$and":[{"h.name":{"$eq":"' + host + '"}}, {"s.description":{"$eq":"' + service + '"}}]}'
265
266 try:
267 # Get json
268 result = self.fetch_url(url_service, giveback='raw')
269
270 data = json.loads(result.result)
271 error = result.error
272 status_code = result.status_code
273
274 # check if any error occured
275 errors_occured = self.check_for_error(data, error, status_code)
276 if errors_occured is not None:
277 return (errors_occured)
278
279 if host == "Meta_Services":
280 host_id = 0
281 else:
282 host_id = data["result"][0]["parent"]["id"]
283 service_id = data["result"][0]["id"]
284
285 if conf.debug_mode:
286 self.debug(server='[' + self.get_name() + ']',
287 debug='Get Host / Service ID : ' + str(host_id) + " / " + str(service_id))
288 return host_id, service_id
289
290 except:
291 traceback.print_exc(file=sys.stdout)
292 # set checking flag back to False
293 self.isChecking = False
294 result, error = self.error(sys.exc_info())
295 return Result(result=result, error=error)
296
297 def get_start_end(self, host):
298 # I don’t know how to get this info...
299 # self.defaults_downtime_duration_hours = 2
300 # self.defaults_downtime_duration_minutes = 0
301 start = datetime.now()
302 end = datetime.now() + timedelta(hours=2)
303
304 return (str(start.strftime('%Y-%m-%d %H:%M')),
305 str(end.strftime('%Y-%m-%d %H:%M')))
306
307 def _get_status(self):
308 '''
309 Get status from Centreon Server
310 '''
311 # Be sure that the session is still active
312 result = self.check_session()
313 if result is not None:
314 if result.result == 'ERROR':
315 if 'urls_centreon' in result.error:
316 result.error = 'Connection error'
317 return result
318
319 # filter regexep to reduce network traffic
320 # waiting to find a solution to reverse regexp
321 # my first idea is
322 # begin by (^(?!(.*
323 # ending by )))
324 # replace | by )))(^(?!(.*
325 # replace )( by )|(
326 self.re_service_filter = ''
327 self.re_host_filter = ''
328 if conf.re_service_enabled is True and conf.re_service_reverse is True:
329 self.re_service_filter = '&search={"s.description":{"$rg":"' + str(conf.re_service_pattern) + '"}}'
330 if conf.re_host_enabled is True and conf.re_host_reverse is True:
331 self.re_host_filter = '&search={"h.name":{"$rg":"' + str(conf.re_host_pattern) + '"}}'
332
333 # Services URL
334 # https://demo.centreon.com/centreon/api/latest/monitoring/resources?page=1&limit=30&sort_by={"status_severity_code":"asc","last_status_change":"desc"}&types=["service"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]
335 url_services = self.urls_centreon[
336 'services'] + '?types=["metaservice","service"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]' + self.re_service_filter + '&limit=' + str(
337 self.limit_services_number)
338
339 # Hosts URL
340 # https://demo.centreon.com/centreon/api/latest/monitoring/resources?page=1&limit=30&sort_by={"status_severity_code":"asc","last_status_change":"desc"}&types=["host"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]
341 url_hosts = self.urls_centreon[
342 'hosts'] + '?types=["host"]&statuses=["WARNING","DOWN","CRITICAL","UNKNOWN"]' + self.re_host_filter + '&limit=' + str(
343 self.limit_services_number)
344
345 # Hosts
346 try:
347 # Get json
348 result = self.fetch_url(url_hosts, giveback='raw')
349
350 data = json.loads(result.result)
351 error = result.error
352 status_code = result.status_code
353
354 # check if any error occured
355 errors_occured = self.check_for_error(data, error, status_code)
356 if errors_occured is not None:
357 return (errors_occured)
358
359 if data["meta"]["total"] == 0:
360 self.debug(server='[' + self.get_name() + ']', debug='No host down')
361 else:
362 for alerts in data["result"]:
363 new_host = alerts["name"]
364 self.new_hosts[new_host] = GenericHost()
365 self.new_hosts[new_host].name = alerts["name"]
366 self.new_hosts[new_host].server = self.name
367 # API inconsistency, even by fixing exact version number, changed starting with 22.04
368 if self.centreon_version_major == 21 or (self.centreon_version_major == 22 and self.centreon_version_minor == 4):
369 self.new_hosts[new_host].criticality = alerts["severity_level"]
370 else:
371 self.new_hosts[new_host].criticality = alerts["severity"]
372 self.new_hosts[new_host].status = alerts["status"]["name"]
373 self.new_hosts[new_host].last_check = alerts["last_check"]
374 # last_state_change = datetime.strptime(alerts["last_status_change"], '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
375 self.new_hosts[new_host].duration = alerts["duration"]
376 self.new_hosts[new_host].attempt = alerts["tries"]
377 self.new_hosts[new_host].status_information = alerts["information"]
378 # Change starting with 23.10
379 if (self.centreon_version_major >= 23 and self.centreon_version_minor >= 10) or self.centreon_version_major > 23:
380 self.new_hosts[new_host].passiveonly = alerts["has_passive_checks_enabled"]
381 self.new_hosts[new_host].notifications_disabled = not alerts["is_notification_enabled"]
382 self.new_hosts[new_host].acknowledged = alerts["is_acknowledged"]
383 self.new_hosts[new_host].scheduled_downtime = alerts["is_in_downtime"]
384 else:
385 self.new_hosts[new_host].passiveonly = alerts["passive_checks"]
386 self.new_hosts[new_host].notifications_disabled = not alerts["notification_enabled"]
387 self.new_hosts[new_host].acknowledged = alerts["acknowledged"]
388 self.new_hosts[new_host].scheduled_downtime = alerts["in_downtime"]
389 # avoid crash if flapping is not configured in Centreon
390 # according to https://github.com/HenriWahl/Nagstamon/issues/866#issuecomment-1302257034
391 self.new_hosts[new_host].flapping = alerts.get("flapping", False)
392 if "(S)" in alerts["tries"]:
393 self.new_hosts[new_host].status_type = self.HARD_SOFT['(S)']
394 else:
395 self.new_hosts[new_host].status_type = self.HARD_SOFT['(H)']
396 self.debug(server='[' + self.get_name() + ']', debug='Host indexed : ' + new_host)
397
398 except:
399 traceback.print_exc(file=sys.stdout)
400 # set checking flag back to False
401 self.isChecking = False
402 result, error = self.error(sys.exc_info())
403 return Result(result=result, error=error)
404
405 # Services
406 try:
407 # Get json
408 result = self.fetch_url(url_services, giveback='raw')
409
410 data = json.loads(result.result)
411 error = result.error
412 status_code = result.status_code
413
414 # check if any error occured
415 errors_occured = self.check_for_error(data, error, status_code)
416 if errors_occured is not None:
417 return (errors_occured)
418
419 if data["meta"]["total"] == 0:
420 self.debug(server='[' + self.get_name() + ']', debug='No service down')
421 else:
422 for alerts in data["result"]:
423 if alerts["type"] == "metaservice":
424 new_host = "Meta_Services"
425 else:
426 new_host = alerts["parent"]["name"]
427 new_service = alerts["name"]
428 # Needed if non-ok services are on a UP host
429 if not new_host in self.new_hosts:
430 self.new_hosts[new_host] = GenericHost()
431 self.new_hosts[new_host].name = new_host
432 self.new_hosts[new_host].status = 'UP'
433 self.new_hosts[new_host].services[new_service] = GenericService()
434 # Attributs à remplir
435 self.debug(server='[' + self.get_name() + ']',
436 debug='Service indexed : ' + new_host + ' / ' + new_service)
437
438 self.new_hosts[new_host].services[new_service].server = self.name
439 self.new_hosts[new_host].services[new_service].host = new_host
440 self.new_hosts[new_host].services[new_service].name = new_service
441 self.new_hosts[new_host].services[new_service].status = alerts["status"]["name"]
442 self.new_hosts[new_host].services[new_service].last_check = alerts["last_check"]
443 # last_state_change = datetime.strptime(alerts["last_state_change"], '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
444 # self.new_hosts[new_host].services[new_service].duration = datetime.now() - last_state_change
445 self.new_hosts[new_host].services[new_service].duration = alerts["duration"]
446 self.new_hosts[new_host].services[new_service].attempt = alerts["tries"]
447 self.new_hosts[new_host].services[new_service].status_information = alerts["information"]
448 # Change starting with 23.10
449 if (self.centreon_version_major >= 23 and self.centreon_version_minor >= 10) or self.centreon_version_major > 23:
450 self.new_hosts[new_host].services[new_service].passiveonly = alerts["has_passive_checks_enabled"]
451 self.new_hosts[new_host].services[new_service].notifications_disabled = not alerts["is_notification_enabled"]
452 self.new_hosts[new_host].services[new_service].acknowledged = alerts["is_acknowledged"]
453 self.new_hosts[new_host].services[new_service].scheduled_downtime = alerts["is_in_downtime"]
454 else:
455 self.new_hosts[new_host].services[new_service].passiveonly = alerts["passive_checks"]
456 self.new_hosts[new_host].services[new_service].notifications_disabled = not alerts["notification_enabled"]
457 self.new_hosts[new_host].services[new_service].acknowledged = alerts["acknowledged"]
458 self.new_hosts[new_host].services[new_service].scheduled_downtime = alerts["in_downtime"]
459 # avoid crash if flapping is not configured in Centreon
460 # according to https://github.com/HenriWahl/Nagstamon/issues/866#issuecomment-1302257034
461 self.new_hosts[new_host].services[new_service].flapping = alerts.get("flapping", False)
462 if "(S)" in alerts["tries"]:
463 self.new_hosts[new_host].services[new_service].status_type = self.HARD_SOFT['(S)']
464 else:
465 self.new_hosts[new_host].services[new_service].status_type = self.HARD_SOFT['(H)']
466 # API inconsistency, even by fixing exact version number, changed starting with 22.04
467 if self.centreon_version_major == 21 or (self.centreon_version_major == 22 and self.centreon_version_minor == 4):
468 self.new_hosts[new_host].services[new_service].criticality = alerts["severity_level"]
469 else:
470 self.new_hosts[new_host].services[new_service].criticality = alerts["severity"]
471
472 except:
473 traceback.print_exc(file=sys.stdout)
474 # set checking flag back to False
475 self.isChecking = False
476 result, error = self.error(sys.exc_info())
477 return Result(result=result, error=error)
478
479 # return True if all worked well
480 return Result()
481
482 def _set_acknowledge(self, host, service, author, comment, sticky, notify, persistent, all_services=None):
483 try:
484
485 acknowledgements = {
486 "acknowledgement": {
487 "comment": comment,
488 "with_services": True,
489 "is_notify_contacts": notify,
490 "is_persistent_comment": persistent,
491 "is_sticky": sticky
492 },
493 "resources": [
494 ]
495 }
496
497 # host
498 if service == '':
499 host_id = self.get_host_and_service_id(host)
500 if self.centreon_version_major >= 24:
501 new_resource = {
502 "type": "host",
503 "id": host_id,
504 "parent": {
505 "id": host_id
506 }
507 }
508 else:
509 new_resource = {
510 "type": "host",
511 "id": host_id,
512 "parent": {
513 "id": None
514 }
515 }
516
517 acknowledgements["resources"].append(new_resource)
518
519 # Post json
520 json_string = json.dumps(acknowledgements)
521 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/hosts/{host_id}/acknowledgements
522 result = self.fetch_url(self.urls_centreon['resources'] + '/acknowledge', cgi_data=json_string,
523 giveback='raw')
524
525 error = result.error
526 status_code = result.status_code
527
528 if conf.debug_mode:
529 self.debug(server='[' + self.get_name() + ']',
530 debug="Set Ack on Host, status code : " + str(status_code))
531
532 # Service
533 if service != '' or all_services:
534 if not all_services:
535 all_services = [service]
536
537 for s in all_services:
538 host_id, service_id = self.get_host_and_service_id(host, service)
539
540 if host == "Meta_Services":
541 new_resource = {
542 "type": "metaservice",
543 "id": service_id,
544 "parent": {
545 "id": None
546 }
547 }
548
549 else:
550 new_resource = {
551 "type": "service",
552 "id": service_id,
553 "parent": {
554 "id": host_id
555 }
556 }
557
558 acknowledgements["resources"].append(new_resource)
559 if conf.debug_mode:
560 self.debug(server='[' + self.get_name() + ']',
561 debug="Stack ack for Host (" + host + ") / Service (" + service + ")")
562
563 # Post json
564 json_string = json.dumps(acknowledgements)
565 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/services/acknowledgements
566 result = self.fetch_url(self.urls_centreon['resources'] + '/acknowledge', cgi_data=json_string,
567 giveback='raw')
568
569 error = result.error
570 status_code = result.status_code
571
572 if conf.debug_mode:
573 self.debug(server='[' + self.get_name() + ']',
574 debug="Set Acks, status code : " + str(status_code))
575
576 except:
577 traceback.print_exc(file=sys.stdout)
578 # set checking flag back to False
579 self.isChecking = False
580 result, error = self.error(sys.exc_info())
581 return Result(result=result, error=error)
582
583 def _set_recheck(self, host, service):
584 rechecks = {
585 "resources": [
586 ]
587 }
588
589 # This new parameter was added in 23.04
590 if self.centreon_version_major >= 23:
591 property_to_add = {
592 "check": {
593 "is_forced": True
594 }
595 }
596 rechecks.update(property_to_add)
597
598 try:
599 # Host
600 if service == '':
601 host_id = self.get_host_and_service_id(host)
602
603 new_resource = {
604 "type": "host",
605 "id": host_id,
606 "parent": None
607 }
608
609 rechecks["resources"].append(new_resource)
610
611 # Post json
612 json_string = json.dumps(rechecks)
613 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/resources/check
614 result = self.fetch_url(self.urls_centreon['resources'] + '/check', cgi_data=json_string, giveback='raw')
615
616 error = result.error
617 status_code = result.status_code
618
619 if conf.debug_mode:
620 self.debug(server='[' + self.get_name() + ']',
621 debug="Recheck on Host : " + host + ", status code : " + str(status_code))
622
623 # Service
624 else:
625 host_id, service_id = self.get_host_and_service_id(host, service)
626
627 if host == "Meta_Services":
628 new_resource = {
629 "type": "metaservice",
630 "id": service_id,
631 "parent": None
632 }
633
634 else:
635 new_resource = {
636 "type": "service",
637 "id": service_id,
638 "parent": {
639 "id": host_id
640 }
641 }
642
643 rechecks["resources"].append(new_resource)
644
645 # Post json
646 json_string = json.dumps(rechecks)
647 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/resources/check
648 result = self.fetch_url(self.urls_centreon['resources'] + '/check', cgi_data=json_string, giveback='raw')
649
650 error = result.error
651 status_code = result.status_code
652
653 if conf.debug_mode:
654 self.debug(server='[' + self.get_name() + ']',
655 debug="Reckeck on Host (" + host + ") / Service (" + service + "), status code : " + str(
656 status_code))
657
658 except:
659 traceback.print_exc(file=sys.stdout)
660 # set checking flag back to False
661 self.isChecking = False
662 result, error = self.error(sys.exc_info())
663 return Result(result=result, error=error)
664
665 def _set_downtime(self, host, service, author, comment, fixed, start_time, end_time, hours, minutes):
666 obj_start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M')
667 obj_end_time = datetime.strptime(end_time, '%Y-%m-%d %H:%M')
668
669 # Nagstamon don’t provide the TZ, we need to get it from the OS
670 obj_start_time = obj_start_time.replace(tzinfo=datetime.now().astimezone().tzinfo)
671 obj_end_time = obj_end_time.replace(tzinfo=datetime.now().astimezone().tzinfo)
672
673 # duration unit is second
674 duration = (hours * 3600) + (minutes * 60)
675
676 #  API require boolean
677 if fixed == 1:
678 fixed = True
679 else:
680 fixed = False
681
682 downtimes = {
683 "downtime": {
684 "comment": comment,
685 "with_services": True,
686 "is_fixed": fixed,
687 "duration": duration,
688 "start_time": obj_start_time.strftime('%Y-%m-%dT%H:%M:%S%z'),
689 "end_time": obj_end_time.strftime('%Y-%m-%dT%H:%M:%S%z')
690 },
691 "resources": [
692 ]
693 }
694
695 try:
696 if service == '':
697 # Host
698 host_id = self.get_host_and_service_id(host)
699
700 new_resource = {
701 "type": "host",
702 "id": host_id,
703 "parent": None
704 }
705
706 downtimes["resources"].append(new_resource)
707
708 # Post json
709 json_string = json.dumps(downtimes)
710 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/resources/downtime
711 result = self.fetch_url(self.urls_centreon['resources'] + '/downtime', cgi_data=json_string,
712 giveback='raw')
713
714 error = result.error
715 status_code = result.status_code
716
717 if conf.debug_mode:
718 self.debug(server='[' + self.get_name() + ']',
719 debug="Downtime on Host : " + host + ", status code : " + str(status_code))
720
721 # Service
722 else:
723 host_id, service_id = self.get_host_and_service_id(host, service)
724
725 if host == "Meta_Services":
726 new_resource = {
727 "type": "metaservice",
728 "id": service_id,
729 "parent": {
730 "id": None
731 }
732 }
733
734 else:
735 new_resource = {
736 "type": "service",
737 "id": service_id,
738 "parent": {
739 "id": host_id
740 }
741 }
742
743 downtimes["resources"].append(new_resource)
744
745 # Post json
746 json_string = json.dumps(downtimes)
747 # {protocol}://{server}:{port}/centreon/api/{version}/monitoring/resources/downtime
748 result = self.fetch_url(self.urls_centreon['resources'] + '/downtime', cgi_data=json_string,
749 giveback='raw')
750
751 error = result.error
752 status_code = result.status_code
753
754 if conf.debug_mode:
755 self.debug(server='[' + self.get_name() + ']',
756 debug="Downtime on Host (" + host + ") / Service (" + service + "), status code : " + str(
757 status_code))
758
759
760 except:
761 traceback.print_exc(file=sys.stdout)
762 # set checking flag back to False
763 self.isChecking = False
764 result, error = self.error(sys.exc_info())
765 return Result(result=result, error=error)
766
767 def check_session(self):
768 if conf.debug_mode:
769 self.debug(server='[' + self.get_name() + ']', debug='Checking session status')
770
771 try:
772 if conf.debug_mode:
773 self.debug(server='[' + self.get_name() + ']',
774 debug='Check-session, the token expire if not been used for more than one hour. Current Token = ' + str(
775 self.token))
776
777 cgi_data = {'limit': '1'}
778 # Get en small service list, to check the status of the current token
779 # This request must be done in a GET, so just encode the parameters and fetch
780 result = self.fetch_url(self.urls_centreon['resources'] + '?' + urllib.parse.urlencode(cgi_data),
781 giveback="raw")
782
783 # If we got an 403 or 401 (and 500 for version 21.), the token expired and must be renewed
784 if self.centreon_version_major == 21:
785 ressources_response_list = [401, 403, 500]
786 else:
787 ressources_response_list = [400, 401, 403]
788
789 if result.status_code in ressources_response_list:
790 get_token_result = self.get_token()
791 if get_token_result.result == 'ERROR':
792 return Result(result='ERROR', error=get_token_result.error)
793 else:
794 self.token = get_token_result.result
795 if conf.debug_mode:
796 self.debug(server='[' + self.get_name() + ']', debug='Check-session, session renewed')
797 result = self.fetch_url(self.urls_centreon['resources'] + '?' + urllib.parse.urlencode(cgi_data),
798 giveback="raw")
799 if not 'ConnectTimeoutError' in result.error and \
800 not 'NewConnectionError' in result.error:
801 data = json.loads(result.result)
802 error = result.error
803 status_code = result.status_code
804 else:
805 return Result(result='ERROR',
806 error='Connection error')
807
808 if conf.debug_mode:
809 self.debug(server=self.get_name(),
810 debug="Check-session, Fetched JSON: " + pprint.pformat(data))
811 self.debug(server=self.get_name(),
812 debug="Check-session, Error : " + error + ", Status code : " + str(status_code))
813
814 except:
815 traceback.print_exc(file=sys.stdout)
816 result, error = self.error(sys.exc_info())
817 return Result(result=result, error=error)