3 # Helper functions that minipulate the PLC api.
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
6 # Copyright (C) 2006, 2007 The Trustees of Princeton University
8 # $Id: plc.py,v 1.5 2007/02/08 19:43:09 mef Exp $
11 from emailTxt import *
16 import getpass, getopt
19 logger = logging.getLogger("monitor")
20 XMLRPC_SERVER = 'https://www.planet-lab.org/PLCAPI/'
21 api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none = True)
25 """Returns list of nodes in dbg as reported by PLC"""
29 allnodes = api.GetNodes(auth, None, ['hostname','boot_state'])
31 if node['boot_state'] == 'dbg': dbgNodes.append(node['hostname'])
32 logger.info("%d nodes in debug according to PLC." %len(dbgNodes))
37 """Returns loginbase for given nodename"""
41 site_ids = api.GetNodes(auth, [nodename], ['site_id'])
42 if len(site_ids) == 1:
43 site_id = [site_ids[0]['site_id']]
44 loginbase = api.GetSites (auth, site_id, ["login_base"])
45 return loginbase[0]['login_base']
48 """Returns list of slices for a site."""
50 global api, anon, auth
53 printUsage("requires admin privs")
55 return api.SliceListNames (auth, loginbase)
58 """Returns dict of PCU info of a given node."""
60 global api, anon, auth
61 nodename = argv[0].lower()
63 printUsage("requires admin privs")
67 site_id = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
70 sitepcus = api.AdmGetSitePowerControlUnits(auth, site_id[0])
71 for sitepcu in sitepcus:
72 sitepcuports = api.AdmGetPowerControlUnitNodes(auth, sitepcu['pcu_id'])
73 for sitepcuport in sitepcuports:
74 node_id = [sitepcuport['node_id']]
75 node = api.AnonAdmGetNodes(anon,node_id,["hostname"])
79 hostname = node['hostname'].lower()
80 if hostname == nodename:
81 sitepcu['port_number']=sitepcuport['port_number']
84 except Exception, err:
85 logger.debug("getpcu: %s" % err)
88 logger.info("Cant find site for %s" % nodename)
91 def getSiteNodes(argv):
92 """Returns all site nodes for site id (loginbase)."""
93 global api, anon, auth
97 site_id = api.AnonAdmQuerySite(anon, {'site_loginbase': "%s" % loginbase})
98 node_ids = api.AnonAdmGetSiteNodes(anon, site_id)
99 for node in api.AnonAdmGetNodes(anon, node_ids["%s" % site_id[0]], ["hostname"]):
100 nodelist.append(node['hostname'])
101 except Exception, exc:
102 logger.info("getSiteNodes: %s" % exc)
106 def renewAllSlices (argv):
107 """Sets the expiration date of all slices to given date"""
108 global api, anon, auth
111 # convert time string using fmt "%B %d %Y" to epoch integer
113 newexp = int(time.mktime(time.strptime(newexp,"%B %d %Y")))
114 except ValueError, e:
115 errormsg = """Expecting date to be in Month Day Year
117 new expiration date provided %s""" % newexp
121 slices = api.GetSlices(auth)
124 exp = int(slice['expires'])
125 olddate = time.asctime(time.localtime(exp))
126 slice_attributes = api.GetSliceAttributes(auth,slice['slice_attribute_ids'])
127 for slice_attribute in slice_attributes:
128 if slice_attribute['name'] == "enabled":
129 print "%s is suspended" % name
132 newdate = time.asctime(time.localtime(newexp))
133 ret = api.SliceRenew(auth,name,newexp)
135 print "failed to renew %s" %name
137 def nodeBootState(argv):
138 """Sets boot state of a node."""
140 global api, anon, auth
142 printUsage("not enough arguments")
149 printUsage("requires admin privs")
152 node_id = api.AnonAdmQueryNode(anon, {'node_hostname' : nodename})
153 if len(node_id) == 1:
154 logger.info("Setting node %s to %s" %(nodename, state))
157 api.AdmUpdateNode(auth, node_id[0], {'boot_state': state})
158 except Exception, exc:
159 logger.info("nodeBootState: %s" % exc)
161 logger.info("Cant find node %s to toggle boot state" % nodename)
164 """Sends Ping Of Death to node."""
166 global api, anon, auth
169 printUsage("requires admin privs")
172 node_id = api.AnonAdmQueryNode(anon, {'node_hostname' : nodename})
173 if len(node_id) == 1:
174 logger.info("Sending POD to %s" % nodename)
177 api.AdmRebootNode(auth, node_id[0])
178 except Exception, exc:
179 logger.info("nodePOD: %s" % exc)
181 logger.info("Cant find node %s to send POD." % nodename)
183 def suspendSlices(argv):
184 """Freeze all site slices."""
186 global api, anon, auth
188 printUsage("requires admin privs")
191 if argv[0].find(".") <> -1: siteslices = slices([siteId(argv)])
192 else: siteslices = slices(argv)
194 for slice in siteslices:
195 logger.info("Suspending slice %s" % slice)
198 api.SliceAttributeAdd(auth, slice, "plc_slice_state",
199 {"state" : "suspended"})
200 except Exception, exc:
201 logger.info("suspendSlices: %s" % exc)
204 def enableSlices(argv):
205 """Enable suspended site slices."""
207 global api, anon, auth
209 printUsage("requires admin privs")
212 if argv[0].find(".") <> -1: siteslices = slices([siteId(argv)])
213 else: siteslices = slices(argv)
215 for slice in siteslices:
216 logger.info("unfreezing slice %s" % slice)
217 api.SliceAttributeDelete(auth, slice, "plc_slice_state")
220 def removeSliceCreation(argv):
221 """Removes ability to create slices. Returns previous max_slices"""
223 global api, anon, auth
225 printUsage("requires admin privs")
229 if name.find(".") <> -1:
230 siteid = api.AnonAdmQuerySite (anon, {"node_hostname": name})
231 loginbase = siteId(name)
233 siteid = api.AnonAdmQuerySite (anon, {"site_loginbase": name})
236 numslices = api.AdmGetSites(auth, siteid, ["max_slices"])[0]['max_slices']
238 logger.info("Removing slice creation for site %s" % loginbase)
241 api.AdmUpdateSite(auth, siteid[0], {'max_slices': 0})
243 except Exception, exc:
244 logger.info("removeSliceCreation: %s" % exc)
246 logger.debug("Cant find site for %s. Cannot revoke creation." % loginbase)
248 def enableSliceCreation(argv):
251 global api, anon, auth
253 printUsage("requires admin privs")
257 printUsage("requires maxslice arg")
260 maxslices = int(argv[1])
262 if name.find(".") <> -1:
263 siteid = api.AnonAdmQuerySite (anon, {"node_hostname": name})
264 loginbase = siteId(name)
266 siteid = api.AnonAdmQuerySite (anon, {"site_loginbase": name})
270 logger.info("Enabling slice creation for site %s" % loginbase)
273 api.AdmUpdateSite(auth, siteid[0], {"max_slices" : maxslices})
274 except Exception, exc:
275 logger.info("API: %s" % exc)
277 logger.debug("Cant find site for %s. Cannot enable creation." % loginbase)
282 Usage: %s [-u user] [-p password] [-r role] CMD
285 -u PLC account username
286 -p PLC account password
291 def printUsage(error = None):
294 print "%s %s" %(sys.argv[0],error)
297 for name,function in funclist:
298 print "%20s\t%20s" % (name, function.__doc__)
301 global api, auth, anon
303 anon = {"AuthMethod":"anonymous"}
309 (opts, argv) = getopt.getopt(sys.argv[1:], "u:p:r:h")
314 for (opt, optval) in opts:
328 password = getpass.getpass()
329 except (EOFError, KeyboardInterrupt):
333 auth['Username'] = user
334 auth['AuthMethod'] = "password"
335 auth['AuthString'] = password
338 cmd = functbl.get(argv[0], None)
343 logger.setLevel(logging.DEBUG)
344 ch = logging.StreamHandler()
345 ch.setLevel(logging.DEBUG)
346 formatter = logging.Formatter('logger - %(message)s')
347 ch.setFormatter(formatter)
348 logger.addHandler(ch)
349 result = cmd(argv[1:])
353 funclist = (("nodesDbg",nodesDbg),
357 ("siteNodes", getSiteNodes),
358 ("nodeBootState", nodeBootState),
359 ("nodePOD", nodePOD),
360 ("freezeSlices", suspendSlices),
361 ("unfreezeSlices", enableSlices),
362 ("disableSliceCreation",removeSliceCreation),
363 ("enableSliceCreation", enableSliceCreation),
364 ("renewAllSlices", renewAllSlices))
370 if __name__=="__main__":