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
20 class Slices(SimpleStorage):
22 def __init__(self, api, ttl = .5, caller_cred=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)
33 self.caller_cred=caller_cred
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
42 # get this slice's authority (site)
43 slice_authority = get_authority(hrn)
45 # get this site's authority (sfa root authority or sub authority)
46 site_authority = get_authority(slice_authority).lower()
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']
59 Update the cached list of slices
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()
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]
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)
81 slice_details = {'hrn': slice_hrns,
82 'timestamp': hr_timestamp,
83 'threshold': hr_threshold
85 self.update(slice_details)
89 def refresh_slices_smgr(self):
91 aggregates = Aggregates(self.api)
92 credential = self.api.getCredential()
93 for aggregate in aggregates:
95 slices = aggregates[aggregate].get_slices(credential)
96 slice_hrns.extend(slices)
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)
106 slice_details = {'hrn': slice_hrns,
107 'timestamp': hr_timestamp,
108 'threshold': hr_threshold
110 self.update(slice_details)
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)
120 def delete_slice_aggregate(self, hrn):
122 slicename = hrn_to_pl_slicename(hrn)
123 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename})
128 # determine if this is a peer slice
129 peer = self.get_peer(hrn)
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'])
134 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
137 def delete_slice_smgr(self, hrn):
138 credential = self.api.getCredential()
139 aggregates = Aggregates(self.api)
140 for aggregate in aggregates:
142 aggregates[aggregate].delete_slice(credential, hrn, caller_cred=self.caller_cred)
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
149 def create_slice(self, hrn, rspec):
151 # check our slice policy before we procede
152 whitelist = self.policy['slice_whitelist']
153 blacklist = self.policy['slice_blacklist']
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()
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)
166 def create_slice_aggregate(self, hrn, rspec):
168 # Determine if this is a peer slice
169 peer = self.get_peer(hrn)
172 # Get the slice record from sfa
175 registries = Registries(self.api)
176 registry = registries[self.api.hrn]
177 credential = self.api.getCredential()
178 slice_records = registry.resolve(credential, hrn)
179 for record in slice_records:
180 if record.get_type() in ['slice']:
181 slice_record = record.as_dict()
183 raise RecordNotFound(hrn)
185 # Get the slice's site record
186 authority = get_authority(hrn)
187 site_records = registry.resolve(credential, authority)
189 for site_record in site_records:
190 if site_record.get_type() in ['authority']:
191 site = site_record.as_dict()
193 raise RecordNotFound(authority)
194 remote_site_id = site.pop('site_id')
196 # Make sure slice exists at plc, if it doesnt add it
197 slicename = hrn_to_pl_slicename(hrn)
198 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename], ['slice_id', 'node_ids', 'site_id'] )
199 parts = slicename.split("_")
200 login_base = parts[0]
201 # if site doesnt exist add it
202 sites = self.api.plshell.GetSites(self.api.plauth, [login_base])
206 site_id = self.api.plshell.AddSite(self.api.plauth, site)
207 # this belongs to a peer
209 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
211 site_id = sites[0]['site_id']
212 remote_site_id = sites[0]['peer_site_id']
214 # create slice object
216 slice_keys = ['name', 'url', 'description']
217 for key in slice_keys:
218 if key in slice_record and slice_record[key]:
219 slice_fields[key] = slice_record[key]
222 slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
225 #this belongs to a peer
227 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
228 slice['node_ids'] = []
231 slice_id = slice['slice_id']
232 site_id = slice['site_id']
233 remote_site_id = sites[0]['peer_site_id']
234 # get the list of valid slice users from the registry and make
235 # they are added to the slice
236 researchers = record.get('researcher', [])
237 for researcher in researchers:
239 person_records = registry.resolve(credential, researcher)
240 for record in person_records:
241 if record.get_type() in ['user']:
242 person_record = record
243 if not person_record:
245 person_dict = person_record.as_dict()
247 peer_id=self.api.plshell.GetPeers(self.api.plauth, {'shortname' : peer}, ['peer_id'])[0]['peer_id']
248 persons = self.api.plshell.GetPersons(self.api.plauth, {'email' : [person_dict['email']], 'peer_id' : peer_id}, ['person_id', 'key_ids'])
250 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
252 # Create the person record
254 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
256 # The line below enables the user account on the remote
257 # aggregate soon after it is created. without this the
258 # user key is not transfered to the slice (as GetSlivers
259 # returns key of only enabled users), which prevents the
260 # user from login to the slice. We may do additional checks
261 # before enabling the user.
263 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
265 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
268 person_id = persons[0]['person_id']
269 key_ids = persons[0]['key_ids']
271 # if this is a peer person, we must unbind them from the peer or PLCAPI will throw
274 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
275 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'site', site_id, peer)
277 self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
278 self.api.plshell.AddPersonToSite(self.api.plauth, person_dict['email'], site_id)
280 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
281 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
283 # Get this users local keys
284 keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key'])
285 keys = [key['key'] for key in keylist]
287 # add keys that arent already there
288 key_ids=person_dict['key_ids']
289 for personkey in person_dict['keys']:
290 if personkey not in keys:
291 key = {'key_type': 'ssh', 'key': personkey}
293 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
294 key_id=self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
296 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_dict['pointer'])
297 # BindObjectToPeer may faill if type is key and it's already bound to the peer
298 # so lets just put a try/except here
299 try: self.api.plshell.BindObjectToPeer(self.api.plauth, 'key', key_id, peer, key_ids.pop(0))
302 # find out where this slice is currently running
303 nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
304 hostnames = [node['hostname'] for node in nodelist]
306 # get netspec details
307 nodespecs = spec.getDictsByTagName('NodeSpec')
309 for nodespec in nodespecs:
310 if isinstance(nodespec['name'], list):
311 nodes.extend(nodespec['name'])
312 elif isinstance(nodespec['name'], StringTypes):
313 nodes.append(nodespec['name'])
315 # remove nodes not in rspec
316 deleted_nodes = list(set(hostnames).difference(nodes))
317 # add nodes from rspec
318 added_nodes = list(set(nodes).difference(hostnames))
321 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice_id, peer)
322 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
323 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
325 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
329 def create_slice_smgr(self, hrn, rspec):
332 spec.parseString(rspec)
333 slicename = hrn_to_pl_slicename(hrn)
334 specDict = spec.toDict()
335 if specDict.has_key('Rspec'): specDict = specDict['Rspec']
336 if specDict.has_key('start_time'): start_time = specDict['start_time']
338 if specDict.has_key('end_time'): end_time = specDict['end_time']
342 aggregates = Aggregates(self.api)
343 credential = self.api.getCredential()
345 # split the netspecs into individual rspecs
346 netspecs = spec.getDictsByTagName('NetSpec')
347 for netspec in netspecs:
348 net_hrn = netspec['name']
349 resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
350 resourceDict = {'Rspec': resources}
351 tempspec.parseDict(resourceDict)
352 rspecs[net_hrn] = tempspec.toxml()
354 # send each rspec to the appropriate aggregate/sm
355 for net_hrn in rspecs:
357 # if we are directly connected to the aggregate then we can just send them the rspec
358 # if not, then we may be connected to an sm thats connected to the aggregate
359 if net_hrn in aggregates:
360 # send the whloe rspec to the local aggregate
361 if net_hrn in [self.api.hrn]:
362 aggregates[net_hrn].create_slice(credential, hrn, rspec, caller_cred=self.caller_cred)
364 aggregates[net_hrn].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
366 # lets forward this rspec to a sm that knows about the network
367 for aggregate in aggregates:
368 network_found = aggregates[aggregate].get_aggregates(credential, net_hrn)
370 aggregates[aggregate].create_slice(credential, hrn, rspecs[net_hrn], caller_cred=self.caller_cred)
373 print >> log, "Error creating slice %(hrn)s at aggregate %(net_hrn)s" % locals()
374 traceback.print_exc()
378 def start_slice(self, hrn):
379 if self.api.interface in ['aggregate']:
380 self.start_slice_aggregate(hrn)
381 elif self.api.interface in ['slicemgr']:
382 self.start_slice_smgr(hrn)
384 def start_slice_aggregate(self, hrn):
385 slicename = hrn_to_pl_slicename(hrn)
386 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
388 raise RecordNotFound(hrn)
390 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
391 attribute_id = attreibutes[0]['slice_attribute_id']
392 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
395 def start_slice_smgr(self, hrn):
396 credential = self.api.getCredential()
397 aggregates = Aggregates(self.api)
398 for aggregate in aggregates:
399 aggregates[aggregate].start_slice(credential, hrn)
403 def stop_slice(self, hrn):
404 if self.api.interface in ['aggregate']:
405 self.stop_slice_aggregate(hrn)
406 elif self.api.interface in ['slicemgr']:
407 self.stop_slice_smgr(hrn)
409 def stop_slice_aggregate(self, hrn):
410 slicename = hrn_to_pl_slicename(hrn)
411 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
413 raise RecordNotFound(hrn)
414 slice_id = slices[0]['slice_id']
415 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
416 attribute_id = attributes[0]['slice_attribute_id']
417 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
420 def stop_slice_smgr(self, hrn):
421 credential = self.api.getCredential()
422 aggregates = Aggregates(self.api)
423 for aggregate in aggregates:
424 aggregates[aggregate].stop_slice(credential, hrn)