added filter method used to remove elements from the dom tree
[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.conf = Config(config)
47         self.basedir = self.conf.GENI_BASE_DIR + os.sep
48         self.server_basedir = self.basedir + os.sep + "geni" + os.sep
49         self.hrn = self.conf.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.policy'])
60         self.policy = SimpleStorage(policy_file)
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.conf.GENI_PLC_USER,
89                      'AuthMethod': 'password',
90                      'AuthString': self.conf.GENI_PLC_PASSWORD}
91
92         try:
93            # try to import PLC.Shell directly
94             sys.path.append(self.conf.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.conf.GENI_PLC_HOST
101             plc_port = self.conf.GENI_PLC_PORT
102             plc_api_path = self.conf.GENI_PLC_API_PATH                 
103             url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
104             self.auth = {'Username': self.conf.GENI_PLC_USER,
105                  'AuthMethod': 'password',
106                  'AuthString': self.conf.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             self.credential = ma_cred
135
136     def hostname_to_hrn(self, login_base, hostname):
137         """
138         Convert hrn to plantelab name.
139         """
140         genihostname = "_".join(hostname.split("."))
141         return ".".join([self.hrn, login_base, genihostname])
142
143     def slicename_to_hrn(self, slicename):
144         """
145         Convert hrn to planetlab name.
146         """
147         slicename = slicename.replace("_", ".")
148         return ".".join([self.hrn, slicename])
149
150     def refresh_components(self):
151         """
152         Update the cached list of nodes.
153         """
154         # resolve component hostnames 
155         nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
156     
157         # resolve site login_bases
158         site_ids = [node['site_id'] for node in nodes]
159         sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
160         site_dict = {}
161         for site in sites:
162             site_dict[site['site_id']] = site['login_base']
163
164         # convert plc names to geni hrn
165         nodedict = {}
166         for node in nodes:
167             node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
168             # apply policy. 
169             # Do not allow nodes found in blacklist, only allow nodes found in whitelist
170             if self.polciy['whitelist'] and node_hrn not in self.polciy['whitelist']:
171                 continue
172             if self.polciy['blacklist'] and node_hrn in self.policy['blacklist']:
173                 continue
174             nodedict[node_hrn] = node['hostname']
175         
176         self.nodes = SimpleStorage(self.nodes.db_filename, nodedict)
177         self.nodes.write()
178
179         # update timestamp and threshold
180         self.timestamp['timestamp'] =  datetime.datetime.now()
181         delta = datetime.timedelta(hours=self.nodes_ttl)
182         self.threshold = self.timestamp['timestamp'] + delta 
183         self.timestamp.write()        
184  
185     def load_components(self):
186         """
187         Read cached list of nodes.
188         """
189         # Read component list from cached file 
190         self.nodes.load()
191         self.timestamp.load() 
192         time_format = "%Y-%m-%d %H:%M:%S"
193         timestamp = self.timestamp['timestamp']
194         self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
195         delta = datetime.timedelta(hours=self.nodes_ttl)
196         self.threshold = self.timestamp['timestamp'] + delta
197
198     def load_policy(self):
199         """
200         Read the list of blacklisted and whitelisted nodes.
201         """
202         self.policy.load()
203
204
205     def get_components(self):
206         """
207         Return a list of components at this aggregate.
208         """
209         # Reload components list
210         now = datetime.datetime.now()
211         #self.load_components()
212         if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
213             self.refresh_components()
214         elif now < self.threshold and not self.nodes.keys(): 
215             self.load_components()
216         return self.nodes.keys()
217      
218     def get_rspec(self, hrn, type):
219         """
220         Get resource information from PLC
221         """
222         
223         # Get the required nodes
224         if type in ['aggregate']:
225             nodes = self.shell.GetNodes(self.auth)
226         elif type in ['slice']:
227             slicename = hrn_to_pl_slicename(hrn)
228             slices = self.shell.GetSlices(self.auth, [slicename])
229             node_ids = slices[0]['node_ids']
230             nodes = self.shell.GetNodes(self.auth, node_ids) 
231         
232         # Get all network interfaces
233         interface_ids = []
234         for node in nodes:
235             interface_ids.extend(node['nodenetwork_ids'])
236         interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
237         interface_dict = {}
238         for interface in interfaces:
239             interface_dict[interface['nodenetwork_id']] = interface
240         
241         # join nodes with thier interfaces
242         for node in nodes:
243             node['interfaces'] = []
244             for nodenetwork_id in node['nodenetwork_ids']:
245                 node['interfaces'].append(interface_dict[nodenetwork_id])
246
247         # convert and threshold to ints
248         timestamp = self.timestamp['timestamp']
249         start_time = int(self.timestamp['timestamp'].strftime("%s"))
250         end_time = int(self.threshold.strftime("%s"))
251         duration = end_time - start_time
252
253         # create the plc dict
254         networks = {'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration} 
255         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
256
257         # convert the plc dict to an rspec dict
258         resouceDict = RspecDict(resources)
259
260         # convert the rspec dict to xml
261         rspec = Rspec()
262         rspec.parseDict(resourceDict)
263         return rspec.toxml()
264
265     def get_resources(self, slice_hrn):
266         """
267         Return the current rspec for the specified slice.
268         """
269         slicename = hrn_to_plcslicename(slice_hrn)
270         rspec = self.get_rspec(slicenamem, 'slice')
271         
272         return rspec
273  
274     def create_slice(self, slice_hrn, rspec, attributes = []):
275         """
276         Instantiate the specified slice according to whats defined in the rspec.
277         """
278
279         # save slice state locally
280         # we can assume that spec object has been validated so its safer to
281         # save this instead of the unvalidated rspec the user gave us
282         self.slices[slice_hrn] = spec.toxml()
283         self.slices.write()
284
285         # extract node list from rspec
286         slicename = self.hrn_to_plcslicename(slice_hrn)
287         spec = Rspec(rspec)
288         nodespecs = spec.getDictsByTagName('NodeSpec')
289         nodes = [nodespec['name'] for nodespec in nodespecs]
290
291         # add slice to nodes at plc    
292         self.shell.AddSliceToNodes(self.auth, slicename, nodes)
293         for attribute in attributes:
294             type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
295             shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
296
297         # XX contact the registry to get the list of users on this slice and
298         # their keys.
299         slice_record = self.registry.resolve(self.credential, slice_hrn)
300         #person_records = slice_record['users']
301         # for person in person_record:
302         #    email = person['email']
303         #    self.shell.AddPersonToSlice(self.auth, email, slicename) 
304      
305
306         return 1
307
308     def update_slice(self, slice_hrn, rspec, attributes = []):
309         """
310         Update the specified slice.
311         """
312         # Get slice info
313         slicename = self.hrn_to_plcslicename(slice_hrn)
314         slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
315         if not slice:
316             raise RecordNotFound(slice_hrn)
317         slice = slices[0]
318
319         # find out where this slice is currently running
320         nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
321         hostnames = [node['hostname'] for node in nodes]
322
323         # get netspec details
324         spec = Rspec(rspec)
325         nodespecs = spec.getDictsByTagName('NodeSpec')
326         nodes = [nodespec['name'] for nodespec in nodespecs]    
327        
328         # save slice state locally
329         # we can assume that spec object has been validated so its safer to 
330         # save this instead of the unvalidated rspec the user gave us
331         self.slices[slice_hrn] = spec.toxml()
332         self.slices.write()
333
334         # remove nodes not in rspec
335         delete_nodes = set(hostnames).difference(nodes)
336         # add nodes from rspec
337         added_nodes = set(nodes).difference(hostnames)
338     
339         shell.AddSliceToNodes(self.auth, slicename, added_nodes)
340         shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
341
342         for attribute in attributes:
343             type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
344             shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
345     
346         # contact registry to get slice users and add them to the slice
347         slice_record = self.registry.resolve(self.credential, slice_hrn)
348         # persons = slice_record['users']
349         
350         #for person in persons:
351         #    shell.AddPersonToSlice(person['email'], slice_name)
352
353          
354     def delete_slice_(self, slice_hrn):
355         """
356         Remove this slice from all components it was previouly associated with and 
357         free up the resources it was using.
358         """
359         if self.slices.has_key(slice_hrn):
360             self.slices.pop(slice_hrn)
361             self.slices.write()
362
363         slicename = self.hrn_to_plcslicename(slice_hrn)
364         slices = shell.GetSlices(self.auth, [slicename])
365         if not slice:
366             return 1  
367         slice = slices[0]
368       
369         shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
370         return 1
371
372     def start_slice(self, slice_hrn):
373         """
374         Stop the slice at plc.
375         """
376         slicename = hrn_to_plcslicename(slice_hrn)
377         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
378         if not slices:
379             #raise RecordNotFound(slice_hrn)
380             return 1 
381         slice_id = slices[0]
382         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
383         attribute_id = attreibutes[0] 
384         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
385         return 1
386
387     def stop_slice(self, slice_hrn):
388         """
389         Stop the slice at plc
390         """
391         slicename = hrn_to_plcslicename(slice_hrn)
392         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
393         if not slices:
394             #raise RecordNotFound(slice_hrn)
395             return 1
396         slice_id = slices[0]
397         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
398         attribute_id = attreibutes[0]
399         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
400         return 1
401
402
403     def reset_slice(self, slice_hrn):
404         """
405         Reset the slice
406         """
407         # XX not yet implemented
408         return 1
409
410     def get_policy(self):
411         """
412         Return this aggregates policy.
413         """
414     
415         return self.policy
416         
417     
418
419 ##############################
420 ## Server methods here for now
421 ##############################
422
423     def components(self):
424         return self.get_components()
425
426     #def slices(self):
427     #    return self.get_slices()
428
429     def resources(self, cred, hrn):
430         self.decode_authentication(cred, 'info')
431         self.verify_object_belongs_to_me(hrn)
432
433         return self.get_resources(hrn)
434
435     def createSlice(self, cred, hrn, rspec):
436         self.decode_authentication(cred, 'embed')
437         self.verify_object_belongs_to_me(hrn)
438         return self.create_slice(hrn)
439
440     def updateSlice(self, cred, hrn, rspec):
441         self.decode_authentication(cred, 'embed')
442         self.verify_object_belongs_to_me(hrn)
443         return self.update_slice(hrn)    
444
445     def deleteSlice(self, cred, hrn):
446         self.decode_authentication(cred, 'embed')
447         self.verify_object_belongs_to_me(hrn)
448         return self.delete_slice(hrn)
449
450     def startSlice(self, cred, hrn):
451         self.decode_authentication(cred, 'control')
452         return self.start_slice(hrn)
453
454     def stopSlice(self, cred, hrn):
455         self.decode_authentication(cred, 'control')
456         return self.stop(hrn)
457
458     def resetSlice(self, cred, hrn):
459         self.decode_authentication(cred, 'control')
460         return self.reset(hrn)
461
462     def policy(self, cred):
463         self.decode_authentication(cred, 'info')
464         return self.get_policy()
465
466     def register_functions(self):
467         GeniServer.register_functions(self)
468
469         # Aggregate interface methods
470         self.server.register_function(self.components)
471         #self.server.register_function(self.slices)
472         self.server.register_function(self.resources)
473         self.server.register_function(self.createSlice)
474         self.server.register_function(self.deleteSlice)
475         self.server.register_function(self.startSlice)
476         self.server.register_function(self.stopSlice)
477         self.server.register_function(self.resetSlice)
478         self.server.register_function(self.policy)
479