oops
[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 = 'http://%(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         # see if this file exists
120         ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
121         try:
122             self.credential = Credential(filename = ma_cred_filename)
123         except IOError:
124             # get self credential
125             self.credential = self.getCredentialFromRegistry()
126
127     def getCredentialFromRegistry(self):
128         """
129         Get our current credential from the registry
130         """
131         # get self credential
132         self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
133         self_cred = self.registry.get_credential(None, 'ma', self.hrn)
134         self_cred.save_to_file(self_cred_filename, save_parents = True)
135
136         # get ma credential
137         ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
138         ma_cred = self.registry.get_credential(self_cred, 'ma', self.hrn)
139         ma_cred.save_to_file(ma_cred_filename, save_parents=True)
140         return ma_cred
141
142     def hostname_to_hrn(self, login_base, hostname):
143         """
144         Convert hrn to plantelab name.
145         """
146         genihostname = "_".join(hostname.split("."))
147         return ".".join([self.hrn, login_base, genihostname])
148
149     def slicename_to_hrn(self, slicename):
150         """
151         Convert hrn to planetlab name.
152         """
153         slicename = slicename.replace("_", ".")
154         return ".".join([self.hrn, slicename])
155
156     def refresh_components(self):
157         """
158         Update the cached list of nodes and save in 4 differnt formats
159         (rspec, dns, ip)
160         """
161
162         # get node list in rspec format
163         rspec = Rspec()
164         rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
165         
166         # filter nodes according to policy
167         rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
168         
169         # extract ifspecs from rspec to get ip's
170         ips = []
171         ifspecs = rspec.getDictsByTagName('IfSpec')
172         for ifspec in ifspecs:
173             if ifspec.has_key('addr') and ifspec['addr']:
174                 ips.append(ifspec['addr']) 
175
176         # extract nodespecs from rspec to get dns names
177         hostnames = []
178         nodespecs = rspec.getDictsByTagName('NodeSpec')
179         for nodespec in nodespecs:
180             if nodespec.has_key('name') and nodespec['name']:
181                 hostnames.append(nodespec['name'])
182
183         
184         node_details = {}
185         node_details['rspec'] = rspec.toxml()
186         node_details['ip'] = ips
187         node_details['dns'] = hostnames
188         # save state 
189         self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
190         self.nodes.write()
191
192         
193         # update timestamp and threshold
194         self.timestamp['timestamp'] =  datetime.datetime.now()
195         delta = datetime.timedelta(hours=self.nodes_ttl)
196         self.threshold = self.timestamp['timestamp'] + delta 
197         self.timestamp.write()        
198  
199     def load_components(self):
200         """
201         Read cached list of nodes.
202         """
203         # Read component list from cached file 
204         self.nodes.load()
205         self.timestamp.load() 
206         time_format = "%Y-%m-%d %H:%M:%S"
207         timestamp = self.timestamp['timestamp']
208         self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
209         delta = datetime.timedelta(hours=self.nodes_ttl)
210         self.threshold = self.timestamp['timestamp'] + delta
211
212     def load_policy(self):
213         """
214         Read the list of blacklisted and whitelisted nodes.
215         """
216         self.policy.load()
217
218
219     def getNodes(self, format = 'rspec'):
220         """
221         Return a list of components at this aggregate.
222         """
223         valid_formats = ['rspec', 'hrn', 'dns', 'ip']
224         if not format:
225             format = 'rspec'
226         if format not in valid_formats:
227             raise Exception, "Invalid format specified, must be one of the following: %s" \
228                              % ", ".join(valid_formats)
229         
230         # Reload components list
231         now = datetime.datetime.now()
232         #self.load_components()
233         if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
234             self.refresh_components()
235         elif now < self.threshold and not self.nodes.keys(): 
236             self.load_components()
237         return self.nodes[format]
238     
239     def getSlices(self):
240         """
241         Return a list of instnatiated managed by this slice manager.
242         """
243
244         slices = self.shell.GetSlices(self.auth, {}, ['name'])
245         slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]  
246
247         return slice_hrns
248  
249     def get_rspec(self, hrn, type):
250         """
251         Get resource information from PLC
252         """
253         
254         # Get the required nodes
255         if type in ['aggregate']:
256             nodes = self.shell.GetNodes(self.auth)
257             try:  linkspecs = self.shell.GetLinkSpecs() # if call is supported
258             except:  linkspecs = []
259         elif type in ['slice']:
260             slicename = hrn_to_pl_slicename(hrn)
261             slices = self.shell.GetSlices(self.auth, [slicename])
262             node_ids = slices[0]['node_ids']
263             nodes = self.shell.GetNodes(self.auth, node_ids) 
264         
265         # Filter out whitelisted nodes
266         public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
267         nodes = filter(public_nodes, nodes)
268  
269         # Get all network interfaces
270         interface_ids = []
271         for node in nodes:
272             interface_ids.extend(node['nodenetwork_ids'])
273         interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
274         interface_dict = {}
275         for interface in interfaces:
276             interface_dict[interface['nodenetwork_id']] = interface
277         
278         # join nodes with thier interfaces
279         for node in nodes:
280             node['interfaces'] = []
281             for nodenetwork_id in node['nodenetwork_ids']:
282                 node['interfaces'].append(interface_dict[nodenetwork_id])
283
284         # convert and threshold to ints
285         if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
286             timestamp = self.timestamp['timestamp']
287             threshold = self.threshold
288         else:
289             timestamp = datetime.datetime.now()
290             delta = datetime.timedelta(hours=self.nodes_ttl)
291             threshold = timestamp + delta        
292
293     
294         start_time = int(timestamp.strftime("%s"))
295         end_time = int(threshold.strftime("%s"))
296         duration = end_time - start_time
297
298         # create the plc dict
299         networks = [{'nodes': nodes, 
300                         'name': self.hrn, 
301                         'start_time': start_time, 
302                         'duration': duration, 
303                         'links': linkspecs}] 
304         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
305
306         # convert the plc dict to an rspec dict
307         resourceDict = RspecDict(resources)
308         # convert the rspec dict to xml
309         rspec = Rspec()
310         rspec.parseDict(resourceDict)
311         return rspec.toxml()
312
313     def getResources(self, slice_hrn):
314         """
315         Return the current rspec for the specified slice.
316         """
317         rspec = self.get_rspec(slice_hrn, 'slice')
318         
319         return rspec
320  
321     
322     def getTicket(self, hrn, rspec):
323         """
324         Retrieve a ticket. This operation is currently implemented on PLC
325         only (see SFA, engineering decisions); it is not implemented on
326         components.
327
328         @param name name of the slice to retrieve a ticket for
329         @param rspec resource specification dictionary
330         @return the string representation of a ticket object
331         """
332         #self.registry.get_ticket(name, rspec)
333
334         return         
335
336
337     def createSlice(self, slice_hrn, rspec, attributes = []):
338         """
339         Instantiate the specified slice according to whats defined in the rspec.
340         """
341         
342         spec = Rspec(rspec)
343         # save slice state locally
344         # we can assume that spec object has been validated so its safer to
345         # save this instead of the unvalidated rspec the user gave us
346         self.slices[slice_hrn] = spec.toxml()
347         self.slices.write()
348         
349         # Get slice info
350         # if slice doesnt exist add it
351         slicename = hrn_to_pl_slicename(slice_hrn)
352         slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
353         if not slices:
354             parts = slicename.split("_")
355             login_base = parts[0]
356             slice_record = self.registry.resolve(self.cred, slice_hrn)
357             slice_info = slice_record.as_dict()
358             slice = slice_info['pl_info']
359             
360             # if site doesnt exist add it
361             sites = self.shell.GetSites(self.auth, [login_base])
362             if not sites:
363                 authority = get_authority(slice_hrn)
364                 site_record = self.registry.reolve(self.cred, authority) 
365                 site_info = site_record.as_dict()
366                 site = site_info['pl_info']
367
368                 # add the site
369                 site.pop('site_id')
370                 site_id = self.shell.AddSite(self.auth, site)
371
372             # add the slice
373             self.shell.AddSlice(self.auth, slice_info)
374             
375             # add the slice users
376             
377         else:    
378             slice = slices[0]
379
380
381         # find out where this slice is currently running
382         nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
383         hostnames = [node['hostname'] for node in nodelist]
384
385         # get netspec details
386         nodespecs = spec.getDictsByTagName('NodeSpec')
387         nodes = []
388         for nodespec in nodespecs:
389             if isinstance(nodespec['name'], list):
390                 nodes.extend(nodespec['name'])
391             elif isinstance(nodespec['name'], StringTypes):
392                 nodes.append(nodespec['name'])
393                 
394         # save slice state locally
395         # we can assume that spec object has been validated so its safer to 
396         # save this instead of the unvalidated rspec the user gave us
397         self.slices[slice_hrn] = spec.toxml()
398         self.slices.write()
399
400         # remove nodes not in rspec
401         deleted_nodes = list(set(hostnames).difference(nodes))
402         # add nodes from rspec
403         added_nodes = list(set(nodes).difference(hostnames))
404     
405         self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
406         self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
407
408         # contact registry to get slice users and add them to the slice
409         #slice_record = self.registry.resolve(self.credential, slice_hrn)
410         # persons = slice_record['users']
411         # for perosn in persons:
412         #    shell.AddPersonToSlice(person['email'], slice_name)
413         return 1
414
415     def updateSlice(self, slice_hrn, rspec, attributes = []):
416         return self.create_slice(slice_hrn, rspec, attributes)
417          
418     def deleteSlice(self, slice_hrn):
419         """
420         Remove this slice from all components it was previouly associated with and 
421         free up the resources it was using.
422         """
423         if self.slices.has_key(slice_hrn):
424             self.slices.pop(slice_hrn)
425             self.slices.write()
426
427         slicename = hrn_to_pl_slicename(slice_hrn)
428         slices = self.shell.GetSlices(self.auth, [slicename])
429         if not slices:
430             return 1  
431         slice = slices[0]
432       
433         self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
434         return 1
435
436     def startSlice(self, slice_hrn):
437         """
438         Stop the slice at plc.
439         """
440         slicename = hrn_to_pl_slicename(slice_hrn)
441         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
442         if not slices:
443             #raise RecordNotFound(slice_hrn)
444             return 1 
445         slice_id = slices[0]
446         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
447         attribute_id = attreibutes[0] 
448         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
449         return 1
450
451     def stopSlice(self, slice_hrn):
452         """
453         Stop the slice at plc
454         """
455         slicename = hrn_to_pl_slicename(slice_hrn)
456         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
457         if not slices:
458             #raise RecordNotFound(slice_hrn)
459             return 1
460         slice_id = slices[0]
461         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
462         attribute_id = attreibutes[0]
463         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
464         return 1
465
466
467     def resetSlice(self, slice_hrn):
468         """
469         Reset the slice
470         """
471         # XX not yet implemented
472         return 1
473
474     def getPolicy(self):
475         """
476         Return this aggregates policy.
477         """
478     
479         return self.policy
480         
481     
482
483 ##############################
484 ## Server methods here for now
485 ##############################
486
487
488     # XX fix rights, should be function name defined in 
489     # privilege_table (from util/rights.py)
490     def list_nodes(self, cred):
491         self.decode_authentication(cred, 'listnodes')
492         return self.getNodes()
493
494     def list_slices(self, cred):
495         self.decode_authentication(cred, 'listslices')
496         return self.getSlices()
497
498     def get_resources(self, cred, hrn):
499         self.decode_authentication(cred, 'listnodes')
500         return self.getResources(hrn)
501
502     def get_ticket(self, cred, hrn, rspec):
503         self.decode_authentication(cred, 'getticket')
504         return self.getTicket(hrn, rspec)
505  
506     def get_policy(self, cred):
507         self.decode_authentication(cred, 'getpolicy')
508         return self.getPolicy()
509
510     def create_slice(self, cred, hrn, rspec):
511         self.decode_authentication(cred, 'createslice')
512         return self.createSlice(hrn, rspec)
513
514     def update_slice(self, cred, hrn, rspec):
515         self.decode_authentication(cred, 'updateslice')
516         return self.updateSlice(hrn)    
517
518     def delete_slice(self, cred, hrn):
519         self.decode_authentication(cred, 'deleteslice')
520         return self.deleteSlice(hrn)
521
522     def start_slice(self, cred, hrn):
523         self.decode_authentication(cred, 'startslice')
524         return self.startSlice(hrn)
525
526     def stop_slice(self, cred, hrn):
527         self.decode_authentication(cred, 'stopslice')
528         return self.stopSlice(hrn)
529
530     def reset_slice(self, cred, hrn):
531         self.decode_authentication(cred, 'resetslice')
532         return self.resetSlice(hrn)
533
534     def register_functions(self):
535         GeniServer.register_functions(self)
536
537         # Aggregate interface methods
538         self.server.register_function(self.list_nodes)
539         self.server.register_function(self.list_slices)
540         self.server.register_function(self.get_resources)
541         self.server.register_function(self.get_policy)
542         self.server.register_function(self.create_slice)
543         self.server.register_function(self.update_slice)
544         self.server.register_function(self.delete_slice)
545         self.server.register_function(self.start_slice)
546         self.server.register_function(self.stop_slice)
547         self.server.register_function(self.reset_slice)
548