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__(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 # XX do we use simplestorage to maintain this file manually?
54 aggregates_file = self.server_basedir + os.sep + 'aggregates'
55 self.aggregates = SimpleStorage(aggregates_file)
57 nodes_file = os.sep.join([self.server_basedir, 'smgr.' + self.hrn + '.components'])
58 self.nodes = SimpleStorage(nodes_file)
61 slices_file = os.sep.join([self.server_basedir, 'smgr' + self.hrn + '.slices'])
62 self.slices = SimpleStorage(slices_file)
65 policy_file = os.sep.join([self.server_basedir, 'smgr.' + self.hrn + '.policy'])
66 self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
69 # How long before we refresh nodes cache
72 self.connectRegistry()
74 self.connectAggregates(aggregates_file)
77 def loadCredential(self):
79 Attempt to load credential from file if it exists. If it doesnt get
80 credential from registry.
83 self_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".cred"
84 ma_cred_filename = self.server_basedir + os.sep + "smgr." + self.hrn + ".sa.cred"
86 # see if this file exists
88 self.credential = Credential(filename = ma_cred_filename)
91 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
92 self_cred.save_to_file(self_cred_filename, save_parents=True)
95 ma_cred = self.registry.get_credential(self_cred, 'sa', self.hrn)
96 ma_cred.save_to_file(ma_cred_filename, save_parents=True)
97 self.credential = ma_cred
99 def connectRegistry(self):
101 Connect to the registry
103 # connect to registry using GeniClient
104 address = self.config.GENI_REGISTRY_HOSTNAME
105 port = self.config.GENI_REGISTRY_PORT
106 url = 'http://%(address)s:%(port)s' % locals()
107 self.registry = GeniClient(url, self.key_file, self.cert_file)
109 def connectAggregates(self, aggregates_file):
111 Get info about the aggregates available to us from file and create
112 an xmlrpc connection to each. If any info is invalid, skip it.
116 f = open(aggregates_file, 'r')
117 lines = f.readlines()
123 if line.strip().startswith("#"):
125 line = line.replace("\t", " ").replace("\n", "").replace("\r", "").strip()
126 agg_info = line.split(" ")
129 if len(agg_info) != 3:
132 # create xmlrpc connection using GeniClient
133 hrn, address, port = agg_info[0], agg_info[1], agg_info[2]
134 url = 'http://%(address)s:%(port)s' % locals()
135 self.aggregates[hrn] = GeniClient(url, self.key_file, self.cert_file)
137 def item_hrns(self, items):
139 Take a list of items (components or slices) and return a dictionary where
140 the key is the authoritative hrn and the value is a list of items at that
144 agg_hrns = self.aggregates.keys()
145 for agg_hrn in agg_hrns:
146 item_hrns[agg_hrn] = []
148 for agg_hrn in agg_hrns:
149 if item.startswith(agg_hrn):
150 item_hrns[agg_hrn] = item
155 def hostname_to_hrn(self, login_base, hostname):
157 Convert hrn to plantelab name.
159 genihostname = "_".join(hostname.split("."))
160 return ".".join([self.hrn, login_base, genihostname])
162 def slicename_to_hrn(self, slicename):
164 Convert hrn to planetlab name.
166 slicename = slicename.replace("_", ".")
167 return ".".join([self.hrn, slicename])
169 def refresh_components(self):
171 Update the cached list of nodes.
174 # convert and threshold to ints
175 if self.nodes.has_key('timestamp') and self.nodes['timestamp']:
176 hr_timestamp = self.nodes['timestamp']
177 timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_timestamp, self.time_format)))
178 hr_threshold = self.nodes['threshold']
179 threshold = datetime.datetime.fromtimestamp(time.mktime(time.strptime(hr_threshold, self.time_format)))
181 timestamp = datetime.datetime.now()
182 hr_timestamp = timestamp.strftime(self.time_format)
183 delta = datetime.timedelta(hours=self.nodes_ttl)
184 threshold = timestamp + delta
185 hr_threshold = threshold.strftime(self.time_format)
187 start_time = int(timestamp.strftime("%s"))
188 end_time = int(threshold.strftime("%s"))
189 duration = end_time - start_time
191 aggregates = self.aggregates.keys()
195 for aggregate in aggregates:
197 # get the rspec from the aggregate
198 agg_server = self.aggregates[aggregate]
199 agg_rspec = self.aggregates[aggregate].list_nodes(self.credential)
201 # extract the netspec from each aggregates rspec
202 rspec.parseString(agg_rspec)
203 networks.extend(rspec.getDictsByTagName('NetSpec'))
205 # XX print out to some error log
206 print "Error calling list nodes at aggregate %s" % aggregate
209 # create the rspec dict
210 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
211 resourceDict = {'Rspec': resources}
212 # convert rspec dict to xml
213 rspec.parseDict(resourceDict)
215 # filter according to policy
216 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
218 # update timestamp and threshold
219 timestamp = datetime.datetime.now()
220 hr_timestamp = timestamp.strftime(self.time_format)
221 delta = datetime.timedelta(hours=self.nodes_ttl)
222 threshold = timestamp + delta
223 hr_threshold = threshold.strftime(self.time_format)
225 nodedict = {'rspec': rspec.toxml(),
226 'timestamp': hr_timestamp,
227 'threshold': hr_threshold}
229 self.nodes = SimpleStorage(self.nodes.db_filename, nodedict)
232 def load_policy(self):
234 Read the list of blacklisted and whitelisted nodes.
238 def load_slices(self):
240 Read current slice instantiation states.
245 def getNodes(self, format = 'rspec'):
247 Return a list of components managed by this slice manager.
249 # Reload components list
250 now = datetime.datetime.now()
251 if not self.nodes.has_key('threshold') or not self.nodes['threshold'] or not self.nodes.has_key('timestamp') or not self.nodes['timestamp'] or now > self.nodes['threshold']:
252 self.refresh_components()
253 return self.nodes[format]
258 Return a list of instnatiated managed by this slice manager.
261 for aggregate in self.aggregates:
263 slices = self.aggregates[aggregate].list_slices(self.credential)
264 slice_hrns.extend(slices)
267 # print to some error log
272 def getResources(self, slice_hrn):
274 Return the current rspec for the specified slice.
277 if slice_hrn in self.slices.keys():
278 # check if we alreay have this slices state saved
279 return self.slices[slice_hrn]
281 # request this slices state from all known aggregates
285 for hrn in self.aggregates.keys():
286 # check if the slice has resources at this hrn
287 slice_resources = self.aggregates[hrn].get_resources(self.credential, slice_hrn)
288 rspec.parseString(slice_resources)
289 networks.extend(rspec.getDictsByTagName('NetSpec'))
291 # merge all these rspecs into one
292 start_time = int(datetime.datetime.now().strftime("%s"))
293 end_time = start_time
294 duration = end_time - start_time
296 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
297 resourceDict = {'Rspec': resources}
298 # convert rspec dict to xml
299 rspec.parseDict(resourceDict)
300 # save this slices resources
301 self.slices[slice_hrn] = rspec.toxml()
306 def createSlice(self, cred, slice_hrn, rspec):
308 Instantiate the specified slice according to whats defined in the rspec.
311 # save slice state locally
312 # we can assume that spec object has been validated so its safer to
313 # save this instead of the unvalidated rspec the user gave us
316 rspec.parseString(rspec)
318 self.slices[slice_hrn] = rspec.toxml()
321 # extract network list from the rspec and create a separate
322 # rspec for each network
323 slicename = self.hrn_to_plcslicename(slice_hrn)
324 specDict = rspec.toDict()
325 start_time = specDict['start_time']
326 end_time = specDict['end_time']
329 # only attempt to extract information about the aggregates we know about
330 for hrn in self.aggregates.keys():
331 netspec = spec.getDictByTagNameValue('NetSpec', hrn)
334 resources = {'start_time': star_time, 'end_time': end_time, 'networks': netspec}
335 resourceDict = {'Rspec': resources}
336 tempspec.parseDict(resourceDict)
337 rspecs[hrn] = tempspec.toxml()
339 # notify the aggregates
340 for hrn in self.rspecs.keys():
341 self.aggregates[hrn].createSlice(self.credential, rspecs[hrn])
345 def updateSlice(self, slice_hrn, rspec, attributes = []):
347 Update the specifed slice
349 self.create_slice(slice_hrn, rspec, attributes)
351 def deleteSlice_(self, slice_hrn):
353 Remove this slice from all components it was previouly associated with and
354 free up the resources it was using.
356 # XX need to get the correct credential
357 cred = self.credential
359 if self.slices.has_key(slice_hrn):
360 self.slices.pop(slice_hrn)
363 for hrn in self.aggregates.keys():
364 self.aggregates[hrn].deleteSlice(cred, slice_hrn)
368 def startSlice(self, slice_hrn):
370 Stop the slice at plc.
372 cred = self.credential
374 for hrn in self.aggregates.keys():
375 self.aggregates[hrn].startSlice(cred, slice_hrn)
378 def stopSlice(self, slice_hrn):
380 Stop the slice at plc
382 cred = self.credential
383 for hrn in self.aggregates.keys():
384 self.aggregates[hrn].startSlice(cred, slice_hrn)
387 def resetSlice(self, slice_hrn):
391 # XX not yet implemented
396 Return the policy of this slice manager.
403 ##############################
404 ## Server methods here for now
405 ##############################
407 def list_nodes(self, cred):
408 self.decode_authentication(cred, 'listnodes')
409 return self.getNodes()
411 def list_slices(self, cred):
412 self.decode_authentication(cred, 'listslices')
413 return self.getSlices()
415 def get_resources(self, cred, hrn):
416 self.decode_authentication(cred, 'listnodes')
417 return self.getResources(hrn)
419 def get_ticket(self, cred, hrn, rspec):
420 self.decode_authentication(cred, 'getticket')
421 return self.getTicket(hrn, rspec)
423 def get_policy(self, cred):
424 self.decode_authentication(cred, 'getpolicy')
425 return self.getPolicy()
427 def create_slice(self, cred, hrn, rspec):
428 self.decode_authentication(cred, 'creatslice')
429 return self.createSlice(cred, hrn, rspec)
431 def delete_slice(self, cred, hrn):
432 self.decode_authentication(cred, 'deleteslice')
433 return self.deleteSlice(hrn)
435 def start_slice(self, cred, hrn):
436 self.decode_authentication(cred, 'startslice')
437 return self.startSlice(hrn)
439 def stop_slice(self, cred, hrn):
440 self.decode_authentication(cred, 'stopslice')
441 return self.stopSlice(hrn)
443 def reset_slice(self, cred, hrn):
444 self.decode_authentication(cred, 'resetslice')
445 return self.resetSlice(hrn)
447 def register_functions(self):
448 GeniServer.register_functions(self)
450 # Aggregate interface methods
451 self.server.register_function(self.list_nodes)
452 self.server.register_function(self.list_slices)
453 self.server.register_function(self.get_resources)
454 self.server.register_function(self.get_policy)
455 self.server.register_function(self.create_slice)
456 self.server.register_function(self.delete_slice)
457 self.server.register_function(self.start_slice)
458 self.server.register_function(self.stop_slice)
459 self.server.register_function(self.reset_slice)