def live(self) -> livestatus.SingleSiteConnection: # Note: If the site comes from a SiteFactory instance, the TCP connection # is insecure, i.e. no TLS. live = ( livestatus.LocalConnection() if self._is_running_as_site_user() else livestatus.SingleSiteConnection( "tcp:%s:%d" % (self.http_address, self.livestatus_port) ) ) live.set_timeout(2) return live
def test_livestatus_ipv4_connection(): with closing(socket.socket(socket.AF_INET)) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Pick a random port sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] sock.listen(1) live = livestatus.SingleSiteConnection("tcp:127.0.0.1:%d" % port) live.connect()
def get_query(self, get, columns, filtering, *args): command = [] c_list = [] output_str = 'OutputFormat: python\n' command = [ 'GET ' + get, 'Columns: ' + ' '.join([column for column in columns]) ] + ['Filter: ' + fltr for fltr in filtering] + [arg for arg in args] + [output_str] get_command = '\n'.join(command) status = livestatus.SingleSiteConnection( self.socket_path).query_table(get_command) return status
def get_rrd_data(hostname: HostName, service_description: ServiceName, varname: MetricName, cf: ConsolidationFunctionName, fromtime: Timestamp, untiltime: Timestamp, max_entries: int = 400) -> TimeSeries: """Fetch RRD historic metrics data of a specific service, within the specified time range returns a TimeSeries object holding interval and data information Query to livestatus always returns if database is found, thus: - Values can be None when there is no data for a given timestamp - Reply from livestatus/rrdtool is always enough to describe the queried interval. That means, the returned bounds are always outside the queried interval. LEGEND O timestamps of measurements | query values, fromtime and untiltime x returned start, no data contained v returned data rows, includes end y --O---O---O---O---O---O---O---O |---------------| x---v---v---v---v---y """ step = 1 rpn = "%s.%s" % (varname, cf.lower()) # "MAX" -> "max" point_range = ":".join( livestatus.lqencode(str(x)) for x in (fromtime, untiltime, step, max_entries)) column = "rrddata:m1:%s:%s" % (rpn, point_range) lql = livestatus_lql([hostname], [column], service_description) + "OutputFormat: python\n" try: connection = livestatus.SingleSiteConnection("unix:%s" % cmk.utils.paths.livestatus_unix_socket) response = connection.query_value(lql) except livestatus.MKLivestatusNotFoundError as e: if cmk.utils.debug.enabled(): raise raise MKGeneralException("Cannot get historic metrics via Livestatus: %s" % e) if response is None: raise MKGeneralException("Cannot retrieve historic data with Nagios Core") return TimeSeries(response)
def show_New_Logs(socket_path): logs = [] try: t = calendar.timegm(time.gmtime()) logs = livestatus.SingleSiteConnection(socket_path).query_table( "GET log\nColumns: host_name service_description time state\nWaitTrigger: log\nFilter: time >= %d\nFilter: class = 1\nOutputFormat: python" % t) if logs: print(logs, t) except Exception as e: print("Livestatus Error %s" % str(e)) return logs
def module_init(args): global wanted_types, wanted_names global have_type_arg, have_name_arg global mst, lsc, ls_path, qh qh_path = False rem_args = [] i = -1 for arg in args: i += 1 if arg == '--': rem_args += args[i:] break if arg.startswith('--merlin-cfg=') or arg.startswith('--config='): mconf.config_file = arg.split('=', 1)[1] elif arg.startswith('--type='): wanted_types = arg.split('=')[1].split(',') have_type_arg = True elif arg.startswith('--name='): wanted_names = arg.split('=')[1].split(',') have_name_arg = True elif arg.startswith('--qh-socket='): qh_path = arg.split('=', 1)[1] else: # not an argument we recognize, so stash it and move on rem_args += [arg] continue if os.access(nagios_cfg, os.R_OK): comp = cconf.parse_nagios_cfg(nagios_cfg) qh = comp.query_socket for k, v in comp.params: if k == 'broker_module' and 'livestatus' in v: ary = v[1].rsplit(' ') for p in ary[1:]: if not '=' in p: ls_path = p break elif k == 'check_result_path': check_result_path = v if qh_path: qh = qh_path lsc = livestatus.SingleSiteConnection('unix:' + ls_path) return rem_args
def log_Since_Time(socket_path): import livestatus, time, calendar t = calendar.timegm(time.gmtime()) zeitraum = input( "Auf welchen Zeitraum sollen die Ergebnisse eingegrenzt werden? Eingabe in Minuten:" ) zeitraum = zeitraum * 60 t = t - zeitraum try: services = livestatus.SingleSiteConnection(socket_path).query_table( "GET log\nFilter: time >= %d\nFilter: class = 1\nColumns: host_name service_description time state\nOutputFormat: python" % t) for host_name, service_description, time, state in services: print("%-12s %-25s %-12s %-5s" % (host_name, service_description, time, state)) except Exception as e: print("Livestatus Error %s" % str(e))
def get_rrd_data(hostname, service_description, varname, cf, fromtime, untiltime): step = 1 rpn = "%s.%s" % (varname, cf.lower()) # "MAX" -> "max" lql = "GET services\n" \ "Columns: rrddata:m1:%s:%d:%d:%d\n" \ "OutputFormat: python\n" \ "Filter: host_name = %s\n" \ "Filter: description = %s\n" % ( rpn, fromtime, untiltime, step, hostname, service_description) try: connection = livestatus.SingleSiteConnection("unix:%s" % cmk.paths.livestatus_unix_socket) response = connection.query_value(lql) except Exception, e: if cmk.debug.enabled(): raise raise MKGeneralException("Cannot get historic metrics via Livestatus: %s" % e)
def test_livestatus_ipv6_connection(): with closing(socket.socket(socket.AF_INET6)) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Pick a random port try: sock.bind(("::1", 0)) except socket.error as e: # Skip this test in case ::1 can not be bound to # (happened in docker container with IPv6 disabled) if e.errno == errno.EADDRNOTAVAIL: pytest.skip("Unable to bind to ::1 (%s)" % e) port = sock.getsockname()[1] sock.listen(1) live = livestatus.SingleSiteConnection("tcp6:::1:%d" % port) live.connect()
def show_Services(socket_path): try: print("\nServices mit genauer Beschreibung") t = time.ctime() print("Zeitpunkt der Abfrage: %s\n" % t) services = livestatus.SingleSiteConnection(socket_path).query_table( "GET services\nColumns: host_name description state") for host_name, description, state in services: print("%-10s %-20s %s" % (host_name, description, state)) fobj_out = open( "/home/service/Schreibtisch/Testprogramme/ServiceLOG.txt", "a") fobj_out.write("Zeitpunkt der Abfrage: %s\n" % t) for host_name in services: fobj_out.write("%s\n" % (host_name)) except Exception as e: print("Livestatus Error %s" % str(e)) return services
def show_Availability(socket_path): try: t = calendar.timegm(time.gmtime()) z = input( "Geben Sie den Zeitraum ein, in dem die Verfügbarkeit der Services bestimmt werden soll. (Eingabe in Stunden):" ) k = z * 3600 k = t - k availability = livestatus.SingleSiteConnection( socket_path ).query_table( "GET statehist\nColumns: host_name service_description\nFilter: time < %d\nFilter: time >= %d\nStats: sum duration_part_ok\nStats: sum duration_part_warning\nStats: sum duration_part_critical\nStats: sum duration_part_unknown\nStats: sum duration_part_unmonitored" % (t, k)) for line in availability: print(line) except Exception as e: print("Livestatus Error %s" % str(e))
def module_init(args): global wanted_types, wanted_names global have_type_arg, have_name_arg global mst, lsc, ls_path, qh rem_args = [] i = -1 for arg in args: i += 1 if arg == '--': rem_args += args[i:] break if arg.startswith('--merlin-cfg=') or arg.startswith('--config='): mconf.config_file = arg.split('=', 1)[1] elif arg.startswith('--type='): wanted_types = arg.split('=')[1].split(',') have_type_arg = True elif arg.startswith('--name='): wanted_names = arg.split('=')[1].split(',') have_name_arg = True else: # not an argument we recognize, so stash it and move on rem_args += [arg] continue comp = cconf.parse_conf(nagios_cfg) for v in comp.params: if v[0] == 'query_socket': qh = v[1] elif v[0] == 'broker_module' and 'livestatus' in v[1]: ary = v[1].rsplit(' ') for p in ary[1:]: if not '=' in p: ls_path = p break lsc = livestatus.SingleSiteConnection('unix:' + ls_path) mst = merlin_status(lsc, qh) return rem_args
def test_create_socket_no_cert(tmpdir): open("%s/z.pem" % tmpdir, "wb") live = livestatus.SingleSiteConnection( "unix:/tmp/xyz", tls=True, verify=True, ca_file_path="%s/z.pem" % tmpdir) with pytest.raises(livestatus.MKLivestatusConfigError, match="Failed to load CA file"): live._create_socket(socket.AF_INET)
import os, sys import livestatus try: omd_root = os.getenv("OMD_ROOT") socket_path = "unix:" + omd_root + "/tmp/run/live" except: sys.stderr.write("This example is indented to run in an OMD site\n") sys.stderr.write("Please change socket_path in this example, if you are\n") sys.stderr.write("not using OMD.\n") sys.exit(1) try: # Make a single connection for each query print "\nPerformance:" for key, value in livestatus.SingleSiteConnection( socket_path).query_row_assoc("GET status").items(): print "%-30s: %s" % (key, value) print "\nHosts:" hosts = livestatus.SingleSiteConnection(socket_path).query_table( "GET hosts\nColumns: name alias address") for name, alias, address in hosts: print "%-16s %-16s %s" % (name, address, alias) # Do several queries in one connection conn = livestatus.SingleSiteConnection(socket_path) num_up = conn.query_value("GET hosts\nStats: hard_state = 0") print "\nHosts up: %d" % num_up stats = conn.query_row("GET services\n" "Stats: state = 0\n" "Stats: state = 1\n"
def live(self): import livestatus live = livestatus.SingleSiteConnection("tcp:127.0.0.1:%d" % self.livestatus_port) live.set_timeout(2) return live
gleicheWerte = 0 once = False while (1): if once == False: try: omd_root = os.getenv("OMD_ROOT") socket_path = "unix:" + omd_root + "/tmp/run/live" except: sys.stderr.write("Fehler! OMD!") sys.exit(1) try: t = time.ctime() services = livestatus.SingleSiteConnection(socket_path).query_table( "GET services\nColumns: host_name description state\nKeepAlive: on" ) if Erstanlauf == False: print "\nServices mit genauerer Beschreibung:" print "Zeitpunkt der Abfrage: %s\n" % t for host_name, description, state in services: print "%-10s %-20s %s" % (host_name, description, state) fobj_out = open( "/home/service/Schreibtisch/Testprogramme/ServiceLOG.txt", "a") fobj_out.write("Zeitpunkt der Abfrage: %s\n" % t) for host_name in services: fobj_out.write("%s\n" % (host_name)) Erstanlauf = True
def get_livestatus_data(query): try: return livestatus.SingleSiteConnection(socket_path).query_table(query) except Exception as e: # livestatus.MKLivestatusException, e: print "Livestatus error: %s" % str(e) sys.exit(1)
try: omd_root = os.getenv("OMD_ROOT") socket_path = "unix:" + omd_root + "/tmp/run/live" except: sys.stderr.write("Fehler! OMD!") sys.exit(1) try: t = calendar.timegm(time.gmtime()) zeitraum = input( "Auf welchen Zeitraum sollen die Ergebnisse eingegrenzt werden? Eingabe in Minuten:" ) zeitraum = zeitraum * 60 t = t - zeitraum services = livestatus.SingleSiteConnection(socket_path).query_table( "GET log\nFilter: time >= %d\nFilter: class = 1\nColumns: host_name service_description time state\nOutputFormat: python" % t) for host_name, service_description, time, state in services: print "%-12s %-25s %-12s %-5s" % (host_name, service_description, time, state) # for line in services: # print line except Exception, e: print "Livestatus error %s" % str(e)
def test_create_socket_not_existing_ca_file(): live = livestatus.SingleSiteConnection( "unix:/tmp/xyz", tls=True, verify=True, ca_file_path="/x/y/z.pem") with pytest.raises(livestatus.MKLivestatusConfigError, match="No such file or"): live._create_socket(socket.AF_INET)
y=%d url=/pnp4nagios/graph?host=%s&srv=%s } """ % (host, service, x + 30 + shift * num, g_y, host, service) # Gesamtzustand Thermometer display_servicegroup(name + "_therm", x_therm) # Auflistung der USV-Parameter display_servicegroup(name + "_usv", x_usv) socket_path = "unix:/var/run/nagios/rw/live" live = livestatus.SingleSiteConnection(socket_path) print """ define global { allowed_for_config=nagiosadmin allowed_user=nagiosadmin map_image=demo_background.png iconset=std_medium } """ # hostgroups = live.query("GET hostgroups\nColumns: name alias") hostgroups = [ ( "s02", "S-02" ), ( "s06", "S-06" ),
def connect_to_livestatus(html): html.site_status = {} # site_status keeps a dictionary for each site with the following # keys: # "state" --> "online", "disabled", "down", "unreach", "dead" or "waiting" # "exception" --> An error exception in case of down, unreach, dead or waiting # "status_host_state" --> host state of status host (0, 1, 2 or None) # "livestatus_version" --> Version of sites livestatus if "online" # "program_version" --> Version of Nagios if "online" # If there is only one site (non-multisite), than # user cannot enable/disable. if config.is_multisite(): # do not contact those sites the user has disabled. # Also honor HTML-variables for switching off sites # right now. This is generally done by the variable # _site_switch=sitename1:on,sitename2:off,... switch_var = html.var("_site_switch") if switch_var: for info in switch_var.split(","): sitename, onoff = info.split(":") d = config.user_siteconf.get(sitename, {}) if onoff == "on": d["disabled"] = False else: d["disabled"] = True config.user_siteconf[sitename] = d config.save_site_config() # Make lists of enabled and disabled sites enabled_sites = {} disabled_sites = {} for sitename, site in config.allsites().items(): siteconf = config.user_siteconf.get(sitename, {}) if siteconf.get("disabled", False): html.site_status[sitename] = { "state": "disabled", "site": site } disabled_sites[sitename] = site else: html.site_status[sitename] = {"state": "dead", "site": site} enabled_sites[sitename] = site html.live = livestatus.MultiSiteConnection(enabled_sites, disabled_sites) # Fetch status of sites by querying the version of Nagios and livestatus html.live.set_prepend_site(True) for sitename, v1, v2, ps, num_hosts, num_services in html.live.query( "GET status\n" "Columns: livestatus_version program_version program_start num_hosts num_services" ): html.site_status[sitename].update({ "state": "online", "livestatus_version": v1, "program_version": v2, "program_start": ps, "num_hosts": num_hosts, "num_services": num_services, }) html.live.set_prepend_site(False) # Get exceptions in case of dead sites for sitename, deadinfo in html.live.dead_sites().items(): html.site_status[sitename]["exception"] = deadinfo["exception"] shs = deadinfo.get("status_host_state") html.site_status[sitename]["status_host_state"] = shs if shs == None: statename = "dead" else: statename = { 1: "down", 2: "unreach", 3: "waiting", }.get(shs, "unknown") html.site_status[sitename]["state"] = statename else: html.live = livestatus.SingleSiteConnection( "unix:" + defaults.livestatus_unix_socket) html.live.set_timeout(10) # default timeout is 10 seconds html.site_status = {'': {"state": "dead", "site": config.site('')}} v1, v2, ps = html.live.query_row( "GET status\nColumns: livestatus_version program_version program_start" ) html.site_status[''].update({ "state": "online", "livestatus_version": v1, "program_version": v2, "program_start": ps }) # If Multisite is retricted to data user is a nagios contact for, # we need to set an AuthUser: header for livestatus if not config.may("general.see_all"): html.live.set_auth_user('read', config.user_id) html.live.set_auth_user('action', config.user_id) # May the user see all objects in BI aggregations or only some? if not config.may("bi.see_all"): html.live.set_auth_user('bi', config.user_id) # Default auth domain is read. Please set to None to switch off authorization html.live.set_auth_domain('read')
import os, sys import livestatus try: omd_root = os.getenv("OMD_ROOT") socket_path = "unix:" + omd_root + "/tmp/run/live" except: sys.stderr.write("This test is intended to run in OMD") sys.exit(1) try: print "\nHosts:" hosts = livestatus.SingleSiteConnection(socket_path).query_table( "GET hosts\nColumns: name alias address") for name, alias, address in hosts: print "%-16s %-16s %s" % (name, address, alias) except Exception, e: print "Livestatus error %s" % str(e)