use new monitorconfig.py format
[monitor.git] / 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 try:
16         from config import config
17         config = config()
18         debug = config.debug
19 except:
20         debug = False
21 logger = logging.getLogger("monitor")
22         
23 class Auth:
24         def __init__(self):
25                 self.auth = {'AuthMethod': "anonymous"}
26
27 # NOTE: this host is used by default when there are no auth files.
28 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
29
30 # NOTE: by default, use anonymous access, but if auth files are 
31 #       configured, use them, with their auth definitions.
32 auth = Auth()
33 try:
34         import monitorconfig
35         auth.auth = {'Username' : monitorconfig.API_AUTH_USER,
36                      'AuthMethod' : 'password',
37                                  'AuthString' : monitorconfig.API_AUTH_PASSWORD}
38         auth.server = monitorconfig.API_SERVER
39 except:
40         try:
41                 import auth
42                 auth.server = auth.plc
43         except:
44                 auth = Auth()
45                 auth.server = XMLRPC_SERVER
46
47 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
48
49 class PLC:
50         def __init__(self, auth, url):
51                 self.auth = auth
52                 self.url = url
53                 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
54
55         def __getattr__(self, name):
56                 method = getattr(self.api, name)
57                 if method is None:
58                         raise AssertionError("method does not exist")
59
60                 return lambda *params : method(self.auth, *params)
61
62         def __repr__(self):
63                 return self.api.__repr__()
64
65 def getAPI(url):
66         return xmlrpclib.Server(url, verbose=False, allow_none=True)
67
68 def getAuthAPI():
69         return PLC(auth.auth, auth.server)
70
71 '''
72 Returns list of nodes in dbg as reported by PLC
73 '''
74 def nodesDbg():
75         dbgNodes = []
76         api = xmlrpclib.Server(auth.server, verbose=False)
77         anon = {'AuthMethod': "anonymous"}
78         for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
79                 dbgNodes.append(node['hostname'])
80         logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
81         return dbgNodes
82
83
84 '''
85 Returns loginbase for given nodename
86 '''
87 def siteId(nodename):
88         api = xmlrpclib.Server(auth.server, verbose=False)
89         anon = {'AuthMethod': "anonymous"}
90         site_id = api.GetNodes (anon, {"hostname": nodename}, ['site_id'])
91         if len(site_id) == 1:
92                 loginbase = api.GetSites (anon, site_id[0], ["login_base"])
93                 return loginbase[0]['login_base']
94
95 '''
96 Returns list of slices for a site.
97 '''
98 def slices(loginbase):
99         siteslices = []
100         api = xmlrpclib.Server(auth.server, verbose=False)
101         sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
102         for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
103                 siteslices.append(slice['name'])
104         return siteslices
105
106 '''
107 Returns dict of PCU info of a given node.
108 '''
109 def getpcu(nodename):
110         api = xmlrpclib.Server(auth.server, verbose=False)
111         anon = {'AuthMethod': "anonymous"}
112         nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
113         if nodeinfo['pcu_ids']:
114                 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
115                 sitepcu[nodename] = nodeinfo["ports"][0]
116                 return sitepcu
117         else:
118                 logger.info("%s doesn't have PCU" % nodename)
119                 return False
120
121 def GetPCUs(filter=None, fields=None):
122         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
123         pcu_list = api.GetPCUs(auth.auth, filter, fields)
124         return pcu_list 
125
126 '''
127 Returns all site nodes for site id (loginbase).
128 '''
129 def getSiteNodes(loginbase, fields=None):
130         api = xmlrpclib.Server(auth.server, verbose=False)
131         nodelist = []
132         anon = {'AuthMethod': "anonymous"}
133         try:
134                 nodeids = api.GetSites(anon, {"login_base": loginbase}, fields)[0]['node_ids']
135                 for node in api.GetNodes(anon, {"node_id": nodeids}, ['hostname']):
136                         nodelist.append(node['hostname'])
137         except Exception, exc:
138                 logger.info("getSiteNodes:  %s" % exc)
139                 print "getSiteNodes:  %s" % exc
140         return nodelist
141
142 def getPersons(filter=None, fields=None):
143         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
144         persons = []
145         try:
146                 persons = api.GetPersons(auth.auth, filter, fields)
147         except Exception, exc:
148                 print "getPersons:  %s" % exc
149                 logger.info("getPersons:  %s" % exc)
150         return persons
151
152 def getSites(filter=None, fields=None):
153         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
154         sites = []
155         anon = {'AuthMethod': "anonymous"}
156         try:
157                 #sites = api.GetSites(anon, filter, fields)
158                 sites = api.GetSites(auth.auth, filter, fields)
159         except Exception, exc:
160                 traceback.print_exc()
161                 print "getSites:  %s" % exc
162                 logger.info("getSites:  %s" % exc)
163         return sites
164
165 def getSiteNodes2(loginbase):
166         api = xmlrpclib.Server(auth.server, verbose=False)
167         nodelist = []
168         anon = {'AuthMethod': "anonymous"}
169         try:
170                 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
171                 nodelist += getNodes({'node_id':nodeids})
172         except Exception, exc:
173                 logger.info("getSiteNodes2:  %s" % exc)
174         return nodelist
175
176 def getNodeNetworks(filter=None):
177         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
178         nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
179         return nodenetworks
180
181 def getNodes(filter=None, fields=None):
182         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
183         nodes = api.GetNodes(auth.auth, filter, fields) 
184                         #['boot_state', 'hostname', 
185                         #'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
186                         #'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
187         return nodes
188
189 '''
190 Sets boot state of a node.
191 '''
192 def nodeBootState(nodename, state):
193         api = xmlrpclib.Server(auth.server, verbose=False)
194         try:
195                 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
196         except Exception, exc:
197                 logger.info("nodeBootState:  %s" % exc)
198
199 def updateNodeKey(nodename, key):
200         api = xmlrpclib.Server(auth.server, verbose=False)
201         try:
202                 return api.UpdateNode(auth.auth, nodename, {'key': key})
203         except Exception, exc:
204                 logger.info("updateNodeKey:  %s" % exc)
205
206 '''
207 Sends Ping Of Death to node.
208 '''
209 def nodePOD(nodename):
210         api = xmlrpclib.Server(auth.server, verbose=False)
211         logger.info("Sending POD to %s" % nodename)
212         try:
213                 if not debug:
214                         return api.RebootNode(auth.auth, nodename)
215         except Exception, exc:
216                         logger.info("nodePOD:  %s" % exc)
217
218 '''
219 Freeze all site slices.
220 '''
221 def suspendSlices(nodename):
222         api = xmlrpclib.Server(auth.server, verbose=False)
223         for slice in slices(siteId(nodename)):
224                 logger.info("Suspending slice %s" % slice)
225                 try:
226                         if not debug:
227                                 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
228                 except Exception, exc:
229                         logger.info("suspendSlices:  %s" % exc)
230
231 def enableSlices(nodename):
232         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
233         for slice in slices(siteId(nodename)):
234                 logger.info("Enabling slices %s" % slice)
235                 try:
236                         if not debug:
237                                 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
238                                 if len(slice_list) == 0:
239                                         return
240                                 slice_id = slice_list[0]['slice_id']
241                                 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
242                                 for attr in l_attr:
243                                         if "enabled" == attr['name'] and attr['value'] == "0":
244                                                 logger.info("Deleted enable=0 attribute from slice %s" % slice)
245                                                 api.DeleteSliceAttribute(auth.auth, attr['slice_attribute_id'])
246                 except Exception, exc:
247                         logger.info("enableSlices: %s" % exc)
248                         print "exception: %s" % exc
249
250 #I'm commenting this because this really should be a manual process.  
251 #'''
252 #Enable suspended site slices.
253 #'''
254 #def enableSlices(nodename, slicelist):
255 #       api = xmlrpclib.Server(auth.server, verbose=False)
256 #       for slice in  slices(siteId(nodename)):
257 #               logger.info("Suspending slice %s" % slice)
258 #               api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
259 #
260 def enableSliceCreation(nodename):
261         api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
262         try:
263                 loginbase = siteId(nodename)
264                 logger.info("Enabling slice creation for site %s" % loginbase)
265                 if not debug:
266                         logger.info("\tcalling UpdateSite(%s, enabled=True)" % loginbase)
267                         api.UpdateSite(auth.auth, loginbase, {'enabled': True})
268         except Exception, exc:
269                 print "ERROR: enableSliceCreation:  %s" % exc
270                 logger.info("ERROR: enableSliceCreation:  %s" % exc)
271
272 '''
273 Removes ability to create slices. Returns previous max_slices
274 '''
275 def removeSliceCreation(nodename):
276         print "removeSliceCreation(%s)" % nodename
277         api = xmlrpclib.Server(auth.server, verbose=False)
278         try:
279                 loginbase = siteId(nodename)
280                 #numslices = api.GetSites(auth.auth, {"login_base": loginbase}, 
281                 #               ["max_slices"])[0]['max_slices']
282                 logger.info("Removing slice creation for site %s" % loginbase)
283                 if not debug:
284                         #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
285                         api.UpdateSite(auth.auth, loginbase, {'enabled': False})
286         except Exception, exc:
287                 logger.info("removeSliceCreation:  %s" % exc)
288
289 '''
290 QED
291 '''
292 #def enableSliceCreation(nodename, maxslices):
293 #       api = xmlrpclib.Server(auth.server, verbose=False)
294 #       anon = {'AuthMethod': "anonymous"}
295 #       siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
296 #       if len(siteid) == 1:
297 #               logger.info("Enabling slice creation for site %s" % siteId(nodename))
298 #               try:
299 #                       if not debug:
300 #                               api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
301 #               except Exception, exc:
302 #                       logger.info("API:  %s" % exc)
303 #       else:
304 #               logger.debug("Cant find site for %s.  Cannot enable creation." % nodename)
305
306 def main():
307         logger.setLevel(logging.DEBUG)
308         ch = logging.StreamHandler()
309         ch.setLevel(logging.DEBUG)
310         formatter = logging.Formatter('logger - %(message)s')
311         ch.setFormatter(formatter)
312         logger.addHandler(ch)
313         #print getpcu("kupl2.ittc.ku.edu")
314         #print getpcu("planetlab1.cse.msu.edu")
315         #print getpcu("alice.cs.princeton.edu")
316         #print nodesDbg()
317         #nodeBootState("alice.cs.princeton.edu", "boot")
318         #freezeSite("alice.cs.princeton.edu")
319         print removeSliceCreation("alice.cs.princeton.edu")
320         #enableSliceCreation("alice.cs.princeton.edu", 1024)
321         #print getSiteNodes("princeton")
322         #print siteId("alice.cs.princeton.edu")
323         #print nodePOD("alice.cs.princeton.edu")
324         #print slices("princeton")
325
326 if __name__=="__main__":
327         main()