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