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