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