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
21 class Slices(SimpleStorage):
23 def __init__(self, api, ttl = .5, caller_cred=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)
34 self.caller_cred=caller_cred
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
43 # get this slice's authority (site)
44 slice_authority = get_authority(hrn)
46 # get this site's authority (sfa root authority or sub authority)
47 site_authority = get_authority(slice_authority).lower()
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']
58 def get_sfa_peer(self, hrn):
59 # return the authority for this hrn or None if we are the authority
61 slice_authority = get_authority(hrn)
62 site_authority = get_authority(slice_authority)
64 if site_authority != self.api.hrn:
65 sfa_peer = site_authority
71 Update the cached list of slices
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()
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]
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)
93 slice_details = {'hrn': slice_hrns,
94 'timestamp': hr_timestamp,
95 'threshold': hr_threshold
97 self.update(slice_details)
101 def refresh_slices_smgr(self):
103 aggregates = Aggregates(self.api)
104 credential = self.api.getCredential()
105 for aggregate in aggregates:
107 slices = aggregates[aggregate].get_slices(credential)
108 slice_hrns.extend(slices)
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)
118 slice_details = {'hrn': slice_hrns,
119 'timestamp': hr_timestamp,
120 'threshold': hr_threshold
122 self.update(slice_details)
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)
132 def delete_slice_aggregate(self, hrn):
134 slicename = hrn_to_pl_slicename(hrn)
135 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename})
140 # determine if this is a peer slice
141 peer = self.get_peer(hrn)
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'])
146 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
149 def delete_slice_smgr(self, hrn):
150 credential = self.api.getCredential()
151 aggregates = Aggregates(self.api)
152 for aggregate in aggregates:
154 aggregates[aggregate].delete_slice(credential, hrn, caller_cred=self.caller_cred)
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
161 def create_slice(self, hrn, rspec):
163 # check our slice policy before we procede
164 whitelist = self.policy['slice_whitelist']
165 blacklist = self.policy['slice_blacklist']
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()
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)
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)
182 for site_record in site_records:
183 if site_record['type'] == 'authority':
184 site = site_record.as_dict()
186 raise RecordNotFound(authority)
187 remote_site_id = site.pop('site_id')
189 login_base = get_leaf(authority)
190 sites = self.api.plshell.GetSites(self.api.plauth, login_base)
192 site_id = self.api.plshell.AddSite(self.api.plauth, site)
194 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
195 # mark this site as an sfa peer record
197 #regsitry.register_peer(credential, authority, 'authority', sfa_peer)
200 site_id = sites[0]['site_id']
201 remote_site_id = sites[0]['peer_site_id']
204 return (site_id, remote_site_id)
206 def verify_slice(self, registry, credential, slice_hrn, site_id, remote_site_id, peer, sfa_peer):
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
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'])
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]
228 slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
230 slice['slice_id'] = slice_id
232 # mark this slice as an sfa peer record
234 #registry.register_peer(credential, slice_hrn, 'slice', authority)
237 #this belongs to a peer
239 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
240 slice['node_ids'] = []
243 slice_id = slice['slice_id']
244 site_id = slice['site_id']
246 slice['peer_slice_id'] = slice_record['pointer']
247 self.verify_persons(registry, credential, slice_record, site_id, remote_site_id, peer, sfa_peer)
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:
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:
264 person_dict = person_record.as_dict()
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'])
270 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
273 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
274 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
276 # mark this person as an sfa peer record
278 #registry.register_peer(credential, researcher, 'user', authority)
282 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
285 person_id = persons[0]['person_id']
286 key_ids = persons[0]['key_ids']
289 # if this is a peer person, we must unbind them from the peer or PLCAPI will throw
292 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
293 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'site', site_id, peer)
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)
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)
301 self.verify_keys(registry, credential, person_dict, key_ids, person_id, peer)
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]
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}
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)
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))
321 def create_slice_aggregate(self, hrn, rspec):
323 # Determine if this is a peer slice
324 peer = self.get_peer(hrn)
325 sfa_peer = self.get_sfa_peer(hrn)
328 # Get the slice record from sfa
329 slicename = hrn_to_pl_slicename(hrn)
332 registries = Registries(self.api)
333 registry = registries[self.api.hrn]
334 credential = self.api.getCredential()
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)
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]
343 # get netspec details
344 nodespecs = spec.getDictsByTagName('NodeSpec')
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'])
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))
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)
362 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
366 def create_slice_smgr(self, hrn, 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']
375 if specDict.has_key('end_time'): end_time = specDict['end_time']
379 aggregates = Aggregates(self.api)
380 credential = self.api.getCredential()
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()
391 # send each rspec to the appropriate aggregate/sm
392 for net_hrn in rspecs:
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)
401 aggregates[net_hrn].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
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)
407 aggregates[aggregate].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
410 print >> log, "Error creating slice %(hrn)s at aggregate %(net_hrn)s" % locals()
411 traceback.print_exc()
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)
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'])
425 raise RecordNotFound(hrn)
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" )
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)
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)
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'])
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")
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)