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()
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)
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_gredential(self_cred)
132 #ma_credential = Credential(string = ma_cred)
133 #ma_credential.save_to_file(ma_cred_filename)
135 ma_cred = Certificate(filename = self.cert_file)
137 self.credential = ma_cred.save_to_string()
139 def hostname_to_hrn(self, login_base, hostname):
141 Convert hrn to plantelab name.
143 genihostname = "_".join(hostname.split("."))
144 return ".".join([self.hrn, login_base, genihostname])
146 def slicename_to_hrn(self, slicename):
148 Convert hrn to planetlab name.
150 slicename = slicename.replace("_", ".")
151 return ".".join([self.hrn, slicename])
153 def refresh_components(self):
155 Update the cached list of nodes and save in 4 differnt formats
156 (rspec, dns, ip, hrn)
160 # get node list in rspec format
162 rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
163 # filter nodes according to policy
164 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
165 # extract ifspec info 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 # resolve component hostnames
173 nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
175 # resolve site login_bases
176 site_ids = [node['site_id'] for node in nodes]
177 sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
180 site_dict[site['site_id']] = site['login_base']
182 # filter nodes according to policy
183 # convert plc names to geni hrn
186 node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
188 # Do not allow nodes found in blacklist, only allow nodes found in whitelist
189 if self.policy['whitelist'] and node_hrn not in self.polciy['whitelist']:
191 if self.policy['blacklist'] and node_hrn in self.policy['blacklist']:
193 nodedict[node_hrn] = node['hostname']
196 node_details['rspec'] = rspec.toxml()
197 node_details['hrn'] = nodedict.keys()
198 node_details['dns'] = nodedict.values()
199 node_details['ip'] = ips
201 self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
205 # update timestamp and threshold
206 self.timestamp['timestamp'] = datetime.datetime.now()
207 delta = datetime.timedelta(hours=self.nodes_ttl)
208 self.threshold = self.timestamp['timestamp'] + delta
209 self.timestamp.write()
211 def load_components(self):
213 Read cached list of nodes.
215 # Read component list from cached file
217 self.timestamp.load()
218 time_format = "%Y-%m-%d %H:%M:%S"
219 timestamp = self.timestamp['timestamp']
220 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
221 delta = datetime.timedelta(hours=self.nodes_ttl)
222 self.threshold = self.timestamp['timestamp'] + delta
224 def load_policy(self):
226 Read the list of blacklisted and whitelisted nodes.
231 def getComponents(self, type = 'rspec'):
233 Return a list of components at this aggregate.
235 valid_types = ['rspec', 'hrn', 'dns', 'ip']
236 if type not in valid_types:
237 raise Exception, "Invalid type specified, must be one of the following: %s" \
238 % ", ".join(valid_types)
240 # Reload components list
241 now = datetime.datetime.now()
242 #self.load_components()
243 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
244 self.refresh_components()
245 elif now < self.threshold and not self.nodes.keys():
246 self.load_components()
247 return self.nodes.keys()
249 def getSlices(self, hrn):
251 Return a list of instnatiated managed by this slice manager.
254 # XX list only the slices at the specfied hrn
255 return dict(self.slices)
257 def get_rspec(self, hrn, type):
259 Get resource information from PLC
262 # Get the required nodes
263 if type in ['aggregate']:
264 nodes = self.shell.GetNodes(self.auth)
265 elif type in ['slice']:
266 slicename = hrn_to_pl_slicename(hrn)
267 slices = self.shell.GetSlices(self.auth, [slicename])
268 node_ids = slices[0]['node_ids']
269 nodes = self.shell.GetNodes(self.auth, node_ids)
271 # Get all network interfaces
274 interface_ids.extend(node['nodenetwork_ids'])
275 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
277 for interface in interfaces:
278 interface_dict[interface['nodenetwork_id']] = interface
280 # join nodes with thier interfaces
282 node['interfaces'] = []
283 for nodenetwork_id in node['nodenetwork_ids']:
284 node['interfaces'].append(interface_dict[nodenetwork_id])
286 # convert and threshold to ints
287 if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
288 timestamp = self.timestamp['timestamp']
289 threshold = self.threshold
291 timestamp = datetime.datetime.now()
292 delta = datetime.timedelta(hours=self.nodes_ttl)
293 threshold = timestamp + delta
296 start_time = int(timestamp.strftime("%s"))
297 end_time = int(threshold.strftime("%s"))
298 duration = end_time - start_time
300 # create the plc dict
301 networks = {'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}
302 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
304 # convert the plc dict to an rspec dict
305 resouceDict = RspecDict(resources)
307 # convert the rspec dict to xml
309 rspec.parseDict(resourceDict)
312 def getResources(self, slice_hrn):
314 Return the current rspec for the specified slice.
316 slicename = self.hrn_to_plcslicename(slice_hrn)
317 rspec = self.get_rspec(slicenamem, 'slice')
322 def createSlice(self, slice_hrn, rspec, attributes = []):
324 Instantiate the specified slice according to whats defined in the rspec.
327 # save slice state locally
328 # we can assume that spec object has been validated so its safer to
329 # save this instead of the unvalidated rspec the user gave us
330 self.slices[slice_hrn] = spec.toxml()
334 slicename = self.hrn_to_plcslicename(slice_hrn)
335 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
337 raise RecordNotFound(slice_hrn)
340 # find out where this slice is currently running
341 nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
342 hostnames = [node['hostname'] for node in nodes]
344 # get netspec details
346 nodespecs = spec.getDictsByTagName('NodeSpec')
347 nodes = [nodespec['name'] for nodespec in nodespecs]
349 # save slice state locally
350 # we can assume that spec object has been validated so its safer to
351 # save this instead of the unvalidated rspec the user gave us
352 self.slices[slice_hrn] = spec.toxml()
355 # remove nodes not in rspec
356 delete_nodes = set(hostnames).difference(nodes)
357 # add nodes from rspec
358 added_nodes = set(nodes).difference(hostnames)
360 shell.AddSliceToNodes(self.auth, slicename, added_nodes)
361 shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
363 for attribute in attributes:
364 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
365 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
367 # contact registry to get slice users and add them to the slice
368 slice_record = self.registry.resolve(self.credential, slice_hrn)
369 # persons = slice_record['users']
371 #for person in persons:
372 # shell.AddPersonToSlice(person['email'], slice_name)
375 def update_slice(self, slice_hrn, rspec, attributes = []):
376 return self.create_slice(slice_hrn, rspec, attributes)
378 def deleteSlice_(self, slice_hrn):
380 Remove this slice from all components it was previouly associated with and
381 free up the resources it was using.
383 if self.slices.has_key(slice_hrn):
384 self.slices.pop(slice_hrn)
387 slicename = self.hrn_to_plcslicename(slice_hrn)
388 slices = shell.GetSlices(self.auth, [slicename])
393 shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
396 def startSlice(self, slice_hrn):
398 Stop the slice at plc.
400 slicename = hrn_to_plcslicename(slice_hrn)
401 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
403 #raise RecordNotFound(slice_hrn)
406 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
407 attribute_id = attreibutes[0]
408 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
411 def stopSlice(self, slice_hrn):
413 Stop the slice at plc
415 slicename = hrn_to_plcslicename(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, "0")
427 def resetSlice(self, slice_hrn):
431 # XX not yet implemented
436 Return this aggregates policy.
443 ##############################
444 ## Server methods here for now
445 ##############################
447 def list_components(self):
448 return self.getComponents()
450 def list_slices(self, cred, hrn):
451 self.decode_authentication(cred, 'list')
452 return self.getSlices(hrn)
454 def get_resources(self, cred, hrn):
455 self.decode_authentication(cred, 'info')
456 return self.getResources(hrn)
458 def get_policy(self, cred):
459 self.decode_authentication(cred, 'info')
460 return self.getPolicy()
462 def create_slice(self, cred, hrn, rspec):
463 self.decode_authentication(cred, 'embed')
464 return self.createSlice(hrn)
466 def update_slice(self, cred, hrn, rspec):
467 self.decode_authentication(cred, 'embed')
468 return self.updateSlice(hrn)
470 def delete_slice(self, cred, hrn):
471 self.decode_authentication(cred, 'embed')
472 return self.deleteSlice(hrn)
474 def start_slice(self, cred, hrn):
475 self.decode_authentication(cred, 'control')
476 return self.startSlice(hrn)
478 def stop_slice(self, cred, hrn):
479 self.decode_authentication(cred, 'control')
480 return self.stopSlice(hrn)
482 def reset_slice(self, cred, hrn):
483 self.decode_authentication(cred, 'control')
484 return self.resetSlice(hrn)
486 def register_functions(self):
487 GeniServer.register_functions(self)
489 # Aggregate interface methods
490 self.server.register_function(self.list_components)
491 self.server.register_function(self.list_slices)
492 self.server.register_function(self.get_resources)
493 self.server.register_function(self.get_policy)
494 self.server.register_function(self.create_slice)
495 self.server.register_function(self.update_slice)
496 self.server.register_function(self.delete_slice)
497 self.server.register_function(self.start_slice)
498 self.server.register_function(self.stop_slice)
499 self.server.register_function(self.reset_slice)