Ejemplo n.º 1
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)

    config = item.config

    statii = [pynsca.OK, pynsca.WARNING, pynsca.CRITICAL, pynsca.UNKNOWN]
    status = pynsca.OK
    try:
        prio = item.priority
        status = statii[prio]
    except:
        pass

    nsca_host = str(config['nsca_host'])

    host_name = item.addrs[0]
    service_description = item.addrs[1]

    # If the incoming payload has been transformed, use that,
    # else the original payload
    text = item.message

    try:
        notif = NSCANotifier(nsca_host)
        notif.svc_result(host_name, service_description, status, text)
    except Exception as e:
        srv.logging.warning("Cannot notify to NSCA host `%s': %s" %
                            (nsca_host, e))
        return False

    return True
Ejemplo n.º 2
0
def on_message(mosq, userdata, msg):
    print "%s (qos=%s, r=%s) %s" % (msg.topic, str(
        msg.qos), msg.retain, str(msg.payload))
    if msg.retain == 1:
        return

    try:
        # owntracks/username/deviceid
        prefix, username, device = msg.topic.split('/', 3)
    except:
        return

    try:
        data = json.loads(msg.payload)
    except:
        return

    if 'batt' not in data:
        return

    level = int(data['batt'])

    status = pynsca.OK
    if level < 50:
        status = pynsca.WARNING
    if level < 20:
        status = pynsca.CRITICAL

    service = 'OwnTracks %s' % username
    message = 'Battery level for %s is %s' % (device, level)
    notif = NSCANotifier(icinga_host)
    notif.svc_result('localhost', service, status, message)
Ejemplo n.º 3
0
def on_message(mosq, userdata, msg):
    print "%s (qos=%s, r=%s) %s" % (msg.topic, str(msg.qos), msg.retain, str(msg.payload))
    if msg.retain == 1:
        return

    try:
        # owntracks/username/deviceid
        prefix, username, device = msg.topic.split('/', 3)
    except:
        return

    try:
        data = json.loads(msg.payload)
    except:
        return

    if 'batt' not in data:
        return

    level = int(data['batt'])

    status = pynsca.OK
    if level < 50:
        status = pynsca.WARNING
    if level < 20:
        status = pynsca.CRITICAL

    service = 'OwnTracks %s' % username
    message = 'Battery level for %s is %s' % (device, level)
    notif = NSCANotifier(icinga_host)
    notif.svc_result('localhost', service, status, message)
Ejemplo n.º 4
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    if HAVE_NSCA == False:
        return False

    config   = item.config

    statii = [ pynsca.OK, pynsca.WARNING, pynsca.CRITICAL, pynsca.UNKNOWN ]
    status = pynsca.OK
    try:
        prio = item.priority
        status = statii[prio]
    except:
        pass

    nsca_host = config['nsca_host']

    host_name = item.addrs[0]
    service_description = item.addrs[1]

    # If the incoming payload has been transformed, use that,
    # else the original payload
    text = item.message

    try:
        notif = NSCANotifier(nsca_host)
        notif.svc_result(host_name, service_description, status, text)
    except Exception, e:
        srv.logging.warning("Cannot notify to NSCA host `%s': %s" % (nsca_host, str(e)))
        return False
def nagios_passive_report(host,monitoredhost,service,level,message):
	# use nsca to report to nagios
	status={0:"OK: ",1:"WARNING: ",2:"CRITICAL: "}
	try:
		notif = NSCANotifier(host,5667,0)
		notif.svc_result(monitoredhost, service, level, status[level]+message)
	except:
		return False
	return True
def nagios_passive_report(host,monitoredhost,service,level,message):
	# use nsca to report to nagios
	status={0:"OK: ",1:"WARNING: ",2:"CRITICAL: "}
	try:
		notif = NSCANotifier(host,5667,0)
		notif.svc_result(monitoredhost, service, level, status[level]+message)
	except:
		return False
	return True
Ejemplo n.º 7
0
def verifyDBRestore(app=None, pod=None):
  '''Verify if a week old mysql DB backup can be restored. Requires to supply application name'''
  if app == "production_mysql" and  pod == "sc":
    ##check if instance running, mail possible verification in progress
    region = "us-west-1"
    nagios = "monitor.sc.recurly.net"
    host = getInstance(region, tName='DBRecoveryTest')
  elif app == "production_mysql" and  pod == "ny3":
    region = "us-east-1"
    nagios = "monitor.sc.recurly.net"
    host = getInstance(region, tName='NY3DBVerify')
  else:
    print "did you provide an app who's DB to verify?" 
    print "Like production_mysql"
    sys.exit(3)
  
  print region
  if host.state != "running":
    print "Instance not running, restarting to clear ephemeral"
    startInstance(host.id, region)
  else:
    print "Instance still running, for now we'll do nothing, just restart and continue as normal"
    stopInstance(host.id, region)
    startInstance(host.id, region)
  
  env.host_string = getHostString(host.id, region)
  print env.host_string

  sleep(45)
  sudo("echo started: %s > /var/run/backup_verify" %date.today())
  dlfname = bldBkupFname(app, pod)
  dlfpath = getS3BkupFile(dlfname, '/mnt/')
  rstrpath = unpack(app, dlfpath, pod)
  restore(rstrpath)
  sleep(10)
 
  rslt = None
  cnt = 0
  while rslt == None and cnt < 6:
    rslt = prodQueries()
    sleep (20)
    cnt = cnt +1 
  
  notif = NSCANotifier(nagios)
  if rslt != None:
    graph("mysql.sc.backup_verify.recurly_production.subscriptions",  rslt )
    graph("mysql.sc.backup_verify.status", "10")
    notif.svc_result("BackupVerify", "MySQL_Prod_verify", pynsca.OK, "Subscription count: %s" %rslt)
  else:
    graph("mysql.sc.backup_verify.status", "1")  
    notif.svc_result("BackupVerify", "MySQL_Prod_verify", pynsca.WARNING, "Subscription count: %s" %rslt)

  #stopInstance(host.id, region)
  sys.exit(0)
