+ new XMLRPC_SERVER name to boot.planet-lab.org
[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.15 2007/06/29 12:42:22 soltesz Exp $
9 #
10
11 from emailTxt import *
12 import xml, xmlrpclib
13 import logging
14 import auth
15 import time
16 from config import config,XMLRPC_SERVER
17
18 logger = logging.getLogger("monitor")
19
20 #XMLRPC_SERVER = config.XMLRPC_SERVER
21
22 config = config()
23
24 '''
25 Returns list of nodes in dbg as reported by PLC
26 '''
27 def nodesDbg():
28         dbgNodes = []
29         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
30         anon = {'AuthMethod': "anonymous"}
31         for node in api.GetNodes(anon, {"boot_state":"dbg"},["hostname"]):
32                 dbgNodes.append(node['hostname'])
33         logger.info("%s nodes in debug according to PLC." %len(dbgNodes))
34         return dbgNodes
35
36
37 '''
38 Returns loginbase for given nodename
39 '''
40 def siteId(nodename):
41         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
42         anon = {'AuthMethod': "anonymous"}
43         site_id = api.GetNodes (anon, {"hostname": nodename}, ['site_id'])
44         if len(site_id) == 1:
45                 loginbase = api.GetSites (anon, site_id[0], ["login_base"])
46                 return loginbase[0]['login_base']
47
48 '''
49 Returns list of slices for a site.
50 '''
51 def slices(loginbase):
52         siteslices = []
53         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
54         sliceids = api.GetSites (auth.auth, {"login_base" : loginbase}, ["slice_ids"])[0]['slice_ids']
55         for slice in api.GetSlices(auth.auth, {"slice_id" : sliceids}, ["name"]):
56                 siteslices.append(slice['name'])
57         return siteslices
58
59 '''
60 Returns dict of PCU info of a given node.
61 '''
62 def getpcu(nodename):
63         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
64         anon = {'AuthMethod': "anonymous"}
65         nodeinfo = api.GetNodes(auth.auth, {"hostname": nodename}, ["pcu_ids", "ports"])[0]
66         if nodeinfo['pcu_ids']:
67                 sitepcu = api.GetPCUs(auth.auth, nodeinfo['pcu_ids'])[0]
68                 sitepcu[nodename] = nodeinfo["ports"][0]
69                 return sitepcu
70         else:
71                 logger.info("%s doesn't have PCU" % nodename)
72                 return False
73
74 '''
75 Returns all site nodes for site id (loginbase).
76 '''
77 def getSiteNodes(loginbase):
78         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
79         nodelist = []
80         anon = {'AuthMethod': "anonymous"}
81         try:
82                 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
83                 for node in api.GetNodes(anon, {"node_id": nodeids}):
84                         nodelist.append(node['hostname'])
85         except Exception, exc:
86                 logger.info("getSiteNodes:  %s" % exc)
87         return nodelist
88
89 def getSites(filter=None):
90         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
91         sites = []
92         anon = {'AuthMethod': "anonymous"}
93         try:
94                 sites = api.GetSites(anon, filter, None)
95         except Exception, exc:
96                 print "getSiteNodes2:  %s" % exc
97                 logger.info("getSiteNodes2:  %s" % exc)
98         return sites
99
100 def getSiteNodes2(loginbase):
101         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
102         nodelist = []
103         anon = {'AuthMethod': "anonymous"}
104         try:
105                 nodeids = api.GetSites(anon, {"login_base": loginbase})[0]['node_ids']
106                 nodelist += getNodes({'node_id':nodeids})
107         except Exception, exc:
108                 logger.info("getSiteNodes2:  %s" % exc)
109         return nodelist
110
111 def getNodeNetworks(filter=None):
112         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
113         nodenetworks = api.GetNodeNetworks(auth.auth, filter, None)
114         return nodenetworks
115
116 def getNodes(filter=None):
117         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False, allow_none=True)
118         nodes = api.GetNodes(auth.auth, filter, ['boot_state', 'hostname', 
119                         'site_id', 'date_created', 'node_id', 'version', 'nodenetwork_ids',
120                         'last_updated', 'peer_node_id', 'ssh_rsa_key' ])
121         return nodes
122
123 '''
124 Sets boot state of a node.
125 '''
126 def nodeBootState(nodename, state):
127         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
128         try:
129                 return api.UpdateNode(auth.auth, nodename, {'boot_state': state})
130         except Exception, exc:
131                 logger.info("nodeBootState:  %s" % exc)
132
133 '''
134 Sends Ping Of Death to node.
135 '''
136 def nodePOD(nodename):
137         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
138         logger.info("Sending POD to %s" % nodename)
139         try:
140                 if not config.debug:
141                         return api.RebootNode(auth.auth, nodename)
142         except Exception, exc:
143                         logger.info("nodePOD:  %s" % exc)
144
145 '''
146 Freeze all site slices.
147 '''
148 def suspendSlices(nodename):
149         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
150         for slice in slices(siteId(nodename)):
151                 logger.info("Suspending slice %s" % slice)
152                 try:
153                         if not config.debug:
154                                 api.AddSliceAttribute(auth.auth, slice, "enabled", "0")
155                 except Exception, exc:
156                         logger.info("suspendSlices:  %s" % exc)
157
158
159 #I'm commenting this because this really should be a manual process.  
160 #'''
161 #Enable suspended site slices.
162 #'''
163 #def enableSlices(nodename, slicelist):
164 #       api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
165 #       for slice in  slices(siteId(nodename)):
166 #               logger.info("Suspending slice %s" % slice)
167 #               api.SliceAttributeAdd(auth.auth, slice, "plc_slice_state", {"state" : "suspended"})
168 #
169
170 '''
171 Removes ability to create slices. Returns previous max_slices
172 '''
173 def removeSliceCreation(nodename):
174         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
175         try:
176                 loginbase = siteId(nodename)
177                 #numslices = api.GetSites(auth.auth, {"login_base": loginbase}, 
178                 #               ["max_slices"])[0]['max_slices']
179                 logger.info("Removing slice creation for site %s" % loginbase)
180                 if not config.debug:
181                         #api.UpdateSite(auth.auth, loginbase, {'max_slices': 0})
182                         api.UpdateSite(auth.auth, loginbase, {'enabled': False})
183         except Exception, exc:
184                 logger.info("removeSliceCreation:  %s" % exc)
185
186 '''
187 QED
188 '''
189 def enableSliceCreation(nodename, maxslices):
190         api = xmlrpclib.Server(XMLRPC_SERVER, verbose=False)
191         anon = {'AuthMethod': "anonymous"}
192         siteid = api.AnonAdmQuerySite (anon, {"node_hostname": nodename})
193         if len(siteid) == 1:
194                 logger.info("Enabling slice creation for site %s" % siteId(nodename))
195                 try:
196                         if not config.debug:
197                                 api.AdmUpdateSite(auth.auth, siteid[0], {"max_slices" : maxslices})
198                 except Exception, exc:
199                         logger.info("API:  %s" % exc)
200         else:
201                 logger.debug("Cant find site for %s.  Cannot enable creation." % nodename)
202
203 def main():
204         logger.setLevel(logging.DEBUG)
205         ch = logging.StreamHandler()
206         ch.setLevel(logging.DEBUG)
207         formatter = logging.Formatter('logger - %(message)s')
208         ch.setFormatter(formatter)
209         logger.addHandler(ch)
210         #print getpcu("kupl2.ittc.ku.edu")
211         #print getpcu("planetlab1.cse.msu.edu")
212         #print getpcu("alice.cs.princeton.edu")
213         #print nodesDbg()
214         #nodeBootState("alice.cs.princeton.edu", "boot")
215         #freezeSite("alice.cs.princeton.edu")
216         print removeSliceCreation("alice.cs.princeton.edu")
217         #enableSliceCreation("alice.cs.princeton.edu", 1024)
218         #print getSiteNodes("princeton")
219         #print siteId("alice.cs.princeton.edu")
220         #print nodePOD("alice.cs.princeton.edu")
221         #print slices("princeton")
222
223 if __name__=="__main__":
224         import reboot
225         main()