added templates for emailTxt
[monitor.git] / monitor / database / info / interface.py
1
2 from monitor import reboot
3 from monitor.common import *
4 from monitor.model import *
5 from monitor.wrapper import plc
6 from monitor.wrapper import plccache
7 from monitor.wrapper.emailTxt import mailtxt
8 from monitor.database.info.model import *
9
10 class SiteInterface(HistorySiteRecord):
11         @classmethod
12         def get_or_make(cls, if_new_set={}, **kwargs):
13                 if 'hostname' in kwargs:
14                         kwargs['loginbase'] = plccache.plcdb_hn2lb[kwargs['hostname']]
15                         del kwargs['hostname']
16                 res = HistorySiteRecord.findby_or_create(if_new_set, **kwargs)
17                 return SiteInterface(res)
18         
19         def __init__(self, sitehist):
20                 self.db = sitehist
21
22         def getRecentActions(self, **kwargs):
23                 # TODO: make query only return records within a certin time range,
24                 # i.e. greater than 0.5 days ago. or 5 days, etc.
25
26                 #print "kwargs: ", kwargs
27
28                 recent_actions = []
29                 if 'loginbase' in kwargs:
30                         recent_actions = ActionRecord.query.filter_by(loginbase=kwargs['loginbase']).order_by(ActionRecord.date_created.desc())
31                 elif 'hostname' in kwargs:
32                         recent_actions = ActionRecord.query.filter_by(hostname=kwargs['hostname']).order_by(ActionRecord.date_created.desc())
33                 return recent_actions
34         
35         def increasePenalty(self):
36                 #act = ActionRecord(loginbase=self.db.loginbase, action='penalty', action_type='increase_penalty',)
37                 self.db.penalty_level += 1
38                 # NOTE: this is to prevent overflow or index errors in applyPenalty.
39                 #       there's probably a better approach to this.
40                 if self.db.penalty_level >= 2:
41                         self.db.penalty_level = 2
42                 self.db.penalty_applied = True
43         
44         def applyPenalty(self):
45                 penalty_map = [] 
46                 penalty_map.append( { 'name': 'noop',                   'enable'   : lambda site: None,
47                                                                                                                 'disable'  : lambda site: None } )
48                 penalty_map.append( { 'name': 'nocreate',               'enable'   : lambda site: plc.removeSiteSliceCreation(site),
49                                                                                                                 'disable'  : lambda site: plc.enableSiteSliceCreation(site) } )
50                 penalty_map.append( { 'name': 'suspendslices',  'enable'   : lambda site: plc.suspendSiteSlices(site),
51                                                                                                                 'disable'  : lambda site: plc.enableSiteSlices(site) } )
52
53                 for i in range(len(penalty_map)-1,self.db.penalty_level,-1):
54                         print "\tdisabling %s on %s" % (penalty_map[i]['name'], self.db.loginbase)
55                         penalty_map[i]['disable'](self.db.loginbase) 
56
57                 for i in range(0,self.db.penalty_level+1):
58                         print "\tapplying %s on %s" % (penalty_map[i]['name'], self.db.loginbase)
59                         penalty_map[i]['enable'](self.db.loginbase)
60
61                 return
62
63         def pausePenalty(self):
64                 act = ActionRecord(loginbase=self.db.loginbase,
65                                                         action='penalty',
66                                                         action_type='pause_penalty',)
67         
68         def clearPenalty(self):
69                 #act = ActionRecord(loginbase=self.db.loginbase, action='penalty', action_type='clear_penalty',)
70                 self.db.penalty_level = 0
71                 self.db.penalty_applied = False
72         
73         def getTicketStatus(self):
74                 if self.db.message_id != 0:
75                         rtstatus = mailer.getTicketStatus(self.db.message_id)
76                         self.db.message_status = rtstatus['Status']
77                         self.db.message_queue = rtstatus['Queue']
78                         self.db.message_created = datetime.fromtimestamp(rtstatus['Created'])
79
80         def setTicketStatus(self, status):
81                 print 'SETTING status %s' % status
82                 if self.db.message_id != 0:
83                         rtstatus = mailer.setTicketStatus(self.db.message_id, status)
84
85         def getContacts(self):
86                 contacts = []
87                 if self.db.penalty_level >= 0:
88                         contacts += plc.getTechEmails(self.db.loginbase)
89
90                 if self.db.penalty_level >= 1:
91                         contacts += plc.getPIEmails(self.db.loginbase)
92
93                 if self.db.penalty_level >= 2:
94                         contacts += plc.getSliceUserEmails(self.db.loginbase)
95
96                 return contacts
97
98         def sendMessage(self, type, **kwargs):
99
100                 # NOTE: evidently changing an RT message's subject opens the ticket.
101                 #       the logic in this policy depends up a ticket only being 'open'
102         #       if a user has replied to it.
103         #       So, to preserve these semantics, we check the status before
104         #           sending, then after sending, reset the status to the
105         #           previous status.
106         #       There is a very tiny race here, where a user sends a reply
107         #           within the time it takes to check, send, and reset.
108         #       This sucks.  It's almost certainly fragile.
109
110                 # 
111                 # TODO: catch any errors here, and add an ActionRecord that contains
112                 #       those errors.
113                 
114                 args = {'loginbase' : self.db.loginbase, 
115                                 'penalty_level' : self.db.penalty_level,
116                                 'monitor_hostname' : config.MONITOR_HOSTNAME,
117                                 'support_email'   : config.support_email,
118                                 'plc_name' : config.PLC_NAME,
119                                 'plc_hostname' : config.PLC_WWW_HOSTNAME}
120                 args.update(kwargs)
121
122                 hostname = None
123                 if 'hostname' in args:
124                         hostname = args['hostname']
125
126                 if hasattr(mailtxt, type):
127
128                         message = getattr(mailtxt, type)
129
130                         saveact = True
131                         viart = True
132                         if 'viart' in kwargs: 
133                                 saveact = kwargs['viart']
134                                 viart = kwargs['viart']
135
136                         if 'saveact' in kwargs: 
137                                 saveact = kwargs['saveact']
138
139                         if viart:
140                                 self.getTicketStatus()          # get current message status
141                                 if self.db.message_status not in ['open', 'new']:
142                                         self.closeTicket()
143
144                         m = Message(message[0] % args, message[1] % args, viart, self.db.message_id)
145
146                         contacts = self.getContacts()
147                         #contacts = [config.cc_email]
148
149                         print "sending message: %s to site %s for host %s" % (type, self.db.loginbase, hostname)
150
151                         ret = m.send(contacts)
152                         if viart:
153                                 self.db.message_id = ret
154                                 # reset to previous status, since a new subject 'opens' RT tickets.
155                                 self.setTicketStatus(self.db.message_status) 
156
157                         if saveact:
158                                 # NOTE: only make a record of it if it's in RT.
159                                 act = ActionRecord(loginbase=self.db.loginbase, hostname=hostname, action='notice', 
160                                                                 action_type=type, message_id=self.db.message_id)
161
162                 else:
163                         print "+-- WARNING! ------------------------------"
164                         print "| No such message name in emailTxt.mailtxt: %s" % type
165                         print "+------------------------------------------"
166
167                 return
168
169         def closeTicket(self):
170                 if self.db.message_id:
171                         mailer.closeTicketViaRT(self.db.message_id, "Ticket Closed by Monitor")
172                         act = ActionRecord(loginbase=self.db.loginbase, action='notice', 
173                                                                 action_type='close_ticket', message_id=self.db.message_id)
174                         self.db.message_id = 0
175                         self.db.message_status = "new"
176
177         def runBootManager(self, hostname):
178                 from monitor import bootman
179                 print "attempting BM reboot of %s" % hostname
180                 ret = ""
181                 try:
182                         ret = bootman.restore(self, hostname)
183                         err = ""
184                 except:
185                         err = traceback.format_exc()
186                         print err
187
188                 act = ActionRecord(loginbase=self.db.loginbase,
189                                                         hostname=hostname,
190                                                         action='reboot',
191                                                         action_type='bootmanager_restore',
192                                                         error_string=err)
193                 return ret
194
195         def attemptReboot(self, hostname):
196                 print "attempting PCU reboot of %s" % hostname
197                 err = ""
198                 try:
199                         ret = reboot.reboot_str(hostname)
200                 except Exception, e:
201                         err = traceback.format_exc()
202                         ret = str(e)
203
204                 if ret == 0 or ret == "0":
205                         ret = ""
206
207                 act = ActionRecord(loginbase=self.db.loginbase,
208                                                         hostname=hostname,
209                                                         action='reboot',
210                                                         action_type='try_reboot',
211                                                         error_string=err)
212