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 *
14 from geni.util.rspec import Rspec
15 from geni.util.specdict import *
16 from geni.util.storage import SimpleStorage, XmlStorage
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__(self, ip, port, key_file, cert_file)
44 self.key_file = key_file
45 self.cert_file = cert_file
46 self.config = Config(config)
47 self.basedir = self.config.GENI_BASE_DIR + os.sep
48 self.server_basedir = self.basedir + os.sep + "geni" + os.sep
49 self.hrn = self.config.GENI_INTERFACE_HRN
50 self.time_format = "%Y-%m-%d %H:%M:%S"
52 # Get list of aggregates this sm talks to
53 aggregates_file = self.server_basedir + os.sep + 'aggregates.xml'
54 connection_dict = {'hrn': '', 'addr': '', 'port': ''}
55 self.aggregate_info = XmlStorage(aggregates_file, {'aggregates': {'aggregate': [connection_dict]}} )
56 self.aggregate_info.load()
58 # Get cached list of nodes (rspec)
59 nodes_file = os.sep.join([self.server_basedir, 'smgr.' + self.hrn + '.components'])
60 self.nodes = SimpleStorage(nodes_file)
63 # Get cacheds slice states
64 slices_file = os.sep.join([self.server_basedir, 'smgr.' + self.hrn + '.slices'])
65 self.slices = SimpleStorage(slices_file)
69 policy_file = os.sep.join([self.server_basedir, 'smgr.' + self.hrn + '.policy'])
70 self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
73 # How long before we refresh nodes cache
76 self.connectRegistry()
78 self.connectAggregates()
81 def loadCredential(self):
83 Attempt to load credential from file if it exists. If it doesnt get
84 credential from registry.
87 # see if this file exists
88 ma_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".sa.cred"
90 self.credential = Credential(filename = ma_cred_filename)
92 self.credential = self.getCredentialFromRegistry()
95 def getCredentialFromRegistry(self):
97 Get our current credential from the registry.
100 self_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".cred"
101 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
102 self_cred.save_to_file(self_cred_filename, save_parents=True)
105 ma_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".sa.cred"
106 ma_cred = self.registry.get_credential(self_cred, 'sa', self.hrn)
107 ma_cred.save_to_file(ma_cred_filename, save_parents=True)
110 def connectRegistry(self):
112 Connect to the registry
114 # connect to registry using GeniClient
115 address = self.config.GENI_REGISTRY_HOSTNAME
116 port = self.config.GENI_REGISTRY_PORT
117 url = 'http://%(address)s:%(port)s' % locals()
118 self.registry = GeniClient(url, self.key_file, self.cert_file)
120 def connectAggregates(self):
122 Get connection details for the trusted peer aggregates from file and
123 create a GeniClient connection to each.
126 aggregates = self.aggregate_info['aggregates']['aggregate']
127 if isinstance(aggregates, dict):
128 aggregates = [aggregates]
129 if isinstance(aggregates, list):
130 for aggregate in aggregates:
131 # create xmlrpc connection using GeniClient
132 hrn, address, port = aggregate['hrn'], aggregate['addr'], aggregate['port']
133 url = 'http://%(address)s:%(port)s' % locals()
134 self.aggregates[hrn] = GeniClient(url, self.key_file, self.cert_file)
136 def item_hrns(self, items):
138 Take a list of items (components or slices) and return a dictionary where
139 the key is the authoritative hrn and the value is a list of items at that
143 agg_hrns = self.aggregates.keys()
144 for agg_hrn in agg_hrns:
145 item_hrns[agg_hrn] = []
147 for agg_hrn in agg_hrns:
148 if item.startswith(agg_hrn):
149 item_hrns[agg_hrn] = item
154 def hostname_to_hrn(self, login_base, hostname):
156 Convert hrn to plantelab name.
158 genihostname = "_".join(hostname.split("."))
159 return ".".join([self.hrn, login_base, genihostname])
161 def slicename_to_hrn(self, slicename):
163 Convert hrn to planetlab name.
165 slicename = slicename.replace("_", ".")
166 return ".".join([self.hrn, slicename])
168 def refresh_components(self):
170 Update the cached list of nodes.
173 # convert and threshold to ints
174 if self.nodes.has_key('timestamp') and self.nodes['timestamp']:
175 hr_timestamp = self.nodes['timestamp']
176 timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_timestamp, self.time_format)))
177 hr_threshold = self.nodes['threshold']
178 threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_threshold, self.time_format)))
180 timestamp = datetime.datetime.now()
181 hr_timestamp = timestamp.strftime(self.time_format)
182 delta = datetime.timedelta(hours=self.nodes_ttl)
183 threshold = timestamp + delta
184 hr_threshold = threshold.strftime(self.time_format)
186 start_time = int(timestamp.strftime("%s"))
187 end_time = int(threshold.strftime("%s"))
188 duration = end_time - start_time
190 aggregates = self.aggregates.keys()
194 for aggregate in aggregates:
196 # get the rspec from the aggregate
197 agg_rspec = self.aggregates[aggregate].list_nodes(self.credential)
198 # extract the netspec from each aggregates rspec
199 rspec.parseString(agg_rspec)
200 networks.extend([{'NetSpec': rspec.getDictsByTagName('NetSpec')}])
202 # XX print out to some error log
203 print "Error calling list nodes at aggregate %s" % aggregate
206 # create the rspec dict
207 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
208 resourceDict = {'Rspec': resources}
209 # convert rspec dict to xml
210 rspec.parseDict(resourceDict)
212 # filter according to policy
213 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
215 # update timestamp and threshold
216 timestamp = datetime.datetime.now()
217 hr_timestamp = timestamp.strftime(self.time_format)
218 delta = datetime.timedelta(hours=self.nodes_ttl)
219 threshold = timestamp + delta
220 hr_threshold = threshold.strftime(self.time_format)
222 nodedict = {'rspec': rspec.toxml(),
223 'timestamp': hr_timestamp,
224 'threshold': hr_threshold}
226 self.nodes = SimpleStorage(self.nodes.db_filename, nodedict)
229 def load_policy(self):
231 Read the list of blacklisted and whitelisted nodes.
235 def load_slices(self):
237 Read current slice instantiation states.
242 def getNodes(self, format = 'rspec'):
244 Return a list of components managed by this slice manager.
246 # Reload components list
247 if not self.nodes.has_key('threshold') or not self.nodes['threshold'] or not self.nodes.has_key('timestamp') or not self.nodes['timestamp']:
248 self.refresh_components()
250 now = datetime.datetime.now()
251 threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(self.nodes['threshold'], self.time_format)))
253 self.refresh_components()
254 return self.nodes[format]
259 Return a list of instnatiated managed by this slice manager.
262 for aggregate in self.aggregates:
264 slices = self.aggregates[aggregate].list_slices(self.credential)
265 slice_hrns.extend(slices)
268 # print to some error log
273 def getResources(self, slice_hrn):
275 Return the current rspec for the specified slice.
278 # request this slices state from all known aggregates
282 for hrn in self.aggregates.keys():
283 # check if the slice has resources at this hrn
284 slice_resources = self.aggregates[hrn].get_resources(self.credential, slice_hrn)
285 rspec.parseString(slice_resources)
286 networks.extend({'NetSpec': rspec.getDictsByTagName('NetSpec')})
288 # merge all these rspecs into one
289 start_time = int(datetime.datetime.now().strftime("%s"))
290 end_time = start_time
291 duration = end_time - start_time
293 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
294 resourceDict = {'Rspec': resources}
295 # convert rspec dict to xml
296 rspec.parseDict(resourceDict)
297 # save this slices resources
298 #self.slices[slice_hrn] = rspec.toxml()
303 def createSlice(self, cred, slice_hrn, rspec):
305 Instantiate the specified slice according to whats defined in the rspec.
308 # save slice state locally
309 # we can assume that spec object has been validated so its safer to
310 # save this instead of the unvalidated rspec the user gave us
313 rspec.parseString(rspec)
315 self.slices[slice_hrn] = rspec.toxml()
318 # extract network list from the rspec and create a separate
319 # rspec for each network
320 slicename = self.hrn_to_plcslicename(slice_hrn)
321 specDict = rspec.toDict()
322 start_time = specDict['start_time']
323 end_time = specDict['end_time']
326 # only attempt to extract information about the aggregates we know about
327 for hrn in self.aggregates.keys():
328 netspec = spec.getDictByTagNameValue('NetSpec', hrn)
331 resources = {'start_time': star_time, 'end_time': end_time, 'networks': netspec}
332 resourceDict = {'Rspec': resources}
333 tempspec.parseDict(resourceDict)
334 rspecs[hrn] = tempspec.toxml()
336 # notify the aggregates
337 for hrn in self.rspecs.keys():
338 self.aggregates[hrn].createSlice(self.credential, rspecs[hrn])
342 def updateSlice(self, slice_hrn, rspec, attributes = []):
344 Update the specifed slice
346 self.create_slice(slice_hrn, rspec, attributes)
348 def deleteSlice_(self, slice_hrn):
350 Remove this slice from all components it was previouly associated with and
351 free up the resources it was using.
353 # XX need to get the correct credential
354 cred = self.credential
356 if self.slices.has_key(slice_hrn):
357 self.slices.pop(slice_hrn)
360 for hrn in self.aggregates.keys():
361 self.aggregates[hrn].deleteSlice(cred, slice_hrn)
365 def startSlice(self, slice_hrn):
367 Stop the slice at plc.
369 cred = self.credential
371 for hrn in self.aggregates.keys():
372 self.aggregates[hrn].startSlice(cred, slice_hrn)
375 def stopSlice(self, slice_hrn):
377 Stop the slice at plc
379 cred = self.credential
380 for hrn in self.aggregates.keys():
381 self.aggregates[hrn].startSlice(cred, slice_hrn)
384 def resetSlice(self, slice_hrn):
388 # XX not yet implemented
393 Return the policy of this slice manager.
400 ##############################
401 ## Server methods here for now
402 ##############################
404 def list_nodes(self, cred):
405 self.decode_authentication(cred, 'listnodes')
406 return self.getNodes()
408 def list_slices(self, cred):
409 self.decode_authentication(cred, 'listslices')
410 return self.getSlices()
412 def get_resources(self, cred, hrn):
413 self.decode_authentication(cred, 'listnodes')
414 return self.getResources(hrn)
416 def get_ticket(self, cred, hrn, rspec):
417 self.decode_authentication(cred, 'getticket')
418 return self.getTicket(hrn, rspec)
420 def get_policy(self, cred):
421 self.decode_authentication(cred, 'getpolicy')
422 return self.getPolicy()
424 def create_slice(self, cred, hrn, rspec):
425 self.decode_authentication(cred, 'creatslice')
426 return self.createSlice(cred, hrn, rspec)
428 def delete_slice(self, cred, hrn):
429 self.decode_authentication(cred, 'deleteslice')
430 return self.deleteSlice(hrn)
432 def start_slice(self, cred, hrn):
433 self.decode_authentication(cred, 'startslice')
434 return self.startSlice(hrn)
436 def stop_slice(self, cred, hrn):
437 self.decode_authentication(cred, 'stopslice')
438 return self.stopSlice(hrn)
440 def reset_slice(self, cred, hrn):
441 self.decode_authentication(cred, 'resetslice')
442 return self.resetSlice(hrn)
444 def register_functions(self):
445 GeniServer.register_functions(self)
447 # Aggregate interface methods
448 self.server.register_function(self.list_nodes)
449 self.server.register_function(self.list_slices)
450 self.server.register_function(self.get_resources)
451 self.server.register_function(self.get_policy)
452 self.server.register_function(self.create_slice)
453 self.server.register_function(self.delete_slice)
454 self.server.register_function(self.start_slice)
455 self.server.register_function(self.stop_slice)
456 self.server.register_function(self.reset_slice)