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.7 2007/02/08 22:43:11 mef Exp $
11 from emailTxt import *
16 import getpass, getopt
19 logger = logging.getLogger("monitor")
20 XMLRPC_SERVER = 'https://www2.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
52 printUsage("not enough arguments; please provide loginbase")
57 printUsage("requires admin privs")
60 slices = api.GetSlices (auth, {'name':"%s_*"%loginbase},['name'])
61 slices = map(lambda x: x['name'],slices)
65 """Returns dict of PCU info of a given node."""
67 global api, anon, auth
68 nodename = argv[0].lower()
70 printUsage("requires admin privs")
73 pcus = api.GetNodes(auth, [nodename], ['pcu_ids'])
75 pcus = map(lambda x: x['pcu_ids'],pcus)[0]
76 nodepcus = api.GetPCUs(auth,pcus)
82 def getSiteNodes(argv):
83 """Returns all site nodes for site id (loginbase)."""
86 printUsage("not enough arguments; please provide loginbase")
91 site_ids = api.GetSites(auth, {'login_base': "%s" % loginbase}, ['node_ids'])
92 if len(site_ids) == 1:
93 node_ids = site_ids[0]['node_ids']
94 nodes = api.GetNodes(auth,node_ids,['hostname'])
95 nodelist = map(lambda x: x['hostname'], nodes)
96 elif len(site_ids) == 0:
97 logger.info("getSiteNodes: can't find site %s" %loginbase)
101 def renewAllSlices (argv):
102 """Sets the expiration date of all slices to given date"""
106 # convert time string using fmt "%B %d %Y" to epoch integer
108 newexp = int(time.mktime(time.strptime(newexp,"%B %d %Y")))
109 except ValueError, e:
110 errormsg = """Expecting date to be in Month Day Year
112 new expiration date provided %s""" % newexp
116 slices = api.GetSlices(auth)
119 exp = int(slice['expires'])
120 olddate = time.asctime(time.localtime(exp))
121 slice_attributes = api.GetSliceAttributes(auth,slice['slice_attribute_ids'])
122 for slice_attribute in slice_attributes:
123 if slice_attribute['name'] == "enabled":
124 print "%s is suspended" % name
127 newdate = time.asctime(time.localtime(newexp))
128 ret = api.SliceRenew(auth,name,newexp)
130 print "failed to renew %s" %name
132 def nodeBootState(argv):
133 """Sets boot state of a node."""
135 global api, anon, auth
137 printUsage("not enough arguments")
146 printUsage("requires admin privs")
149 node = api.GetNodes(auth, [nodename], ['node_id','boot_state'])
153 logger.info("%s boot_state=%s" %(nodename, node['boot_state']))
154 if len(argv) >=2 and not config.debug:
155 logger.info("Setting node %s boot_state=%s" %(nodename, state))
156 node_id = node['node_id']
157 api.UpdateNode(auth, node_id, {'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."""
168 printUsage("not enough arguments")
173 printUsage("requires admin privs")
176 node = api.GetNodes(auth, [nodename], ['node_id'])
179 logger.info("Sending POD to %s" % nodename)
182 api.RebootNode(auth, node['node_id'])
183 except Exception, exc:
184 logger.info("nodePOD: %s" % exc)
186 logger.info("Cant find node %s to send POD." % nodename)
188 def suspendSlices(argv):
189 """Freeze all site slices."""
191 global api, anon, auth
193 printUsage("requires admin privs")
196 if argv[0].find(".") <> -1: siteslices = slices([siteId(argv)])
197 else: siteslices = slices(argv)
199 for slice in siteslices:
200 logger.info("Suspending slice %s" % slice)
203 api.SliceAttributeAdd(auth, slice, "plc_slice_state",
204 {"state" : "suspended"})
205 except Exception, exc:
206 logger.info("suspendSlices: %s" % exc)
209 def enableSlices(argv):
210 """Enable suspended site slices."""
212 global api, anon, auth
214 printUsage("requires admin privs")
217 if argv[0].find(".") <> -1: siteslices = slices([siteId(argv)])
218 else: siteslices = slices(argv)
220 for slice in siteslices:
221 logger.info("unfreezing slice %s" % slice)
222 api.SliceAttributeDelete(auth, slice, "plc_slice_state")
225 def removeSliceCreation(argv):
226 """Removes ability to create slices. Returns previous max_slices"""
228 global api, anon, auth
230 printUsage("requires admin privs")
234 if name.find(".") <> -1:
235 siteid = api.AnonAdmQuerySite (anon, {"node_hostname": name})
236 loginbase = siteId(name)
238 siteid = api.AnonAdmQuerySite (anon, {"site_loginbase": name})
241 numslices = api.AdmGetSites(auth, siteid, ["max_slices"])[0]['max_slices']
243 logger.info("Removing slice creation for site %s" % loginbase)
246 api.AdmUpdateSite(auth, siteid[0], {'max_slices': 0})
248 except Exception, exc:
249 logger.info("removeSliceCreation: %s" % exc)
251 logger.debug("Cant find site for %s. Cannot revoke creation." % loginbase)
253 def enableSliceCreation(argv):
256 global api, anon, auth
258 printUsage("requires admin privs")
262 printUsage("requires maxslice arg")
265 maxslices = int(argv[1])
267 if name.find(".") <> -1:
268 siteid = api.AnonAdmQuerySite (anon, {"node_hostname": name})
269 loginbase = siteId(name)
271 siteid = api.AnonAdmQuerySite (anon, {"site_loginbase": name})
275 logger.info("Enabling slice creation for site %s" % loginbase)
278 api.AdmUpdateSite(auth, siteid[0], {"max_slices" : maxslices})
279 except Exception, exc:
280 logger.info("API: %s" % exc)
282 logger.debug("Cant find site for %s. Cannot enable creation." % loginbase)
287 Usage: %s [-u user] [-p password] [-r role] CMD
290 -u PLC account username
291 -p PLC account password
296 def printUsage(error = None):
299 print "%s %s" %(sys.argv[0],error)
302 for name,function in funclist:
303 print "%20s\t%20s" % (name, function.__doc__)
306 global api, auth, anon
308 anon = {"AuthMethod":"anonymous"}
314 (opts, argv) = getopt.getopt(sys.argv[1:], "u:p:r:h")
319 for (opt, optval) in opts:
333 password = getpass.getpass()
334 except (EOFError, KeyboardInterrupt):
338 auth['Username'] = user
339 auth['AuthMethod'] = "password"
340 auth['AuthString'] = password
343 cmd = functbl.get(argv[0], None)
348 logger.setLevel(logging.DEBUG)
349 ch = logging.StreamHandler()
350 ch.setLevel(logging.DEBUG)
351 formatter = logging.Formatter('logger - %(message)s')
352 ch.setFormatter(formatter)
353 logger.addHandler(ch)
354 result = cmd(argv[1:])
358 funclist = (("nodesDbg",nodesDbg),
362 ("siteNodes", getSiteNodes),
363 ("nodeBootState", nodeBootState),
364 ("nodePOD", nodePOD),
365 ("freezeSlices", suspendSlices),
366 ("unfreezeSlices", enableSlices),
367 ("disableSliceCreation",removeSliceCreation),
368 ("enableSliceCreation", enableSliceCreation),
369 ("renewAllSlices", renewAllSlices))
375 if __name__=="__main__":