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 elif type in ['slice']:
254 slicename = hrn_to_pl_slicename(hrn)
255 slices = self.shell.GetSlices(self.auth, [slicename])
256 node_ids = slices[0]['node_ids']
257 nodes = self.shell.GetNodes(self.auth, node_ids)
259 # Filter out whitelisted nodes
260 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
261 nodes = filter(public_nodes, nodes)
263 # Get all network interfaces
266 interface_ids.extend(node['nodenetwork_ids'])
267 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
269 for interface in interfaces:
270 interface_dict[interface['nodenetwork_id']] = interface
272 # join nodes with thier interfaces
274 node['interfaces'] = []
275 for nodenetwork_id in node['nodenetwork_ids']:
276 node['interfaces'].append(interface_dict[nodenetwork_id])
278 # convert and threshold to ints
279 if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
280 timestamp = self.timestamp['timestamp']
281 threshold = self.threshold
283 timestamp = datetime.datetime.now()
284 delta = datetime.timedelta(hours=self.nodes_ttl)
285 threshold = timestamp + delta
288 start_time = int(timestamp.strftime("%s"))
289 end_time = int(threshold.strftime("%s"))
290 duration = end_time - start_time
292 # create the plc dict
293 networks = [{'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}]
294 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
296 # convert the plc dict to an rspec dict
297 resourceDict = RspecDict(resources)
298 # convert the rspec dict to xml
300 rspec.parseDict(resourceDict)
303 def getResources(self, slice_hrn):
305 Return the current rspec for the specified slice.
307 rspec = self.get_rspec(slice_hrn, 'slice')
312 def getTicket(self, hrn, rspec):
314 Retrieve a ticket. This operation is currently implemented on PLC
315 only (see SFA, engineering decisions); it is not implemented on
318 @param name name of the slice to retrieve a ticket for
319 @param rspec resource specification dictionary
320 @return the string representation of a ticket object
322 #self.registry.get_ticket(name, rspec)
327 def createSlice(self, slice_hrn, rspec, attributes = []):
329 Instantiate the specified slice according to whats defined in the rspec.
333 # save slice state locally
334 # we can assume that spec object has been validated so its safer to
335 # save this instead of the unvalidated rspec the user gave us
336 self.slices[slice_hrn] = spec.toxml()
340 slicename = hrn_to_pl_slicename(slice_hrn)
341 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
343 raise RecordNotFound(slice_hrn)
346 # find out where this slice is currently running
347 nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
348 hostnames = [node['hostname'] for node in nodelist]
350 # get netspec details
351 nodespecs = spec.getDictsByTagName('NodeSpec')
353 for nodespec in nodespecs:
354 if isinstance(nodespec['name'], list):
355 nodes.extend(nodespec['name'])
356 elif isinstance(nodespec['name'], StringTypes):
357 nodes.append(nodespec['name'])
359 # save slice state locally
360 # we can assume that spec object has been validated so its safer to
361 # save this instead of the unvalidated rspec the user gave us
362 self.slices[slice_hrn] = spec.toxml()
365 # remove nodes not in rspec
366 deleted_nodes = list(set(hostnames).difference(nodes))
367 # add nodes from rspec
368 added_nodes = list(set(nodes).difference(hostnames))
370 self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
371 self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
373 for attribute in attributes:
374 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
375 self.shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
377 # contact registry to get slice users and add them to the slice
378 #slice_record = self.registry.resolve(self.credential, slice_hrn)
379 # persons = slice_record['users']
381 #for person in persons:
382 # shell.AddPersonToSlice(person['email'], slice_name)
385 def updateSlice(self, slice_hrn, rspec, attributes = []):
386 return self.create_slice(slice_hrn, rspec, attributes)
388 def deleteSlice(self, slice_hrn):
390 Remove this slice from all components it was previouly associated with and
391 free up the resources it was using.
393 if self.slices.has_key(slice_hrn):
394 self.slices.pop(slice_hrn)
397 slicename = hrn_to_pl_slicename(slice_hrn)
398 slices = self.shell.GetSlices(self.auth, [slicename])
403 self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
406 def startSlice(self, slice_hrn):
408 Stop the slice at plc.
410 slicename = hrn_to_pl_slicename(slice_hrn)
411 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
413 #raise RecordNotFound(slice_hrn)
416 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
417 attribute_id = attreibutes[0]
418 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
421 def stopSlice(self, slice_hrn):
423 Stop the slice at plc
425 slicename = hrn_to_pl_slicename(slice_hrn)
426 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
428 #raise RecordNotFound(slice_hrn)
431 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
432 attribute_id = attreibutes[0]
433 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
437 def resetSlice(self, slice_hrn):
441 # XX not yet implemented
446 Return this aggregates policy.
453 ##############################
454 ## Server methods here for now
455 ##############################
458 # XX fix rights, should be function name defined in
459 # privilege_table (from util/rights.py)
460 def list_nodes(self, cred):
461 self.decode_authentication(cred, 'listnodes')
462 return self.getNodes()
464 def list_slices(self, cred):
465 self.decode_authentication(cred, 'listslices')
466 return self.getSlices()
468 def get_resources(self, cred, hrn):
469 self.decode_authentication(cred, 'listnodes')
470 return self.getResources(hrn)
472 def get_ticket(self, cred, hrn, rspec):
473 self.decode_authentication(cred, 'getticket')
474 return self.getTicket(hrn, rspec)
476 def get_policy(self, cred):
477 self.decode_authentication(cred, 'getpolicy')
478 return self.getPolicy()
480 def create_slice(self, cred, hrn, rspec):
481 self.decode_authentication(cred, 'createslice')
482 return self.createSlice(hrn, rspec)
484 def update_slice(self, cred, hrn, rspec):
485 self.decode_authentication(cred, 'updateslice')
486 return self.updateSlice(hrn)
488 def delete_slice(self, cred, hrn):
489 self.decode_authentication(cred, 'deleteslice')
490 return self.deleteSlice(hrn)
492 def start_slice(self, cred, hrn):
493 self.decode_authentication(cred, 'startslice')
494 return self.startSlice(hrn)
496 def stop_slice(self, cred, hrn):
497 self.decode_authentication(cred, 'stopslice')
498 return self.stopSlice(hrn)
500 def reset_slice(self, cred, hrn):
501 self.decode_authentication(cred, 'resetslice')
502 return self.resetSlice(hrn)
504 def register_functions(self):
505 GeniServer.register_functions(self)
507 # Aggregate interface methods
508 self.server.register_function(self.list_nodes)
509 self.server.register_function(self.list_slices)
510 self.server.register_function(self.get_resources)
511 self.server.register_function(self.get_policy)
512 self.server.register_function(self.create_slice)
513 self.server.register_function(self.update_slice)
514 self.server.register_function(self.delete_slice)
515 self.server.register_function(self.start_slice)
516 self.server.register_function(self.stop_slice)
517 self.server.register_function(self.reset_slice)