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