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