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
19 class Slices(SimpleStorage):
21 def __init__(self, api, ttl = .5):
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)
36 Update the cached list of slices
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()
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]
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)
58 slice_details = {'hrn': slice_hrns,
59 'timestamp': hr_timestamp,
60 'threshold': hr_threshold
62 self.update(slice_details)
66 def refresh_slices_smgr(self):
68 aggregates = Aggregates(self.api)
69 credential = self.api.getCredential()
70 for aggregate in aggregates:
72 slices = aggregates[aggregate].get_slices(credential)
73 slice_hrns.extend(slices)
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)
83 slice_details = {'hrn': slice_hrns,
84 'timestamp': hr_timestamp,
85 'threshold': hr_threshold
87 self.update(slice_details)
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)
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})
104 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, slice['node_ids'])
107 def delete_slice_smgr(self, hrn):
108 credential = self.api.getCredential()
109 aggregates = Aggregates(self.api)
110 for aggregate in aggregates:
112 aggregates[aggregate].delete_slice(credential, hrn)
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
119 def create_slice(self, hrn, rspec):
121 # check our slice policy before we procede
122 whitelist = self.policy['slice_whitelist']
123 blacklist = self.policy['slice_blacklist']
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()
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)
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
142 # get this slice's authority (site)
143 slice_authority = get_authority(hrn)
145 # get this site's authority (sfa root authority or sub authority)
146 site_authority = get_authority(slice_authority)
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']
155 # Get the slice record from geni
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()
166 raise RecordNotFound(hrn)
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], ['slice_id', 'node_ids'])
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])
177 authority = get_authority(hrn)
178 site_records = registry.resolve(credential, authority)
181 raise RecordNotFound(authority)
182 site_record = site_records[0]
183 site = site_record.as_dict()
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
190 self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
194 # create slice object
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]
202 slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
205 #this belongs to a peer
207 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
208 slice['node_ids'] = []
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:
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:
223 person_dict = person_record.as_dict()
224 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
226 # Create the person record
228 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
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.
237 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
239 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
242 person_id = persons[0]['person_id']
243 key_ids = persons[0]['key_ids']
245 # if this is a peer person, we must unbind them from the peer or PLCAPI will throw
248 self.api.plshell.UnBindObjectFromPeer(self.api.plauth, 'person', person_id, peer)
249 self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
251 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
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]
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}
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)
265 self.api.plshell.BindObjectToPeer(self.api.plauth, 'person', person_id, peer, person_record['pointer'])
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]
271 # get netspec details
272 nodespecs = spec.getDictsByTagName('NodeSpec')
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'])
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))
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)
290 self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
294 def create_slice_smgr(self, hrn, 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']
303 if specDict.has_key('end_time'): end_time = specDict['end_time']
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)
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()
319 # notify the aggregates
320 for aggregate in rspecs.keys():
322 # send the whloe rspec to the local aggregate
323 if aggregate in [self.api.hrn]:
324 aggregates[aggregate].create_slice(credential, hrn, rspec)
326 aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
328 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
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)
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'])
342 raise RecordNotFound(hrn)
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" )
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)
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)
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'])
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")
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)