convert GetNodeNetworks to GetInterfaces and nodenetwork_ids to interface_ids
[monitor.git] / monitor / wrapper / plc.py
1 #
2 # plc.py
3 #
4 # Helper functions that minipulate the PLC api.
5
6 # Faiyaz Ahmed <faiyaza@cs.princeton.edu
7 #
8 # $Id: plc.py,v 1.18 2007/08/29 17:26:50 soltesz Exp $
9 #
10
11 import xml, xmlrpclib
12 import logging
13 import time
14 import traceback
15 from monitor import database
16
17 try:
18         from monitor import config
19         debug = config.debug
20         XMLRPC_SERVER=config.API_SERVER
21 except:
22         debug = False
23         # NOTE: this host is used by default when there are no auth files.
24         XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
25
26 logger = logging.getLogger("monitor")
27         
28 class Auth:
29         def __init__(self, username=None, password=None, **kwargs):
30                 if 'session' in kwargs:
31                         self.auth= { 'AuthMethod' : 'session',
32                                         'session' : kwargs['session'] }
33                 else:
34                         if username==None and password==None:
35                                 self.auth = {'AuthMethod': "anonymous"}
36                         else:
37                                 self.auth = {'Username' : username,
38                                                         'AuthMethod' : 'password',
39                                                         'AuthString' : password}
40
41
42 # NOTE: by default, use anonymous access, but if auth files are 
43 #       configured, use them, with their auth definitions.
44 auth = Auth()
45 try:
46         from monitor import config
47         auth.auth = {'Username' : config.API_AUTH_USER,
48                      'AuthMethod' : 'password',
49                                  'AuthString' : config.API_AUTH_PASSWORD}
50         auth.server = config.API_SERVER
51 except:
52         try:
53                 import auth
54                 auth.server = auth.plc
55         except:
56                 auth = Auth()
57                 auth.server = XMLRPC_SERVER
58
59 global_error_count = 0
60
61 class PLC:
62         def __init__(self, auth, url):
63                 self.auth = auth
64                 self.url = url
65                 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
66
67         def __getattr__(self, name):
68                 method = getattr(self.api, name)
69                 if method is None:
70                         raise AssertionError("method does not exist")
71
72                 try:
73                         return lambda *params : method(self.auth, *params)
74                 except ProtocolError:
75                         traceback.print_exc()
76                         global_error_count += 1
77                         if global_error_count >= 10:
78                                 print "maximum error count exceeded; exiting..."
79                                 sys.exit(1)
80                         else:
81                                 print "%s errors have occurred" % global_error_count
82                         raise Exception("ProtocolError continuing")
83
84         def __repr__(self):
85                 return self.api.__repr__()
86
87 api = PLC(auth.auth, auth.server)
88
89 class CachedPLC(PLC):
90
91         def _param_to_str(self, name, *params):
92                 fields = len(params)
93                 retstr = ""
94                 retstr += "%s-" % name
95                 for x in params:
96                         retstr += "%s-" % x
97                 return retstr[:-1]
98
99         def __getattr__(self, name):
100                 method = getattr(self.api, name)
101                 if method is None:
102                         raise AssertionError("method does not exist")
103
104                 def run_or_returncached(*params):
105                         cachename = self._param_to_str(name, *params)
106                         #print "cachename is %s" % cachename
107                         if hasattr(config, 'refresh'):
108                                 refresh = config.refresh
109                         else:
110                                 refresh = False
111
112                         if 'Get' in name:
113                                 if not database.cachedRecently(cachename):
114                                         load_old_cache = False
115                                         try:
116                                                 values = method(self.auth, *params)
117                                         except:
118                                                 print "Call %s FAILED: Using old cached data" % cachename
119                                                 load_old_cache = True
120                                                 
121                                         if load_old_cache:
122                                                 values = database.dbLoad(cachename)
123                                         else:
124                                                 database.dbDump(cachename, values)
125                                                 
126                                         return values
127                                 else:
128                                         values = database.dbLoad(cachename)
129                                         return values
130                         else:
131                                 return method(self.auth, *params)
132
133                 return run_or_returncached
134
135
136 def getAPI(url):
137         return xmlrpclib.Server(url, verbose=False, allow_none=True)
138
139 def getNodeAPI(session):
140         nodeauth = Auth(session=session)
141         return PLC(nodeauth.auth, auth.server)
142
143 def getAuthAPI():
144         return PLC(auth.auth, auth.server)
145
146 def getCachedAuthAPI():
147         return CachedPLC(auth.auth, auth.server)
148
149 def getTechEmails(loginbase):
150         """
151                 For the given site, return all user email addresses that have the 'tech' role.
152         """
153         api = getAuthAPI()
154         # get site details.
155         s = api.GetSites(loginbase)[0]
156         # get people at site
157         p = api.GetPersons(s['person_ids'])
158         # pull out those with the right role.
159         emails = [ person['email'] for person in filter(lambda x: 'tech' in x['roles'], p) ]
160         return emails
161
162 def getPIEmails(loginbase):
163         """
164                 For the given site, return all user email addresses that have the 'tech' role.
165         """
166         api = getAuthAPI()
167         # get site details.
168         s = api.GetSites(loginbase)[0]
169         # get people at site
170         p = api.GetPersons(s['person_ids'])
171         # pull out those with the right role.
172         emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], p) ]
173         return emails
174
175 def getSliceUserEmails(loginbase):
176         """
177                 For the given site, return all user email addresses that have the 'tech' role.
178         """
179         api = getAuthAPI()
180         # get site details.
181         s = api.GetSites(loginbase)[0]
182         # get people at site
183         slices = api.GetSlices(s['slice_ids'])
184         people = []
185         for slice in slices:
186                 people += api.GetPersons(slice['person_ids'])
187         # pull out those with the right role.
188         emails = [ person['email'] for person in filter(lambda x: 'pi' in x['roles'], people) ]
189         unique_emails = [ x for x in set(emails) ]
190         return unique_emails
191
192 '''
193 Returns list of nodes in dbg as reported by PLC
194 '''
195 def nodesDbg():
196         dbgNodes = []
197         api = xmlrpclib.Server(auth.server, verbose=False)
198         anon = {'AuthMethod': "anonymous"}
199         for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
200                 dbgNodes.append(node['hostname'])
201         logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
202         return dbgNodes
203
204
205 '''
206 Returns loginbase for given nodename
207 '''
208 def siteId(nodename):
209         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
210         site_id = api.GetNodes (auth.auth, {"hostname": nodename}, ['site_id'])
211         if len(site_id) == 1:
212                 loginbase = api.GetSites (auth.auth, site_id[0], ["login_base"])
213                 return loginbase[0]['login_base']
214         else:
215                 print "Not nodes returned!!!!"
216
217 '''
218 Returns list of slices for a site.
219 '''
220 def slices(loginbase):
221         siteslices = []
222         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
223         sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
224         for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
225                 siteslices.append(slice['name'])
226         return siteslices
227
228 '''
229 Returns dict of PCU info of a given node.
230 '''
231 def getpcu(nodename):
232         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
233         anon = {'AuthMethod': "anonymous"}
234         nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
235         if nodeinfo['pcu_ids']:
236                 print nodeinfo
237                 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
238                 print sitepcu
239                 print nodeinfo["ports"]
240                 sitepcu[nodename] = nodeinfo["ports"][0]
241                 return sitepcu
242         else:
243                 logger.info("%s doesn't have PCU" % nodename)
244                 return False
245
246 def GetPCUs(filter=None, fields=None):
247         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
248         pcu_list = api.GetPCUs(auth.auth, filter, fields)
249         return pcu_list 
250
251 '''
252 Returns all site nodes for site id (loginbase).
253 '''
254 def getSiteNodes(loginbase, fields=None):
255         api = xmlrpclib.Server(auth.server, verbose=False)
256         nodelist = []
257         anon = {'AuthMethod': "anonymous"}
258         try:
259                 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
260                 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
261                         nodelist.append(node['hostname'])
262         except Exception, exc:
263                 logger.info("getSiteNodes:  %s" % exc)
264                 print "getSiteNodes:  %s" % exc
265         return nodelist
266
267
268 def getPersons(filter=None, fields=None):
269         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
270         persons = []
271         try:
272                 persons = api.GetPersons(auth.auth, filter, fields)
273         except Exception, exc:
274                 print "getPersons:  %s" % exc
275                 logger.info("getPersons:  %s" % exc)
276         return persons
277
278 def getSites(filter=None, fields=None):
279         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
280         sites = []
281         anon = {'AuthMethod': "anonymous"}
282         try:
283                 #sites = api.GetSites(anon, filter, fields)
284                 sites = api.GetSites(auth.auth, filter, fields)
285         except Exception, exc:
286                 traceback.print_exc()
287                 print "getSites:  %s" % exc
288                 logger.info("getSites:  %s" % exc)
289         return sites
290
291 def getSiteNodes2(loginbase):
292         api = xmlrpclib.Server(auth.server, verbose=False)
293         nodelist = []
294         anon = {'AuthMethod': "anonymous"}
295         try:
296                 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
297                 nodelist += getNodes({'node_id':nodeids})
298         except Exception, exc:
299                 logger.info("getSiteNodes2:  %s" % exc)
300         return nodelist
301
302 def getNodeNetworks(filter=None):
303         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
304         nodenetworks = api.GetInterfaces(auth.auth, filter, None)
305         return nodenetworks
306
307 def getNodes(filter=None, fields=None):
308         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
309         nodes = api.GetNodes(auth.auth, filter, fields) 
310                         #['boot_state', 'hostname', 
311                         #'site_id', 'date_created', 'node_id', 'version', 'interface_ids',
312                         #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
313         return nodes
314
315 '''
316 Sets boot state of a node.
317 '''
318 def nodeBootState(nodename, state):
319         api = xmlrpclib.Server(auth.server, verbose=False)
320         try:
321                 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
322         except Exception, exc:
323                 logger.info("nodeBootState:  %s" % exc)
324
325 def updateNodeKey(nodename, key):
326         api = xmlrpclib.Server(auth.server, verbose=False)
327         try:
328                 return api.UpdateNode(auth.auth, nodename, {'key': key})
329         except Exception, exc:
330                 logger.info("updateNodeKey:  %s" % exc)
331
332 '''
333 Sends Ping Of Death to node.
334 '''
335 def nodePOD(nodename):
336         api = xmlrpclib.Server(auth.server, verbose=False)
337         logger.info("Sending POD to %s" % nodename)
338         try:
339                 if not debug:
340                         return api.RebootNode(auth.auth, nodename)
341         except Exception, exc:
342                         logger.info("nodePOD:  %s" % exc)
343
344 '''
345 Freeze all site slices.
346 '''
347 def suspendSiteSlices(loginbase):
348         api = xmlrpclib.Server(auth.server, verbose=False)
349         for slice in slices(loginbase):
350                 logger.info("Suspending slice %s" % slice)
351                 try:
352                         if not debug:
353                                 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
354                 except Exception, exc:
355                         logger.info("suspendSlices:  %s" % exc)
356
357 '''
358 Freeze all site slices.
359 '''
360 def suspendSlices(nodename):
361         api = xmlrpclib.Server(auth.server, verbose=False)
362         for slice in slices(siteId(nodename)):
363                 logger.info("Suspending slice %s" % slice)
364                 try:
365                         if not debug:
366                                 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
367                 except Exception, exc:
368                         logger.info("suspendSlices:  %s" % exc)
369
370 def enableSiteSlices(loginbase):
371         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
372         for slice in slices(loginbase):
373                 logger.info("Enabling slices %s" % slice)
374                 try:
375                         if not debug:
376                                 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
377                                 if len(slice_list) == 0:
378                                         return
379                                 slice_id = slice_list[0]['slice_id']
380                                 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
381                                 for attr in l_attr:
382                                         if "enabled" == attr['name'] and attr['value'] == "0":
383                                                 logger.info("Deleted enable=0 attribute from slice %s" % slice)
384                                                 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
385                 except Exception, exc:
386                         logger.info("enableSiteSlices: %s" % exc)
387                         print "exception: %s" % exc
388
389 def enableSlices(nodename):
390         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
391         for slice in slices(siteId(nodename)):
392                 logger.info("Enabling slices %s" % slice)
393                 try:
394                         if not debug:
395                                 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
396                                 if len(slice_list) == 0:
397                                         return
398                                 slice_id = slice_list[0]['slice_id']
399                                 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
400                                 for attr in l_attr:
401                                         if "enabled" == attr['name'] and attr['value'] == "0":
402                                                 logger.info("Deleted enable=0 attribute from slice %s" % slice)
403                                                 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
404                 except Exception, exc:
405                         logger.info("enableSlices: %s" % exc)
406                         print "exception: %s" % exc
407
408 #I'm commenting this because this really should be a manual process.  
409 #'''
410 #Enable suspended site slices.
411 #'''
412 #def enableSlices(nodename, slicelist):
413 #       api = xmlrpclib.Server(auth.server, verbose=False)
414 #       for slice in  slices(siteId(nodename)):
415 #               logger.info("Suspending slice %s" % slice)
416 #               api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
417 #
418 def enableSiteSliceCreation(loginbase):
419         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
420         try:
421                 logger.info("Enabling slice creation for site %s" % loginbase)
422                 if not debug:
423                         logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
424                         api.UpdateSite(auth.auth, loginbase, {'enabled': True})
425         except Exception, exc:
426                 print "ERROR: enableSiteSliceCreation:  %s" % exc
427                 logger.info("ERROR: enableSiteSliceCreation:  %s" % exc)
428
429 def enableSliceCreation(nodename):
430         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
431         try:
432                 loginbase = siteId(nodename)
433                 logger.info("Enabling slice creation for site %s" % loginbase)
434                 if not debug:
435                         logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
436                         api.UpdateSite(auth.auth, loginbase, {'enabled': True})
437         except Exception, exc:
438                 print "ERROR: enableSliceCreation:  %s" % exc
439                 logger.info("ERROR: enableSliceCreation:  %s" % exc)
440
441 '''
442 Removes site's ability to create slices. Returns previous max_slices
443 '''
444 def removeSiteSliceCreation(sitename):
445         print "removeSiteSliceCreation(%s)" % sitename
446         api = xmlrpclib.Server(auth.server, verbose=False)
447         try:
448                 logger.info("Removing slice creation for site %s" % sitename)
449                 if not debug:
450                         api.UpdateSite(auth.auth, sitename, {'enabled': False})
451         except Exception, exc:
452                 logger.info("removeSiteSliceCreation:  %s" % exc)
453
454 '''
455 Removes ability to create slices. Returns previous max_slices
456 '''
457 def removeSliceCreation(nodename):
458         print "removeSliceCreation(%s)" % nodename
459         api = xmlrpclib.Server(auth.server, verbose=False)
460         try:
461                 loginbase = siteId(nodename)
462                 #numslices = api.GetSites(auth.auth, {"login_base": loginbase}, 
463                 #               ["max_slices"])[0]['max_slices']
464                 logger.info("Removing slice creation for site %s" % loginbase)
465                 if not debug:
466                         #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
467                         api.UpdateSite(auth.auth, loginbase, {'enabled': False})
468         except Exception, exc:
469                 logger.info("removeSliceCreation:  %s" % exc)
470
471 '''
472 QED
473 '''
474 #def enableSliceCreation(nodename, maxslices):
475 #       api = xmlrpclib.Server(auth.server, verbose=False)
476 #       anon = {'AuthMethod': "anonymous"}
477 #       siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
478 #       if len(siteid) == 1:
479 #               logger.info("Enabling slice creation for site %s" % siteId(nodename))
480 #               try:
481 #                       if not debug:
482 #                               api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
483 #               except Exception, exc:
484 #                       logger.info("API:  %s" % exc)
485 #       else:
486 #               logger.debug("Cant find site for %s.  Cannot enable creation." % nodename)
487
488 def main():
489         logger.setLevel(logging.DEBUG)
490         ch = logging.StreamHandler()
491         ch.setLevel(logging.DEBUG)
492         formatter = logging.Formatter('logger - %(message)s')
493         ch.setFormatter(formatter)
494         logger.addHandler(ch)
495         #print getpcu("kupl2.ittc.ku.edu")
496         #print getpcu("planetlab1.cse.msu.edu")
497         #print getpcu("alice.cs.princeton.edu")
498         #print nodesDbg()
499         #nodeBootState("alice.cs.princeton.edu", "boot")
500         #freezeSite("alice.cs.princeton.edu")
501         print removeSliceCreation("alice.cs.princeton.edu")
502         #enableSliceCreation("alice.cs.princeton.edu", 1024)
503         #print getSiteNodes("princeton")
504         #print siteId("alice.cs.princeton.edu")
505         #print nodePOD("alice.cs.princeton.edu")
506         #print slices("princeton")
507
508 if __name__=="__main__":
509         main()