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