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 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']
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], ['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 # print site_id, peer, remote_site_id
191 # self.api.plshell.BindObjectToPeer(self.api.plauth, 'site', site_id, peer, remote_site_id)
195 # create slice object
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]
203 slice_id = self.api.plshell.AddSlice(self.api.plauth, slice_fields)
206 #this belongs to a peer
208 # self.api.plshell.BindObjectToPeer(self.api.plauth, 'slice', slice_id, peer, slice_record['pointer'])
209 slice['node_ids'] = 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:
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 key_ids = persons[0]['key_ids']
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]
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}
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)
257 self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
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]
263 # get netspec details
264 nodespecs = spec.getDictsByTagName('NodeSpec')
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'])
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))
277 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
278 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
282 def create_slice_smgr(self, hrn, 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']
291 if specDict.has_key('end_time'): end_time = specDict['end_time']
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)
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()
307 # notify the aggregates
308 for aggregate in rspecs.keys():
310 # send the whloe rspec to the local aggregate
311 if aggregate in [self.api.hrn]:
312 aggregates[aggregate].create_slice(credential, hrn, rspec)
314 aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
316 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
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)
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'])
330 raise RecordNotFound(hrn)
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" )
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)
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)
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'])
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")
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)