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