reorganized code
[sfa.git] / sfa / plc / slices.py
1 ### $Id$
2 ### $URL$
3
4 import datetime
5 import time
6 import traceback
7 import sys
8
9 from types import StringTypes
10 from sfa.util.misc import *
11 from sfa.util.rspec import *
12 from sfa.util.specdict import *
13 from sfa.util.faults import *
14 from sfa.util.storage import *
15 from sfa.util.policy import Policy
16 from sfa.util.prefixTree import prefixTree
17 from sfa.util.debug import log
18 from sfa.server.aggregate import Aggregates
19 from sfa.server.registry import Registries
20
21 class Slices(SimpleStorage):
22
23     def __init__(self, api, ttl = .5, caller_cred=None):
24         self.api = api
25         self.ttl = ttl
26         self.threshold = None
27         path = self.api.config.SFA_BASE_DIR
28         filename = ".".join([self.api.interface, self.api.hrn, "slices"])
29         filepath = path + os.sep + filename
30         self.slices_file = filepath
31         SimpleStorage.__init__(self, self.slices_file)
32         self.policy = Policy(self.api)    
33         self.load()
34         self.caller_cred=caller_cred
35
36
37     def get_peer(self, hrn):
38         # Becaues of myplc federation,  we first need to determine if this
39         # slice belongs to out local plc or a myplc peer. We will assume it 
40         # is a local site, unless we find out otherwise  
41         peer = None
42
43         # get this slice's authority (site)
44         slice_authority = get_authority(hrn)
45
46         # get this site's authority (sfa root authority or sub authority)
47         site_authority = get_authority(slice_authority).lower()
48
49         # check if we are already peered with this site_authority, if so
50         peers = self.api.plshell.GetPeers(self.api.plauth, {}, ['peer_id', 'peername', 'shortname', 'hrn_root'])
51         for peer_record in peers:
52             names = [name.lower() for name in peer_record.values() if isinstance(name, StringTypes)]
53             if site_authority in names:
54                 peer = peer_record['shortname']
55
56         return peer
57
58     def get_sfa_peer(self, hrn):
59         # return the authority for this hrn or None if we are the authority
60         sfa_peer = None
61         slice_authority = get_authority(hrn)
62         site_authority = get_authority(slice_authority)
63
64         if site_authority != self.api.hrn:
65             sfa_peer = site_authority
66
67         return sfa_peer 
68
69     def refresh(self):
70         """
71         Update the cached list of slices
72         """
73         # Reload components list
74         now = datetime.datetime.now()
75         if not self.has_key('threshold') or not self.has_key('timestamp') or \
76            now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))):
77             if self.api.interface in ['aggregate']:
78                 self.refresh_slices_aggregate()
79             elif self.api.interface in ['slicemgr']:
80                 self.refresh_slices_smgr()
81
82     def refresh_slices_aggregate(self):
83         slices = self.api.plshell.GetSlices(self.api.plauth, {'peer_id': None}, ['name'])
84         slice_hrns = [slicename_to_hrn(self.api.hrn, slice['name']) for slice in slices]
85
86          # update timestamp and threshold
87         timestamp = datetime.datetime.now()
88         hr_timestamp = timestamp.strftime(self.api.time_format)
89         delta = datetime.timedelta(hours=self.ttl)
90         threshold = timestamp + delta
91         hr_threshold = threshold.strftime(self.api.time_format)
92         
93         slice_details = {'hrn': slice_hrns,
94                          'timestamp': hr_timestamp,
95                          'threshold': hr_threshold
96                         }
97         self.update(slice_details)
98         self.write()     
99         
100
101     def refresh_slices_smgr(self):
102         slice_hrns = []
103         aggregates = Aggregates(self.api)
104         credential = self.api.getCredential()
105         for aggregate in aggregates:
106             try:
107                 slices = aggregates[aggregate].get_slices(credential)
108                 slice_hrns.extend(slices)
109             except:
110                 print >> log, "Error calling slices at aggregate %(aggregate)s" % locals()
111          # update timestamp and threshold
112         timestamp = datetime.datetime.now()
113         hr_timestamp = timestamp.strftime(self.api.time_format)
114         delta = datetime.timedelta(hours=self.ttl)
115         threshold = timestamp + delta
116         hr_threshold = threshold.strftime(self.api.time_format)
117
118         slice_details = {'hrn': slice_hrns,
119                          'timestamp': hr_timestamp,
120                          'threshold': hr_threshold
121                         }
122         self.update(slice_details)
123         self.write()
124
125
126     def delete_slice(self, hrn):
127         if self.api.interface in ['aggregate']:
128             self.delete_slice_aggregate(hrn)
129         elif self.api.interface in ['slicemgr']:
130             self.delete_slice_smgr(hrn)
131         
132     def delete_slice_aggregate(self, hrn):
133
134         slicename = hrn_to_pl_slicename(hrn)
135         slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename})
136         if not slices:
137             return 1        
138         slice = slices[0]
139
140         # determine if this is a peer slice
141         peer = self.get_peer(hrn)
142         if peer:
143             self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice['slice_id'], peer)
144         self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, slice['node_ids'])
145         if peer:
146             self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
147         return 1
148
149     def delete_slice_smgr(self, hrn):
150         credential = self.api.getCredential()
151         aggregates = Aggregates(self.api)
152         for aggregate in aggregates:
153             try:
154                 aggregates[aggregate].delete_slice(credential, hrn, caller_cred=self.caller_cred)
155             except:
156                 print >> log, "Error calling list nodes at aggregate %s" % aggregate
157                 traceback.print_exc(log)
158                 exc_type, exc_value, exc_traceback = sys.exc_info()
159                 print exc_type, exc_value, exc_traceback
160
161     def create_slice(self, hrn, rspec):
162         
163         # check our slice policy before we procede
164         whitelist = self.policy['slice_whitelist']     
165         blacklist = self.policy['slice_blacklist']
166        
167         if whitelist and hrn not in whitelist or \
168            blacklist and hrn in blacklist:
169             policy_file = self.policy.policy_file
170             print >> log, "Slice %(hrn)s not allowed by policy %(policy_file)s" % locals()
171             return 1
172
173         if self.api.interface in ['aggregate']:     
174             self.create_slice_aggregate(hrn, rspec)
175         elif self.api.interface in ['slicemgr']:
176             self.create_slice_smgr(hrn, rspec)
177
178     def verify_site(self, registry, credential, slice_hrn, peer, sfa_peer):
179         authority = get_authority(slice_hrn)
180         site_records = registry.resolve(credential, authority)
181         site = {}
182         for site_record in site_records:
183             if site_record['type'] == 'authority':
184                 site = site_record.as_dict()
185         if not site:
186             raise RecordNotFound(authority)
187         remote_site_id = site.pop('site_id')    
188                 
189         login_base = get_leaf(authority)
190         sites = self.api.plshell.GetSites(self.api.plauth, login_base)
191         if not sites:
192             site_id = self.api.plshell.AddSite(self.api.plauth, site)
193             if peer:
194                 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)   
195             # mark this site as an sfa peer record
196             if sfa_peer:
197                 #regsitry.register_peer(credential, authority, 'authority', sfa_peer)
198                 pass
199         else:
200             site_id = sites[0]['site_id']
201             remote_site_id = sites[0]['peer_site_id']
202
203
204         return (site_id, remote_site_id) 
205
206     def verify_slice(self, registry, credential, slice_hrn, site_id, remote_site_id, peer, sfa_peer):
207         slice = {}
208         slice_record = None
209         authority = get_authority(slice_hrn)
210         slice_records = registry.resolve(credential, slice_hrn)
211         for record in slice_records:
212             if record['type'] in ['slice']:
213                 slice_record = record
214         if not slice_record:
215             raise RecordNotFound(hrn)
216         slicename = hrn_to_pl_slicename(slice_hrn)
217         parts = slicename.split("_")
218         login_base = parts[0]
219         slices = self.api.plshell.GetSlices(self.api.plauth, [slicename], ['slice_id', 'node_ids', 'site_id']) 
220         if not slices:
221             slice_fields = {}
222             slice_keys = ['name', 'url', 'description']
223             for key in slice_keys:
224                 if key in slice_record and slice_record[key]:
225                     slice_fields[key] = slice_record[key]
226
227             # add the slice  
228             slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
229             slice = slice_fields
230             slice['slice_id'] = slice_id
231
232             # mark this slice as an sfa peer record
233             if sfa_peer:
234                 #registry.register_peer(credential, slice_hrn, 'slice', authority)
235                 pass
236
237             #this belongs to a peer
238             if peer:
239                 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
240             slice['node_ids'] = []
241         else:
242             slice = slices[0]
243             slice_id = slice['slice_id']
244             site_id = slice['site_id']
245
246         slice['peer_slice_id'] = slice_record['pointer']
247         self.verify_persons(registry, credential, slice_record, site_id, remote_site_id, peer, sfa_peer)
248     
249         return slice        
250
251     def verify_persons(self, registry, credential, slice_record, site_id, remote_site_id, peer, sfa_peer):
252         # get the list of valid slice users from the registry and make 
253         # sure they are added to the slice 
254         slicename = hrn_to_pl_slicename(slice_record['hrn'])
255         researchers = slice_record.get('researcher', [])
256         for researcher in researchers:
257             person_record = {}
258             person_records = registry.resolve(credential, researcher)
259             for record in person_records:
260                 if record['type'] in ['user']:
261                     person_record = record
262             if not person_record:
263                 pass
264             person_dict = person_record.as_dict()
265             if peer:
266                 peer_id = self.api.plshell.GetPeers(self.api.plauth, {'shortname': peer}, ['peer_id'])[0]['peer_id']
267                 persons = self.api.plshell.GetPersons(self.api.plauth, {'email': [person_dict['email']], 'peer_id': peer_id}, ['person_id', 'key_ids'])
268
269             else:
270                 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])   
271         
272             if not persons:
273                 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
274                 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
275                 
276                 # mark this person as an sfa peer record
277                 if sfa_peer:
278                     #registry.register_peer(credential, researcher, 'user', authority)
279                     pass
280
281                 if peer:
282                     self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
283                 key_ids = []
284             else:
285                 person_id = persons[0]['person_id']
286                 key_ids = persons[0]['key_ids']
287
288
289             # if this is a peer person, we must unbind them from the peer or PLCAPI will throw
290             # an error
291             if peer:
292                 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
293                 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'site', site_id,  peer)
294
295             self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
296             self.api.plshell.AddPersonToSite(self.api.plauth, person_dict['email'], site_id)
297             if peer:
298                 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
299                 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
300             
301             self.verify_keys(registry, credential, person_dict, key_ids, person_id, peer)
302
303     def verify_keys(self, registry, credential, person_dict, key_ids, person_id,  peer):
304         keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key'])
305         keys = [key['key'] for key in keylist]
306         
307         #add keys that arent already there
308         key_ids = person_dict['key_ids']
309         for personkey in person_dict['keys']:
310             if personkey not in keys:
311                 key = {'key_type': 'ssh', 'key': personkey}
312                 if peer:
313                     self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
314                 key_id = self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
315                 if peer:
316                     self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
317                     try: self.api.plshell.BindObjectToPeer(self.api.plauth, 'key', key_id, peer, key_ids.pop(0))
318
319                     except: pass   
320
321     def create_slice_aggregate(self, hrn, rspec):
322
323         # Determine if this is a peer slice
324         peer = self.get_peer(hrn)
325         sfa_peer = self.get_sfa_peer(hrn)
326
327         spec = Rspec(rspec)
328         # Get the slice record from sfa
329         slicename = hrn_to_pl_slicename(hrn) 
330         slice = {}
331         slice_record = None
332         registries = Registries(self.api)
333         registry = registries[self.api.hrn]
334         credential = self.api.getCredential()
335
336         site_id, remote_site_id = self.verify_site(registry, credential, hrn, peer, sfa_peer)
337         slice = self.verify_slice(registry, credential, hrn, site_id, remote_site_id, peer, sfa_peer)
338
339         # find out where this slice is currently running
340         nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
341         hostnames = [node['hostname'] for node in nodelist]
342
343         # get netspec details
344         nodespecs = spec.getDictsByTagName('NodeSpec')
345         nodes = []
346         for nodespec in nodespecs:
347             if isinstance(nodespec['name'], list):
348                 nodes.extend(nodespec['name'])
349             elif isinstance(nodespec['name'], StringTypes):
350                 nodes.append(nodespec['name'])
351
352         # remove nodes not in rspec
353         deleted_nodes = list(set(hostnames).difference(nodes))
354         # add nodes from rspec
355         added_nodes = list(set(nodes).difference(hostnames))
356
357         if peer:
358             self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice['slice_id'], peer)
359         self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes) 
360         self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
361         if peer:
362             self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
363
364         return 1
365
366     def create_slice_smgr(self, hrn, rspec):
367         spec = Rspec()
368         tempspec = Rspec()
369         spec.parseString(rspec)
370         slicename = hrn_to_pl_slicename(hrn)
371         specDict = spec.toDict()
372         if specDict.has_key('Rspec'): specDict = specDict['Rspec']
373         if specDict.has_key('start_time'): start_time = specDict['start_time']
374         else: start_time = 0
375         if specDict.has_key('end_time'): end_time = specDict['end_time']
376         else: end_time = 0
377
378         rspecs = {}
379         aggregates = Aggregates(self.api)
380         credential = self.api.getCredential()
381
382         # split the netspecs into individual rspecs
383         netspecs = spec.getDictsByTagName('NetSpec')
384         for netspec in netspecs:
385             net_hrn = netspec['name']
386             resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
387             resourceDict = {'Rspec': resources}
388             tempspec.parseDict(resourceDict)
389             rspecs[net_hrn] = tempspec.toxml()
390
391         # send each rspec to the appropriate aggregate/sm 
392         for net_hrn in rspecs:
393             try:
394                 # if we are directly connected to the aggregate then we can just send them the rspec
395                 # if not, then we may be connected to an sm thats connected to the aggregate  
396                 if net_hrn in aggregates:
397                     # send the whloe rspec to the local aggregate
398                     if net_hrn in [self.api.hrn]:
399                         aggregates[net_hrn].create_slice(credential, hrn, rspec, caller_cred=self.caller_cred)
400                     else:
401                         aggregates[net_hrn].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
402                 else:
403                     # lets forward this rspec to a sm that knows about the network    
404                     for aggregate in aggregates:
405                         network_found = aggregates[aggregate].get_aggregates(credential, net_hrn)
406                         if network_networks:
407                             aggregates[aggregate].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
408                      
409             except:
410                 print >> log, "Error creating slice %(hrn)s at aggregate %(net_hrn)s" % locals()
411                 traceback.print_exc()
412         return 1
413
414
415     def start_slice(self, hrn):
416         if self.api.interface in ['aggregate']:
417             self.start_slice_aggregate(hrn)
418         elif self.api.interface in ['slicemgr']:
419             self.start_slice_smgr(hrn)
420
421     def start_slice_aggregate(self, hrn):
422         slicename = hrn_to_pl_slicename(hrn)
423         slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
424         if not slices:
425             raise RecordNotFound(hrn)
426         slice_id = slices[0]
427         attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
428         attribute_id = attreibutes[0]['slice_attribute_id']
429         self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
430         return 1
431
432     def start_slice_smgr(self, hrn):
433         credential = self.api.getCredential()
434         aggregates = Aggregates(self.api)
435         for aggregate in aggregates:
436             aggregates[aggregate].start_slice(credential, hrn)
437         return 1
438
439
440     def stop_slice(self, hrn):
441         if self.api.interface in ['aggregate']:
442             self.stop_slice_aggregate(hrn)
443         elif self.api.interface in ['slicemgr']:
444             self.stop_slice_smgr(hrn)
445
446     def stop_slice_aggregate(self, hrn):
447         slicename = hrn_to_pl_slicename(hrn)
448         slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
449         if not slices:
450             raise RecordNotFound(hrn)
451         slice_id = slices[0]['slice_id']
452         attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
453         attribute_id = attributes[0]['slice_attribute_id']
454         self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
455         return 1
456
457     def stop_slice_smgr(self, hrn):
458         credential = self.api.getCredential()
459         aggregates = Aggregates(self.api)
460         for aggregate in aggregates:
461             aggregates[aggregate].stop_slice(credential, hrn)  
462