completed updates to the info model.
[monitor.git] / zabbix / zabbixsite.py
1 #!/usr/bin/python
2
3 from os import getcwd
4 from os.path import dirname, exists, join
5 import sys
6 import md5
7 import glob
8
9 from monitor import config
10 from monitor.database.dborm import zab_session as session
11 from monitor.database.zabbixapi.model import *
12 from monitor.database.zabbixapi.emailZabbix import *
13 from monitor.database.zabbixapi import defines
14 from monitor.util.file import *
15
16
17
18 HOSTGROUP_NAME="%s_hostgroup"
19 USERGROUP_NAME="%s_usergroup"
20         
21 DISCOVERY_RULE_NAME="discovery rule for %s"
22 DISCOVERY_ACTION_NAME="Auto-discover %s action"
23 ESCALATION_ACTION_NAME="Escalation Action for %s"
24
25 def delete_site(loginbase):
26
27         # get host group, usrgrp
28         # get all users in usrgrp, delete each
29         usergroupname = USERGROUP_NAME % loginbase
30         hostgroupname = HOSTGROUP_NAME % loginbase
31         discovery_action_name = DISCOVERY_ACTION_NAME % loginbase
32         discovery_rule_name = DISCOVERY_RULE_NAME % loginbase
33         escalation_action_name = ESCALATION_ACTION_NAME % loginbase
34
35         ug = UsrGrp.get_by(name=usergroupname)
36         if ug:
37                 for user in ug.user_list:
38                         # remove user from group, if a member of no other groups, 
39                         # delete user.
40                         #user.delete()
41                         pass
42                 ug.delete()
43
44         hg = HostGroup.get_by(name=hostgroupname)
45         if hg: 
46                 # figure out how to delete all the hosts...
47                 # NOTE: hosts are listed in hg.host_list
48                 for host in hg.host_list:
49                         host.delete()
50                 hg.delete()
51
52         # delete dr
53         dr = DiscoveryRule.get_by(name=discovery_rule_name)
54         if dr: dr.delete()
55
56         da = Action.get_by(name=discovery_action_name)
57         if da: da.delete()
58
59         ea = Action.get_by(name=escalation_action_name)
60         if ea: ea.delete()
61
62         return
63
64
65 def setup_global():
66         # GLOBAL:
67         #       update mediatype for email.
68         ############################### MAIL
69         print "checking for MediaType Email"
70         mediatype = MediaType.get_by(description="Email")
71         if not mediatype:
72                 print "ERROR:  There is no defined media type for 'Email'"
73                 raise Exception("No Email Media type in Zabbix db")
74
75         print "checking for correct configuration"
76         mediatype = MediaType.get_by(smtp_email=config.from_email)
77         if not mediatype:
78                 mediatype = MediaType.get_by(description="Email")
79                 # NOTE: assumes smtp server is local to this machine.
80                 print "updating email server configuration"
81                 mediatype.smtp_server='localhost'
82                 mediatype.smtp_helo=".".join(config.MONITOR_HOSTNAME.split('.')[1:])
83                 mediatype.smtp_email=config.from_email
84
85         ############################# EMAIL
86         mailtxt.reformat({'hostname' : config.MONITOR_HOSTNAME, 
87                                           'support_email' : config.support_email})
88
89         ############################### CENTRAL SERVER
90         print "checking zabbix server host info"
91         zabbixserver = Host.get_by(host="ZABBIX Server")
92         if zabbixserver:
93                 # TODO: verify that this works.  it has failed once on fresh
94                 # install... not sure why.
95                 print "Removing default Zabbix server entry"
96                 zabbixserver.delete()
97
98                 # NOTE: creating a host and assigning a template cannot work 
99                 #       due to the crazy item, trigger, action
100                 #               copying that the php code does during a host add.
101                 # NOTE: Instead, reformat any *xml.in templates and import those
102                 #               during /etc/plc.d/monitor sync
103                 for file in glob.glob("%s/zabbix/templates/*.xml.in" config.MONITOR_SCRIPT_ROOT):
104                         if 'zabbix_server' in file:
105                                 buf = loadFile(file)
106                                 args = {'hostname' : config.MONITOR_HOSTNAME, 'ip' : config.MONITOR_IP}
107                                 dumpFile(file[:-3], buf % args)
108
109
110         ##################### SCRIPTS 
111         ## TODO: add calls to check/reset the boot states.
112         print "checking scripts"
113         script1 = Script.find_or_create(name="RebootNode",
114                                                                         set_if_new = {
115                                                                                 'command':"%s/reboot.py {HOST.CONN}" % config.MONITOR_SCRIPT_ROOT,
116                                                                                 'host_access':3 # r/w)
117                                                                         })
118         script2 = Script.find_or_create(name="NMap",
119                                                         set_if_new = {
120                                                                 'command':"/usr/bin/nmap -A {HOST.CONN}",
121                                                                 'host_access':2 # r/o)
122                                                 })
123         return
124
125 def merge_iplist(iplist):
126         # TODO:  rewrite addresses as x.x.x.y-z rather than x.x.x.y,x.x.x.z if y-z==1
127         ips = iplist.split(',')
128         ips.sort()
129         prev=None
130         newlist=""
131         for ip in ips:
132                 fields = ip.split('.')
133                 first = ".".join(fields[:2])
134                 last  = int(fields[3])
135                 if prev:
136                         if last - prev == 1:
137                                 pass
138                 prev=last
139                 newlist += "%s,"
140         return newlist[:-1]
141
142 def setup_site(loginbase, techemail, piemail, iplist):
143
144         # TODO: send a message when host is discovered.
145
146         # TODO: update 'discovered' hosts with dns name.
147         # TODO: remove old nodes that are no longer in the plcdb.
148         # TODO: remove old users that are no longer in the plcdb.
149         # TODO: consider creating two user groups for Tech & PI emails
150
151         # NOTE: setup default valus for EMAIL
152         mailtxt.reformat({'hostname' : config.MONITOR_HOSTNAME, 
153                                           'support_email' : config.support_email})
154
155         # NOTE: verify arguments
156         if len(iplist) > 255:
157                 raise Exception("iplist length is too long!")
158
159         BI_WEEKLY_ESC_PERIOD = int(60*60*24)
160         #BI_WEEKLY_ESC_PERIOD = int(60) # testing...
161
162         # User Group
163         site_user_group = UsrGrp.find_or_create(name=USERGROUP_NAME % loginbase)
164         for user in set(techemail + piemail + [config.cc_email]):
165                 if not user: continue
166                 # USER
167                 u = User.find_or_create(alias=user, type=1,
168                                                                 set_if_new={'passwd' : md5.md5(user).hexdigest()},
169                                                                 # exec_if_new avoids creating a Media object that
170                                                                 # will not actually be used, if the user already exists
171                                                                 exec_if_new=lambda obj: \
172                                                                 obj.media_list.append( Media(mediatypeid=1, sendto=user)))
173
174                 if site_user_group not in u.usrgrp_list:
175                         u.append_group(site_user_group)
176
177         # HOST GROUP
178         plc_host_group = HostGroup.find_or_create(name="MyPLC Hosts")
179         site_host_group = HostGroup.find_or_create(name=HOSTGROUP_NAME % loginbase)
180         plctemplate = Host.get_by(host="Template_Linux_PLC_Host")
181         escalation_action_name = ESCALATION_ACTION_NAME % loginbase
182         discovery_action_name = DISCOVERY_ACTION_NAME % loginbase
183         discovery_rule_name = DISCOVERY_RULE_NAME % loginbase
184
185         # ADD hg to ug
186         if site_host_group not in site_user_group.hostgroup_list:
187                 site_user_group.append_hostgroup(site_host_group)
188
189         # DISCOVERY RULE & CHECK
190         dr = DiscoveryRule.find_or_create(name=discovery_rule_name,
191                           delay=3600,
192                           proxy_hostid=0,
193                           set_if_new = {'iprange':iplist},
194                           exec_if_new=lambda obj: \
195                                 obj.discoverycheck_list.append( DiscoveryCheck(type=9, 
196                                                                                 key_="system.uname", ports=10050) )
197                         )
198         if dr.iprange != iplist:
199                 dr.iprange = iplist
200                 
201
202         # DISCOVERY ACTION for these servers
203         a = Action.find_or_create(name=discovery_action_name,
204                         eventsource=defines.EVENT_SOURCE_DISCOVERY,
205                         status=defines.DRULE_STATUS_ACTIVE,
206                         evaltype=defines.ACTION_EVAL_TYPE_AND_OR)
207         if len(a.actioncondition_list) == 0:
208                 a.actioncondition_list=[
209                                         # Host IP Matches
210                                         ActionCondition(
211                                                 conditiontype=defines.CONDITION_TYPE_DHOST_IP,
212                                                 operator=defines.CONDITION_OPERATOR_EQUAL,
213                                                 value=iplist),
214                                         # AND, Service type is Zabbix agent
215                                         ActionCondition(
216                                                 conditiontype=defines.CONDITION_TYPE_DSERVICE_TYPE,
217                                                 operator=defines.CONDITION_OPERATOR_EQUAL,
218                                                 value=defines.SVC_AGENT),
219                                         # AND, Received system.uname value like 'Linux'
220                                         ActionCondition(
221                                                 conditiontype=defines.CONDITION_TYPE_DVALUE,
222                                                 operator=defines.CONDITION_OPERATOR_LIKE,
223                                                 value="Linux"),
224                                         # AND, Discovery status is Discover
225                                         ActionCondition(
226                                                 conditiontype=defines.CONDITION_TYPE_DSTATUS,
227                                                 operator=defines.CONDITION_OPERATOR_EQUAL,
228                                                 value=defines.DOBJECT_STATUS_DISCOVER),
229                                 ]
230                                 # THEN
231                 a.actionoperation_list=[
232                                         # Add Host
233                                         ActionOperation(
234                                                 operationtype=defines.OPERATION_TYPE_HOST_ADD,
235                                                 object=0, objectid=0,
236                                                 esc_period=0, esc_step_from=1, esc_step_to=1),
237                                         # Add To Group PLC Hosts
238                                         ActionOperation(
239                                                 operationtype=defines.OPERATION_TYPE_GROUP_ADD,
240                                                 object=0, objectid=plc_host_group.groupid,
241                                                 esc_period=0, esc_step_from=1, esc_step_to=1),
242                                         # Add To Group LoginbaseSiteGroup
243                                         ActionOperation(
244                                                 operationtype=defines.OPERATION_TYPE_GROUP_ADD,
245                                                 object=0, objectid=site_host_group.groupid,
246                                                 esc_period=0, esc_step_from=1, esc_step_to=1),
247                                         # Link to Template 'Template_Linux_Minimal'
248                                         ActionOperation(
249                                                 operationtype=defines.OPERATION_TYPE_TEMPLATE_ADD,
250                                                 object=0, objectid=plctemplate.hostid,
251                                                 esc_period=0, esc_step_from=1, esc_step_to=1),
252                                 ]
253         else:
254                 # TODO: verify iplist is up-to-date
255                 # NOTE: len(a.actioncondition_list) > 0
256                 ip_condition  = a.actioncondition_list[0]
257                 assert ip_condition.conditiontype == defines.CONDITION_TYPE_DHOST_IP
258                 if ip_condition.value != iplist:
259                         ip_condition.value = iplist
260
261         # ESCALATION ACTION for these servers
262         ea = Action.find_or_create(name=escalation_action_name,
263                         eventsource=defines.EVENT_SOURCE_TRIGGERS,
264                         status=defines.ACTION_STATUS_ENABLED,
265                         evaltype=defines.ACTION_EVAL_TYPE_AND_OR,
266                         esc_period=BI_WEEKLY_ESC_PERIOD,        # three days
267                         recovery_msg=1,
268                         set_if_new={
269                                 'r_shortdata':"Thank you for maintaining {HOSTNAME}!",
270                                 'r_longdata': mailtxt.thankyou_nodeup, }
271                         )
272         if len(ea.actioncondition_list) == 0:
273                         # THEN this is a new entry
274                 print "SETTING UP ESCALATION ACTION"
275                 ea.actioncondition_list=[
276                                 ActionCondition(conditiontype=defines.CONDITION_TYPE_TRIGGER_VALUE, 
277                                                                 operator=defines.CONDITION_OPERATOR_EQUAL, 
278                                                                 value=defines.TRIGGER_VALUE_TRUE),
279                                 ActionCondition(conditiontype=defines.CONDITION_TYPE_TRIGGER_NAME, 
280                                                                 operator=defines.CONDITION_OPERATOR_LIKE, 
281                                                                 value="is unreachable"),
282                                 ActionCondition(conditiontype=defines.CONDITION_TYPE_HOST_GROUP, 
283                                                                 operator=defines.CONDITION_OPERATOR_EQUAL, 
284                                                                 value=site_host_group.groupid),
285                         ]
286                 ea.actionoperation_list=[
287                                 # STAGE 1
288                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE,
289                                         shortdata=mailtxt.nodedown_one_subject,
290                                         longdata=mailtxt.nodedown_one,
291                                         object=defines.OPERATION_OBJECT_GROUP, 
292                                         objectid=site_user_group.usrgrpid, 
293                                         esc_period=0, esc_step_to=3, esc_step_from=3, 
294                                         operationcondition_list=[ OperationConditionNotAck() ] ),
295                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE,
296                                         shortdata=mailtxt.nodedown_one_subject,
297                                         longdata=mailtxt.nodedown_one,
298                                         object=defines.OPERATION_OBJECT_GROUP, 
299                                         objectid=site_user_group.usrgrpid, 
300                                         esc_period=0, esc_step_to=7, esc_step_from=7, 
301                                         operationcondition_list=[ OperationConditionNotAck() ] ),
302                                 # STAGE 2
303                                 ActionOperation(operationtype=defines.OPERATION_TYPE_COMMAND, 
304                                         esc_step_from=10, esc_step_to=10, 
305                                         esc_period=0,
306                                         shortdata="",
307                                         longdata="%s:%s/checkslices.py {HOSTNAME} disablesite" % ( config.MONITOR_HOSTNAME, config.MONITOR_SCRIPT_ROOT ), 
308                                         operationcondition_list=[ OperationConditionNotAck() ]),
309                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE, 
310                                         shortdata=mailtxt.nodedown_two_subject,
311                                         longdata=mailtxt.nodedown_two,
312                                         esc_step_from=10, esc_step_to=10, 
313                                         esc_period=0, 
314                                         object=defines.OPERATION_OBJECT_GROUP, 
315                                         objectid=site_user_group.usrgrpid, 
316                                         operationcondition_list=[ OperationConditionNotAck() ] ), 
317                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE, 
318                                         shortdata=mailtxt.nodedown_two_subject,
319                                         longdata=mailtxt.nodedown_two,
320                                         esc_step_from=14, esc_step_to=14, 
321                                         esc_period=0, 
322                                         object=defines.OPERATION_OBJECT_GROUP, 
323                                         objectid=site_user_group.usrgrpid, 
324                                         operationcondition_list=[ OperationConditionNotAck() ] ), 
325
326                                 # STAGE 3
327                                 ActionOperation(operationtype=defines.OPERATION_TYPE_COMMAND, 
328                                         esc_step_from=17, esc_step_to=17, 
329                                         esc_period=0, 
330                                         shortdata="",
331                                         longdata="%s:%s/checkslices.py {HOSTNAME} disableslices" % ( config.MONITOR_HOSTNAME, config.MONITOR_SCRIPT_ROOT ), 
332                                         # TODO: send notice to users of slices
333                                         operationcondition_list=[ OperationConditionNotAck() ]),
334                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE, 
335                                         shortdata=mailtxt.nodedown_three_subject,
336                                         longdata=mailtxt.nodedown_three,
337                                         esc_step_from=17, esc_step_to=17, 
338                                         esc_period=0, 
339                                         object=defines.OPERATION_OBJECT_GROUP, 
340                                         objectid=site_user_group.usrgrpid, 
341                                         operationcondition_list=[ OperationConditionNotAck() ] ), 
342                                 # STAGE 4++
343                                 ActionOperation(operationtype=defines.OPERATION_TYPE_COMMAND, 
344                                         esc_step_from=21, esc_step_to=0, 
345                                         esc_period=int(BI_WEEKLY_ESC_PERIOD*3.5),
346                                         shortdata="",
347                                         longdata="%s:%s/checkslices.py {HOSTNAME} forever" % ( config.MONITOR_HOSTNAME, config.MONITOR_SCRIPT_ROOT), 
348                                         operationcondition_list=[ OperationConditionNotAck() ]),
349                                 ActionOperation(operationtype=defines.OPERATION_TYPE_MESSAGE, 
350                                         shortdata=mailtxt.nodedown_four_subject,
351                                         longdata=mailtxt.nodedown_four,
352                                         esc_step_from=21, esc_step_to=0, 
353                                         esc_period=int(BI_WEEKLY_ESC_PERIOD*3.5),
354                                         object=defines.OPERATION_OBJECT_GROUP, 
355                                         objectid=site_user_group.usrgrpid, 
356                                         operationcondition_list=[ OperationConditionNotAck() ] ), 
357                         ]
358
359 if __name__ == "__main__":
360         setup_global()
361         session.flush()