clearer names for actions, and infer actions better
[monitor.git] / zabbix / zabbixsync.py
index 8c078e7..340b4d8 100755 (executable)
@@ -1,18 +1,22 @@
 #!/usr/bin/python
 
 import sys
+import os
 import site
-from monitor.wrapper import plc
+from monitor.config import config
+config.zabbix_enabled = True
+
+from monitor.wrapper import plc, plccache
 from monitor import database
 
 import zabbixsite
-from monitor.database.dborm import session
+from monitor.database.dborm import zab_session as session
+from monitor.database.zabbixapi.model import confirm_ids, HostGroup
 
-print "test"
 
-plcdb = database.dbLoad("l_plcsites")
-netid2ip = database.dbLoad("plcdb_netid2ip")
-lb2hn = database.dbLoad("plcdb_lb2hn")
+plcdb = plccache.l_sites # database.dbLoad("l_plcsites")
+#netid2ip = plccache.plcdb_netid2ip # database.dbLoad("plcdb_netid2ip")
+lb2hn = plccache.plcdb_lb2hn # database.dbLoad("plcdb_lb2hn")
 
 def get_site_iplist(loginbase):
        node_list = lb2hn[loginbase]
@@ -21,9 +25,13 @@ def get_site_iplist(loginbase):
        # TODO: if it is, then we need to break up the discovery rule.
        ip_list = ""
        for node in node_list:
-               ip = netid2ip[node['nodenetwork_ids'][0]]
-               if len(ip_list) > 0: ip_list += ","
-               ip_list += ip
+               if len(node['interface_ids']) > 0:
+                       ifs = plc.api.GetInterfaces({'interface_id' : node['interface_ids'], 'is_primary' : True})
+                       print ifs
+                       #ip = netid2ip[node['interface_ids'][0]]
+                       ip = ifs[0]['ip']
+                       if len(ip_list) > 0: ip_list += ","
+                       ip_list += ip
 
        return ip_list
        
@@ -33,43 +41,66 @@ def add_loginbase(loginbase):
        pis = plc.getPIEmails(loginbase)
        iplist = get_site_iplist(loginbase)
 
+       os.system("""echo '%s' | tr ',' '\n' >> /usr/share/monitor/nodelist.txt""" % iplist )
+
        print "zabbixsite.setup_site('%s', %s, %s, '%s')" % (loginbase,techs, pis, iplist)
        zabbixsite.setup_site(loginbase, techs, pis, iplist)
 
 if __name__=="__main__":
-       #sites = api.GetSites({'peer_id' : None}, ['login_base'])
-       for loginbase in ['princeton', 'princetondsl', 'monitorsite']:
-               add_loginbase(loginbase)
-
-       session.flush()
-
-## Scripts : includes external scripts to: 
-#                - reboot.py
-#                - nmap
-
-## UserGroups
-# define technical contact, principal investigator groups
-# define a Group for every site
-
-## Users
-# define a User for every user with admin/tech/pi roles
-#              get passwords from a combination of site&name, perhaps?
-#              I'm guessing we could use the grpid or userid as part of the passwd,
-#              so that it varies in general, and can be guessed from the templates
-# add user to groups
-
-## Discovery Rules and Actions
-# define a discovery rule for every site's hosts.
-# define discovery action for online hosts.
-
-## Messages & Escalations
-# define actions and escellations for trigger sources:
-#              - unreachable host,
-
-## HostGroups
-# add host group for every site
-# add host group for global network (PLC name)
-
-## Hosts & Templates
-# no need to define hosts?
-# add template?  It appears that the xml-based tempate system is sufficient.
+
+       from monitor import parser as parsermodule
+       parser = parsermodule.getParser(['cacheset'])
+       parser.set_defaults( setupglobal=False, syncsite=True, site=None, sitelist=None, setupids=False)
+       parser.add_option("", "--setupids", action="store_true", dest="setupids",
+                                               help="Setup global IDs.")
+       parser.add_option("", "--setupglobal", action="store_true", dest="setupglobal",
+                                               help="Setup global settings.")
+       parser.add_option("", "--nosite", action="store_false", dest="syncsite",
+                                               help="Do not sync sites.")
+       parser.add_option("", "--site", dest="site",
+                                               help="Sync only given site name.")
+       parser.add_option("", "--sitelist", dest="sitelist",
+                                               help="Sync only given site names in the list.")
+       opts = parsermodule.parse_args(parser)
+
+       os.system("""echo '' > /usr/share/monitor/nodelist.txt""")
+
+       if opts.setupids:
+               # Not sure why, but this doesn't work if we continue.  so exit.
+               # This step only needs to be called once, but there is no harm in
+               # calling it multiple times.
+               confirm_ids()
+               session.flush()
+               sys.exit(0)
+
+       if opts.setupglobal:
+               zabbixsite.setup_global()
+               session.flush()
+
+       if opts.syncsite:
+               api = plc.getCachedAuthAPI()
+               query = {'peer_id' : None}
+               if opts.site:
+                       query.update({'login_base' : opts.site})
+               elif opts.sitelist:
+                       l = opts.sitelist.split(",")
+                       query.update({'login_base' : l})
+
+               # ADD SITES
+               sites = api.GetSites(query, ['login_base'])
+               site_api_list = [ site['login_base'] for site in sites ]
+               for site in sites: # [:20]:
+                       add_loginbase(site['login_base'])
+                       session.flush()
+
+               if not opts.site:
+                       # NOTE: for all sites in DB but not API, call zabbixsite.delete_site()
+                       hg_list = filter(lambda x: '_hostgroup' in x.name, HostGroup.query.all() )
+                       site_db_list = [ hg.name[:-len('_hostgroup')] for hg in hg_list ]
+                       in_db_not_plc = set(site_db_list) - set(site_api_list)
+                       for login_base in in_db_not_plc:
+                               print "Deleting %s" % login_base
+                               zabbixsite.delete_site(login_base)
+                               session.flush()
+
+