added comonquery command-line tool.
[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, 'penalty_level' : self.db.penalty_level}
115                 args.update(kwargs)
116
117                 hostname = None
118                 if 'hostname' in args:
119                         hostname = args['hostname']
120
121                 if hasattr(mailtxt, type):
122
123                         message = getattr(mailtxt, type)
124                         viart = True
125                         if 'viart' in kwargs:
126                                 viart = kwargs['viart']
127
128                         if viart:
129                                 self.getTicketStatus()          # get current message status
130
131                         m = Message(message[0] % args, message[1] % args, viart, self.db.message_id)
132
133                         contacts = self.getContacts()
134                         contacts = [config.cc_email]    # TODO: remove after testing...
135
136                         print "sending message: %s to site %s for host %s" % (type, self.db.loginbase, hostname)
137
138                         ret = m.send(contacts)
139                         if viart:
140                                 self.db.message_id = ret
141                                 # reset to previous status, since a new subject 'opens' RT tickets.
142                                 self.setTicketStatus(self.db.message_status) 
143
144                                 # NOTE: only make a record of it if it's in RT.
145                                 act = ActionRecord(loginbase=self.db.loginbase, hostname=hostname, action='notice', 
146                                                                 action_type=type, message_id=self.db.message_id)
147
148                 else:
149                         print "+-- WARNING! ------------------------------"
150                         print "| No such message name in emailTxt.mailtxt: %s" % type
151                         print "+------------------------------------------"
152
153                 return
154
155         def closeTicket(self):
156                 # TODO: close the rt ticket before overwriting the message_id
157                 mailer.closeTicketViaRT(self.db.message_id, "Ticket Closed by Monitor")
158                 act = ActionRecord(loginbase=self.db.loginbase, action='notice', 
159                                                         action_type='close_ticket', message_id=self.db.message_id)
160                 self.db.message_id = 0
161                 self.db.message_status = "new"
162
163         def runBootManager(self, hostname):
164                 from monitor import bootman
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