4 # Helper functions that minipulate the PLC api.
6 # Faiyaz Ahmed <faiyaza@cs.princeton.edu
8 # $Id: plc.py,v 1.18 2007/08/29 17:26:50 soltesz Exp $
16 from config import config
21 logger = logging.getLogger("monitor")
25 self.auth = {'AuthMethod': "anonymous"}
27 # NOTE: this host is used by default when there are no auth files.
28 XMLRPC_SERVER="https://boot.planet-lab.org/PLCAPI/"
30 # NOTE: by default, use anonymous access, but if auth files are
31 # configured, use them, with their auth definitions.
35 auth.auth = {'Username' : monitorconfig.API_AUTH_USER,
36 'AuthMethod' : 'password',
37 'AuthString' : monitorconfig.API_AUTH_PASSWORD}
38 auth.server = monitorconfig.API_SERVER
42 auth.server = auth.plc
45 auth.server = XMLRPC_SERVER
47 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
50 def __init__(self, auth, url):
53 self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
55 def __getattr__(self, name):
56 method = getattr(self.api, name)
58 raise AssertionError("method does not exist")
60 return lambda *params : method(self.auth, *params)
63 return self.api.__repr__()
66 return xmlrpclib.Server(url, verbose=False, allow_none=True)
69 return PLC(auth.auth, auth.server)
72 Returns list of nodes in dbg as reported by PLC
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))
85 Returns loginbase for given nodename
88 api = xmlrpclib.Server(auth.server, verbose=False)
89 anon = {'AuthMethod': "anonymous"}
90 site_id = api.GetNodes (anon, {"hostname": nodename}, ['site_id'])
92 loginbase = api.GetSites (anon, site_id[0], ["login_base"])
93 return loginbase[0]['login_base']
96 Returns list of slices for a site.
98 def slices(loginbase):
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'])
107 Returns dict of PCU info of a given node.
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]
118 logger.info("%s doesn't have PCU" % nodename)
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)
127 Returns all site nodes for site id (loginbase).
129 def getSiteNodes(loginbase, fields=None):
130 api = xmlrpclib.Server(auth.server, verbose=False)
132 anon = {'AuthMethod': "anonymous"}
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
142 def getPersons(filter=None, fields=None):
143 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
146 persons = api.GetPersons(auth.auth, filter, fields)
147 except Exception, exc:
148 print "getPersons: %s" % exc
149 logger.info("getPersons: %s" % exc)
152 def getSites(filter=None, fields=None):
153 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
155 anon = {'AuthMethod': "anonymous"}
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)
165 def getSiteNodes2(loginbase):
166 api = xmlrpclib.Server(auth.server, verbose=False)
168 anon = {'AuthMethod': "anonymous"}
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)
176 def getNodeNetworks(filter=None):
177 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
178 nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
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' ])
190 Sets boot state of a node.
192 def nodeBootState(nodename, state):
193 api = xmlrpclib.Server(auth.server, verbose=False)
195 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
196 except Exception, exc:
197 logger.info("nodeBootState: %s" % exc)
199 def updateNodeKey(nodename, key):
200 api = xmlrpclib.Server(auth.server, verbose=False)
202 return api.UpdateNode(auth.auth, nodename, {'key': key})
203 except Exception, exc:
204 logger.info("updateNodeKey: %s" % exc)
207 Sends Ping Of Death to node.
209 def nodePOD(nodename):
210 api = xmlrpclib.Server(auth.server, verbose=False)
211 logger.info("Sending POD to %s" % nodename)
214 return api.RebootNode(auth.auth, nodename)
215 except Exception, exc:
216 logger.info("nodePOD: %s" % exc)
219 Freeze all site slices.
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)
227 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
228 except Exception, exc:
229 logger.info("suspendSlices: %s" % exc)
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)
237 slice_list = api.GetSlices(auth.auth, {'name': slice}, None)
238 if len(slice_list) == 0:
240 slice_id = slice_list[0]['slice_id']
241 l_attr = api.GetSliceAttributes(auth.auth, {'slice_id': slice_id}, None)
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
250 #I'm commenting this because this really should be a manual process.
252 #Enable suspended site slices.
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"})
260 def enableSliceCreation(nodename):
261 api = xmlrpclib.Server(auth.server, verbose=False, allow_none=True)
263 loginbase = siteId(nodename)
264 logger.info("Enabling slice creation for site %s" % loginbase)
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)
273 Removes ability to create slices. Returns previous max_slices
275 def removeSliceCreation(nodename):
276 print "removeSliceCreation(%s)" % nodename
277 api = xmlrpclib.Server(auth.server, verbose=False)
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)
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)
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))
300 # api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
301 # except Exception, exc:
302 # logger.info("API: %s" % exc)
304 # logger.debug("Cant find site for %s. Cannot enable creation." % nodename)
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")
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")
326 if __name__=="__main__":