7 from types import StringTypes, ListType
8 from geni.util.geniserver import GeniServer
9 from geni.util.geniclient import *
10 from geni.util.cert import Keypair, Certificate
11 from geni.util.credential import Credential
12 from geni.util.trustedroot import TrustedRootList
13 from geni.util.excep import *
14 from geni.util.misc import *
15 from geni.util.config import Config
16 from geni.util.rspec import Rspec
17 from geni.util.specdict import *
18 from geni.util.storage import SimpleStorage
20 class Aggregate(GeniServer):
36 # Create a new aggregate object.
38 # @param ip the ip address to listen on
39 # @param port the port to listen on
40 # @param key_file private key filename of registry
41 # @param cert_file certificate filename containing public key (could be a GID file)
43 def __init__(self, ip, port, key_file, cert_file, config = "/usr/share/geniwrapper/geni/util/geni_config"):
44 GeniServer.__init__(self, ip, port, key_file, cert_file)
45 self.key_file = key_file
46 self.cert_file = cert_file
47 self.config = Config(config)
48 self.basedir = self.config.GENI_BASE_DIR + os.sep
49 self.server_basedir = self.basedir + os.sep + "geni" + os.sep
50 self.hrn = self.config.GENI_INTERFACE_HRN
52 nodes_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.components'])
53 self.nodes = SimpleStorage(nodes_file)
56 slices_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.slices'])
57 self.slices = SimpleStorage(slices_file)
60 policy_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.policy'])
61 self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
64 timestamp_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.timestamp'])
65 self.timestamp = SimpleStorage(timestamp_file)
67 # How long before we refresh nodes cache
71 #self.connectRegistry()
72 #self.loadCredential()
74 def connectRegistry(self):
76 Connect to the registry
78 # connect to registry using GeniClient
79 address = self.config.GENI_REGISTRY_HOSTNAME
80 port = self.config.GENI_REGISTRY_PORT
81 url = 'https://%(address)s:%(port)s' % locals()
82 self.registry = GeniClient(url, self.key_file, self.cert_file)
87 Connect to the plc api interface. First attempt to impor thte shell, if that fails
88 try to connect to the xmlrpc server.
90 self.auth = {'Username': self.config.GENI_PLC_USER,
91 'AuthMethod': 'password',
92 'AuthString': self.config.GENI_PLC_PASSWORD}
95 # try to import PLC.Shell directly
96 sys.path.append(self.config.GENI_PLC_SHELL_PATH)
98 self.shell = PLC.Shell.Shell(globals())
99 self.shell.AuthCheck()
101 # connect to plc api via xmlrpc
102 plc_host = self.config.GENI_PLC_HOST
103 plc_port = self.config.GENI_PLC_PORT
104 plc_api_path = self.config.GENI_PLC_API_PATH
105 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
106 self.auth = {'Username': self.config.GENI_PLC_USER,
107 'AuthMethod': 'password',
108 'AuthString': self.config.GENI_PLC_PASSWORD}
110 self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
111 self.shell.AuthCheck(self.auth)
113 def loadCredential(self):
115 Attempt to load credential from file if it exists. If it doesnt get
116 credential from registry.
119 self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
120 ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
122 # see if this file exists
124 cred = Credential(filename = ma_cred_filename, subject=self.hrn)
125 self.credential = cred.save_to_string()
127 # get self credential
128 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
129 self_credential = Credential(string = self_cred)
130 self_credential.save_to_file(self_cred_filename)
133 ma_cred = self.registry.get_credential(self_cred)
134 ma_credential = Credential(string = ma_cred)
135 ma_credential.save_to_file(ma_cred_filename)
136 self.credential = ma_cred
138 def hostname_to_hrn(self, login_base, hostname):
140 Convert hrn to plantelab name.
142 genihostname = "_".join(hostname.split("."))
143 return ".".join([self.hrn, login_base, genihostname])
145 def slicename_to_hrn(self, slicename):
147 Convert hrn to planetlab name.
149 slicename = slicename.replace("_", ".")
150 return ".".join([self.hrn, slicename])
152 def refresh_components(self):
154 Update the cached list of nodes and save in 4 differnt formats
158 # get node list in rspec format
160 rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
162 # filter nodes according to policy
163 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
165 # extract ifspecs from rspec to get ip's
167 ifspecs = rspec.getDictsByTagName('IfSpec')
168 for ifspec in ifspecs:
169 if ifspec.has_key('addr') and ifspec['addr']:
170 ips.append(ifspec['addr'])
172 # extract nodespecs from rspec to get dns names
174 nodespecs = rspec.getDictsByTagName('NodeSpec')
175 for nodespec in nodespecs:
176 if nodespec.has_key('name') and nodespec['name']:
177 hostnames.append(nodespec['name'])
181 node_details['rspec'] = rspec.toxml()
182 node_details['ip'] = ips
183 node_details['dns'] = hostnames
185 self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
189 # update timestamp and threshold
190 self.timestamp['timestamp'] = datetime.datetime.now()
191 delta = datetime.timedelta(hours=self.nodes_ttl)
192 self.threshold = self.timestamp['timestamp'] + delta
193 self.timestamp.write()
195 def load_components(self):
197 Read cached list of nodes.
199 # Read component list from cached file
201 self.timestamp.load()
202 time_format = "%Y-%m-%d %H:%M:%S"
203 timestamp = self.timestamp['timestamp']
204 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
205 delta = datetime.timedelta(hours=self.nodes_ttl)
206 self.threshold = self.timestamp['timestamp'] + delta
208 def load_policy(self):
210 Read the list of blacklisted and whitelisted nodes.
215 def getNodes(self, format = 'rspec'):
217 Return a list of components at this aggregate.
219 valid_formats = ['rspec', 'hrn', 'dns', 'ip']
222 if format not in valid_formats:
223 raise Exception, "Invalid format specified, must be one of the following: %s" \
224 % ", ".join(valid_formats)
226 # Reload components list
227 now = datetime.datetime.now()
228 #self.load_components()
229 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
230 self.refresh_components()
231 elif now < self.threshold and not self.nodes.keys():
232 self.load_components()
233 return self.nodes[format]
237 Return a list of instnatiated managed by this slice manager.
240 slices = self.shell.GetSlices(self.auth, {}, ['name'])
241 slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]
245 def get_rspec(self, hrn, type):
247 Get resource information from PLC
250 # Get the required nodes
251 if type in ['aggregate']:
252 nodes = self.shell.GetNodes(self.auth)
253 try: linkspecs = self.shell.GetLinkSpecs() # if call is supported
254 except: linkspecs = []
255 elif type in ['slice']:
256 slicename = hrn_to_pl_slicename(hrn)
257 slices = self.shell.GetSlices(self.auth, [slicename])
258 node_ids = slices[0]['node_ids']
259 nodes = self.shell.GetNodes(self.auth, node_ids)
261 # Filter out whitelisted nodes
262 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
263 nodes = filter(public_nodes, nodes)
265 # Get all network interfaces
268 interface_ids.extend(node['nodenetwork_ids'])
269 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
271 for interface in interfaces:
272 interface_dict[interface['nodenetwork_id']] = interface
274 # join nodes with thier interfaces
276 node['interfaces'] = []
277 for nodenetwork_id in node['nodenetwork_ids']:
278 node['interfaces'].append(interface_dict[nodenetwork_id])
280 # convert and threshold to ints
281 if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
282 timestamp = self.timestamp['timestamp']
283 threshold = self.threshold
285 timestamp = datetime.datetime.now()
286 delta = datetime.timedelta(hours=self.nodes_ttl)
287 threshold = timestamp + delta
290 start_time = int(timestamp.strftime("%s"))
291 end_time = int(threshold.strftime("%s"))
292 duration = end_time - start_time
294 # create the plc dict
295 networks = [{'nodes': nodes,
298 'start_time': start_time,
299 'duration': duration}]
300 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
302 # convert the plc dict to an rspec dict
303 resourceDict = RspecDict(resources)
304 # convert the rspec dict to xml
306 rspec.parseDict(resourceDict)
309 def getResources(self, slice_hrn):
311 Return the current rspec for the specified slice.
313 rspec = self.get_rspec(slice_hrn, 'slice')
318 def getTicket(self, hrn, rspec):
320 Retrieve a ticket. This operation is currently implemented on PLC
321 only (see SFA, engineering decisions); it is not implemented on
324 @param name name of the slice to retrieve a ticket for
325 @param rspec resource specification dictionary
326 @return the string representation of a ticket object
328 #self.registry.get_ticket(name, rspec)
333 def createSlice(self, slice_hrn, rspec, attributes = []):
335 Instantiate the specified slice according to whats defined in the rspec.
339 # save slice state locally
340 # we can assume that spec object has been validated so its safer to
341 # save this instead of the unvalidated rspec the user gave us
342 self.slices[slice_hrn] = spec.toxml()
346 slicename = hrn_to_pl_slicename(slice_hrn)
347 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
349 raise RecordNotFound(slice_hrn)
352 # find out where this slice is currently running
353 nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
354 hostnames = [node['hostname'] for node in nodelist]
356 # get netspec details
357 nodespecs = spec.getDictsByTagName('NodeSpec')
359 for nodespec in nodespecs:
360 if isinstance(nodespec['name'], list):
361 nodes.extend(nodespec['name'])
362 elif isinstance(nodespec['name'], StringTypes):
363 nodes.append(nodespec['name'])
365 # save slice state locally
366 # we can assume that spec object has been validated so its safer to
367 # save this instead of the unvalidated rspec the user gave us
368 self.slices[slice_hrn] = spec.toxml()
371 # remove nodes not in rspec
372 deleted_nodes = list(set(hostnames).difference(nodes))
373 # add nodes from rspec
374 added_nodes = list(set(nodes).difference(hostnames))
376 self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
377 self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
379 for attribute in attributes:
380 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
381 self.shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
383 # contact registry to get slice users and add them to the slice
384 #slice_record = self.registry.resolve(self.credential, slice_hrn)
385 # persons = slice_record['users']
386 # for perosn in persons:
387 # shell.AddPersonToSlice(person['email'], slice_name)
390 def updateSlice(self, slice_hrn, rspec, attributes = []):
391 return self.create_slice(slice_hrn, rspec, attributes)
393 def deleteSlice(self, slice_hrn):
395 Remove this slice from all components it was previouly associated with and
396 free up the resources it was using.
398 if self.slices.has_key(slice_hrn):
399 self.slices.pop(slice_hrn)
402 slicename = hrn_to_pl_slicename(slice_hrn)
403 slices = self.shell.GetSlices(self.auth, [slicename])
408 self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
411 def startSlice(self, slice_hrn):
413 Stop the slice at plc.
415 slicename = hrn_to_pl_slicename(slice_hrn)
416 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
418 #raise RecordNotFound(slice_hrn)
421 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
422 attribute_id = attreibutes[0]
423 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
426 def stopSlice(self, slice_hrn):
428 Stop the slice at plc
430 slicename = hrn_to_pl_slicename(slice_hrn)
431 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
433 #raise RecordNotFound(slice_hrn)
436 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
437 attribute_id = attreibutes[0]
438 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
442 def resetSlice(self, slice_hrn):
446 # XX not yet implemented
451 Return this aggregates policy.
458 ##############################
459 ## Server methods here for now
460 ##############################
463 # XX fix rights, should be function name defined in
464 # privilege_table (from util/rights.py)
465 def list_nodes(self, cred):
466 self.decode_authentication(cred, 'listnodes')
467 return self.getNodes()
469 def list_slices(self, cred):
470 self.decode_authentication(cred, 'listslices')
471 return self.getSlices()
473 def get_resources(self, cred, hrn):
474 self.decode_authentication(cred, 'listnodes')
475 return self.getResources(hrn)
477 def get_ticket(self, cred, hrn, rspec):
478 self.decode_authentication(cred, 'getticket')
479 return self.getTicket(hrn, rspec)
481 def get_policy(self, cred):
482 self.decode_authentication(cred, 'getpolicy')
483 return self.getPolicy()
485 def create_slice(self, cred, hrn, rspec):
486 self.decode_authentication(cred, 'createslice')
487 return self.createSlice(hrn, rspec)
489 def update_slice(self, cred, hrn, rspec):
490 self.decode_authentication(cred, 'updateslice')
491 return self.updateSlice(hrn)
493 def delete_slice(self, cred, hrn):
494 self.decode_authentication(cred, 'deleteslice')
495 return self.deleteSlice(hrn)
497 def start_slice(self, cred, hrn):
498 self.decode_authentication(cred, 'startslice')
499 return self.startSlice(hrn)
501 def stop_slice(self, cred, hrn):
502 self.decode_authentication(cred, 'stopslice')
503 return self.stopSlice(hrn)
505 def reset_slice(self, cred, hrn):
506 self.decode_authentication(cred, 'resetslice')
507 return self.resetSlice(hrn)
509 def register_functions(self):
510 GeniServer.register_functions(self)
512 # Aggregate interface methods
513 self.server.register_function(self.list_nodes)
514 self.server.register_function(self.list_slices)
515 self.server.register_function(self.get_resources)
516 self.server.register_function(self.get_policy)
517 self.server.register_function(self.create_slice)
518 self.server.register_function(self.update_slice)
519 self.server.register_function(self.delete_slice)
520 self.server.register_function(self.start_slice)
521 self.server.register_function(self.stop_slice)
522 self.server.register_function(self.reset_slice)