fail silently
[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 at ple, 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                 #    print site_id, peer, remote_site_id
191                 #    self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
192             else:
193                 site = sites[0]
194             
195             # create slice object
196             slice_fields = {}
197             slice_keys = ['name', 'url', 'description']
198             for key in slice_keys:
199                 if key in slice_record and slice_record[key]:
200                     slice_fields[key] = slice_record[key]
201
202             # add the slice  
203             slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
204             slice = slice_fields
205             
206             #this belongs to a peer
207             #if peer:
208             #    self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
209             slice['node_ids'] = 0
210         else:
211             slice = slices[0]    
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                 key_ids = persons[0]['key_ids']
243
244             self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)        
245             # Get this users local keys
246             keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key'])
247             keys = [key['key'] for key in keylist]
248
249             # add keys that arent already there 
250             for personkey in person_dict['keys']:
251                 if personkey not in keys:
252                     key = {'key_type': 'ssh', 'key': personkey}
253                     #if peer:
254                         # XX Need to get the key_id from remote registry somehow 
255                         #self.api.plshell.BindObjectToPeer(self.api.plauth, 'key', None, peer, key_id)   
256                         #pass
257                     self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
258
259         # find out where this slice is currently running
260         nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
261         hostnames = [node['hostname'] for node in nodelist]
262
263         # get netspec details
264         nodespecs = spec.getDictsByTagName('NodeSpec')
265         nodes = []
266         for nodespec in nodespecs:
267             if isinstance(nodespec['name'], list):
268                 nodes.extend(nodespec['name'])
269             elif isinstance(nodespec['name'], StringTypes):
270                 nodes.append(nodespec['name'])
271
272         # remove nodes not in rspec
273         deleted_nodes = list(set(hostnames).difference(nodes))
274         # add nodes from rspec
275         added_nodes = list(set(nodes).difference(hostnames))
276
277         self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes) 
278         self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
279
280         return 1
281
282     def create_slice_smgr(self, hrn, rspec):
283         spec = Rspec()
284         tempspec = Rspec()
285         spec.parseString(rspec)
286         slicename = hrn_to_pl_slicename(hrn)
287         specDict = spec.toDict()
288         if specDict.has_key('Rspec'): specDict = specDict['Rspec']
289         if specDict.has_key('start_time'): start_time = specDict['start_time']
290         else: start_time = 0
291         if specDict.has_key('end_time'): end_time = specDict['end_time']
292         else: end_time = 0
293
294         rspecs = {}
295         aggregates = Aggregates(self.api)
296         credential = self.api.getCredential()
297         # only attempt to extract information about the aggregates we know about
298         for aggregate in aggregates:
299             netspec = spec.getDictByTagNameValue('NetSpec', aggregate)
300             if netspec:
301                 # creat a plc dict 
302                 resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
303                 resourceDict = {'Rspec': resources}
304                 tempspec.parseDict(resourceDict)
305                 rspecs[aggregate] = tempspec.toxml()
306
307         # notify the aggregates
308         for aggregate in rspecs.keys():
309             try:
310                 # send the whloe rspec to the local aggregate
311                 if aggregate in [self.api.hrn]:
312                     aggregates[aggregate].create_slice(credential, hrn, rspec)
313                 else:
314                     aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
315             except:
316                 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
317         return 1
318
319
320     def start_slice(self, hrn):
321         if self.api.interface in ['aggregate']:
322             self.start_slice_aggregate(hrn)
323         elif self.api.interface in ['slicemgr']:
324             self.start_slice_smgr(hrn)
325
326     def start_slice_aggregate(self, hrn):
327         slicename = hrn_to_pl_slicename(hrn)
328         slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
329         if not slices:
330             raise RecordNotFound(hrn)
331         slice_id = slices[0]
332         attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
333         attribute_id = attreibutes[0]['slice_attribute_id']
334         self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
335         return 1
336
337     def start_slice_smgr(self, hrn):
338         credential = self.api.getCredential()
339         aggregates = Aggregates(self.api)
340         for aggregate in aggregates:
341             aggregates[aggregate].start_slice(credential, hrn)
342         return 1
343
344
345     def stop_slice(self, hrn):
346         if self.api.interface in ['aggregate']:
347             self.stop_slice_aggregate(hrn)
348         elif self.api.interface in ['slicemgr']:
349             self.stop_slice_smgr(hrn)
350
351     def stop_slice_aggregate(self, hrn):
352         slicename = hrn_to_pl_slicename(hrn)
353         slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
354         if not slices:
355             raise RecordNotFound(hrn)
356         slice_id = slices[0]['slice_id']
357         attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
358         attribute_id = attributes[0]['slice_attribute_id']
359         self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
360         return 1
361
362     def stop_slice_smgr(self, hrn):
363         credential = self.api.getCredential()
364         aggregates = Aggregates(self.api)
365         for aggregate in aggregates:
366             aggregates[aggregate].stop_slice(credential, hrn)  
367