fixed bug in get_resources() and get_rspec()
[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         self.nodes_ttl = 1
67
68         self.connectPLC()
69         self.connectRegistry()
70         self.loadCredential()
71
72     def connectRegistry(self):
73         """
74         Connect to the registry
75         """
76         # connect to registry using GeniClient
77         address = self.config.GENI_REGISTRY_HOSTNAME
78         port = self.config.GENI_REGISTRY_PORT
79         url = 'https://%(address)s:%(port)s' % locals()
80         self.registry = GeniClient(url, self.key_file, self.cert_file)
81
82     
83     def connectPLC(self):
84         """
85         Connect to the plc api interface. First attempt to impor thte shell, if that fails
86         try to connect to the xmlrpc server.
87         """
88         self.auth = {'Username': self.config.GENI_PLC_USER,
89                      'AuthMethod': 'password',
90                      'AuthString': self.config.GENI_PLC_PASSWORD}
91
92         try:
93            # try to import PLC.Shell directly
94             sys.path.append(self.config.GENI_PLC_SHELL_PATH) 
95             import PLC.Shell
96             self.shell = PLC.Shell.Shell(globals())
97             self.shell.AuthCheck()
98         except ImportError:
99             # connect to plc api via xmlrpc
100             plc_host = self.config.GENI_PLC_HOST
101             plc_port = self.config.GENI_PLC_PORT
102             plc_api_path = self.config.GENI_PLC_API_PATH                 
103             url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
104             self.auth = {'Username': self.config.GENI_PLC_USER,
105                  'AuthMethod': 'password',
106                  'AuthString': self.config.GENI_PLC_PASSWORD} 
107
108             self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True) 
109             self.shell.AuthCheck(self.auth)
110
111     def loadCredential(self):
112         """
113         Attempt to load credential from file if it exists. If it doesnt get 
114         credential from registry.
115         """ 
116
117         self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
118         ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
119         
120         # see if this file exists
121         try:
122             cred = Credential(filename = ma_cred_filename)
123             self.credential = cred.save_to_string()
124         except IOError:
125             # get self credential
126             #self_cred = self.registry.get_credential(None, 'ma', self.hrn)
127             #self_credential = Credential(string = self_cred)
128             #self_credential.save_to_file(self_cred_filename)
129
130             # get ma credential
131             #ma_cred = self.registry.get_gredential(self_cred)
132             #ma_credential = Credential(string = ma_cred)
133             #ma_credential.save_to_file(ma_cred_filename)
134
135             ma_cred = Certificate(filename = self.cert_file)
136             
137             self.credential = ma_cred.save_to_string()
138
139     def hostname_to_hrn(self, login_base, hostname):
140         """
141         Convert hrn to plantelab name.
142         """
143         genihostname = "_".join(hostname.split("."))
144         return ".".join([self.hrn, login_base, genihostname])
145
146     def slicename_to_hrn(self, slicename):
147         """
148         Convert hrn to planetlab name.
149         """
150         slicename = slicename.replace("_", ".")
151         return ".".join([self.hrn, slicename])
152
153     def refresh_components(self):
154         """
155         Update the cached list of nodes and save in 4 differnt formats
156         (rspec, dns, ip, hrn)
157         """
158
159         node_details = {}
160         # get node list in rspec format
161         rspec = Rspec()
162         rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
163         # filter nodes according to policy
164         rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
165         # extract ifspec info to get ip's
166         ips = []
167         ifspecs = rspec.getDictsByTagName('IfSpec')
168         for ifspec in ifspecs:
169             if ifspec.has_key('addr') and ifspec['addr']:
170                 ips.append(ifspec['addr']) 
171
172         # resolve component hostnames 
173         nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
174     
175         # resolve site login_bases
176         site_ids = [node['site_id'] for node in nodes]
177         sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
178         site_dict = {}
179         for site in sites:
180             site_dict[site['site_id']] = site['login_base']
181
182         # filter nodes according to policy
183         # convert plc names to geni hrn
184         nodedict = {}
185         for node in nodes:
186             node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
187             # apply policy. 
188             # Do not allow nodes found in blacklist, only allow nodes found in whitelist
189             if self.policy['whitelist'] and node_hrn not in self.polciy['whitelist']:
190                 continue
191             if self.policy['blacklist'] and node_hrn in self.policy['blacklist']:
192                 continue
193             nodedict[node_hrn] = node['hostname']
194
195         
196         node_details['rspec'] = rspec.toxml()
197         node_details['hrn'] = nodedict.keys()
198         node_details['dns'] = nodedict.values()
199         node_details['ip'] = ips
200         # save state 
201         self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
202         self.nodes.write()
203
204         
205         # update timestamp and threshold
206         self.timestamp['timestamp'] =  datetime.datetime.now()
207         delta = datetime.timedelta(hours=self.nodes_ttl)
208         self.threshold = self.timestamp['timestamp'] + delta 
209         self.timestamp.write()        
210  
211     def load_components(self):
212         """
213         Read cached list of nodes.
214         """
215         # Read component list from cached file 
216         self.nodes.load()
217         self.timestamp.load() 
218         time_format = "%Y-%m-%d %H:%M:%S"
219         timestamp = self.timestamp['timestamp']
220         self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
221         delta = datetime.timedelta(hours=self.nodes_ttl)
222         self.threshold = self.timestamp['timestamp'] + delta
223
224     def load_policy(self):
225         """
226         Read the list of blacklisted and whitelisted nodes.
227         """
228         self.policy.load()
229
230
231     def getComponents(self, type = 'rspec'):
232         """
233         Return a list of components at this aggregate.
234         """
235         valid_types = ['rspec', 'hrn', 'dns', 'ip']
236         if type not in valid_types:
237             raise Exception, "Invalid type specified, must be one of the following: %s" \
238                              % ", ".join(valid_types)
239         
240         # Reload components list
241         now = datetime.datetime.now()
242         #self.load_components()
243         if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
244             self.refresh_components()
245         elif now < self.threshold and not self.nodes.keys(): 
246             self.load_components()
247         return self.nodes.keys()
248     
249     def getSlices(self, hrn):
250         """
251         Return a list of instnatiated managed by this slice manager.
252         """
253
254         # XX list only the slices at the specfied hrn
255         return dict(self.slices)
256  
257     def get_rspec(self, hrn, type):
258         """
259         Get resource information from PLC
260         """
261         
262         # Get the required nodes
263         if type in ['aggregate']:
264             nodes = self.shell.GetNodes(self.auth)
265         elif type in ['slice']:
266             print hrn
267             slicename = hrn_to_pl_slicename(hrn)
268             slices = self.shell.GetSlices(self.auth, [slicename])
269             node_ids = slices[0]['node_ids']
270             nodes = self.shell.GetNodes(self.auth, node_ids) 
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, 'name': self.hrn, 'start_time': start_time, 'duration': duration}] 
303         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
304
305         # convert the plc dict to an rspec dict
306         resourceDict = RspecDict(resources)
307         # convert the rspec dict to xml
308         rspec = Rspec()
309         rspec.parseDict(resourceDict)
310         return rspec.toxml()
311
312     def getResources(self, slice_hrn):
313         """
314         Return the current rspec for the specified slice.
315         """
316         rspec = self.get_rspec(slice_hrn, 'slice')
317         
318         return rspec
319  
320
321     def createSlice(self, slice_hrn, rspec, attributes = []):
322         """
323         Instantiate the specified slice according to whats defined in the rspec.
324         """
325         
326         # save slice state locally
327         # we can assume that spec object has been validated so its safer to
328         # save this instead of the unvalidated rspec the user gave us
329         self.slices[slice_hrn] = spec.toxml()
330         self.slices.write()
331         
332         # Get slice info
333         slicename = hrn_to_pl_slicename(slice_hrn)
334         slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
335         if not slice:
336             raise RecordNotFound(slice_hrn)
337         slice = slices[0]
338
339         # find out where this slice is currently running
340         nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
341         hostnames = [node['hostname'] for node in nodes]
342
343         # get netspec details
344         spec = Rspec(rspec)
345         nodespecs = spec.getDictsByTagName('NodeSpec')
346         nodes = [nodespec['name'] for nodespec in nodespecs]    
347        
348         # save slice state locally
349         # we can assume that spec object has been validated so its safer to 
350         # save this instead of the unvalidated rspec the user gave us
351         self.slices[slice_hrn] = spec.toxml()
352         self.slices.write()
353
354         # remove nodes not in rspec
355         delete_nodes = set(hostnames).difference(nodes)
356         # add nodes from rspec
357         added_nodes = set(nodes).difference(hostnames)
358     
359         shell.AddSliceToNodes(self.auth, slicename, added_nodes)
360         shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
361
362         for attribute in attributes:
363             type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
364             shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
365     
366         # contact registry to get slice users and add them to the slice
367         slice_record = self.registry.resolve(self.credential, slice_hrn)
368         # persons = slice_record['users']
369         
370         #for person in persons:
371         #    shell.AddPersonToSlice(person['email'], slice_name)
372         return 1
373
374     def update_slice(self, slice_hrn, rspec, attributes = []):
375         return self.create_slice(slice_hrn, rspec, attributes)
376          
377     def deleteSlice_(self, slice_hrn):
378         """
379         Remove this slice from all components it was previouly associated with and 
380         free up the resources it was using.
381         """
382         if self.slices.has_key(slice_hrn):
383             self.slices.pop(slice_hrn)
384             self.slices.write()
385
386         slicename = hrn_to_pl_slicename(slice_hrn)
387         slices = shell.GetSlices(self.auth, [slicename])
388         if not slice:
389             return 1  
390         slice = slices[0]
391       
392         shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
393         return 1
394
395     def startSlice(self, slice_hrn):
396         """
397         Stop the slice at plc.
398         """
399         slicename = hrn_to_pl_slicename(slice_hrn)
400         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
401         if not slices:
402             #raise RecordNotFound(slice_hrn)
403             return 1 
404         slice_id = slices[0]
405         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
406         attribute_id = attreibutes[0] 
407         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
408         return 1
409
410     def stopSlice(self, slice_hrn):
411         """
412         Stop the slice at plc
413         """
414         slicename = hrn_to_pl_slicename(slice_hrn)
415         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
416         if not slices:
417             #raise RecordNotFound(slice_hrn)
418             return 1
419         slice_id = slices[0]
420         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
421         attribute_id = attreibutes[0]
422         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
423         return 1
424
425
426     def resetSlice(self, slice_hrn):
427         """
428         Reset the slice
429         """
430         # XX not yet implemented
431         return 1
432
433     def getPolicy(self):
434         """
435         Return this aggregates policy.
436         """
437     
438         return self.policy
439         
440     
441
442 ##############################
443 ## Server methods here for now
444 ##############################
445
446     def list_components(self):
447         return self.getComponents()
448
449     def list_slices(self, cred, hrn):
450         self.decode_authentication(cred, 'list')
451         return self.getSlices(hrn)
452
453     def get_resources(self, cred, hrn):
454         self.decode_authentication(cred, 'info')
455         return self.getResources(hrn)
456
457     def get_policy(self, cred):
458         self.decode_authentication(cred, 'info')
459         return self.getPolicy()
460
461     def create_slice(self, cred, hrn, rspec):
462         self.decode_authentication(cred, 'embed')
463         return self.createSlice(hrn)
464
465     def update_slice(self, cred, hrn, rspec):
466         self.decode_authentication(cred, 'embed')
467         return self.updateSlice(hrn)    
468
469     def delete_slice(self, cred, hrn):
470         self.decode_authentication(cred, 'embed')
471         return self.deleteSlice(hrn)
472
473     def start_slice(self, cred, hrn):
474         self.decode_authentication(cred, 'control')
475         return self.startSlice(hrn)
476
477     def stop_slice(self, cred, hrn):
478         self.decode_authentication(cred, 'control')
479         return self.stopSlice(hrn)
480
481     def reset_slice(self, cred, hrn):
482         self.decode_authentication(cred, 'control')
483         return self.resetSlice(hrn)
484
485     def register_functions(self):
486         GeniServer.register_functions(self)
487
488         # Aggregate interface methods
489         self.server.register_function(self.list_components)
490         self.server.register_function(self.list_slices)
491         self.server.register_function(self.get_resources)
492         self.server.register_function(self.get_policy)
493         self.server.register_function(self.create_slice)
494         self.server.register_function(self.update_slice)
495         self.server.register_function(self.delete_slice)
496         self.server.register_function(self.start_slice)
497         self.server.register_function(self.stop_slice)
498         self.server.register_function(self.reset_slice)
499