604d759b52309abc6c66f38b7d7ef447480de91f
[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 = 'https://%(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         self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
120         ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
121         
122         # see if this file exists
123         try:
124             cred = Credential(filename = ma_cred_filename, subject=self.hrn)
125             self.credential = cred.save_to_string()
126         except IOError:
127             # get self credential
128             self_cred = self.registry.get_credential(None, 'ma', self.hrn)
129             self_credential = Credential(string = self_cred)
130             self_credential.save_to_file(self_cred_filename)
131
132             # get ma credential
133             ma_cred = self.registry.get_credential(self_cred)
134             ma_credential = Credential(string = ma_cred)
135             ma_credential.save_to_file(ma_cred_filename)
136             self.credential = ma_cred
137
138     def hostname_to_hrn(self, login_base, hostname):
139         """
140         Convert hrn to plantelab name.
141         """
142         genihostname = "_".join(hostname.split("."))
143         return ".".join([self.hrn, login_base, genihostname])
144
145     def slicename_to_hrn(self, slicename):
146         """
147         Convert hrn to planetlab name.
148         """
149         slicename = slicename.replace("_", ".")
150         return ".".join([self.hrn, slicename])
151
152     def refresh_components(self):
153         """
154         Update the cached list of nodes and save in 4 differnt formats
155         (rspec, dns, ip)
156         """
157
158         # get node list in rspec format
159         rspec = Rspec()
160         rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
161         
162         # filter nodes according to policy
163         rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
164         
165         # extract ifspecs from rspec 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         # extract nodespecs from rspec to get dns names
173         hostnames = []
174         nodespecs = rspec.getDictsByTagName('NodeSpec')
175         for nodespec in nodespecs:
176             if nodespec.has_key('name') and nodespec['name']:
177                 hostnames.append(nodespec['name'])
178
179         
180         node_details = {}
181         node_details['rspec'] = rspec.toxml()
182         node_details['ip'] = ips
183         node_details['dns'] = hostnames
184         # save state 
185         self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
186         self.nodes.write()
187
188         
189         # update timestamp and threshold
190         self.timestamp['timestamp'] =  datetime.datetime.now()
191         delta = datetime.timedelta(hours=self.nodes_ttl)
192         self.threshold = self.timestamp['timestamp'] + delta 
193         self.timestamp.write()        
194  
195     def load_components(self):
196         """
197         Read cached list of nodes.
198         """
199         # Read component list from cached file 
200         self.nodes.load()
201         self.timestamp.load() 
202         time_format = "%Y-%m-%d %H:%M:%S"
203         timestamp = self.timestamp['timestamp']
204         self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
205         delta = datetime.timedelta(hours=self.nodes_ttl)
206         self.threshold = self.timestamp['timestamp'] + delta
207
208     def load_policy(self):
209         """
210         Read the list of blacklisted and whitelisted nodes.
211         """
212         self.policy.load()
213
214
215     def getNodes(self, format = 'rspec'):
216         """
217         Return a list of components at this aggregate.
218         """
219         valid_formats = ['rspec', 'hrn', 'dns', 'ip']
220         if not format:
221             format = 'rspec'
222         if format not in valid_formats:
223             raise Exception, "Invalid format specified, must be one of the following: %s" \
224                              % ", ".join(valid_formats)
225         
226         # Reload components list
227         now = datetime.datetime.now()
228         #self.load_components()
229         if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
230             self.refresh_components()
231         elif now < self.threshold and not self.nodes.keys(): 
232             self.load_components()
233         return self.nodes[format]
234     
235     def getSlices(self):
236         """
237         Return a list of instnatiated managed by this slice manager.
238         """
239
240         slices = self.shell.GetSlices(self.auth, {}, ['name'])
241         slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]  
242
243         return slice_hrns
244  
245     def get_rspec(self, hrn, type):
246         """
247         Get resource information from PLC
248         """
249         
250         # Get the required nodes
251         if type in ['aggregate']:
252             nodes = self.shell.GetNodes(self.auth)
253         elif type in ['slice']:
254             slicename = hrn_to_pl_slicename(hrn)
255             slices = self.shell.GetSlices(self.auth, [slicename])
256             node_ids = slices[0]['node_ids']
257             nodes = self.shell.GetNodes(self.auth, node_ids) 
258         
259         # Filter out whitelisted nodes
260         public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
261         nodes = filter(public_nodes, nodes)
262  
263         # Get all network interfaces
264         interface_ids = []
265         for node in nodes:
266             interface_ids.extend(node['nodenetwork_ids'])
267         interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
268         interface_dict = {}
269         for interface in interfaces:
270             interface_dict[interface['nodenetwork_id']] = interface
271         
272         # join nodes with thier interfaces
273         for node in nodes:
274             node['interfaces'] = []
275             for nodenetwork_id in node['nodenetwork_ids']:
276                 node['interfaces'].append(interface_dict[nodenetwork_id])
277
278         # convert and threshold to ints
279         if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
280             timestamp = self.timestamp['timestamp']
281             threshold = self.threshold
282         else:
283             timestamp = datetime.datetime.now()
284             delta = datetime.timedelta(hours=self.nodes_ttl)
285             threshold = timestamp + delta        
286
287     
288         start_time = int(timestamp.strftime("%s"))
289         end_time = int(threshold.strftime("%s"))
290         duration = end_time - start_time
291
292         # create the plc dict
293         networks = [{'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}] 
294         resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
295
296         # convert the plc dict to an rspec dict
297         resourceDict = RspecDict(resources)
298         # convert the rspec dict to xml
299         rspec = Rspec()
300         rspec.parseDict(resourceDict)
301         return rspec.toxml()
302
303     def getResources(self, slice_hrn):
304         """
305         Return the current rspec for the specified slice.
306         """
307         rspec = self.get_rspec(slice_hrn, 'slice')
308         
309         return rspec
310  
311     
312     def getTicket(self, hrn, rspec):
313         """
314         Retrieve a ticket. This operation is currently implemented on PLC
315         only (see SFA, engineering decisions); it is not implemented on
316         components.
317
318         @param name name of the slice to retrieve a ticket for
319         @param rspec resource specification dictionary
320         @return the string representation of a ticket object
321         """
322         #self.registry.get_ticket(name, rspec)
323
324         return         
325
326
327     def createSlice(self, slice_hrn, rspec, attributes = []):
328         """
329         Instantiate the specified slice according to whats defined in the rspec.
330         """
331         
332         spec = Rspec(rspec)
333         # save slice state locally
334         # we can assume that spec object has been validated so its safer to
335         # save this instead of the unvalidated rspec the user gave us
336         self.slices[slice_hrn] = spec.toxml()
337         self.slices.write()
338         
339         # Get slice info
340         slicename = hrn_to_pl_slicename(slice_hrn)
341         slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
342         if not slices:
343             raise RecordNotFound(slice_hrn)
344         slice = slices[0]
345
346         # find out where this slice is currently running
347         nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
348         hostnames = [node['hostname'] for node in nodelist]
349
350         # get netspec details
351         nodespecs = spec.getDictsByTagName('NodeSpec')
352         nodes = []
353         for nodespec in nodespecs:
354             if isinstance(nodespec['name'], list):
355                 nodes.extend(nodespec['name'])
356             elif isinstance(nodespec['name'], StringTypes):
357                 nodes.append(nodespec['name'])
358                 
359         # save slice state locally
360         # we can assume that spec object has been validated so its safer to 
361         # save this instead of the unvalidated rspec the user gave us
362         self.slices[slice_hrn] = spec.toxml()
363         self.slices.write()
364
365         # remove nodes not in rspec
366         deleted_nodes = list(set(hostnames).difference(nodes))
367         # add nodes from rspec
368         added_nodes = list(set(nodes).difference(hostnames))
369     
370         self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
371         self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
372
373         for attribute in attributes:
374             type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
375             self.shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
376     
377         # contact registry to get slice users and add them to the slice
378         #slice_record = self.registry.resolve(self.credential, slice_hrn)
379         # persons = slice_record['users']
380         # for perosn in persons:
381         #    shell.AddPersonToSlice(person['email'], slice_name)
382         return 1
383
384     def updateSlice(self, slice_hrn, rspec, attributes = []):
385         return self.create_slice(slice_hrn, rspec, attributes)
386          
387     def deleteSlice(self, slice_hrn):
388         """
389         Remove this slice from all components it was previouly associated with and 
390         free up the resources it was using.
391         """
392         if self.slices.has_key(slice_hrn):
393             self.slices.pop(slice_hrn)
394             self.slices.write()
395
396         slicename = hrn_to_pl_slicename(slice_hrn)
397         slices = self.shell.GetSlices(self.auth, [slicename])
398         if not slices:
399             return 1  
400         slice = slices[0]
401       
402         self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
403         return 1
404
405     def startSlice(self, slice_hrn):
406         """
407         Stop the slice at plc.
408         """
409         slicename = hrn_to_pl_slicename(slice_hrn)
410         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
411         if not slices:
412             #raise RecordNotFound(slice_hrn)
413             return 1 
414         slice_id = slices[0]
415         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
416         attribute_id = attreibutes[0] 
417         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
418         return 1
419
420     def stopSlice(self, slice_hrn):
421         """
422         Stop the slice at plc
423         """
424         slicename = hrn_to_pl_slicename(slice_hrn)
425         slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
426         if not slices:
427             #raise RecordNotFound(slice_hrn)
428             return 1
429         slice_id = slices[0]
430         atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
431         attribute_id = attreibutes[0]
432         self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
433         return 1
434
435
436     def resetSlice(self, slice_hrn):
437         """
438         Reset the slice
439         """
440         # XX not yet implemented
441         return 1
442
443     def getPolicy(self):
444         """
445         Return this aggregates policy.
446         """
447     
448         return self.policy
449         
450     
451
452 ##############################
453 ## Server methods here for now
454 ##############################
455
456
457     # XX fix rights, should be function name defined in 
458     # privilege_table (from util/rights.py)
459     def list_nodes(self, cred):
460         self.decode_authentication(cred, 'listnodes')
461         return self.getNodes()
462
463     def list_slices(self, cred):
464         self.decode_authentication(cred, 'listslices')
465         return self.getSlices()
466
467     def get_resources(self, cred, hrn):
468         self.decode_authentication(cred, 'listnodes')
469         return self.getResources(hrn)
470
471     def get_ticket(self, cred, hrn, rspec):
472         self.decode_authentication(cred, 'getticket')
473         return self.getTicket(hrn, rspec)
474  
475     def get_policy(self, cred):
476         self.decode_authentication(cred, 'getpolicy')
477         return self.getPolicy()
478
479     def create_slice(self, cred, hrn, rspec):
480         self.decode_authentication(cred, 'createslice')
481         return self.createSlice(hrn, rspec)
482
483     def update_slice(self, cred, hrn, rspec):
484         self.decode_authentication(cred, 'updateslice')
485         return self.updateSlice(hrn)    
486
487     def delete_slice(self, cred, hrn):
488         self.decode_authentication(cred, 'deleteslice')
489         return self.deleteSlice(hrn)
490
491     def start_slice(self, cred, hrn):
492         self.decode_authentication(cred, 'startslice')
493         return self.startSlice(hrn)
494
495     def stop_slice(self, cred, hrn):
496         self.decode_authentication(cred, 'stopslice')
497         return self.stopSlice(hrn)
498
499     def reset_slice(self, cred, hrn):
500         self.decode_authentication(cred, 'resetslice')
501         return self.resetSlice(hrn)
502
503     def register_functions(self):
504         GeniServer.register_functions(self)
505
506         # Aggregate interface methods
507         self.server.register_function(self.list_nodes)
508         self.server.register_function(self.list_slices)
509         self.server.register_function(self.get_resources)
510         self.server.register_function(self.get_policy)
511         self.server.register_function(self.create_slice)
512         self.server.register_function(self.update_slice)
513         self.server.register_function(self.delete_slice)
514         self.server.register_function(self.start_slice)
515         self.server.register_function(self.stop_slice)
516         self.server.register_function(self.reset_slice)
517