3 from geni.util.misc import *
4 from geni.util.rspec import *
5 from geni.util.specdict import *
6 from geni.util.excep import *
7 from geni.util.storage import *
8 from geni.util.policy import Policy
9 from geni.util.debug import log
10 from geni.aggregate import Aggregates
11 from geni.registry import Registries
13 class Slices(SimpleStorage):
15 def __init__(self, api, ttl = .5):
19 path = self.api.config.basepath
20 filename = ".".join([self.api.interface, self.api.hrn, "slices"])
21 filepath = path + os.sep + filename
22 self.slices_file = filepath
23 SimpleStorage.__init__(self, self.slices_file)
24 self.policy = Policy(self.api)
30 Update the cached list of slices
32 # Reload components list
33 now = datetime.datetime.now()
34 if not self.has_key('threshold') or not self.has_key('timestamp') or \
35 now > datetime.datetime.fromtimestamp(time.mktime(time.strptime(self['threshold'], self.api.time_format))):
36 if self.api.interface in ['aggregate']:
37 self.refresh_slices_aggregate()
38 elif self.api.interface in ['slicemgr']:
39 self.refresh_slices_smgr()
41 def refresh_slices_aggregate(self):
42 slices = self.api.plshell.GetSlices(self.api.plauth, {'peer_id': None}, ['name'])
43 slice_hrns = [slicename_to_hrn(self.api.hrn, slice['name']) for slice in slices]
45 # update timestamp and threshold
46 timestamp = datetime.datetime.now()
47 hr_timestamp = timestamp.strftime(self.api.time_format)
48 delta = datetime.timedelta(hours=self.ttl)
49 threshold = timestamp + delta
50 hr_threshold = threshold.strftime(self.api.time_format)
52 slice_details = {'hrn': slice_hrns,
53 'timestamp': hr_timestamp,
54 'threshold': hr_threshold
56 self.update(slice_details)
60 def refresh_slices_smgr(self):
62 aggregates = Aggregates(self.api)
63 credential = self.api.getCredential()
64 for aggregate in aggregates:
66 slices = aggregates[aggregate].get_slices(credential)
67 slice_hrns.extend(slices)
69 print >> log, "Error calling slices at aggregate %(aggregate)s" % locals()
70 # update timestamp and threshold
71 timestamp = datetime.datetime.now()
72 hr_timestamp = timestamp.strftime(self.api.time_format)
73 delta = datetime.timedelta(hours=self.ttl)
74 threshold = timestamp + delta
75 hr_threshold = threshold.strftime(self.api.time_format)
77 slice_details = {'hrn': slice_hrns,
78 'timestamp': hr_timestamp,
79 'threshold': hr_threshold
81 self.update(slice_details)
85 def delete_slice(self, hrn):
86 if self.api.interface in ['aggregate']:
87 self.delete_slice_aggregate(hrn)
88 elif self.api.interface in ['slicemgr']:
89 self.delete_slice_smgr(hrn)
91 def delete_slice_aggregate(self, hrn):
92 slicename = hrn_to_pl_slicename(hrn)
93 slices = self.api.plshell.GetSlices(self.api.plauth, {'peer_id': None, 'name': slicename})
98 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, slice['node_ids'])
101 def delete_slice_smgr(self, hrn):
102 credential = self.api.getCredential()
103 aggregates = Aggregates(self.api)
104 for aggregate in aggregates:
105 aggregates[aggregate].delete_slice(credential, hrn)
107 def create_slice(self, hrn, rspec):
108 # check our slice policy before we procede
109 whitelist = self.policy['slice_whitelist']
110 blacklist = self.policy['slice_blacklist']
112 if whitelist and hrn not in whitelist or \
113 blacklist and hrn in blacklist:
114 policy_file = self.policy.policy_file
115 print >> log, "Slice %(hrn)s not allowed by policy %(policy_file)s" % locals()
117 if self.api.interface in ['aggregate']:
118 self.create_slice_aggregate(hrn, rspec)
119 elif self.api.interface in ['slicemgr']:
120 self.create_slice_smgr(hrn, rspec)
122 def create_slice_aggregate(self, hrn, rspec):
124 # Get the slice record from geni
126 registries = Registries(self.api)
127 registry = registries[self.api.hrn]
128 credential = self.api.getCredential()
129 records = registry.resolve(credential, hrn)
130 for record in records:
131 if record.get_type() in ['slice']:
132 slice = record.as_dict()
134 raise RecordNotFound(hrn)
136 # Make sure slice exists at plc, if it doesnt add it
137 slicename = hrn_to_pl_slicename(hrn)
138 slices = self.api.plshell.GetSlices(self.api.plauth, [slicename], ['node_ids'])
140 parts = slicename.split("_")
141 login_base = parts[0]
142 # if site doesnt exist add it
143 sites = self.api.plshell.GetSites(self.api.plauth, [login_base])
145 authority = get_authority(hrn)
146 site_records = registry.resolve(credential, authority)
149 raise RecordNotFound(authority)
150 site_record = site_records[0]
151 site = site_record.as_dict()
155 site_id = self.api.plshell.AddSite(self.api.plauth, site)
160 slice_keys = ['name', 'url', 'description']
161 for key in slice_keys:
162 if key in slice and slice[key]:
163 slice_fields[key] = slice[key]
164 self.api.plshell.AddSlice(self.api.plauth, slice_fields)
166 slice['node_ids'] = 0
169 # get the list of valid slice users from the registry and make
170 # they are added to the slice
171 researchers = record.get('researcher', [])
172 for researcher in researchers:
174 person_records = registry.resolve(credential, researcher)
175 for record in person_records:
176 if record.get_type() in ['user']:
177 person_record = record
178 if not person_record:
180 person_dict = person_record.as_dict()
181 persons = self.api.plshell.GetPersons(self.api.plauth, [person_dict['email']], ['person_id', 'key_ids'])
183 # Create the person record
185 self.api.plshell.AddPerson(self.api.plauth, person_dict)
188 key_ids = persons[0]['key_ids']
190 self.api.plshell.AddPersonToSlice(self.api.plauth, person_dict['email'], slicename)
192 # Get this users local keys
193 keylist = self.api.plshell.GetKeys(self.api.plauth, key_ids, ['key'])
194 keys = [key['key'] for key in keylist]
196 # add keys that arent already there
197 for personkey in person_dict['keys']:
198 if personkey not in keys:
199 key = {'key_type': 'ssh', 'key': personkey}
200 self.api.plshell.AddPersonKey(self.api.plauth, person_dict['email'], key)
202 # find out where this slice is currently running
203 nodelist = self.api.plshell.GetNodes(self.api.plauth, slice['node_ids'], ['hostname'])
204 hostnames = [node['hostname'] for node in nodelist]
206 # get netspec details
207 nodespecs = spec.getDictsByTagName('NodeSpec')
209 for nodespec in nodespecs:
210 if isinstance(nodespec['name'], list):
211 nodes.extend(nodespec['name'])
212 elif isinstance(nodespec['name'], StringTypes):
213 nodes.append(nodespec['name'])
215 # remove nodes not in rspec
216 deleted_nodes = list(set(hostnames).difference(nodes))
217 # add nodes from rspec
218 added_nodes = list(set(nodes).difference(hostnames))
220 self.api.plshell.AddSliceToNodes(self.api.plauth, slicename, added_nodes)
221 self.api.plshell.DeleteSliceFromNodes(self.api.plauth, slicename, deleted_nodes)
225 def create_slice_smgr(self, hrn, rspec):
228 spec.parseString(rspec)
229 slicename = hrn_to_pl_slicename(hrn)
230 specDict = spec.toDict()
231 if specDict.has_key('Rspec'): specDict = specDict['Rspec']
232 if specDict.has_key('start_time'): start_time = specDict['start_time']
234 if specDict.has_key('end_time'): end_time = specDict['end_time']
238 aggregates = Aggregates(self.api)
239 credential = self.api.getCredential()
240 # only attempt to extract information about the aggregates we know about
241 for aggregate in aggregates:
242 netspec = spec.getDictByTagNameValue('NetSpec', aggregate)
245 resources = {'start_time': start_time, 'end_time': end_time, 'networks': netspec}
246 resourceDict = {'Rspec': resources}
247 tempspec.parseDict(resourceDict)
248 rspecs[aggregate] = tempspec.toxml()
250 # notify the aggregates
251 for aggregate in rspecs.keys():
253 aggregates[aggregate].create_slice(credential, hrn, rspecs[aggregate])
255 print >> log, "Error creating slice %(hrn)s at aggregate %(aggregate)s" % locals()
259 def start_slice(self, hrn):
260 if self.api.interface in ['aggregate']:
261 self.start_slice_aggregate(hrn)
262 elif self.api.interface in ['slicemgr']:
263 self.start_slice_smgr(hrn)
265 def start_slice_aggregate(self, hrn):
266 slicename = hrn_to_pl_slicename(hrn)
267 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
269 raise RecordNotFound(hrn)
271 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
272 attribute_id = attreibutes[0]['slice_attribute_id']
273 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "1" )
276 def start_slice_smgr(self, hrn):
277 credential = self.api.getCredential()
278 aggregates = Aggregates(self.api)
279 for aggregate in aggregates:
280 aggregates[aggregate].start_slice(credential, hrn)
284 def stop_slice(self, hrn):
285 if self.api.interface in ['aggregate']:
286 self.stop_slice_aggregate(hrn)
287 elif self.api.interface in ['slicemgr']:
288 self.stop_slice_smgr(hrn)
290 def stop_slice_aggregate(self, hrn):
291 slicename = hrn_to_pl_slicename(hrn)
292 slices = self.api.plshell.GetSlices(self.api.plauth, {'name': slicename}, ['slice_id'])
294 raise RecordNotFound(hrn)
295 slice_id = slices[0]['slice_id']
296 attributes = self.api.plshell.GetSliceAttributes(self.api.plauth, {'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
297 attribute_id = attributes[0]['slice_attribute_id']
298 self.api.plshell.UpdateSliceAttribute(self.api.plauth, attribute_id, "0")
301 def stop_slice_smgr(self, hrn):
302 credential = self.api.getCredential()
303 aggregates = Aggregates(self.api)
304 for aggregate in aggregates:
305 aggregates[aggregate].stop_slice(credential, hrn)