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):
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)
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
41 # get this slice's authority (site)
42 slice_authority = get_authority(hrn)
44 # get this site's authority (sfa root authority or sub authority)
45 site_authority = get_authority(slice_authority).lower()
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']
58 Update the cached list of slices
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()
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]
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)
80 slice_details = {'hrn': slice_hrns,
81 'timestamp': hr_timestamp,
82 'threshold': hr_threshold
84 self.update(slice_details)
88 def refresh_slices_smgr(self):
90 aggregates = Aggregates(self.api)
91 credential = self.api.getCredential()
92 for aggregate in aggregates:
94 slices = aggregates[aggregate].get_slices(credential)
95 slice_hrns.extend(slices)
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)
105 slice_details = {'hrn': slice_hrns,
106 'timestamp': hr_timestamp,
107 'threshold': hr_threshold
109 self.update(slice_details)
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)
119 def delete_slice_aggregate(self, hrn):
121 slicename = hrn_to_pl_slicename(hrn)
122 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename})
127 # determine if this is a peer slice
128 peer = self.get_peer(hrn)
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'])
133 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice['slice_id'], peer, slice['peer_slice_id'])
136 def delete_slice_smgr(self, hrn):
137 credential = self.api.getCredential()
138 aggregates = Aggregates(self.api)
139 for aggregate in aggregates:
141 aggregates[aggregate].delete_slice(credential, hrn)
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
148 def create_slice(self, hrn, rspec):
150 # check our slice policy before we procede
151 whitelist = self.policy['slice_whitelist']
152 blacklist = self.policy['slice_blacklist']
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()
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)
165 def create_slice_aggregate(self, hrn, rspec):
167 # Determine if this is a peer slice
168 peer = self.get_peer(hrn)
171 # Get the slice record from geni
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()
182 raise RecordNotFound(hrn)
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'])
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])
193 authority = get_authority(hrn)
194 site_records = registry.resolve(credential, authority)
197 raise RecordNotFound(authority)
198 site_record = site_records[0]
199 site = site_record.as_dict()
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
206 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
210 # create slice object
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]
218 slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
221 #this belongs to a peer
223 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
224 slice['node_ids'] = []
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:
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:
239 person_dict = person_record.as_dict()
240 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
242 # Create the person record
244 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
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.
253 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
255 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
258 person_id = persons[0]['person_id']
259 key_ids = persons[0]['key_ids']
261 # if this is a peer person, we must unbind them from the peer or PLCAPI will throw
264 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
265 self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
267 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
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]
273 # add keys that arent already there
274 key_ids=person_record['key_ids']
275 for personkey in person_dict['keys']:
276 if personkey not in keys:
277 key = {'key_type': 'ssh', 'key': personkey}
279 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
280 key_id=self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
282 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
283 self.api.plshell.BindObjectToPeer(self.api.plauth, 'key', key_id, peer, key_ids.pop(0))
285 # find out where this slice is currently running
286 nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
287 hostnames = [node['hostname'] for node in nodelist]
289 # get netspec details
290 nodespecs = spec.getDictsByTagName('NodeSpec')
292 for nodespec in nodespecs:
293 if isinstance(nodespec['name'], list):
294 nodes.extend(nodespec['name'])
295 elif isinstance(nodespec['name'], StringTypes):
296 nodes.append(nodespec['name'])
298 # remove nodes not in rspec
299 deleted_nodes = list(set(hostnames).difference(nodes))
300 # add nodes from rspec
301 added_nodes = list(set(nodes).difference(hostnames))
304 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'slice', slice_id, peer)
305 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
306 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
308 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
312 def create_slice_smgr(self, hrn, rspec):
315 spec.parseString(rspec)
316 slicename = hrn_to_pl_slicename(hrn)
317 specDict = spec.toDict()
318 if specDict.has_key('Rspec'): specDict = specDict['Rspec']
319 if specDict.has_key('start_time'): start_time = specDict['start_time']
321 if specDict.has_key('end_time'): end_time = specDict['end_time']
325 aggregates = Aggregates(self.api)
326 credential = self.api.getCredential()
327 # only attempt to extract information about the aggregates we know about
328 for aggregate in aggregates:
329 netspec = spec.getDictByTagNameValue('NetSpec', aggregate)
332 resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
333 resourceDict = {'Rspec': resources}
334 tempspec.parseDict(resourceDict)
335 rspecs[aggregate] = tempspec.toxml()
337 # notify the aggregates
338 for aggregate in rspecs.keys():
340 # send the whloe rspec to the local aggregate
341 if aggregate in [self.api.hrn]:
342 aggregates[aggregate].create_slice(credential, hrn, rspec)
344 aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
346 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
347 traceback.print_exc()
351 def start_slice(self, hrn):
352 if self.api.interface in ['aggregate']:
353 self.start_slice_aggregate(hrn)
354 elif self.api.interface in ['slicemgr']:
355 self.start_slice_smgr(hrn)
357 def start_slice_aggregate(self, hrn):
358 slicename = hrn_to_pl_slicename(hrn)
359 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
361 raise RecordNotFound(hrn)
363 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
364 attribute_id = attreibutes[0]['slice_attribute_id']
365 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
368 def start_slice_smgr(self, hrn):
369 credential = self.api.getCredential()
370 aggregates = Aggregates(self.api)
371 for aggregate in aggregates:
372 aggregates[aggregate].start_slice(credential, hrn)
376 def stop_slice(self, hrn):
377 if self.api.interface in ['aggregate']:
378 self.stop_slice_aggregate(hrn)
379 elif self.api.interface in ['slicemgr']:
380 self.stop_slice_smgr(hrn)
382 def stop_slice_aggregate(self, hrn):
383 slicename = hrn_to_pl_slicename(hrn)
384 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
386 raise RecordNotFound(hrn)
387 slice_id = slices[0]['slice_id']
388 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
389 attribute_id = attributes[0]['slice_attribute_id']
390 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
393 def stop_slice_smgr(self, hrn):
394 credential = self.api.getCredential()
395 aggregates = Aggregates(self.api)
396 for aggregate in aggregates:
397 aggregates[aggregate].stop_slice(credential, hrn)