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