7 from sfa.util.misc import *
8 from sfa.util.rspec import *
9 from sfa.util.specdict import *
10 from sfa.util.faults import *
11 from sfa.util.storage import *
12 from sfa.util.policy import Policy
13 from sfa.util.debug import log
14 from sfa.server.aggregate import Aggregates
15 from sfa.server.registry import Registries
17 class Slices(SimpleStorage):
19 def __init__(self, api, ttl = .5):
23 path = self.api.config.config_path
24 filename = ".".join([self.api.interface, self.api.hrn, "slices"])
25 filepath = path + os.sep + filename
26 self.slices_file = filepath
27 SimpleStorage.__init__(self, self.slices_file)
28 self.policy = Policy(self.api)
34 Update the cached list of slices
36 # Reload components list
37 now = datetime.datetime.now()
38 if not self.has_key('threshold') or not self.has_key('timestamp') or \
39 now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))):
40 if self.api.interface in ['aggregate']:
41 self.refresh_slices_aggregate()
42 elif self.api.interface in ['slicemgr']:
43 self.refresh_slices_smgr()
45 def refresh_slices_aggregate(self):
46 slices = self.api.plshell.GetSlices(self.api.plauth, {'peer_id': None}, ['name'])
47 slice_hrns = [slicename_to_hrn(self.api.hrn, slice['name']) for slice in slices]
49 # update timestamp and threshold
50 timestamp = datetime.datetime.now()
51 hr_timestamp = timestamp.strftime(self.api.time_format)
52 delta = datetime.timedelta(hours=self.ttl)
53 threshold = timestamp + delta
54 hr_threshold = threshold.strftime(self.api.time_format)
56 slice_details = {'hrn': slice_hrns,
57 'timestamp': hr_timestamp,
58 'threshold': hr_threshold
60 self.update(slice_details)
64 def refresh_slices_smgr(self):
66 aggregates = Aggregates(self.api)
67 credential = self.api.getCredential()
68 for aggregate in aggregates:
70 slices = aggregates[aggregate].get_slices(credential)
71 slice_hrns.extend(slices)
73 print >> log, "Error calling slices at aggregate %(aggregate)s" % locals()
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 delete_slice(self, hrn):
90 if self.api.interface in ['aggregate']:
91 self.delete_slice_aggregate(hrn)
92 elif self.api.interface in ['slicemgr']:
93 self.delete_slice_smgr(hrn)
95 def delete_slice_aggregate(self, hrn):
96 slicename = hrn_to_pl_slicename(hrn)
97 slices = self.api.plshell.GetSlices(self.api.plauth, {'peer_id': None, 'name': slicename})
102 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, slice['node_ids'])
105 def delete_slice_smgr(self, hrn):
106 credential = self.api.getCredential()
107 aggregates = Aggregates(self.api)
108 for aggregate in aggregates:
109 aggregates[aggregate].delete_slice(credential, hrn)
111 def create_slice(self, hrn, rspec):
112 # check our slice policy before we procede
113 whitelist = self.policy['slice_whitelist']
114 blacklist = self.policy['slice_blacklist']
116 if whitelist and hrn not in whitelist or \
117 blacklist and hrn in blacklist:
118 policy_file = self.policy.policy_file
119 print >> log, "Slice %(hrn)s not allowed by policy %(policy_file)s" % locals()
121 if self.api.interface in ['aggregate']:
122 self.create_slice_aggregate(hrn, rspec)
123 elif self.api.interface in ['slicemgr']:
124 self.create_slice_smgr(hrn, rspec)
126 def create_slice_aggregate(self, hrn, rspec):
128 # Get the slice record from geni
130 registries = Registries(self.api)
131 registry = registries[self.api.hrn]
132 credential = self.api.getCredential()
133 records = registry.resolve(credential, hrn)
134 for record in records:
135 if record.get_type() in ['slice']:
136 slice = record.as_dict()
138 raise RecordNotFound(hrn)
140 # Make sure slice exists at plc, if it doesnt add it
141 slicename = hrn_to_pl_slicename(hrn)
142 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename], ['node_ids'])
144 parts = slicename.split("_")
145 login_base = parts[0]
146 # if site doesnt exist add it
147 sites = self.api.plshell.GetSites(self.api.plauth, [login_base])
149 authority = get_authority(hrn)
150 site_records = registry.resolve(credential, authority)
153 raise RecordNotFound(authority)
154 site_record = site_records[0]
155 site = site_record.as_dict()
159 site_id = self.api.plshell.AddSite(self.api.plauth, site)
164 slice_keys = ['name', 'url', 'description']
165 for key in slice_keys:
166 if key in slice and slice[key]:
167 slice_fields[key] = slice[key]
168 self.api.plshell.AddSlice(self.api.plauth, slice_fields)
170 slice['node_ids'] = 0
173 # get the list of valid slice users from the registry and make
174 # they are added to the slice
175 researchers = record.get('researcher', [])
176 for researcher in researchers:
178 person_records = registry.resolve(credential, researcher)
179 for record in person_records:
180 if record.get_type() in ['user']:
181 person_record = record
182 if not person_record:
184 person_dict = person_record.as_dict()
185 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
187 # Create the person record
189 person_id=self.api.plshell.AddPerson(self.api.plauth, person_dict)
190 self.api.plshell.UpdatePerson(self.api.plauth, person_id, {'enabled' : True})
193 key_ids = persons[0]['key_ids']
195 self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
197 # Get this users local keys
198 keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key'])
199 keys = [key['key'] for key in keylist]
201 # add keys that arent already there
202 for personkey in person_dict['keys']:
203 if personkey not in keys:
204 key = {'key_type': 'ssh', 'key': personkey}
205 self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
207 # find out where this slice is currently running
208 nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
209 hostnames = [node['hostname'] for node in nodelist]
211 # get netspec details
212 nodespecs = spec.getDictsByTagName('NodeSpec')
214 for nodespec in nodespecs:
215 if isinstance(nodespec['name'], list):
216 nodes.extend(nodespec['name'])
217 elif isinstance(nodespec['name'], StringTypes):
218 nodes.append(nodespec['name'])
220 # remove nodes not in rspec
221 deleted_nodes = list(set(hostnames).difference(nodes))
222 # add nodes from rspec
223 added_nodes = list(set(nodes).difference(hostnames))
225 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
226 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
230 def create_slice_smgr(self, hrn, rspec):
233 spec.parseString(rspec)
234 slicename = hrn_to_pl_slicename(hrn)
235 specDict = spec.toDict()
236 if specDict.has_key('Rspec'): specDict = specDict['Rspec']
237 if specDict.has_key('start_time'): start_time = specDict['start_time']
239 if specDict.has_key('end_time'): end_time = specDict['end_time']
243 aggregates = Aggregates(self.api)
244 credential = self.api.getCredential()
245 # only attempt to extract information about the aggregates we know about
246 for aggregate in aggregates:
247 netspec = spec.getDictByTagNameValue('NetSpec', aggregate)
250 resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
251 resourceDict = {'Rspec': resources}
252 tempspec.parseDict(resourceDict)
253 rspecs[aggregate] = tempspec.toxml()
255 # notify the aggregates
256 for aggregate in rspecs.keys():
258 aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
260 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
264 def start_slice(self, hrn):
265 if self.api.interface in ['aggregate']:
266 self.start_slice_aggregate(hrn)
267 elif self.api.interface in ['slicemgr']:
268 self.start_slice_smgr(hrn)
270 def start_slice_aggregate(self, hrn):
271 slicename = hrn_to_pl_slicename(hrn)
272 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
274 raise RecordNotFound(hrn)
276 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
277 attribute_id = attreibutes[0]['slice_attribute_id']
278 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
281 def start_slice_smgr(self, hrn):
282 credential = self.api.getCredential()
283 aggregates = Aggregates(self.api)
284 for aggregate in aggregates:
285 aggregates[aggregate].start_slice(credential, hrn)
289 def stop_slice(self, hrn):
290 if self.api.interface in ['aggregate']:
291 self.stop_slice_aggregate(hrn)
292 elif self.api.interface in ['slicemgr']:
293 self.stop_slice_smgr(hrn)
295 def stop_slice_aggregate(self, hrn):
296 slicename = hrn_to_pl_slicename(hrn)
297 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
299 raise RecordNotFound(hrn)
300 slice_id = slices[0]['slice_id']
301 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
302 attribute_id = attributes[0]['slice_attribute_id']
303 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
306 def stop_slice_smgr(self, hrn):
307 credential = self.api.getCredential()
308 aggregates = Aggregates(self.api)
309 for aggregate in aggregates:
310 aggregates[aggregate].stop_slice(credential, hrn)