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