Sisyphus repositório
Última atualização: 1 outubro 2023 | SRPMs: 18631 | Visitas: 37515408
en ru br
ALT Linux repositórios
S:0.1-alt6

Group :: Development/Python3
RPM: zabbix_tool

 Main   Changelog   Spec   Patches   Sources   Download   Gear   Bugs e FR  Repocop 

pax_global_header00006660000000000000000000000064123222316630014512gustar00rootroot0000000000000052 comment=4d26aa1714e59ce24a2d5a898793f0fb7316d19b
zabbix_tool/000075500000000000000000000000001232223166300133705ustar00rootroot00000000000000zabbix_tool/.gear/000075500000000000000000000000001232223166300143645ustar00rootroot00000000000000zabbix_tool/.gear/rules000064400000000000000000000001311232223166300154340ustar00rootroot00000000000000tar: . name=@name@
spec: .gear/zabbix_tool.spec
copy?: .gear/*.patch
copy?: .gear/*.diff
zabbix_tool/.gear/zabbix_tool-alt.patch000064400000000000000000000012401232223166300204740ustar00rootroot00000000000000diff --git a/zabbix_tool b/zabbix_tool
index 2c487ed..f3b34ce 100755
--- a/zabbix_tool
+++ b/zabbix_tool
@@ -179,6 +179,10 @@ class Tool(object):
except:
return self.z.host.get({self._FILTER:{self._NAME: h}})

+ def search_host(self, h, limit=100):
+ '''Search host by name pattern. Returns a list'''
+ return self.z.host.get({self._SEARCH:{self._NAME: h},self._SEARCHWILDCARDSENABLED:True, self._OUTPUT:self._EXTEND, self._LIMIT:limit})
+
def get_host_applications(self, hostname):
'''List all of the applications represented on the given host.'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
zabbix_tool/.gear/zabbix_tool.spec000064400000000000000000000013351232223166300175560ustar00rootroot00000000000000Name: zabbix_tool
Version: 0.1
Release: alt2
Summary: Tool for CLI interaction with the Zabbix API

Group: Development/Python
License: MIT
Url: https://github.com/BrianGallew/zabbix_tool

Source: %name.tar
Patch: %name-alt.patch
Packager: Evgenii Terechkov <evg@altlinux.org>

BuildArch: noarch

%description
Tool for CLI interaction with the Zabbix API

%prep
%setup -n %name
%patch -p1

%build

%install
mkdir -p %buildroot%_bindir
install -m 755 %name %buildroot%_bindir/%name

%files
%_bindir/%name
%doc README.md LICENSE

%changelog
* Sat Apr 12 2014 Terechkov Evgenii <evg@altlinux.org> 0.1-alt2
- Add search_host function

* Sat Apr 12 2014 Terechkov Evgenii <evg@altlinux.org> 0.1-alt1
- Initial build for ALT Linux Sisyphus
zabbix_tool/LICENSE000064400000000000000000000020671232223166300144020ustar00rootroot00000000000000The MIT License (MIT)

Copyright (c) 2014 Brian Gallew

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zabbix_tool/README.md000064400000000000000000000001071232223166300146450ustar00rootroot00000000000000zabbix_tool
===========

Tool for CLI interaction with the Zabbix API

zabbix_tool/zabbix_tool000075500000000000000000000761771232223166300156540ustar00rootroot00000000000000#!/usr/bin/env python
#
# Zabbix API Python CLI tool
# print_hostgroup_cpu written by Christoph Haas <email@christoph-haas.de>
#

# https://github.com/gescheit/scripts/blob/master/zabbix/zabbix_api.py
import zabbix_api, sys, os, logging, ConfigParser, operator
from pprint import pprint
from pydoc import render_doc
from optparse import OptionParser

CONFIG = 'config'
LOGLEVEL = 'loglevel'
NAME = 'name'
PASSWORD = 'password'
URL = 'url'
VERBOSE = 'verbose'
FILTER = 'filter'
SECTION = 'section'

CONFIG_HELP = '''
The Config file used by %s should look like this:
-------------- CUT HERE -----------------
[zabbix]
username='zabbix-api-user'
password='not-your-password'
url='http://zabbix-api.example.com/'

[dev]
username='zabbix-dev-api-user'
password='not-mine-either'
url='https://zabbix-dev.example.com/'
-------------- CUT HERE -----------------

By default, %s will use the [zabbix] paragraph, but if you use the
-s/--section option, you can tell %s to use a different section.
''' % (sys.argv[0],sys.argv[0],sys.argv[0])

# {{{ class Tool

class Tool(object):
'''Zabbix API CLI tool. All public functions should return a list
which will be printed and summarized.'''
# {{{ commonly used words, interned for my pleasure

_APPLICATIONID = 'applicationid'
_APPLICATIONIDS = 'applicationids'
_DESCRIPTION = 'description'
_ERROR = 'error'
_EXTEND = 'extend'
_FILTER = 'filter'
_GROUPID = 'groupid'
_GROUPIDS = 'groupids'
_HOST = 'host'
_HOSTID = 'hostid'
_HOSTIDS = 'hostids'
_HOSTS = 'hosts'
_ITEMID = 'itemid'
_ITEMIDS = 'itemids'
_KEY = 'key_'
_LIMIT = 'limit'
_NAME = 'name'
_OUTPUT = 'output'
_PROXYID = 'proxyid'
_PROXYIDS = 'proxyids'
_SEARCH = 'search'
_SEARCHWILDCARDSENABLED = 'searchwildcardsenabled'
_SELECTHOSTS = 'selectHosts'
_SELECTTRIGGERS = 'selectTriggers'
_SORTFIELD = 'sortfield'
_SORTORDER = 'sortorder'
_STATUS = 'status'
_TEMPLATEID = 'templateid'
_TEMPLATEIDS = 'templateids'
_TEMPLATES = 'templates'
_TRIGGERIDS = 'triggerids'

# }}}

def _start(self, url, username, password, timeout=60, loglevel=logging.ERROR, **kwargs):
# Connect to Zabbix server
self.z=zabbix_api.ZabbixAPI(server=url, timeout=timeout)
self.z.set_log_level(loglevel)
self.z.login(user=username, password=password)
return

# {{{ print_hostgroup_cpu(self, hg):

def print_hostgroup_cpu(self, hg):
'''This mostly a demonstration function that will print the
5-minute load average for all of the hosts in a single
hostgroup.'''
item_name='system.cpu.load[,avg5]'

for host in self.get_hostgroup_hosts(hg):
hostname = host[self._HOST]
print "Host:", hostname
print "Host-ID:", host[self._HOSTID]

item = self.z.item.get({
self._OUTPUT:self._EXTEND,
self._HOSTIDS:host[self._HOSTID],
self._FILTER:{self._KEY:item_name}})
if item:
print item[0]['lastvalue']
print "Item-ID:", item[0][self._ITEMID]

# Get history
lastvalue = self.z.history.get({
'history': item[0]['value_type'],
self._ITEMIDS: item[0][self._ITEMID],
self._OUTPUT: self._EXTEND,
self._SORTFIELD:'clock', # Sort by timestamp from new to old
self._SORTORDER:'DESC',
self._LIMIT: 1, # Get only the first (=newest) entry
})

# CAVEAT! The history.get function must be told which type the
# values are (float, text, etc.). The item.value_type contains
# the number that needs to be passed to history.get.
if lastvalue:
lastvalue = lastvalue[0]['value']

print "Last value:", lastvalue

else:
print "No item...."

print "---------------------------"
return []

# }}}
# {{{ hostgroup functions

def get_hostgroup(self, hg):
'''Look up a hostgroup by name or ID number. Returns a list with a single element'''
try:
int(hg)
return self.z.hostgroup.get({self._GROUPIDS: hg, self._OUTPUT:self._EXTEND})
except:
return self.z.hostgroup.get({self._FILTER:{self._NAME: hg}})

def get_hostgroup_hosts(self, hg):
'''Look up all of the hosts which belong to a given hostgroup.'''
hg = [x[self._GROUPID] for x in self.get_hostgroup(hg)]
if not hg: return hg
hosts = []
for x in self.z.hostgroup.get({ self._GROUPIDS: hg,
self._SELECTHOSTS:self._EXTEND
}):
hosts.extend(x[self._HOSTS])
hosts.sort(key=operator.itemgetter(self._HOST))
return hosts

def apply_template_to_hostgroup_members(self, template, hostgroup, doit=False):
'''Given a template and a hostgroup, the template will be added to
each host within the hostgroup, assuming a third parameter (which
defaults to False) is set to some true value. Otherwise, it will
simply tell you what it *would* have done.'''
template = self.get_template(template)
hostlist = self.get_hostgroup_hosts(hostgroup)
result = []
if hostlist and doit:
for host in hostlist:
result.extend(self.link_template_to_host(template, host))
return result
print 'would have applied %s to the following %d hosts:' % (str(template), len(hostlist))
return hostlist

# }}}
# {{{ host_* stuff

def get_host(self, h):
'''Look up a host by name or ID number. Returns a list with a single element'''
try:
int(h)
return self.z.host.get({self._HOSTIDS: h, self._OUTPUT:self._EXTEND})
except:
return self.z.host.get({self._FILTER:{self._NAME: h}})

def get_host_applications(self, hostname):
'''List all of the applications represented on the given host.'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
return self.z.application.get({self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})

def get_host_discovery_rule(self, hostname, discoveryrule):
'''Get the actual discovery rule objects associated with a hostname
and discovery rule name.'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
return self.z.discoveryrule.get({self._FILTER:{self._NAME: discoveryrule}, self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})

def get_host_application_items(self, hostname, application):
'''Given a hostname and an application name, return the list if
items which match both.'''
hosts = [x[self._HOSTID] for x in self. get_host(hostname)]
apps = [x[self._APPLICATIONID] for x in self.z.application.get({self._FILTER:{self._NAME: application}, self._HOSTIDS:hosts})]
return self.z.item.get({self._HOSTIDS: hosts, self._APPLICATIONIDS: apps, self._OUTPUT:self._EXTEND})

def get_host_application_triggers(self, hostname, application):
'''Given a hostname and an application name, return the list if
triggers which match both.'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
apps = self.z.application.get({self._FILTER:{self._NAME: application}, self._HOSTIDS:hosts})
return self.z.trigger.get({self._HOSTIDS: hosts, self._APPLICATIONIDS: apps})

def delete_host_application_items(self, hostname, application, doit=False):
'''Given a hostname and an application name, delete all the items
which match both if the final parameter is True (defaults to
False).'''
items = [x[self._ITEMID] for x in self.get_host_application_items(hostname, application)]
if not items: return None
if doit:
return self.z.item.delete(items)
print 'would have deleted the following %d items:' % len(items)
pprint(items)
return []

def delete_host_application_triggers(self, hostname, application, doit=False):
'''Given a hostname and an application name, delete all the triggers
which match both if the final parameter is True (defaults to
False).'''
triggers = [x[self._ITEMID] for x in self.get_host_application_triggers(hostname, application)]
if not triggers: return None
if doit:
return self.z.trigger.delete(triggers)
print 'would have deleted the following %d triggers:' % len(triggers)
pprint(triggers)
return []

def delete_host_application(self, hostname, application, doit=False):
'''Given a hostname and an application name, delete all the
triggers and items which match both if the final parameter is True
(defaults to False).'''
self.delete_host_application_items(hostname, application, doit)
self.delete_host_application_triggers(hostname, application, doit)
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
apps = [x[self._APPLICATIONID] for x in self.z.application.get({self._HOSTIDS: hosts, self._FILTER:{self._NAME: application}})]
if not apps: return None
if doit:
return self.z.application.delete(apps)
print 'would have deleted the following %d applications:' % len(apps)
return apps

def get_host_with_template_and_no_proxy(self, template):
'''Return a list of hosts with the given template and proxy ID.'''
template_objects = self.get_template(template)
if not template_objects:
print 'No such template: %s' % template
return []
template_id = template_objects[0][self._TEMPLATEID]
host_list = self.z.host.get({self._TEMPLATEIDS: template_id, self._OUTPUT: self._EXTEND})
print host_list[0]
return [x for x in host_list if x['proxy_hostid'] == u'0']

# }}}
# {{{ proxy stuff

def get_proxy(self, p):
'''Look up a proxy by name or ID number. Returns a list with a single element'''
try:
int(p)
return self.z.proxy.get({self._PROXYIDS: p, self._OUTPUT:self._EXTEND})
except:
return self.z.proxy.get({self._FILTER:{self._HOST: p}, self._OUTPUT:self._EXTEND})

def get_proxy_interfaces(self, p):
'''Look up a proxy by name or ID number. Returns a list with a single element'''
try:
int(p)
return self.z.proxy.get({self._PROXYIDS: p, self._OUTPUT:self._EXTEND, 'selectInterfaces': self._EXTEND})
except:
return self.z.proxy.get({self._FILTER:{self._HOST: p}, self._OUTPUT:self._EXTEND, 'selectInterfaces': self._EXTEND})

def assign_proxy_hosts(self, proxyname, *args):
'''Assign hosts to a proxy. Takes the name of a proxy (e.g. YVR01)
and a list of hostnames.'''
if not args:
parser.print_help("no hostname(s) passed in for adding to %s" % proxyname)
exit()
# First, the the proxyid as a list
proxy = self.z.proxy.get({self._FILTER:{self._HOST: proxyname}, self._OUTPUT:self._EXTEND})[0][self._PROXYID]
# Now update the hosts from the CLI
results = []
for a in args:
host = self.z.host.get({self._FILTER:{self._NAME: a}, self._OUTPUT:self._EXTEND})[0]
host['proxy_hostid'] = proxy
results.append(self.z.host.update(host))
return results

def switch_proxy(self, source, dest):
'''Move all hosts currently assigned to proxy1 over to proxy2..
Takes the name of a source proxy and destination proxy (e.g. YVR01
YVR02).'''
# First, the the proxyid as a list
dest = self.z.proxy.get({self._FILTER:{self._HOST: dest}, self._OUTPUT:self._EXTEND})[0][self._PROXYID]
# Now update the hosts from the CLI
results = []
for host in self.get_hosts_assigned_to_proxy(source):
host['proxy_hostid'] = dest
results.append(self.z.host.update(host))
return results

def get_hosts_assigned_to_proxy(self, proxyname):
'''List hosts assigned to a proxy. Takes the name of a proxy (e.g. YVR01).'''
# First, the the proxyid as a list
results = self.z.proxy.get({self._FILTER:{self._HOST: proxyname}, 'selectHosts':self._EXTEND})[0][self._HOSTS]
# Now update the hosts from the CLI
return results

# }}}
# {{{ item rules

def get_item(self, i):
'''Look up an item by name or ID number. Returns a list with a single element'''
try:
int(i)
return self.z.item.get({self._ITEMIDS: i, self._OUTPUT:self._EXTEND})
except:
return self.z.item.get({self._FILTER:{self._NAME: i}})

def get_item_host(self, i, h):
'''Look up an item by name or ID number for a given host. Returns a list with a single element'''
hosts = [x[self._HOSTID] for x in self.get_host(h)]
try:
int(i)
return self.z.item.get({self._ITEMIDS: i, self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})
except:
return self.z.item.get({self._FILTER:{self._NAME: i}, self._HOSTIDS: hosts})

def get_host_items(self, hostname):
'''Return all of the items for a single host.'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
return self.z.item.get({self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})

def get_items_with_template(self, item, template):
'''Return matching items from hosts with the given template'''
hosts = [x[self._HOSTID] for x in self.get_template_hosts(template)]
return self.z.item.get({self._FILTER:{self._NAME: item}, self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})

def delete_items_with_template(self, item, template, doit=False):
'''Delete matching items from hosts with the given template'''
hosts = [x[self._HOSTID] for x in self.get_template_hosts(template)]
items = self.z.item.get({self._FILTER:{self._NAME: item}, self._HOSTIDS: hosts, self._OUTPUT:self._EXTEND})
if not items: return []
itemids = [x[self._ITEMID] for x in items]
if not itemids: return []
if doit:
print self.z.item.delete(itemids)
return []
print 'would have deleted the following %d items:' % len(items)
return items

def delete_host_item(self, hostname, item, doit=False):
'''From a given host, Delete the item or items that matched the passed in value (ID or name).'''
hosts = [x[self._HOSTID] for x in self.get_host(hostname)]
items = [x[self._ITEMID] for x in self.get_item(item)]
if not items: return None
if doit:
return self.z.item.delete(items)
print 'would have deleted the following %d items:' % len(items)
return items

def delete_items(self, item, doit=False):
'''Delete the item or items that match the passed in value (ID or name).'''
items = [x[self._ITEMID] for x in self.get_item(item)]
if not items: return []
if doit:
return self.z.item.delete(items)
print 'would have deleted the following %d items:' % len(items)
pprint(items)
return items

def get_unsupported_item_hosts(self, item):
'''One-off function for looking for a particular item. Do not use.'''
all = self.z.item.get({self._FILTER:{self._NAME:item, self._ERROR: 'Received value [10000Mb/s] is not suitable for value type [Numeric (unsigned)] and data type [Decimal]'}, self._OUTPUT:self._EXTEND})
for a in all:
print a[self._NAME], a[self._ERROR], a['key_']
items = [x[self._ITEMID] for x in all]
return self.z.host.get({self._ITEMIDS: items, self._OUTPUT:self._EXTEND})

# }}}
# {{{ template functions

def get_template(self, t):
'''Look up a template by name or ID number. Returns a list with a single element'''
try:
int(t)
return self.z.template.get({self._TEMPLATEIDS: t, self._OUTPUT:self._EXTEND})
except:
return self.z.template.get({self._FILTER:{self._NAME: t}, self._OUTPUT:self._EXTEND})

def get_template_hosts(self, t):
'''Look up all the hosts that use the given template.'''
template = [x[self._TEMPLATEID] for x in self.get_template(t)]
return self.z.host.get({self._TEMPLATEIDS: template, self._OUTPUT:self._EXTEND})

def link_template_to_host(self, template, host):
'''Link the given template to the given host. Takes names or IDs.'''
template = self.get_template(template)
host = self.get_host(host)
print template
print host
return self.z.template.massadd({self._TEMPLATES:template, self._HOSTS:host})

def link_template_parent_to_child(self, parent, child):
'''Makes the child template a linked template of the parent template.'''
pid = self.get_template(parent)
if not pid: usage('No such template: %s' % pid)
pid = pid[0]
cid = self.get_template(child)
if not cid: usage('No such template: %s' % cid)
pid[self._TEMPLATES] = cid
pprint( pid)
return self.z.template.update(pid)

def get_template_triggers_without_urls(self, group):
'''Lists Triggers with an empty URL field. Pass in the name or ID of a Templates hostgroup'''
tmpl_hg = self.get_hostgroup(group)[0]['groupid']

output = []
tmpls = self.z.template.get({self._GROUPIDS: tmpl_hg, self._OUTPUT:self._EXTEND, self._SELECTTRIGGERS:self._EXTEND})
for tmpl in tmpls:
for trig in tmpl['triggers']:
if trig['url'] == '':
output.append(tmpl['name'] + ' - ' + trig['description'])
return output

def add_item_to_template(self, h, *args):
'''Create a new item. Takes a template and dictionary of values.'''
h = self.get_template(h)[0]
kwargs = {}
for line in args:
key, value = line.split('=',1)
try: kwargs[key] = int(value)
except: kwargs[key] = value
kwargs[self._HOSTID] = h[self._HOSTID]
return self.z.item.create(kwargs)

# }}}
# {{{ application functions

def get_application(self, hg, limit=0):
'''Look up an appliation by name or ID number. Returns a list with a single element'''
try:
int(hg)
return self.z.application.get({self._APPLICATIONIDS: hg, self._OUTPUT:self._EXTEND})
except:
return self.z.application.get({self._FILTER:{self._NAME: hg}, self._OUTPUT:self._EXTEND, self._LIMIT:limit})

def get_application_items(self, app, limit=10):
'''Look up all the items which are part of the given application, limit 10 by default.'''
appids = [x[self._APPLICATIONID] for x in self.get_application(app)]
return self.z.item.get({self._APPLICATIONIDS: appids, self._OUTPUT:self._EXTEND, self._LIMIT:limit})

def delete_application_from_hosts(self, application, limit=1, doit=False):
'''Delete an application from some number of hosts, limited to one
by default, and also limited to dry-run by default.'''
apps = self.get_application(application)
limit = int(limit)
count = 0
resultset = []
while apps and (count < limit):
a = apps.pop(0)
h = get_host(a[self._HOSTID])
if not h: continue # It was a template
count += 1
resultset.append(self.delete_host_application(h[0][self._NAME], application, doit))
return resultset

# }}}
# {{{ discovery rules

def get_discovery_rule(self, hg, limit=0):
'''Look up a discovery rule by name or ID number. Returns a list.'''
try:
int(hg)
return self.z.discoveryrule.get({self._ITEMIDS: hg, self._OUTPUT:self._EXTEND})
except:
return self.z.discoveryrule.get({self._FILTER:{self._NAME: hg}, self._OUTPUT:self._EXTEND, self._LIMIT:limit})

def delete_discovery_rule(self, hg, doit=False):
'''Delete a discovery rule from all hosts/templates. Defaults to dry-run only.'''
try:
int(hg)
rules = [hg,]
except:
rules = [x[self._ITEMID] for x in self.get_discovery_rule(hg)]
if not rules: return None
if doit:
return self.z.discoveryrule.delete(rules)
print 'would have deleted the following %d rules:' % len(rules)
return rules

def delete_discovery_rule_hosts(self, hg, limit=1, doit=False):
'''Deletes the indicated discovery rule from hosts, leaving the template untouched.'''
rules = self.get_discovery_rule(hg)
limit = int(limit)
count = 0
resultset = []
while rules and (count < limit):
a = rules.pop(0)
h = self.get_host(a[self._HOSTID])
if not h: continue # It was a template
count += 1
resultset.append(self.delete_discovery_rule(a[self._ITEMID], doit))
return resultset

# }}}
# {{{ trigger functions

def get_trigger(self, t):
'''Look up a trigger by name or ID number. Returns a list with a single element'''
try:
int(t)
return self.z.trigger.get({self._TRIGGERIDS: t, self._OUTPUT:self._EXTEND})
except:
return self.z.trigger.get({self._FILTER:{self._NAME: t}, self._OUTPUT:self._EXTEND})

def get_trigger_hosts(self, trigger):
'''List all the hosts with the given trigger.'''
triggers = self.get_trigger(trigger)
return self.z.trigger.get({self._TRIGGERIDS: triggers, self._OUTPUT:self._EXTEND})

def delete_trigger(self, trigger, doit=False):
'''Delete the given trigger. Defaults to dry-run only.'''
try:
int(trigger)
triggers = [trigger,]
except:
triggers = [x[self._ITEMID] for x in self.get_trigger(trigger)]
if not triggers: return None
if doit:
return self.z.trigger.delete(triggers)
print 'would have deleted the following %d triggers:' % len(triggers)
return triggers

return self.z.trigger.get({self._TRIGGERIDS: triggers, self._OUTPUT:self._EXTEND})

def find_trigger(self, term, limit=10):
'''Search trigger descriptions for a given string.'''
return self.z.trigger.get({self._SEARCH:{self._DESCRIPTION:term, self._SEARCHWILDCARDSENABLED:True}, self._OUTPUT:self._EXTEND, self._LIMIT:limit})

# }}}
# {{{ prototype functions
def get_item_prototype(self, ip, limit=0):
'''Look up an itemprototype. Returns a list'''
try:
int(ip)
return self.z.itemprototype.get({self._ITEMIDS: ip, self._OUTPUT:self._EXTEND})
except:
return self.z.itemprototype.get({self._FILTER:{self._NAME: ip}, self._OUTPUT:self._EXTEND, self._LIMIT:limit})


def get_trigger_prototype(self, ip, limit=0):
'''Look up a triggerprototype. Returns a list'''
try:
int(ip)
return self.z.triggerprototype.get({self._TRIGGERIDS: ip, self._OUTPUT:self._EXTEND})
except:
return self.z.triggerprototype.get({self._FILTER:{self._NAME: ip}, self._OUTPUT:self._EXTEND, self._LIMIT:limit})
# }}}
# {{{special_lld_in_template( template_name, key, lld_name):

def special_lld_in_template(self, template_name, key, lld_name):
'''Add a new LLD rule with the requisite, e.g.

zabbix_tool special_lld_in_template test-template-discovery-geek bletchley 'Discovery - Unlikely Mountpoints'

(with the current code) will create a discovery rule in
test-template-discovery-geek that will use BLETCHLEY as the
differentiator in the key, with 8 items and 4 triggers. Assuming,
of course, that it all completes successfully. There is a great
deal of contention on the `ids` table.
'''
template = self.get_template(template_name)[0]
lld = self.z.discoveryrule.create({
u'key_': "vfs.fs.discovery_llnw[%s]" % key,
self._NAME: lld_name,
self._HOSTID: template[self._HOSTID],
'type': "0",
'delay': 21600,
'filter': '{#%s}:^\/d\d+' % key.upper(),
'status': '1', # 1 is disabled
'interfaceid': "0",
})
lld = self.get_discovery_rule(lld[self._ITEMIDS][0],1)[0]

itemprototypes = self.z.itemprototype.create([
{ 'ruleid': lld[self._ITEMID],
'delay': '1800',
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'key_': 'vfs.fs.size[{#%s},free]' % key.upper(),
'name': 'Free disk space on {#%s}' % key.upper(),
'type': '0',
'value_type': '3',
'history': '7',
'units': 'B'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '1800',
'key_': 'vfs.fs.size[{#%s},pfree]' % key.upper(),
'name': 'Free disk space on {#%s} in %%' % key.upper(),
'units': '%',
'value_type': '0'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '900',
'key_': 'vfs.fs.inode[{#%s},pfree]' % key.upper(),
'name': 'Free number of inodes on {#%s} in %%' % key.upper(),
'units': '%',
'value_type': '0'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '600',
'key_': 'mountpoint[{#%s}]' % key.upper(),
'name': 'Mount point status for {#%s}' % key.upper(),
'units': '',
'value_type': '3'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '21600',
'key_': 'vfs.fs.size[{#%s},total]' % key.upper(),
'name': 'Total disk space on {#%s}' % key.upper(),
'units': 'B',
'value_type': '3'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '21600',
'key_': 'vfs.fs.inode[{#%s},total]' % key.upper(),
'name': 'Total number of inodes on {#%s}' % key.upper(),
'units': '',
'value_type': '3'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '1800',
'key_': 'vfs.fs.size[{#%s},used]' % key.upper(),
'name': 'Used disk space on {#%s}' % key.upper(),
'units': 'B',
'value_type': '3'},
{ 'ruleid': lld[self._ITEMID],
'hostid': lld[self._HOSTID],
'interfaceid': "0",
'type': '0',
'history': '7',
'delay': '600',
'key_': 'vfs.fs.size[{#%s},pused]' % key.upper(),
'name': 'Used disk space on {#%s} in %%' % key.upper(),
'units': '%',
'value_type': '0'}
])

triggerprototypes = self.z.triggerprototype.create([
{'description': 'directory {#%s} does not exist on {HOSTNAME}' % key.upper(),
'expression': '{%s:mountpoint[{#%s}].last(0)}=2' % (template[self._HOST],key.upper()),
'priority': 1},
{'description': 'directory {#%s} is not a moint point on {HOSTNAME}' % key.upper(),
'expression': '{%s:mountpoint[{#%s}].last(0)}=1' % (template[self._HOST],key.upper()),
'priority': 1},
{'description': 'Disk utilization on {#%s} above 98%% on {HOSTNAME}' % key.upper(),
'expression': '{%s:vfs.fs.size[{#%s},pused].last(0)}>98' % (template[self._HOST],key.upper()),
'priority': 1},
{'description': 'Free Inodes on {#%s} below 10%% on {HOSTNAME}' % key.upper(),
'expression': '{%s:vfs.fs.inode[{#%s},pfree].last(0)}<10' % (template[self._HOST],key.upper()),
'priority': 1}, # Information
])

return (lld, itemprototypes, triggerprototypes)

# }}}

# }}}
# {{{ class MyParser

class MyParser(OptionParser):
def format_epilog(self, formatter):
return self.epilog

# }}}
# {{{ main()

if __name__ == '__main__':
tool = Tool() # Cheating!
# Handle command-line options
parser = MyParser(epilog=render_doc(tool, '%s') + CONFIG_HELP)
parser.add_option("-c", "--config", dest="config", default=os.environ['HOME'] + '/.zabbix',
help="CONFIG file", metavar="CONFIG")
parser.add_option("-s", "--section", dest="section", default='zabbix',
help="Section of config file to use file", metavar="SECTION")
parser.add_option("-l", "--loglevel",
dest=LOGLEVEL, default=logging.ERROR, type="int",
help="Set logging level (0-50), defaults to 40 (only errors)")
parser.add_option("--filter",
dest=FILTER, default=None,
help="Only print the named field of the returned items")

(options, args) = parser.parse_args()
options = eval(str(options))

config = ConfigParser.ConfigParser()
try:
config.readfp(open(options[CONFIG]))
except Exception, e:
print 'Unable to parse the configuration file(%s): %s\n\n' % (options.config, e)
raise
if not options[SECTION] in config.sections():
raise SystemExit('No [zabbix] section in the configuration file')

for (key, value) in config.items(options[SECTION], 1):
options[key] = eval(value)

tool._start(**options) # Cheating!
if not args:
parser.print_help()
exit()
func = args.pop(0)
try: cmd = eval('tool.' + func)
except:
print 'No such function: %s' % func
parser.print_help()
exit()

try: results = cmd(*args)
except TypeError:
print render_doc(cmd)
exit()
if options[FILTER]:
for name in results:
output = name.get(options[FILTER], None)
if output: print output
else:
print '********* Results ********'
pprint( results)
print len(results)

# }}}
 
projeto & código: Vladimir Lettiev aka crux © 2004-2005, Andrew Avramenko aka liks © 2007-2008
mantenedor atual: Michael Shigorin
mantenedor da tradução: Fernando Martini aka fmartini © 2009