def main(hostname, port, encryption, password):
    notif = NSCANotifier(hostname, port, encryption, password)

    for line in sys.stdin.readlines():
        line = line.rstrip()
        if not line:
            continue
        notif = line.split(opts.delimiter)
        if len(notif) == 3:
            # only host, rc, output
            notif.insert(1, '')  # insert service
        # line consists of host, service, rc, output
        assert len(notif) == 4
        notif.svc_result(*notif)
Ejemplo n.º 9
0
    def __init__(self, server, check_name, check_host, password=None):
        self.server = server
        self.check_name = check_name
        self.check_host = check_host
        self.password = password
        self.success = 0
        self.warning = 1
        self.critical = 2
        self.notifier = None

        split = self.server.split(":")
        self.server_name = split[0]
        self.server_port = 5667
        if len(split) == 2:
            self.server_port = int(split[1])

        self.mode_type = ''
        self.encryption = 1
        if self.password:
            self.mode_type = 'Secure '
            self.encryption = 16

        req_attrs = ['server', 'check_name', 'check_host']
        for attr in req_attrs:
            if not getattr(self, attr):
                raise Exception, 'NSCA module requires attribute: %s!' % attr, None

        try:
            self.notifier = NSCANotifier(monitoring_server=self.server_name,
                                         monitoring_port=self.server_port,
                                         encryption_mode=self.encryption,
                                         password=self.password)
        except Exception, e:
            logging.error('Error initiating NSCANotifier! Error: %s' % e)
            raise e
Ejemplo n.º 10
0
    def __init__(self, id, queue, nsca_host, nsca_port=5667, nsca_crypt=1, password=None, debug=False):
        print "Initialized SendThread id %i" % id
        self.quit = False
        self.tid = id
        self.queue = queue
        self.nsca = NSCANotifier(nsca_host, monitoring_port=nsca_port, encryption_mode=nsca_crypt, password=password)
        self.debug = debug

        multiprocessing.Process.__init__(self)
def send_nsca(status):
    """Send a nsca notification
    in: status
    """
    
    nagios_service = status['plugin']
    nagios_service += ':'
    if status['plugin_instance']:
        nagios_service += status['plugin_instance']
    nagios_service += ' '
    nagios_service += status['type']
    if status['type_instance']:
        nagios_service += ' '
        nagios_service += status['type_instance']

    notif = NSCANotifier("localhost")
    notif.svc_result(
        status['host'], 
        nagios_service, 
        status['nagios_state'], 
        status['message']
        )
Ejemplo n.º 12
0
    def __init__(self, *args):
        super(NscaAlerter, self).__init__(*args)

        self.nsca_server = self.rule.get('nsca_server', 'localhost')
        self.nsca_port = self.rule.get('nsca_port', 5667)
        self.nsca_password = self.rule.get('nsca_password', None)
        self.nagios_hostname = self.rule.get('nagios_hostname', None)
        self.nagios_service = self.rule.get('nagios_service', None)

        self.nsca_client = NSCANotifier(self.nsca_server,
                                        monitoring_port=self.nsca_port,
                                        password=self.nsca_password,
                                        encryption_mode=3)
