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