6 from geni.util.geniserver import *
7 from geni.util.geniclient import *
8 from geni.util.cert import *
9 from geni.util.credential import Credential
10 from geni.util.trustedroot import *
11 from geni.util.excep import *
12 from geni.util.misc import *
13 from geni.util.config import Config
14 from geni.util.rspec import Rspec
15 from geni.util.specdict import *
16 from geni.util.storage import SimpleStorage
18 class SliceMgr(GeniServer):
35 # Create a new slice manager object.
37 # @param ip the ip address to listen on
38 # @param port the port to listen on
39 # @param key_file private key filename of registry
40 # @param cert_file certificate filename containing public key (could be a GID file)
42 def __init__(self, ip, port, key_file, cert_file, config = "/usr/share/geniwrapper/geni/util/geni_config"):
43 GeniServer.__init__(ip, port, key_file, cert_file)
44 self.key_file = key_file
45 self.cert_file = cert_file
46 self.conf = Config(config)
47 basedir = self.conf.GENI_BASE_DIR + os.sep
48 server_basedir = basedir + os.sep + "geni" + os.sep
49 self.hrn = conf.GENI_INTERFACE_HRN
51 # Get list of aggregates this sm talks to
52 # XX do we use simplestorage to maintain this file manually?
53 aggregates_file = server_basedir + os.sep + 'aggregates'
54 self.aggregates = SimpleStorage(aggregates_file)
55 self.connect_aggregates(aggregates_file)
57 nodes_file = os.sep.join([server_basedir, 'smgr.' + self.hrn + '.components'])
58 self.nodes = SimpleStorage(nodes_file)
61 slices_file = os.sep.join([server_basedir, 'smgr' + self.hrn + '.slices'])
62 self.slices = SimpleStorage(slices_file)
65 policy_file = os.sep.join([server_basedir, 'smgr.' + self.hrn + '.policy'])
66 self.policy = SimpleStorage(policy_file)
69 timestamp_file = os.sep.join([server_basedir, 'smgr.' + self.hrn + '.timestamp'])
70 self.timestamp = SimpleStorage(timestamp_file)
73 self.connectAggregates()
74 self.connectRegistry()
78 def loadCredential(self):
80 Attempt to load credential from file if it exists. If it doesnt get
81 credential from registry.
84 self_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".cred"
85 ma_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".sa.cred"
87 # see if this file exists
89 cred = Credential(filename = ma_cred_filename)
90 self.credential = cred.save_to_string()
93 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
94 self_credential = Credential(string = self_cred)
95 self_credential.save_to_file(self_cred_filename)
98 ma_cred = self.registry.get_gredential(self_cred)
99 ma_credential = Credential(string = ma_cred)
100 ma_credential.save_to_file(ma_cred_filename)
101 self.credential = ma_cred
103 def connect_aggregates(self, aggregates_file):
105 Get info about the aggregates available to us from file and create
106 an xmlrpc connection to each. If any info is invalid, skip it.
110 f = open(aggregates_file, 'r')
111 lines = f.readlines()
117 if line.strip.startswith("#"):
119 agg_info = line.split("\t").split(" ")
122 if len(agg_info) != 3:
125 # create xmlrpc connection using GeniClient
126 hrn, address, port = agg_info[0], agg_info[1], agg_info[2]
127 url = 'https://%(address)s:%(port)s' % locals()
128 self.aggregates[hrn] = GeniClient(url, self.key_file, self.cert_file)
131 def item_hrns(self, items):
133 Take a list of items (components or slices) and return a dictionary where
134 the key is the authoritative hrn and the value is a list of items at that
138 agg_hrns = self.aggregates.keys()
139 for agg_hrn in agg_hrns:
140 item_hrns[agg_hrn] = []
142 for agg_hrn in agg_hrns:
143 if item.startswith(agg_hrn):
144 item_hrns[agg_hrn] = item
149 def hostname_to_hrn(self, login_base, hostname):
151 Convert hrn to plantelab name.
153 genihostname = "_".join(hostname.split("."))
154 return ".".join([self.hrn, login_base, genihostname])
156 def slicename_to_hrn(self, slicename):
158 Convert hrn to planetlab name.
160 slicename = slicename.replace("_", ".")
161 return ".".join([self.hrn, slicename])
163 def refresh_components(self):
165 Update the cached list of nodes.
169 aggregates = self.aggregates.keys()
172 for aggregate in aggregates:
174 # resolve components hostnames
175 nodes = self.aggregates[aggregate].get_components()
176 all_nodes.extend(nodes)
178 # XX print out to some error log
181 for node in all_nodes:
182 if self.polciy['whitelist'] and node not in self.polciy['whitelist']:
184 if self.polciy['blacklist'] and node in self.policy['blacklist']:
187 nodedict[node] = node
189 self.nodes = SimpleStorate(self.nodes.db_filename, nodedict)
192 # update timestamp and threshold
193 self.timestamp['timestamp'] = datetime.datetime.now()
194 delta = datetime.timedelta(hours=self.nodes_tt1)
195 self.threshold = self.timestamp['timestamp'] + delta
196 self.timestamp.write()
199 def load_components(self):
201 Read cached list of nodes and slices.
203 print "loading nodes"
204 # Read component list from cached file
206 self.timestamp.load()
207 time_format = "%Y-%m-%d %H:%M:%S"
208 timestamp = self.timestamp['timestamp']
209 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
210 delta = datetime.timedelta(hours=self.nodes_ttl)
211 self.threshold = self.timestamp['timestamp'] + delta
213 def load_policy(self):
215 Read the list of blacklisted and whitelisted nodes.
219 def load_slices(self):
221 Read current slice instantiation states.
223 print "loading slices"
227 def getComponents(self):
229 Return a list of components managed by this slice manager.
231 # Reload components list
232 now = datetime.datetime.now()
233 #self.load_components()
234 if not self.threshold or not self.timestamp or now > self.threshold:
235 self.refresh_components()
236 elif now < self.threshold and not self.components:
237 self.load_components()
238 return self.nodes.keys()
243 Return a list of instnatiated managed by this slice manager.
245 # XX return only the slices at the specified hrn
246 return dict(self.slices)
248 def getResources(self, slice_hrn):
250 Return the current rspec for the specified slice.
252 cred = self.credential
254 if slice_hrn in self.slices.keys():
255 # check if we alreay have this slices state saved
256 rspec = self.slices[slice_hrn]
258 # request this slices state from all known aggregates
260 for hrn in self.aggregates.keys():
261 # XX need to use the right credentials for this call
262 # check if the slice has resources at this hrn
263 tempresources = self.aggregates[hrn].resources(cred, slice_hrn)
265 temprspec.parseString(temprspec)
266 if temprspec.getDictsByTagName('NodeSpec'):
267 # append this rspec to the list of rspecs
268 rspecdicts.append(temprspec.toDict())
270 # merge all these rspecs into one
271 start_time = int(self.timestamp['timestamp'].strftime("%s"))
272 end_time = int(self.duration.strftime("%s"))
273 duration = end_time - start_time
276 networks = [rspecdict['networks'][0] for rspecdict in rspecdicts]
277 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
278 # convert the plc dict to an rspec dict
279 resourceDict = RspecDict(resources)
280 resourceSpec = Rspec()
281 resourceSpec.parseDict(resourceDict)
282 rspec = resourceSpec.toxml()
283 # save this slices resources
284 self.slices[slice_hrn] = rspec
289 def createSlice(self, slice_hrn, rspec, attributes):
291 Instantiate the specified slice according to whats defined in the rspec.
293 # XX need to gget the correct credentials
294 cred = self.credential
296 # save slice state locally
297 # we can assume that spec object has been validated so its safer to
298 # save this instead of the unvalidated rspec the user gave us
299 self.slices[slice_hrn] = spec.toxml()
302 # extract network list from the rspec and create a separate
303 # rspec for each network
304 slicename = self.hrn_to_plcslicename(slice_hrn)
306 spec.parseString(rspec)
307 specDict = spec.toDict()
308 start_time = specDict['start_time']
309 end_time = specDict['end_time']
312 # only attempt to extract information about the aggregates we know about
313 for hrn in self.aggregates.keys():
314 netspec = spec.getDictByTagNameValue('NetSpec', 'hrn')
317 tempdict = {'start_time': star_time, 'end_time': end_time, 'networks': netspec}
318 #convert the plc dict to rpsec dict
319 resourceDict = RspecDict(tempdict)
322 tempspec.parseDict(resourceDict)
323 rspecs[hrn] = tempspec.toxml()
325 # notify the aggregates
326 for hrn in self.rspecs.keys():
327 self.aggregates[hrn].createSlice(cred, rspecs[hrn])
331 def updateSlice(self, slice_hrn, rspec, attributes = []):
333 Update the specifed slice
335 self.create_slice(slice_hrn, rspec, attributes)
337 def deleteSlice_(self, slice_hrn):
339 Remove this slice from all components it was previouly associated with and
340 free up the resources it was using.
342 # XX need to get the correct credential
343 cred = self.credential
345 if self.slices.has_key(slice_hrn):
346 self.slices.pop(slice_hrn)
349 for hrn in self.aggregates.keys():
350 self.aggregates[hrn].deleteSlice(cred, slice_hrn)
354 def startSlice(self, slice_hrn):
356 Stop the slice at plc.
358 cred = self.credential
360 for hrn in self.aggregates.keys():
361 self.aggregates[hrn].startSlice(cred, slice_hrn)
364 def stopSlice(self, slice_hrn):
366 Stop the slice at plc
368 cred = self.credential
369 for hrn in self.aggregates.keys():
370 self.aggregates[hrn].startSlice(cred, slice_hrn)
373 def resetSlice(self, slice_hrn):
377 # XX not yet implemented
382 Return the policy of this slice manager.
389 ##############################
390 ## Server methods here for now
391 ##############################
393 def list_components(self):
394 return self.getComponents()
396 def list_slices(self, cred, hrn):
397 self.decode_authentication(cred, 'list')
398 return self.getSlices(hrn)
400 def get_resources(self, cred, hrn):
401 self.decode_authentication(cred, 'info')
402 return self.getResources(hrn)
404 def get_policy(self, cred):
405 self.decode_authentication(cred, 'info')
406 return self.getPolicy()
408 def create_slice(self, cred, hrn, rspec):
409 self.decode_authentication(cred, 'embed')
410 return self.createSlice(hrn)
412 def delete_slice(self, cred, hrn):
413 self.decode_authentication(cred, 'embed')
414 return self.deleteSlice(hrn)
416 def start_slice(self, cred, hrn):
417 self.decode_authentication(cred, 'control')
418 return self.startSlice(hrn)
420 def stop_slice(self, cred, hrn):
421 self.decode_authentication(cred, 'control')
422 return self.stopSlice(hrn)
424 def reset_slice(self, cred, hrn):
425 self.decode_authentication(cred, 'control')
426 return self.resetSlice(hrn)
428 def register_functions(self):
429 GeniServer.register_functions(self)
431 # Aggregate interface methods
432 self.server.register_function(self.list_components)
433 self.server.register_function(self.list_slices)
434 self.server.register_function(self.get_resources)
435 self.server.register_function(self.get_policy)
436 self.server.register_function(self.create_slice)
437 self.server.register_function(self.delete_slice)
438 self.server.register_function(self.start_slice)
439 self.server.register_function(self.stop_slice)
440 self.server.register_function(self.reset_slice)