updated
[sfa.git] / geni / aggregate.py
1 import os
2 import sys
3 import datetime
4 import time
5 import xmlrpclib
6
7 from types import StringTypes, ListType
8 from geni.util.geniserver import GeniServer
9 from geni.util.geniclient import *
10 from geni.util.cert import Keypair, Certificate
11 from geni.util.credential import Credential
12 from geni.util.trustedroot import TrustedRootList
13 from geni.util.excep import *
14 from geni.util.misc import *
15 from geni.util.config import Config
16 from geni.util.rspec import Rspec
17 from geni.util.specdict import *
18 from geni.util.storage import SimpleStorage
19
20 class Aggregate(GeniServer):
21
22     hrn = None
23     nodes_ttl = None
24     nodes = None
25     slices = None 
26     policy = None
27     timestamp = None
28     threshold = None    
29     shell = None
30     registry = None
31     key_file = None
32     cert_file = None
33     credential = None
34   
35     ##
36     # Create a new aggregate object.
37     #
38     # @param ip the ip address to listen on
39     # @param port the port to listen on
40     # @param key_file private key filename of registry
41     # @param cert_file certificate filename containing public key (could be a GID file)     
42
43     def __init__(self, ip, port, key_file, cert_file, config = "/usr/share/geniwrapper/geni/util/geni_config"):
44         GeniServer.__init__(self, ip, port, key_file, cert_file)
45         self.key_file = key_file
46         self.cert_file = cert_file
47         self.config = Config(config)
48         self.basedir = self.config.GENI_BASE_DIR + os.sep
49         self.server_basedir = self.basedir + os.sep + "geni" + os.sep
50         self.hrn = self.config.GENI_INTERFACE_HRN
51         
52         nodes_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.components'])
53         self.nodes = SimpleStorage(nodes_file)
54         self.nodes.load()
55        
56         slices_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.slices'])
57         self.slices = SimpleStorage(slices_file)
58         self.slices.load()
59  
60         policy_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.policy'])
61         self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
62         self.policy.load()
63         
64         timestamp_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.timestamp']) 
65         self.timestamp = SimpleStorage(timestamp_file)
66
67         # How long before we refresh nodes cache
68         self.nodes_ttl = 1
69
70         self.connectPLC()
71         #self.connectRegistry()
72         #self.loadCredential()
73
74     def connectRegistry(self):
75         """
76         Connect to the registry
77         """
78         # connect to registry using GeniClient
79         address = self.config.GENI_REGISTRY_HOSTNAME
80         port = self.config.GENI_REGISTRY_PORT
81         url = 'https://%(address)s:%(port)s' % locals()
82         self.registry = GeniClient(url, self.key_file, self.cert_file)
83
84     
85     def connectPLC(self):
86         """
87         Connect to the plc api interface. First attempt to impor thte shell, if that fails
88         try to connect to the xmlrpc server.
89         """
90         self.auth = {'Username': self.config.GENI_PLC_USER,
91                      'AuthMethod': 'password',
92                      'AuthString': self.config.GENI_PLC_PASSWORD}
93
94         try:
95            # try to import PLC.Shell directly
96             sys.path.append(self.config.GENI_PLC_SHELL_PATH) 
97             import PLC.Shell
98             self.shell = PLC.Shell.Shell(globals())
99             self.shell.AuthCheck()
100         except ImportError:
101             # connect to plc api via xmlrpc
102             plc_host = self.config.GENI_PLC_HOST
103             plc_port = self.config.GENI_PLC_PORT
104             plc_api_path = self.config.GENI_PLC_API_PATH                 
105             url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
106             self.auth = {'Username': self.config.GENI_PLC_USER,
107                  'AuthMethod': 'password',
108                  'AuthString': self.config.GENI_PLC_PASSWORD} 
109
110             self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True) 
111             self.shell.AuthCheck(self.auth)
112
113     def loadCredential(self):
114         """
115         Attempt to load credential from file if it exists. If it doesnt get 
116         credential from registry.
117         """ 
118
119         self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
120         ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
121         
122         # see if this file exists
123         try:
124             cred = Credential(filename = ma_cred_filename, subject=self.hrn)
125             self.credential = cred.save_to_string()
126         except IOError:
127             # get self credential
128             self_cred = self.registry.get_credential(None, 'ma', self.hrn)
129             self_credential = Credential(string = self_cred)
130             self_credential.save_to_file(self_cred_filename)
131
132             # get ma credential
133             ma_cred = self.registry.get_credential(self_cred)
134             ma_credential = Credential(string = ma_cred)
135             ma_credential.save_to_file(ma_cred_filename)
136             self.credential = ma_cred
137
138     def hostname_to_hrn(self, login_base, hostname):
139         """
140         Convert hrn to plantelab name.
141         """
142         genihostname = "_".join(hostname.split("."))
143         return ".".join([self.hrn, login_base, genihostname])
144
145     def slicename_to_hrn(self, slicename):
146         """
147         Convert hrn to planetlab name.
148         """
149         slicename = slicename.replace("_", ".")
150         return ".".join([self.hrn, slicename])
151
152     def refresh_components(self):
153         """
154         Update the cached list of nodes and save in 4 differnt formats
155         (rspec, dns, ip)
156         """
157
158         # get node list in rspec format
159         rspec = Rspec()
160         rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
161         
162         # filter nodes according to policy
163         rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
164         
165         # extract ifspecs from rspec to get ip's
166         ips = []
167         ifspecs = rspec.getDictsByTagName('IfSpec')
168         for ifspec in ifspecs:
169             if ifspec.has_key('addr') and ifspec['addr']:
170                 ips.append(ifspec['addr']) 
171
172         # extract nodespecs from rspec to get dns names
173         hostnames = []
174         nodespecs = rspec.getDictsByTagName('NodeSpec')
175         for nodespec in nodespecs:
176             if nodespec.has_key('name') and nodespec['name']:
177                 hostnames.append(nodespec['name'])
178
179         
180         node_details = {}
181         node_details['rspec'] = rspec.toxml()
182         node_details['ip'] = ips
183         node_details['dns'] = hostnames
184         # save state 
185         self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
186         self.nodes.write()
187
188         
189         # update timestamp and threshold
190         self.timestamp['timestamp'] =  datetime.datetime.now()
191         delta = datetime.timedelta(hours=self.nodes_ttl)
192         self.threshold = self.timestamp['timestamp'] + delta 
193         self.timestamp.write()        
194  
195     def load_components(self):
196         """
197         Read cached list of nodes.
198         """
199         # Read component list from cached file 
200         self.nodes.load()
201         self.timestamp.load() 
202         time_format = "%Y-%m-%d %H:%M:%S"
203         timestamp = self.timestamp['timestamp']
204         self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
205         delta = datetime.timedelta(hours=self.nodes_ttl)
206         self.threshold = self.timestamp['timestamp'] + delta
207
208     def load_policy(self):
209         """
210         Read the list of blacklisted and whitelisted nodes.
211         """
212         self.policy.load()
213
214
215     def getNodes(self, format = 'rspec'):
216         """
217         Return a list of components at this aggregate.
218         """
219         valid_formats = ['rspec', 'hrn', 'dns', 'ip']
220         if not format:
221             format = 'rspec'
222         if format not in valid_formats:
223             raise Exception, "Invalid format specified, must be one of the following: %s" \
224                              % ", ".join(valid_formats)
225         
226         # Reload components list
227         now = datetime.datetime.now()
228         #self.load_components()
229         if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
230             self.refresh_components()
231         elif now < self.threshold and not self.nodes.keys(): 
232             self.load_components()
233         return self.nodes[format]
234     
235     def getSlices(self):
236         """
237         Return a list of instnatiated managed by this slice manager.
238         """
239
240         slices = self.shell.GetSlices(self.auth, {}, ['name'])
241         slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]  
242
243         return slice_hrns
244  
245     def get_rspec(self, hrn, type):
246         """
247         Get resource information from PLC
248         """
249         
250         # Get the required nodes
251         if type in ['aggregate']:
252             nodes = self.shell.GetNodes(self.auth)
253             try:  linkspecs = self.shell.GetLinkSpecs() # if call is supported
254             except:  linkspecs = []
255         elif type in ['slice']:
256             slicename = hrn_to_pl_slicename(hrn)
257             slices = self.shell.GetSlices(self.auth, [slicename])
258             node_ids = slices[0]['node_ids']
259             nodes = self.shell.GetNodes(self.auth, node_ids) 
260         
261         # Filter out whitelisted nodes
262         public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
263         nodes = filter(public_nodes, nodes)
264  
265         # Get all network interfaces
266         interface_ids = []
267         for node in nodes:
268             interface_ids.extend(node['nodenetwork_ids'])
269         interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
270         interface_dict = {}
271         for interface in interfaces:
272             interface_dict[interface['nodenetwork_id']] = interface
273         
274         # join nodes with thier interfaces
275         for node in nodes:
276             node['interfaces'] = []
277             for nodenetwork_id in node['nodenetwork_ids']:
278                 node['interfaces'].append(interface_dict[nodenetwork_id])
279
280         # convert and threshold to ints
281         if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
282             timestamp = self.timestamp['timestamp']
283             threshold = self.threshold
284         else:
285             timestamp = datetime.datetime.now()
286             delta = datetime.timedelta(hours=self.nodes_ttl)
287             threshold = timestamp + delta        
288
289     
290         start_time = int(timestamp.strftime("%s"))
291         end_time = int(threshold.strftime("%s"))
292         duration = end_time - start_time
293
294         # create the plc dict
295         networks = [{'nodes': nodes,
296                      'links': linkspecs, 
297                      'name': self.hrn, 
298                      'start_time': start_time, 
299                      'duration': duration}] 
300         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
301
302         # convert the plc dict to an rspec dict
303         resourceDict = RspecDict(resources)
304         # convert the rspec dict to xml
305         rspec = Rspec()
306         rspec.parseDict(resourceDict)
307         return rspec.toxml()
308
309     def getResources(self, slice_hrn):
310         """
311         Return the current rspec for the specified slice.
312         """
313         rspec = self.get_rspec(slice_hrn, 'slice')
314         
315         return rspec
316  
317     
318     def getTicket(self, hrn, rspec):
319         """
320         Retrieve a ticket. This operation is currently implemented on PLC
321         only (see SFA, engineering decisions); it is not implemented on
322         components.
323
324         @param name name of the slice to retrieve a ticket for
325         @param rspec resource specification dictionary
326         @return the string representation of a ticket object
327         """
328         #self.registry.get_ticket(name, rspec)
329
330         return         
331
332
333     def createSlice(self, slice_hrn, rspec, attributes = []):
334         """
335         Instantiate the specified slice according to whats defined in the rspec.
336         """
337         
338         spec = Rspec(rspec)
339         # save slice state locally
340         # we can assume that spec object has been validated so its safer to
341         # save this instead of the unvalidated rspec the user gave us
342         self.slices[slice_hrn] = spec.toxml()
343         self.slices.write()
344         
345         # Get slice info
346         slicename = hrn_to_pl_slicename(slice_hrn)
347         slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
348         if not slices:
349             raise RecordNotFound(slice_hrn)
350         slice = slices[0]
351
352         # find out where this slice is currently running
353         nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
354         hostnames = [node['hostname'] for node in nodelist]
355
356         # get netspec details
357         nodespecs = spec.getDictsByTagName('NodeSpec')
358         nodes = []
359         for nodespec in nodespecs:
360             if isinstance(nodespec['name'], list):
361                 nodes.extend(nodespec['name'])
362             elif isinstance(nodespec['name'], StringTypes):
363                 nodes.append(nodespec['name'])
364                 
365         # save slice state locally
366         # we can assume that spec object has been validated so its safer to 
367         # save this instead of the unvalidated rspec the user gave us
368         self.slices[slice_hrn] = spec.toxml()
369         self.slices.write()
370
371         # remove nodes not in rspec
372         deleted_nodes = list(set(hostnames).difference(nodes))
373         # add nodes from rspec
374         added_nodes = list(set(nodes).difference(hostnames))
375     
376         self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
377         self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
378
379         for attribute in attributes:
380             type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
381             self.shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
382     
383         # contact registry to get slice users and add them to the slice
384         #slice_record = self.registry.resolve(self.credential, slice_hrn)
385         # persons = slice_record['users']
386         # for perosn in persons:
387         #    shell.AddPersonToSlice(person['email'], slice_name)
388         return 1
389
390     def updateSlice(self, slice_hrn, rspec, attributes = []):
391         return self.create_slice(slice_hrn, rspec, attributes)
392          
393     def deleteSlice(self, slice_hrn):
394         """
395         Remove this slice from all components it was previouly associated with and 
396         free up the resources it was using.
397         """
398         if self.slices.has_key(slice_hrn):
399             self.slices.pop(slice_hrn)
400             self.slices.write()
401
402         slicename = hrn_to_pl_slicename(slice_hrn)
403         slices = self.shell.GetSlices(self.auth, [slicename])
404         if not slices:
405             return 1  
406         slice = slices[0]
407       
408         self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
409         return 1
410
411     def startSlice(self, slice_hrn):
412         """
413         Stop the slice at plc.
414         """
415         slicename = hrn_to_pl_slicename(slice_hrn)
416         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
417         if not slices:
418             #raise RecordNotFound(slice_hrn)
419             return 1 
420         slice_id = slices[0]
421         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
422         attribute_id = attreibutes[0] 
423         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
424         return 1
425
426     def stopSlice(self, slice_hrn):
427         """
428         Stop the slice at plc
429         """
430         slicename = hrn_to_pl_slicename(slice_hrn)
431         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
432         if not slices:
433             #raise RecordNotFound(slice_hrn)
434             return 1
435         slice_id = slices[0]
436         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
437         attribute_id = attreibutes[0]
438         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
439         return 1
440
441
442     def resetSlice(self, slice_hrn):
443         """
444         Reset the slice
445         """
446         # XX not yet implemented
447         return 1
448
449     def getPolicy(self):
450         """
451         Return this aggregates policy.
452         """
453     
454         return self.policy
455         
456     
457
458 ##############################
459 ## Server methods here for now
460 ##############################
461
462
463     # XX fix rights, should be function name defined in 
464     # privilege_table (from util/rights.py)
465     def list_nodes(self, cred):
466         self.decode_authentication(cred, 'listnodes')
467         return self.getNodes()
468
469     def list_slices(self, cred):
470         self.decode_authentication(cred, 'listslices')
471         return self.getSlices()
472
473     def get_resources(self, cred, hrn):
474         self.decode_authentication(cred, 'listnodes')
475         return self.getResources(hrn)
476
477     def get_ticket(self, cred, hrn, rspec):
478         self.decode_authentication(cred, 'getticket')
479         return self.getTicket(hrn, rspec)
480  
481     def get_policy(self, cred):
482         self.decode_authentication(cred, 'getpolicy')
483         return self.getPolicy()
484
485     def create_slice(self, cred, hrn, rspec):
486         self.decode_authentication(cred, 'createslice')
487         return self.createSlice(hrn, rspec)
488
489     def update_slice(self, cred, hrn, rspec):
490         self.decode_authentication(cred, 'updateslice')
491         return self.updateSlice(hrn)    
492
493     def delete_slice(self, cred, hrn):
494         self.decode_authentication(cred, 'deleteslice')
495         return self.deleteSlice(hrn)
496
497     def start_slice(self, cred, hrn):
498         self.decode_authentication(cred, 'startslice')
499         return self.startSlice(hrn)
500
501     def stop_slice(self, cred, hrn):
502         self.decode_authentication(cred, 'stopslice')
503         return self.stopSlice(hrn)
504
505     def reset_slice(self, cred, hrn):
506         self.decode_authentication(cred, 'resetslice')
507         return self.resetSlice(hrn)
508
509     def register_functions(self):
510         GeniServer.register_functions(self)
511
512         # Aggregate interface methods
513         self.server.register_function(self.list_nodes)
514         self.server.register_function(self.list_slices)
515         self.server.register_function(self.get_resources)
516         self.server.register_function(self.get_policy)
517         self.server.register_function(self.create_slice)
518         self.server.register_function(self.update_slice)
519         self.server.register_function(self.delete_slice)
520         self.server.register_function(self.start_slice)
521         self.server.register_function(self.stop_slice)
522         self.server.register_function(self.reset_slice)
523