Ejemplo n.º 13
0
class SendThread(multiprocessing.Process):
    def __init__(self, id, queue, nsca_host, nsca_port=5667, nsca_crypt=1, password=None, debug=False):
        print "Initialized SendThread id %i" % id
        self.quit = False
        self.tid = id
        self.queue = queue
        self.nsca = NSCANotifier(nsca_host, monitoring_port=nsca_port, encryption_mode=nsca_crypt, password=password)
        self.debug = debug

        multiprocessing.Process.__init__(self)

    def run(self):
        print "%i | Running SendThread" % self.tid
        while self.quit is False:
            if self.queue.empty():
                time.sleep(1)
                continue
            else:
                line = self.queue.get()
                if self.debug:
                    print "Line from queue: %s" % line

            parsed = self.parse(line.replace('[', '').replace(']', ''))
            if parsed:
                (t, host, service, code, output) = parsed
            else:
                continue
            if t > (int(time.time()) - 60):
                r = self.nsca.svc_result(host, service, code, output)
                if self.debug:
                    print "Line sent: %s" % line
                if not r:
                    print "Socket error, putting event back on queue and sleeping for a while. Error was: %s" % str(r)
                    self.queue.put(line)
                    time.sleep(1)
            else:
                #print str(self.tid) + " | " + str(t) + " " + host + ";" + service + ";" + str(code) + ";" + output + " | Too old, dropping"
                print "%i | %i %s;%s;%i;%s | Too old, dropping" % (self.tid, t,host,service,code,output)
            time.sleep(0.001)
        print "%i | Stopping loop" % self.tid

    def parse(self, line):
        try:
            r = re.match(r'(?P<time>[0-9]+)\sPROCESS_SERVICE_CHECK_RESULT;(?P<host>\S+);(?P<service>\S+);(?P<code>[0-9]+);(?P<output>.+)\n', line)
            return (int(r.group("time")), r.group("host"), r.group("service"), int(r.group("code")), r.group("output"))
        except AttributeError:
            print "AttributeError while parsing line: %s" % line
            return False

    def quit(self):
        self.quit = True
Ejemplo n.º 14
0
class NscaAlerter(Alerter):
    """ Sends alert to Nagios NSCA daemon """

    """ TODO: send WARNING, OK state
              allow to set thresholds
    """

    required_options = frozenset(["nsca_server",
                                  "nsca_port",
                                  "nsca_password",
                                  "nagios_hostname",
                                  "nagios_service"])

    def __init__(self, *args):
        super(NscaAlerter, self).__init__(*args)

        self.nsca_server = self.rule.get('nsca_server', 'localhost')
        self.nsca_port = self.rule.get('nsca_port', 5667)
        self.nsca_password = self.rule.get('nsca_password', None)
        self.nagios_hostname = self.rule.get('nagios_hostname', None)
        self.nagios_service = self.rule.get('nagios_service', None)

        self.nsca_client = NSCANotifier(self.nsca_server,
                                        monitoring_port=self.nsca_port,
                                        password=self.nsca_password,
                                        encryption_mode=3)

    def alert(self, matches):

        for match in matches:
            message = "|".join(basic_match_string(self.rule, match).splitlines())
            self.nsca_client.svc_result(self.nagios_hostname,
                                        self.nagios_service, pynsca.CRITICAL, message)

    def get_info(self):
        return {'type': 'nsca',
                'nagios_service': self.rule['nagios_service'],
                'nagios_hostname': self.rule['nagios_hostname']}
Ejemplo n.º 15
0
def main(hostname, port, encryption, password):
    notif = NSCANotifier(hostname, port, encryption, password)

    for line in sys.stdin.readlines():
        line = line.rstrip()
        if not line:
            continue
        notif = line.split(opts.delimiter)
        if len(notif) == 3:
            # only host, rc, output
            notif.insert(1, '')  # insert service
        # line consists of host, service, rc, output
        assert len(notif) == 4
        notif.svc_result(*notif)
Ejemplo n.º 16
0
    def __init__(self, manager, config, timer, base_dir, backup_dir, **kwargs):
        super(Nsca, self).__init__(self.__class__.__name__, manager, config,
                                   timer, base_dir, backup_dir, **kwargs)
        self.server = self.config.notify.nsca.server
        self.check_name = self.config.notify.nsca.check_name
        self.check_host = self.config.notify.nsca.check_host
        self.password = self.config.notify.nsca.password
        self.success = 0
        self.warning = 1
        self.critical = 2
        self.failed = self.critical
        self.notifier = None

        self.mode_type = ''
        self.encryption = 1
        if self.password:
            self.mode_type = 'Secure '
            self.encryption = 16

        req_attrs = ['server', 'check_name', 'check_host']
        for attr in req_attrs:
            if not getattr(self, attr):
                raise OperationError(
                    'NSCA notifier module requires attribute: %s!' % attr)

        self.server_name = self.server
        self.server_port = 5667
        if ':' in self.server:
            self.server_name, port = self.server.split(":")
            self.server_port = int(port)
        self.server = "%s:%i" % (self.server_name, self.server_port)

        try:
            self.notifier = NSCANotifier(monitoring_server=self.server_name,
                                         monitoring_port=self.server_port,
                                         encryption_mode=self.encryption,
                                         password=self.password)
        except Exception, e:
            logging.error('Error initiating NSCANotifier! Error: %s' % e)
            raise OperationError(e)
Ejemplo n.º 17
0
def send_nsca(nsca_server_name, service_description, return_code,
              return_code_description):
    notify = NSCANotifier(nsca_server_name)
    notify.svc_result(nsca_server_name, service_description, return_code,
                      return_code_description)
Ejemplo n.º 18
0
def send_nsca(nsca_server_name, service_description, return_code, return_code_description):
    notify = NSCANotifier(nsca_server_name)
    notify.svc_result(nsca_server_name, service_description, return_code, return_code_description)
Ejemplo n.º 19
0
def main(hostname, port, encryption, password, to_send):
    notif = NSCANotifier(hostname, port, encryption, password)
    for ts in to_send:
        notif.svc_result(ts[0], ts[1], ts[2], ts[3])