def post_process(self, group, event, is_new, is_sample, **kwargs): """ Process error. """ if not self.is_configured(group.project): return host = self.get_option('server_host', group.project) port = int(self.get_option('server_port', group.project)) prefix = self.get_option('prefix', group.project) hostname = self.get_option('hostname', group.project) or socket.gethostname() resolve_age = group.project.get_option('sentry:resolve_age', None) now = int(time.time()) template = '%s.%%s[%s]' % (prefix, group.project.slug) level = group.get_level_display() label = template % level groups = group.project.group_set.filter(status=STATUS_UNRESOLVED) if resolve_age: oldest = timezone.now() - timedelta(hours=int(resolve_age)) groups = groups.filter(last_seen__gt=oldest) num_errors = groups.filter(level=group.level).count() metric = Metric(hostname, label, num_errors, now) log.info('will send %s=%s to zabbix', label, num_errors) send_to_zabbix([metric], host, port)
def post_process(self, group, event, is_new, is_sample, **kwargs): """ Process error. """ if not self.is_configured(group.project): return host = self.get_option('server_host', group.project) port = self.get_option('server_port', group.project) prefix = self.get_option('prefix', group.project) hostname = self.get_option('hostname', group.project) or socket.gethostname() resolve_age = group.project.get_option('sentry:resolve_age', None) now = int(time.time()) template = '%s.%%s[%s]' % (prefix, group.project.slug) level = group.get_level_display() label = template % level groups = group.project.group_set.filter(status=STATUS_UNRESOLVED) if resolve_age: oldest = timezone.now() - timedelta(hours=int(resolve_age)) groups = groups.filter(last_seen__gt=oldest) num_errors = groups.filter(level=group.level).count() metric = Metric(hostname, label, num_errors, now) log.info('will send %s=%s to zabbix', label, num_errors) send_to_zabbix([metric], host, port)
def process_message(msg): """ What to do with the message that's arrived. Looks up the topic in the KeyMap dictionary, and forwards the message onto Zabbix using the associated Zabbix key """ logging.debug("Processing : " + msg.topic) if msg.topic in KeyMap.mapdict: if msg.payload == "ON": msg.payload = 1 if msg.payload == "OFF": msg.payload = 0 zbxKey = KeyMap.mapdict[msg.topic] (zbxKey, zbxHost) = zbxKey.split("::") if zbxHost == "": zbxHost = KEYHOST logging.info("Sending %s %s to Zabbix to host %s key %s", msg.topic, msg.payload, zbxHost, zbxKey) # Zabbix can also accept text and character data... # should we sanitize input or just accept it as is? send_to_zabbix( [Metric(zbxHost, zbxKey, msg.payload, time.strftime("%s"))], ZBXSERVER, ZBXPORT) else: # Received something with a /raw/ topic, # but it didn't match anything. Log it, and discard it logging.debug("Unknown: %s", msg.topic)
def transmitfacade(configinstance, metrics, logger): """ Send a list of Metric objects to zabbix. Called by check() param configinstance: The current configinstance object param metrics: list of Metrics for zbxsend Returns True if succcess. """ constant_zabbix_port = 10051 try: z_host, z_port = commons.get_hostport_tuple( constant_zabbix_port, configinstance['config']['zabbix']['server'] ) except: logging.error('Could not reference config: zabbix: server in conf') return False try: # Assume 30.0 if key is empty timeout = float(configinstance['config'][ 'zabbix'].get('send_timeout', 30.0)) except: logging.error("Could not reference config: zabbix entry in conf") return False msg = "Transmitting metrics to zabbix" logging.debug( "{m}: {telem}".format( m=msg, telem=metrics ) ) logging.info( "{m} host {zbxhost}:{zbxport}".format( m=msg, metrics=metrics, zbxhost=z_host, zbxport=z_port, logger=logger ) ) # Send metrics to zabbix try: zbxsend.send_to_zabbix( metrics=metrics, zabbix_host=z_host, zabbix_port=z_port, timeout=timeout, logger=logger ) except: logging.debug("event.send_to_zabbix({0},{1},{2},{3}) failed in" " transmitfacade()".format(metrics, z_host, z_port, timeout)) return False # success return True
def send_data_to_zabbix(send_data_from_dict, host_name, zbx_server_ip, zbx_server_port): clock = time.time() send_data_list = [] for keys in send_data_from_dict: send_data_list.append( zbxsend.Metric(host_name, keys, send_data_from_dict[keys], clock)) zbxsend.send_to_zabbix(send_data_list, zabbix_host=zbx_server_ip, zabbix_port=zbx_server_port)
def _send_to_zabbix(self, metrics): if not (self.zabbix_server and self.zabbix_nodename): log.warning('No zabbix connection configured, not sending metrics') return # Work around bug in zbxsend, they keep the fraction which zabbix # then rejects. now = int(time.time()) metrics = [zbxsend.Metric(self.zabbix_nodename, key, value, now) for key, value in metrics.items()] log.debug(metrics) zbxsend.send_to_zabbix(metrics, self.zabbix_server)
def process_message(msg): """ What to do with the message that's arrived. Looks up the topic in the KeyMap dictionary, and forwards the message onto Zabbix using the associated Zabbix key """ logging.debug("Processing : " + msg.topic) if msg.topic in KeyMap.mapdict: logging.info("Sending %s %s to Zabbix key %s", msg.topic, msg.payload, KeyMap.mapdict[msg.topic]) # Zabbix can also accept text and character data... # should we sanitize input or just accept it as is? send_to_zabbix([Metric(KEYHOST, KeyMap.mapdict[msg.topic], msg.payload)], ZBXSERVER, ZBXPORT) else: # Received something with a /raw/ topic, # but it didn't match anything. Log it, and discard it logging.debug("Unknown: %s", msg.topic)
def _send_to_zabbix(self, metrics): if not (self.zabbix_server and self.zabbix_nodename): log.error('zabbix server or nodename not defined, skipping' ' sending metrics') return # Work around bug in zbxsend, they keep the fraction which zabbix # then rejects. now = int(time.time()) metrics = [ zbxsend.Metric(self.zabbix_nodename, key, value, now) for key, value in metrics.items() ] log.debug(metrics) # Try each server in the list if there is more than one. sent = False for server in self.zabbix_server: log.debug('Trying to send metrics to: %s', server) if zbxsend.send_to_zabbix(metrics, server): log.debug('Sent metrics to: %s', server) sent = True break else: log.debug('Failed to send metrics to zabbix server: %s', server) if not sent: log.error('Failed to send metrics to zabbix servers: %s', self.zabbix_server)
def transmitfacade(configinstance, metrics, logger): """ Send a list of Metric objects to zabbix. Called by check() param configinstance: The current configinstance object param metrics: list of Metrics for zbxsend Returns True if succcess. """ constant_zabbix_port = 10051 try: z_host, z_port = commons.get_hostport_tuple( constant_zabbix_port, configinstance['config']['zabbix']['server']) except: logging.error('Could not reference config: zabbix: server in conf') return False try: # Assume 30.0 if key is empty timeout = float(configinstance['config']['zabbix'].get( 'send_timeout', 30.0)) except: logging.error("Could not reference config: zabbix entry in conf") return False msg = "Transmitting metrics to zabbix" logging.debug("{m}: {telem}".format(m=msg, telem=metrics)) logging.info("{m} host {zbxhost}:{zbxport}".format(m=msg, metrics=metrics, zbxhost=z_host, zbxport=z_port, logger=logger)) # Send metrics to zabbix try: zbxsend.send_to_zabbix(metrics=metrics, zabbix_host=z_host, zabbix_port=z_port, timeout=timeout, logger=logger) except: logging.debug("event.send_to_zabbix({0},{1},{2},{3}) failed in" " transmitfacade()".format(metrics, z_host, z_port, timeout)) return False # success return True
def main(): global args parser = argparse.ArgumentParser(description='Retrieve Zabbix stats about docker containers') parser.add_argument('--zhost', default="-", help='host name as configured in Zabbix') parser.add_argument('--zserver', default="localhost", help='Zabbix server') parser.add_argument('--zport', type=int, default=10051, help='Zabbix server trap port') parser.add_argument('--nozsend', default=False, action='store_true', help='do not send to Zabbix') parser.add_argument('--url', default="unix://var/run/docker.sock", help="base docker url") parser.add_argument('--metrics', nargs='+', help="list of metrics to be retrieved") parser.add_argument('--metricnames', nargs='+', help="names of metrics to be retrieved") parser.add_argument('--verbose', default=False, action='store_true', help='verbose output') parser.add_argument('--image', help='container image') args=parser.parse_args() n=min(len(args.metrics), len(args.metricnames)) if not args.image: print "error: need container image name!" sys.exit(-1) dc=docker.Client(base_url=args.url) conts=filter(lambda cnt:cnt['Image']==args.image, dc.containers(quiet=False)) if len(conts)!=1: print "error: could not identify container with image=%s" % args.image sys.exit(-1) cid=conts[0]['Id'] stats=dc.stats(cid) st0=stats.next() time.sleep(1) st1=stats.next() if args.verbose: print "cid=%s" % cid print st0, st1 env={'null': ''} metrics=args.metrics[:n] metricnames=args.metricnames[:n] values=[get_metric(m, eval(st0, env), eval(st1, env)) for m in metrics] zhost = "localhost" if args.zhost=='-' else args.zhost mobjs=[Metric(zhost, tp[0], tp[1]) for tp in zip(metricnames, values) if tp[1]!=""] if args.verbose or args.nozsend: for m in mobjs: print args.zhost, m.key, m.value if not args.nozsend and send_to_zabbix(mobjs, args.zserver, args.zport): print "%d metrics sent successfully!" % len(mobjs)
def send_data_to_zabbix(send_data_from_dict, host_name, zbx_server_ip, zbx_server_port): """ Once we have the processed data as Key/Value pair. Now we create a Metric JSON which is similar to below. Using Zabbix Metric { "request":"sender data", "data":[ { "host":"Host name 1", "key":"item_key", "value":"33", "clock":"123123123123" }, { "host":"Host name 2", "key":"item_key", "value":"55", "clock":"23423423423" } ] } 'Clock' is taken as the current system time when the JSON was picked up. :param send_data_from_dict: :param host_name: :param zbx_server_ip: :param zbx_server_port: :return: """ clock = time.time() send_data_list = [] # Creating JSON for keys in send_data_from_dict: send_data_list.append(zbxsend.Metric(host_name, keys, send_data_from_dict[keys], clock)) logging.info("Sending Data to Zabbix Server, for Host : " + str(host_name)) logging.info("Zabbix IP : " + str(zabbix_server_ip)) logging.info("Zabbix Port : " + str(zbx_server_port)) # Sending JSON to Zabbix Server. zbxsend.send_to_zabbix(send_data_list, zabbix_host=zbx_server_ip, zabbix_port=zbx_server_port)
def send(self, metrics): """Sends the metric information to the zabbix trapper. Args: metrics: a list of UniqueMetrics to send to zabbix. Returns: a boolean True: metrics were successfully sent to zabbix. False: an error occurred. """ return send_to_zabbix(metrics, self.server, self.port)
def run(self): """ main process loop, dequeue and send """ while not self.Finished: try: metrics = self.queue.get(True, 1) except Queue.Empty: continue while not self.Finished: status = send_to_zabbix(metrics, self.server, 10051) if status: break sleep(2) log.msg("Zabbix Connection is currently down!") log.msg("=> Zabbix thread exit")
def run(self): """ main process loop, dequeue and send """ while not self.Finished: try: metrics = self.queue.get(True,1) except Queue.Empty: continue while not self.Finished: status = send_to_zabbix(metrics,self.server,10051) if status: break sleep(2) log.msg("Zabbix Connection is currently down!") log.msg("=> Zabbix thread exit")
def batch(ctx, name): """Send values in batch to zabbix_host (server defined in config file)""" logger = logging.getLogger('es_stats_zabbix') # Since logging is set up in cli() logger.debug('Batch mode with named batch: {0}'.format(name)) if name not in ctx.obj['batches']: click.echo(click.style('Batch {0} not found in configuration file.'.format(name), fg='red', bold=True)) sys.exit(1) from zbxsend import Metric, send_to_zabbix b = ctx.obj['batches'][name] logger.debug('Batch config args: {0}'.format(b)) metrics = [] zserver = b.pop('server') zport = int(b.pop('port')) zhost = b.pop('host') # Should only be Item keys at this point. logger.debug('Batch keys: {0}'.format(b)) # Separate keys into similar APIs apis = { 'health': [], 'clusterstats': [], 'clusterstate': [], 'nodestats': [], 'nodeinfo': [],} for k in b: ztuple = parse_key(b[k]) apis[ztuple[0]].append(ztuple) logger.debug('API-separated keys: {0}'.format(apis)) for api in apis: # ignore empty list if not apis[api]: continue # get the base api object apiobj = map_api(apis[api][0], ctx.obj['client']) # iterate over each tuple for ztuple in apis[api]: result = apiobj.get(ztuple[2], name=ztuple[1]) if result == DotMap(): result = 'ZBX_NOTSUPPORTED' # We do not have the key here, so we need to rebuild it. metrics.append(Metric(zhost, ztuple[0] + '[' + ztuple[2] + ']', result)) logger.debug('Metrics: {0}'.format(metrics)) result = send_to_zabbix(metrics, zserver, zport) logger.debug('Result = {0}'.format(result)) # Spit out exit code to stdout click.echo(0 if result else 1) logger.info('Job completed.')
def flush(self): ts = int(time.time()) stats = 0 stat_string = '' # self.pct_threshold = 10 metrics = [] for k, v in self.counters.items(): v = float(v) / (self.flush_interval / 1000) host, key = k.split(':',1) # Catch the case where an improper host is passed. if not 'zabbix.host' in host: metrics.append(Metric(host, key, str(v), ts)) self.counters[k] = 0 stats += 1 for k, v in self.timers.items(): if len(v) > 0: v.sort() count = len(v) min = v[0] max = v[-1] mean = min max_threshold = max median = min if count > 1: thresh_index = int(round(count*float(self.pct_threshold)/100))#count - int(round((100.0 - self.pct_threshold) / 100) * count) max_threshold = v[thresh_index - 1] total = sum(v[:thresh_index]) mean = total / thresh_index if count%2 == 0: median = (v[count/2] + v[count/2-1])/2.0 else: median = (v[count/2]) self.timers[k] = [] host, key = k.split(':', 1) # Catch the case where an improper host is passed. if not 'zabbix.host' in host: metrics.extend([ Metric(host, key + '[mean]', mean, ts), Metric(host, key + '[upper]', max, ts), Metric(host, key + '[lower]', min, ts), Metric(host, key + '[count]', count, ts), Metric(host, key + '[upper_%s]' % self.pct_threshold, max_threshold, ts), Metric(host, key + '[median]', median, ts), ]) stats += 1 # stat_string += 'statsd.numStats %s %d' % (stats, ts) if (ts - self.timestamp) > 1800: # Guarantee we can still use self.api, if not, use the connect method version = self.api.version() if version == 0: self.api.connect() else: # If we get a version, we're good. pass # Reset self.timestamp self.timestamp = ts # Use our instance of class CachingZbxItemCreator, then send the metrics there ItemCreator = CachingZbxItemCreator(self.api) ItemCreator.process(metrics) send_to_zabbix(metrics, self.zabbix_host, self.zabbix_port) self._set_timer() if self.debug: print metrics
def sendZabbix(metric): ZabbixHelper.logger.debug("send Zabbix " + str(metric)) result = send_to_zabbix([metric], settings.ZBX_SERVER_IP, settings.ZBX_SERVER_PORT) if(result == False): ZabbixHelper.logger.warn("cannot send VM status to Zabbix, continue anyway") return
def main(): global args parser = argparse.ArgumentParser( description='Retrieve Zabbix stats about docker containers') parser.add_argument('--zhost', default="-", help='host name as configured in Zabbix') parser.add_argument('--zserver', default="localhost", help='Zabbix server') parser.add_argument('--zport', type=int, default=10051, help='Zabbix server trap port') parser.add_argument('--nozsend', default=False, action='store_true', help='do not send to Zabbix') parser.add_argument('--url', default="unix://var/run/docker.sock", help="base docker url") parser.add_argument('--metrics', nargs='+', help="list of metrics to be retrieved") parser.add_argument('--metricnames', nargs='+', help="names of metrics to be retrieved") parser.add_argument('--verbose', default=False, action='store_true', help='verbose output') parser.add_argument('--image', help='container image') args = parser.parse_args() n = min(len(args.metrics), len(args.metricnames)) if not args.image: print "error: need container image name!" sys.exit(-1) dc = docker.Client(base_url=args.url) conts = filter(lambda cnt: cnt['Image'] == args.image, dc.containers(quiet=False)) if len(conts) != 1: print "error: could not identify container with image=%s" % args.image sys.exit(-1) cid = conts[0]['Id'] stats = dc.stats(cid) st0 = stats.next() time.sleep(1) st1 = stats.next() if args.verbose: print "cid=%s" % cid print st0, st1 env = {'null': ''} metrics = args.metrics[:n] metricnames = args.metricnames[:n] values = [get_metric(m, eval(st0, env), eval(st1, env)) for m in metrics] zhost = "localhost" if args.zhost == '-' else args.zhost mobjs = [ Metric(zhost, tp[0], tp[1]) for tp in zip(metricnames, values) if tp[1] != "" ] if args.verbose or args.nozsend: for m in mobjs: print args.zhost, m.key, m.value if not args.nozsend and send_to_zabbix(mobjs, args.zserver, args.zport): print "%d metrics sent successfully!" % len(mobjs)
import time from zbxsend import Metric, send_to_zabbix script = argv api_key = 'WP287AY6V8JH16P0' def parseSensor(device,api_key): with open(device, 'r') as infile: data = infile.read() lines = data.splitlines() for l in lines: match = re.search('t=(.*)',l) if match: value = str(int(match.group(1)) / 1000) return value ############# sensors = [['/sys/bus/w1/devices/28-0315a4e462ff/w1_slave','vent'], ['/sys/bus/w1/devices/28-0315a4e46cff/w1_slave','indoor'], ['/sys/bus/w1/devices/28-0315a4ed51ff/w1_slave','outdoor']] querystringList = [] for s in sensors: zabbixserver = 'my.zabbix.server' temperature = parseSensor(s[0],api_key) print s[1] + ' : ' + temperature send_to_zabbix([Metric(zabbixserver, s[1], temperature)], 'zabbix.bignose.ca', 10051)
def main(): global args parser = argparse.ArgumentParser( description='Retrieve items for the etcd zabbix template') parser.add_argument('--host', default="localhost", help='host name') parser.add_argument('--zhost', default="-", help='host name as configured in Zabbix') parser.add_argument('--zserver', default="localhost", help='Zabbix server') parser.add_argument('--zport', type=int, default=10051, help='Zabbix server trap port') parser.add_argument('--port', type=int, default=4001, help="service port") parser.add_argument('--url', default="/v2/stats/store", help="base url to be retrieved") parser.add_argument('--cert', default="/etc/origin/master/master.etcd-client.crt", help="ssl certificate file") parser.add_argument('--key', default="/etc/origin/master/master.etcd-client.key", help="ssl key file") parser.add_argument('--metrics', nargs='+', help="list of metrics to be retrieved") parser.add_argument('--metricnames', nargs='+', help="names of metrics to be retrieved") parser.add_argument('--verbose', default=False, action='store_true', help='verbose output') args = parser.parse_args() n = min(len(args.metrics), len(args.metricnames)) jd = get_json(args.host, args.port, args.url, args.key, args.cert) if jd is None: sys.exit(-1) if args.verbose: print jd metrics = args.metrics[:n] metricnames = args.metricnames[:n] values = [get_metric_value(m, jd) for m in metrics] mobjs = [ Metric(args.zhost, tp[0], tp[1]) for tp in zip(metricnames, values) if tp[1] != "" ] if args.verbose: for m in mobjs: print m.host, m.key, m.value if not send_to_zabbix(mobjs, args.zserver, args.zport): print "zabbix trapper error!" sys.exit(-1) print "%d metrics sent successfully!" % len(mobjs)
def send_zbx(node, dataVector, clock): # print "Tamanho do vetor: ", len(dataVector) #deve ser 16 for index in range(len(dataVector)): send_to_zabbix([Metric(node, ZBX_KEY[index], dataVector[index], clock)], ZBX_SERVER, ZBX_PORT)
PORT = '/dev/ttyUSB0' BAUD_RATE = 9600 ZBX_PORT = 10051 ZBX_SERVER = '10.10.10.162' ZBX_KEY = [ 'temp', 'humi', 'dewpoint', 'temp2', 'mq2Gas', 'presence', 'fire','pressure','pressureSea', 'altitude', 'altitudeSea', 'energyCons', 'noise', 'light', 'counter', 'dewpointPython'] # Configuracao estatica para cada nodo da rede # '1' para ativar funcionalidade e '0' para desativar # @TODO: Funcao ainda a ser imprementada como xbee.send() #NODE_CONFIG[node][1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ''' Metric: (host, key, value, clock) send_to_zabbix([Metric('teste', 'node2.temp', 32)], ZBX_SERVER, ZBX_PORT)''' # Transforma binario em hex def hex(bindata): return ''.join('%02x' % ord(byte) for byte in bindata) # Calcula ponto de orvalho, Formula do arduino def dewPoint(celsius, humidity): RATIO = 373.15 / (273.15 + celsius) SUM = -7.90298 * (RATIO - 1) SUM += 5.02808 * math.log10(RATIO) SUM += (-1.3816e-7) * (math.pow(10, (11.344 * (1 - 1/RATIO ))) - 1) SUM += (8.1328e-3) * (math.pow(10, (-3.49149 * (RATIO - 1))) - 1) SUM += math.log10(1013.246) VP = math.pow(10, (SUM-3)) * humidity;
zabbix_item_key = UNIFIED_CONN_STATUS_TMPL % i zabbix_item_value = e['items'][i] #debug_print('host=%s, key=%s, value=%s, timestamp=%s' % (host, zabbix_item_key, zabbix_item_value, str(datetime.datetime.fromtimestamp(timestamp)))) zabbix_metrics.append( Metric(host, zabbix_item_key, zabbix_item_value, timestamp)) #Storwize block cluster status if e.get('clazz') == 'com.ibm.svc.gui.events.ConnectionStatusEvent': timestamp = float(e['timestamp']) / 1000 debug_print('%s %s %s' % (e.get('clazz'), e.get('id'), str(datetime.datetime.fromtimestamp(timestamp)))) for i in ['externalStorage', 'internalStorage', 'remotePartnerships']: zabbix_item_key = SVC_CONN_STATUS_TMPL % i zabbix_item_value = e[i] #debug_print('host=%s, key=%s, value=%s, timestamp=%s' % (host, zabbix_item_key, zabbix_item_value, str(datetime.datetime.fromtimestamp(timestamp)))) zabbix_metrics.append( Metric(host, zabbix_item_key, zabbix_item_value, timestamp)) if debug: for m in zabbix_metrics: print str(m) #send data to zabbix with zbxsend module if len(zabbix_metrics): if debug: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.WARNING) send_to_zabbix(zabbix_metrics, 'localhost', 10051)
logging.info('sys.argv: ' + repr(sys.argv)) parser = argparse.ArgumentParser( formatter_class=RawTextHelpFormatter, description="""Simple script to send {1} operator reports to Zabbix. Should be used in {1}-dir config instead of mail command: mail = root@localhost,admin@domain = all, !skipped operatorcommand = "{0} [--recipients '%r']" Hostnames in Zabbix and {1} must correspond """.format(os.path.realpath(__file__), conf['type'].title())) parser.add_argument('--recipients', action='store', type=lambda x: x.split(), default=[], help='space-separated list of report recipients (%%r)') args = parser.parse_args() msg = sys.stdin.read() metrics = [ Metric(conf['hostname'], "{0}.custommessage".format(conf['type']), msg) ] logging.info("sending custom message to '{0}': '{1}'".format( conf['zabbix_server'], metrics)) send_to_zabbix(metrics, conf['zabbix_server'], 10051, 20) if args.recipients: sendmail(msg, args.recipients)
if discovery == 'pool': for pool in conn.ExecQuery('WQL', 'select PoolID, ElementName from IBMTSSVC_ConcreteStoragePool'): output.append( '{"{#TYPE}":"%s","{#NAME}":"%s","{#ID}":"%s"}' % ('pool', pool.properties['ElementName'].value, pool.properties['PoolID'].value) ) json = [] json.append('{"data":[') for i, v in enumerate( output ): if i < len(output)-1: json.append(v+',') else: json.append(v) json.append(']}') json_string = ''.join(json) debug_print(json_string) trapper_key = 'svc.discovery.%s' % discovery debug_print('Sending to host=%s, key=%s' % (cluster, trapper_key)) #send json to LLD trapper item with zbxsend module if debug: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.WARNING) send_to_zabbix([Metric(cluster, trapper_key, json_string)], 'localhost', 10051) debug_print('')
for i in e['items'].keys(): zabbix_item_key = UNIFIED_CONN_STATUS_TMPL % i zabbix_item_value = e['items'][i] #debug_print('host=%s, key=%s, value=%s, timestamp=%s' % (host, zabbix_item_key, zabbix_item_value, str(datetime.datetime.fromtimestamp(timestamp)))) zabbix_metrics.append( Metric(host, zabbix_item_key, zabbix_item_value, timestamp)) #Storwize block cluster status if e.get('clazz') == 'com.ibm.svc.gui.events.ConnectionStatusEvent': timestamp = float(e['timestamp'])/1000 debug_print('%s %s %s' % (e.get('clazz'), e.get('id'), str(datetime.datetime.fromtimestamp(timestamp)) ) ) for i in ['externalStorage', 'internalStorage', 'remotePartnerships']: zabbix_item_key = SVC_CONN_STATUS_TMPL % i zabbix_item_value = e[i] #debug_print('host=%s, key=%s, value=%s, timestamp=%s' % (host, zabbix_item_key, zabbix_item_value, str(datetime.datetime.fromtimestamp(timestamp)))) zabbix_metrics.append( Metric(host, zabbix_item_key, zabbix_item_value, timestamp)) if debug: for m in zabbix_metrics: print str(m) #send data to zabbix with zbxsend module if len(zabbix_metrics): if debug: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.WARNING) send_to_zabbix(zabbix_metrics, 'localhost', 10051)
def flush(self): ts = int(time.time()) stats = 0 stat_string = '' # self.pct_threshold = 10 metrics = [] for k, v in self.counters.items(): v = float(v) / (self.flush_interval / 1000) host, key = k.split(':',1) metrics.append(Metric(host, key, str(v), ts)) self.counters[k] = 0 stats += 1 for k, v in self.timers.items(): if len(v) > 0: v.sort() count = len(v) min = v[0] max = v[-1] mean = min max_threshold = max median = min if count > 1: thresh_index = int(round(count*float(self.pct_threshold)/100))#count - int(round((100.0 - self.pct_threshold) / 100) * count) max_threshold = v[thresh_index - 1] total = sum(v[:thresh_index]) mean = total / thresh_index if count%2 == 0: median = (v[count/2] + v[count/2-1])/2.0 else: median = (v[count/2]) self.timers[k] = [] host, key = k.split(':', 1) metrics.extend([ Metric(host, key + '[mean]', mean, ts), Metric(host, key + '[upper]', max, ts), Metric(host, key + '[lower]', min, ts), Metric(host, key + '[count]', count, ts), Metric(host, key + '[upper_%s]' % self.pct_threshold, max_threshold, ts), Metric(host, key + '[median]', median, ts), ]) stats += 1 # stat_string += 'statsd.numStats %s %d' % (stats, ts) send_to_zabbix(metrics, self.zabbix_host, self.zabbix_port) self._set_timer() if self.debug: print metrics
data = getHostName(data, 'host') output = output + data if discovery == 'battery': data = conn.EnumerateInstances('HITACHI_Battery') data = getBatteryName(data, 'battery') output = output + data json = [] json.append('{"data":[') for i, v in enumerate(output): if i < len(output) - 1: json.append(v + ',') else: json.append(v) json.append(']}') json_string = ''.join(json) print(json_string) trapper_key = 'svc.discovery.%s' % discovery debug_print('Sending to host=%s, key=%s' % (hostname, trapper_key)) #send json to LLD trapper item with zbxsend module if debug: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.WARNING) send_to_zabbix([Metric(hostname, trapper_key, json_string)], 'localhost', 10051)
logging.warn("Need python version 2.x to run") quit(1) parser = argparse.ArgumentParser( formatter_class=RawTextHelpFormatter, description= """Simple script to send {1} operator reports to Zabbix. Should be used in {1}-dir config instead of mail command: mail = root@localhost,admin@domain = all, !skipped operatorcommand = "{0} [--recipients '%r']" Hostnames in Zabbix and {1} must correspond """.format(os.path.realpath(__file__), conf['type'].title()) ) parser.add_argument('--recipients', action='store', type=lambda x: x.split(), default=[], help='space-separated list of report recipients (%%r)') args = parser.parse_args() msg = sys.stdin.read() metrics = [ Metric(conf['hostname'], "{0}.custommessage".format(conf['type']), msg) ] logging.info( "sending custom message to '{0}': '{1}'".format(conf['zabbix_server'], metrics) ) send_to_zabbix(metrics, conf['zabbix_server'], 10051, 20) if args.recipients: sendmail(msg, args.recipients)
def metric_send( item, val, host = hostname, zbx_serv = zabbix_server_url, zbx_serv_port = zabbix_server_port ): print "This is sent to zabbix: item - %s value - %s" % (item, val) send_to_zabbix( [ Metric(host, item, val) ], zbx_serv, zbx_serv_port )
'select PoolID, ElementName from IBMTSSVC_ConcreteStoragePool' ): output.append('{"{#TYPE}":"%s","{#NAME}":"%s","{#ID}":"%s"}' % ('pool', pool.properties['ElementName'].value, pool.properties['PoolID'].value)) json = [] json.append('{"data":[') for i, v in enumerate(output): if i < len(output) - 1: json.append(v + ',') else: json.append(v) json.append(']}') json_string = ''.join(json) debug_print(json_string) trapper_key = 'svc.discovery.%s' % discovery debug_print('Sending to host=%s, key=%s' % (cluster, trapper_key)) #send json to LLD trapper item with zbxsend module if debug: logging.basicConfig(level=logging.INFO) else: logging.basicConfig(level=logging.WARNING) send_to_zabbix([Metric(cluster, trapper_key, json_string)], 'localhost', 10051) debug_print('')
str(element['request_response'])) # Applies a key format from the configuration file, allowing custom zabbix keys # for your items reporting to zabbix. Any element in testSet can be substituted, # the {uri} and Pdatatype} are also made available. metrickey = config['config']['zabbix']['item_key_format'].format(**element) metrics.append(Metric('url_monitor', metrickey, element['request_response'])) # Send metrics to zabbix logging.info('Preparing to send metrics: ' + str(metrics)) logging.debug('Zabbix host ' + str(config['config']['zabbix']['host']) + ' port ' + str(config['config']['zabbix']['port'])) event.send_to_zabbix(metrics, config['config']['zabbix']['host'], config['config']['zabbix']['port']) return 0 def discover(args,configinstance,logger): """ Perform the discovery when called upon by argparse in main()""" configinstance.load_yaml_file(args.config) config = configinstance.load() if not args.datatype: logging.error("\nYou must provide a datatype with the --datatype or -t option.\n\n" \ + "Datatypes are found in your yaml config under\n testSet->testTitle-" \ + ">testElements->datatype \n\nAvailable types detected in config:" \ + "\n %s " % configinstance.getDatatypesList()) sys.exit(1) discoveryDict = {}
def send_data_to_zabbix(send_data_from_dict, host_name, zbx_server_ip, zbx_server_port): clock = time.time() send_data_list = [] for keys in send_data_from_dict: send_data_list.append(zbxsend.Metric(host_name, keys, send_data_from_dict[keys], clock)) zbxsend.send_to_zabbix(send_data_list, zabbix_host=zbx_server_ip, zabbix_port=zbx_server_port)