7 from geni.util.geniserver import GeniServer
8 from geni.util.geniclient import *
9 from geni.util.cert import Keypair, Certificate
10 from geni.util.credential import Credential
11 from geni.util.trustedroot import TrustedRootList
12 from geni.util.excep import *
13 from geni.util.misc import *
14 from geni.util.config import Config
15 from geni.util.rspec import Rspec
16 from geni.util.specdict import *
17 from geni.util.storage import SimpleStorage
19 class Aggregate(GeniServer):
35 # Create a new aggregate 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
51 nodes_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.components'])
52 self.nodes = SimpleStorage(nodes_file)
55 slices_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.slices'])
56 self.slices = SimpleStorage(slices_file)
59 policy_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.policy'])
60 self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
63 timestamp_file = os.sep.join([self.server_basedir, 'agg.' + self.hrn + '.timestamp'])
64 self.timestamp = SimpleStorage(timestamp_file)
69 self.connectRegistry()
70 #self.loadCredential()
72 def connectRegistry(self):
74 Connect to the registry
76 # connect to registry using GeniClient
77 address = self.config.GENI_REGISTRY_HOSTNAME
78 port = self.config.GENI_REGISTRY_PORT
79 url = 'https://%(address)s:%(port)s' % locals()
80 self.registry = GeniClient(url, self.key_file, self.cert_file)
85 Connect to the plc api interface. First attempt to impor thte shell, if that fails
86 try to connect to the xmlrpc server.
88 self.auth = {'Username': self.config.GENI_PLC_USER,
89 'AuthMethod': 'password',
90 'AuthString': self.config.GENI_PLC_PASSWORD}
93 # try to import PLC.Shell directly
94 sys.path.append(self.config.GENI_PLC_SHELL_PATH)
96 self.shell = PLC.Shell.Shell(globals())
97 self.shell.AuthCheck()
99 # connect to plc api via xmlrpc
100 plc_host = self.config.GENI_PLC_HOST
101 plc_port = self.config.GENI_PLC_PORT
102 plc_api_path = self.config.GENI_PLC_API_PATH
103 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
104 self.auth = {'Username': self.config.GENI_PLC_USER,
105 'AuthMethod': 'password',
106 'AuthString': self.config.GENI_PLC_PASSWORD}
108 self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
109 self.shell.AuthCheck(self.auth)
111 def loadCredential(self):
113 Attempt to load credential from file if it exists. If it doesnt get
114 credential from registry.
117 self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
118 ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
120 # see if this file exists
122 cred = Credential(filename = ma_cred_filename, subject=self.hrn)
123 self.credential = cred.save_to_string()
125 # get self credential
126 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
127 self_credential = Credential(string = self_cred)
128 self_credential.save_to_file(self_cred_filename)
131 ma_cred = self.registry.get_credential(self_cred)
132 ma_credential = Credential(string = ma_cred)
133 ma_credential.save_to_file(ma_cred_filename)
134 self.credential = ma_cred
136 def hostname_to_hrn(self, login_base, hostname):
138 Convert hrn to plantelab name.
140 genihostname = "_".join(hostname.split("."))
141 return ".".join([self.hrn, login_base, genihostname])
143 def slicename_to_hrn(self, slicename):
145 Convert hrn to planetlab name.
147 slicename = slicename.replace("_", ".")
148 return ".".join([self.hrn, slicename])
150 def refresh_components(self):
152 Update the cached list of nodes and save in 4 differnt formats
153 (rspec, dns, ip, hrn)
157 # get node list in rspec format
159 rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
160 # filter nodes according to policy
161 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
162 # extract ifspec info to get ip's
164 ifspecs = rspec.getDictsByTagName('IfSpec')
165 for ifspec in ifspecs:
166 if ifspec.has_key('addr') and ifspec['addr']:
167 ips.append(ifspec['addr'])
169 # resolve component hostnames
170 nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id', 'slice_ids_whitelist'])
172 # resolve site login_bases
173 site_ids = [node['site_id'] for node in nodes]
174 sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
177 site_dict[site['site_id']] = site['login_base']
179 # filter nodes according to policy policy
180 # filter nodes with whitelist
181 # convert plc names to geni hrn
184 node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
185 # filter nodes with a whitelist
186 if node.has_key('slice_ids_whitelist') and node['slice_ids_whitelist']:
188 # Do not allow nodes not found in whitelist policy
189 if self.policy['whitelist'] and node_hrn not in self.polciy['whitelist']:
191 # Do not allow nodes found in blacklist policy
192 if self.policy['blacklist'] and node_hrn in self.policy['blacklist']:
194 nodedict[node_hrn] = node['hostname']
197 node_details['rspec'] = rspec.toxml()
198 node_details['hrn'] = nodedict.keys()
199 node_details['dns'] = nodedict.values()
200 node_details['ip'] = ips
202 self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
206 # update timestamp and threshold
207 self.timestamp['timestamp'] = datetime.datetime.now()
208 delta = datetime.timedelta(hours=self.nodes_ttl)
209 self.threshold = self.timestamp['timestamp'] + delta
210 self.timestamp.write()
212 def load_components(self):
214 Read cached list of nodes.
216 # Read component list from cached file
218 self.timestamp.load()
219 time_format = "%Y-%m-%d %H:%M:%S"
220 timestamp = self.timestamp['timestamp']
221 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
222 delta = datetime.timedelta(hours=self.nodes_ttl)
223 self.threshold = self.timestamp['timestamp'] + delta
225 def load_policy(self):
227 Read the list of blacklisted and whitelisted nodes.
232 def getNodes(self, format = 'rspec'):
234 Return a list of components at this aggregate.
236 valid_formats = ['rspec', 'hrn', 'dns', 'ip']
239 if format not in valid_formats:
240 raise Exception, "Invalid format specified, must be one of the following: %s" \
241 % ", ".join(valid_formats)
243 # Reload components list
244 now = datetime.datetime.now()
245 #self.load_components()
246 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
247 self.refresh_components()
248 elif now < self.threshold and not self.nodes.keys():
249 self.load_components()
250 return self.nodes[format]
254 Return a list of instnatiated managed by this slice manager.
257 slices = self.shell.GetSlices(self.auth, {}, ['name'])
258 slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]
262 def get_rspec(self, hrn, type):
264 Get resource information from PLC
267 # Get the required nodes
268 if type in ['aggregate']:
269 nodes = self.shell.GetNodes(self.auth)
270 elif type in ['slice']:
271 slicename = hrn_to_pl_slicename(hrn)
272 slices = self.shell.GetSlices(self.auth, [slicename])
273 node_ids = slices[0]['node_ids']
274 nodes = self.shell.GetNodes(self.auth, node_ids)
276 # Filter out whitelisted nodes
277 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
278 nodes = filter(public_nodes, nodes)
280 # Get all network interfaces
283 interface_ids.extend(node['nodenetwork_ids'])
284 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
286 for interface in interfaces:
287 interface_dict[interface['nodenetwork_id']] = interface
289 # join nodes with thier interfaces
291 node['interfaces'] = []
292 for nodenetwork_id in node['nodenetwork_ids']:
293 node['interfaces'].append(interface_dict[nodenetwork_id])
295 # convert and threshold to ints
296 if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
297 timestamp = self.timestamp['timestamp']
298 threshold = self.threshold
300 timestamp = datetime.datetime.now()
301 delta = datetime.timedelta(hours=self.nodes_ttl)
302 threshold = timestamp + delta
305 start_time = int(timestamp.strftime("%s"))
306 end_time = int(threshold.strftime("%s"))
307 duration = end_time - start_time
309 # create the plc dict
310 networks = [{'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}]
311 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
313 # convert the plc dict to an rspec dict
314 resourceDict = RspecDict(resources)
315 # convert the rspec dict to xml
317 rspec.parseDict(resourceDict)
320 def getResources(self, slice_hrn):
322 Return the current rspec for the specified slice.
324 rspec = self.get_rspec(slice_hrn, 'slice')
329 def getTicket(self, hrn, rspec):
331 Retrieve a ticket. This operation is currently implemented on PLC
332 only (see SFA, engineering decisions); it is not implemented on
335 @param name name of the slice to retrieve a ticket for
336 @param rspec resource specification dictionary
337 @return the string representation of a ticket object
339 #self.registry.get_ticket(name, rspec)
344 def createSlice(self, slice_hrn, rspec, attributes = []):
346 Instantiate the specified slice according to whats defined in the rspec.
350 # save slice state locally
351 # we can assume that spec object has been validated so its safer to
352 # save this instead of the unvalidated rspec the user gave us
353 self.slices[slice_hrn] = spec.toxml()
357 slicename = hrn_to_pl_slicename(slice_hrn)
358 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
360 raise RecordNotFound(slice_hrn)
363 # find out where this slice is currently running
364 nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
365 hostnames = [node['hostname'] for node in nodes]
367 # get netspec details
368 nodespecs = spec.getDictsByTagName('NodeSpec')
369 nodes = [nodespec['name'] for nodespec in nodespecs]
371 # save slice state locally
372 # we can assume that spec object has been validated so its safer to
373 # save this instead of the unvalidated rspec the user gave us
374 self.slices[slice_hrn] = spec.toxml()
377 # remove nodes not in rspec
378 deleted_nodes = list(set(hostnames).difference(nodes))
379 # add nodes from rspec
380 added_nodes = list(set(nodes).difference(hostnames))
382 self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
383 self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
385 for attribute in attributes:
386 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
387 self.shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
389 # contact registry to get slice users and add them to the slice
390 #slice_record = self.registry.resolve(self.credential, slice_hrn)
391 # persons = slice_record['users']
393 #for person in persons:
394 # shell.AddPersonToSlice(person['email'], slice_name)
397 def updateSlice(self, slice_hrn, rspec, attributes = []):
398 return self.create_slice(slice_hrn, rspec, attributes)
400 def deleteSlice(self, slice_hrn):
402 Remove this slice from all components it was previouly associated with and
403 free up the resources it was using.
405 if self.slices.has_key(slice_hrn):
406 self.slices.pop(slice_hrn)
409 slicename = hrn_to_pl_slicename(slice_hrn)
410 slices = self.shell.GetSlices(self.auth, [slicename])
415 self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
418 def startSlice(self, slice_hrn):
420 Stop the slice at plc.
422 slicename = hrn_to_pl_slicename(slice_hrn)
423 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
425 #raise RecordNotFound(slice_hrn)
428 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
429 attribute_id = attreibutes[0]
430 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
433 def stopSlice(self, slice_hrn):
435 Stop the slice at plc
437 slicename = hrn_to_pl_slicename(slice_hrn)
438 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
440 #raise RecordNotFound(slice_hrn)
443 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
444 attribute_id = attreibutes[0]
445 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
449 def resetSlice(self, slice_hrn):
453 # XX not yet implemented
458 Return this aggregates policy.
465 ##############################
466 ## Server methods here for now
467 ##############################
470 # XX fix rights, should be function name defined in
471 # privilege_table (from util/rights.py)
472 def list_nodes(self, cred, format):
473 self.decode_authentication(cred, 'listnodes')
474 return self.getNodes(format)
476 def list_slices(self, cred):
477 self.decode_authentication(cred, 'listslices')
478 return self.getSlices()
480 def get_resources(self, cred, hrn):
481 self.decode_authentication(cred, 'listnodes')
482 return self.getResources(hrn)
484 def get_ticket(self, cred, hrn, rspec):
485 self.decode_authentication(cred, 'getticket')
486 return self.getTicket(hrn, rspec)
488 def get_policy(self, cred):
489 self.decode_authentication(cred, 'getpolicy')
490 return self.getPolicy()
492 def create_slice(self, cred, hrn, rspec):
493 self.decode_authentication(cred, 'createslice')
494 return self.createSlice(hrn, rspec)
496 def update_slice(self, cred, hrn, rspec):
497 self.decode_authentication(cred, 'updateslice')
498 return self.updateSlice(hrn)
500 def delete_slice(self, cred, hrn):
501 self.decode_authentication(cred, 'deleteslice')
502 return self.deleteSlice(hrn)
504 def start_slice(self, cred, hrn):
505 self.decode_authentication(cred, 'startslice')
506 return self.startSlice(hrn)
508 def stop_slice(self, cred, hrn):
509 self.decode_authentication(cred, 'stopslice')
510 return self.stopSlice(hrn)
512 def reset_slice(self, cred, hrn):
513 self.decode_authentication(cred, 'resetslice')
514 return self.resetSlice(hrn)
516 def register_functions(self):
517 GeniServer.register_functions(self)
519 # Aggregate interface methods
520 self.server.register_function(self.list_nodes)
521 self.server.register_function(self.list_slices)
522 self.server.register_function(self.get_resources)
523 self.server.register_function(self.get_policy)
524 self.server.register_function(self.create_slice)
525 self.server.register_function(self.update_slice)
526 self.server.register_function(self.delete_slice)
527 self.server.register_function(self.start_slice)
528 self.server.register_function(self.stop_slice)
529 self.server.register_function(self.reset_slice)