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()
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 = 'http://%(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 ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
121 # see if this file exists
123 self.credential = Credential(filename = ma_cred_filename)
125 self.credential = self.getCredentialFromRegistry()
127 def getCredentialFromRegistry(self):
129 Get our current credential from the registry
131 # get self credential
132 self_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".cred"
133 self_cred = self.registry.get_credential(None, 'ma', self.hrn)
134 self_cred.save_to_file(self_cred_filename, save_parents = True)
138 ma_cred_filename = self.server_basedir + os.sep + "agg." + self.hrn + ".ma.cred"
139 ma_cred = self.registry.get_credential(self_cred, 'ma', self.hrn)
140 ma_cred.save_to_file(ma_cred_filename, save_parents=True)
144 def hostname_to_hrn(self, login_base, hostname):
146 Convert hrn to plantelab name.
148 genihostname = "_".join(hostname.split("."))
149 return ".".join([self.hrn, login_base, genihostname])
151 def slicename_to_hrn(self, slicename):
153 Convert hrn to planetlab name.
155 parts = slicename.split("_")
156 slice_hrn = ".".join([self.hrn, parts[0]]) + "." + "_".join(parts[1:])
160 def refresh_components(self):
162 Update the cached list of nodes and save in 4 differnt formats
166 # get node list in rspec format
168 rspec.parseString(self.get_rspec(self.hrn, 'aggregate'))
170 # filter nodes according to policy
171 rspec.filter('NodeSpec', 'name', blacklist=self.policy['blacklist'], whitelist=self.policy['whitelist'])
173 # extract ifspecs from rspec to get ip's
175 ifspecs = rspec.getDictsByTagName('IfSpec')
176 for ifspec in ifspecs:
177 if ifspec.has_key('addr') and ifspec['addr']:
178 ips.append(ifspec['addr'])
180 # extract nodespecs from rspec to get dns names
182 nodespecs = rspec.getDictsByTagName('NodeSpec')
183 for nodespec in nodespecs:
184 if nodespec.has_key('name') and nodespec['name']:
185 hostnames.append(nodespec['name'])
189 node_details['rspec'] = rspec.toxml()
190 node_details['ip'] = ips
191 node_details['dns'] = hostnames
193 self.nodes = SimpleStorage(self.nodes.db_filename, node_details)
197 # update timestamp and threshold
198 self.timestamp['timestamp'] = datetime.datetime.now()
199 delta = datetime.timedelta(hours=self.nodes_ttl)
200 self.threshold = self.timestamp['timestamp'] + delta
201 self.timestamp.write()
203 def load_components(self):
205 Read cached list of nodes.
207 # Read component list from cached file
209 self.timestamp.load()
210 time_format = "%Y-%m-%d %H:%M:%S"
211 timestamp = self.timestamp['timestamp']
212 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
213 delta = datetime.timedelta(hours=self.nodes_ttl)
214 self.threshold = self.timestamp['timestamp'] + delta
216 def load_policy(self):
218 Read the list of blacklisted and whitelisted nodes.
223 def getNodes(self, format = 'rspec'):
225 Return a list of components at this aggregate.
227 valid_formats = ['rspec', 'hrn', 'dns', 'ip']
230 if format not in valid_formats:
231 raise Exception, "Invalid format specified, must be one of the following: %s" \
232 % ", ".join(valid_formats)
234 # Reload components list
235 now = datetime.datetime.now()
236 #self.load_components()
237 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
238 self.refresh_components()
239 elif now < self.threshold and not self.nodes.keys():
240 self.load_components()
241 return self.nodes[format]
245 Return a list of instnatiated managed by this slice manager.
248 slices = self.shell.GetSlices(self.auth, {}, ['name'])
249 slice_hrns = [self.slicename_to_hrn(slice['name']) for slice in slices]
253 def get_rspec(self, hrn, type):
255 Get resource information from PLC
258 # Get the required nodes
259 if type in ['aggregate']:
260 nodes = self.shell.GetNodes(self.auth)
261 try: linkspecs = self.shell.GetLinkSpecs() # if call is supported
262 except: linkspecs = []
263 elif type in ['slice']:
264 slicename = hrn_to_pl_slicename(hrn)
265 slices = self.shell.GetSlices(self.auth, [slicename])
266 node_ids = slices[0]['node_ids']
267 nodes = self.shell.GetNodes(self.auth, node_ids)
269 # Filter out whitelisted nodes
270 public_nodes = lambda n: n.has_key('slice_ids_whitelist') and not n['slice_ids_whitelist']
271 nodes = filter(public_nodes, nodes)
273 # Get all network interfaces
276 interface_ids.extend(node['nodenetwork_ids'])
277 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
279 for interface in interfaces:
280 interface_dict[interface['nodenetwork_id']] = interface
282 # join nodes with thier interfaces
284 node['interfaces'] = []
285 for nodenetwork_id in node['nodenetwork_ids']:
286 node['interfaces'].append(interface_dict[nodenetwork_id])
288 # convert and threshold to ints
289 if self.timestamp.has_key('timestamp') and self.timestamp['timestamp']:
290 timestamp = self.timestamp['timestamp']
291 threshold = self.threshold
293 timestamp = datetime.datetime.now()
294 delta = datetime.timedelta(hours=self.nodes_ttl)
295 threshold = timestamp + delta
298 start_time = int(timestamp.strftime("%s"))
299 end_time = int(threshold.strftime("%s"))
300 duration = end_time - start_time
302 # create the plc dict
303 networks = [{'nodes': nodes,
306 'start_time': start_time,
307 'duration': duration}]
308 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
310 # convert the plc dict to an rspec dict
311 resourceDict = RspecDict(resources)
312 # convert the rspec dict to xml
314 rspec.parseDict(resourceDict)
317 def getResources(self, slice_hrn):
319 Return the current rspec for the specified slice.
321 rspec = self.get_rspec(slice_hrn, 'slice')
326 def getTicket(self, hrn, rspec):
328 Retrieve a ticket. This operation is currently implemented on PLC
329 only (see SFA, engineering decisions); it is not implemented on
332 @param name name of the slice to retrieve a ticket for
333 @param rspec resource specification dictionary
334 @return the string representation of a ticket object
336 #self.registry.get_ticket(name, rspec)
341 def createSlice(self, slice_hrn, rspec, attributes = []):
343 Instantiate the specified slice according to whats defined in the rspec.
347 # save slice state locally
348 # we can assume that spec object has been validated so its safer to
349 # save this instead of the unvalidated rspec the user gave us
350 self.slices[slice_hrn] = spec.toxml()
354 slicename = hrn_to_pl_slicename(slice_hrn)
355 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
357 parts = slicename.split("_")
358 login_base = parts[0]
359 slice_record = self.registry.resolve(self.cred, slice_hrn)
360 slice_info = slice_record.as_dict()
361 slice = slice_info['pl_info']
363 # if site doesnt exist add it
364 sites = self.shell.GetSites(self.auth, [login_base])
366 authority = get_authority(slice_hrn)
367 site_record = self.registry.reolve(self.cred, authority)
368 site_info = site_record.as_dict()
369 site = site_info['pl_info']
373 site_id = self.shell.AddSite(self.auth, site)
377 self.shell.AddSlice(self.auth, slice_info)
382 # get the list of valid slice users from the registry and make
383 # they are added to the slice
384 slice_records = self.registry.resolve(self.credential, slice_hrn)
385 if not slice_records:
386 raise Error, "record for %s not found" % slice_hrn
387 slice_record = slice_records[0]
388 slice_record_dict = slice_record.as_dict()
389 geni_info = slice_record_dict['geni_info']
390 researchers = geni_info['researcher']
391 for researcher in researchers:
392 person_records = self.registry.resolve(self.credential, researcher)
393 if not person_records:
395 person_record = person_records[0]
396 person_dict = person_record.as_dict()['plc_info']
397 persons = self.shell.GetPersons(self.auth, [person_dict['email']], ['person_id', 'key_ids'])
399 # Create the person record
401 self.shell.AddPerson(self.auth, person_dict)
402 self.shell.AddPersonToSlice(self.auth, person_dict['email'], login_base)
403 # Add this person's public keys
404 for personkey in person_dict['keys']:
405 key = {'type': 'ssh', 'key': personkey}
406 self.shellAddPersonKey(self.auth, person_dict['email'], key)
408 # find out where this slice is currently running
409 nodelist = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
410 hostnames = [node['hostname'] for node in nodelist]
412 # get netspec details
413 nodespecs = spec.getDictsByTagName('NodeSpec')
415 for nodespec in nodespecs:
416 if isinstance(nodespec['name'], list):
417 nodes.extend(nodespec['name'])
418 elif isinstance(nodespec['name'], StringTypes):
419 nodes.append(nodespec['name'])
421 # save slice state locally
422 # we can assume that spec object has been validated so its safer to
423 # save this instead of the unvalidated rspec the user gave us
424 self.slices[slice_hrn] = spec.toxml()
427 # remove nodes not in rspec
428 deleted_nodes = list(set(hostnames).difference(nodes))
429 # add nodes from rspec
430 added_nodes = list(set(nodes).difference(hostnames))
432 self.shell.AddSliceToNodes(self.auth, slicename, added_nodes)
433 self.shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
437 def updateSlice(self, slice_hrn, rspec, attributes = []):
438 return self.create_slice(slice_hrn, rspec, attributes)
440 def deleteSlice(self, slice_hrn):
442 Remove this slice from all components it was previouly associated with and
443 free up the resources it was using.
445 if self.slices.has_key(slice_hrn):
446 self.slices.pop(slice_hrn)
449 slicename = hrn_to_pl_slicename(slice_hrn)
450 slices = self.shell.GetSlices(self.auth, [slicename])
455 self.shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
458 def startSlice(self, slice_hrn):
460 Stop the slice at plc.
462 slicename = hrn_to_pl_slicename(slice_hrn)
463 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
465 #raise RecordNotFound(slice_hrn)
468 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
469 attribute_id = attreibutes[0]
470 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
473 def stopSlice(self, slice_hrn):
475 Stop the slice at plc
477 slicename = hrn_to_pl_slicename(slice_hrn)
478 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
480 #raise RecordNotFound(slice_hrn)
483 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
484 attribute_id = attreibutes[0]
485 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
489 def resetSlice(self, slice_hrn):
493 # XX not yet implemented
498 Return this aggregates policy.
505 ##############################
506 ## Server methods here for now
507 ##############################
510 # XX fix rights, should be function name defined in
511 # privilege_table (from util/rights.py)
512 def list_nodes(self, cred):
513 self.decode_authentication(cred, 'listnodes')
514 return self.getNodes()
516 def list_slices(self, cred):
517 self.decode_authentication(cred, 'listslices')
518 return self.getSlices()
520 def get_resources(self, cred, hrn = None):
521 self.decode_authentication(cred, 'listnodes')
523 return self.getNodes()
525 return self.getResources(hrn)
527 def get_ticket(self, cred, hrn, rspec):
528 self.decode_authentication(cred, 'getticket')
529 return self.getTicket(hrn, rspec)
531 def get_policy(self, cred):
532 self.decode_authentication(cred, 'getpolicy')
533 return self.getPolicy()
535 def create_slice(self, cred, hrn, rspec):
536 self.decode_authentication(cred, 'createslice')
537 return self.createSlice(hrn, rspec)
539 def update_slice(self, cred, hrn, rspec):
540 self.decode_authentication(cred, 'updateslice')
541 return self.updateSlice(hrn)
543 def delete_slice(self, cred, hrn):
544 self.decode_authentication(cred, 'deleteslice')
545 return self.deleteSlice(hrn)
547 def start_slice(self, cred, hrn):
548 self.decode_authentication(cred, 'startslice')
549 return self.startSlice(hrn)
551 def stop_slice(self, cred, hrn):
552 self.decode_authentication(cred, 'stopslice')
553 return self.stopSlice(hrn)
555 def reset_slice(self, cred, hrn):
556 self.decode_authentication(cred, 'resetslice')
557 return self.resetSlice(hrn)
559 def register_functions(self):
560 GeniServer.register_functions(self)
562 # Aggregate interface methods
563 self.server.register_function(self.list_nodes)
564 self.server.register_function(self.list_slices)
565 self.server.register_function(self.get_resources)
566 self.server.register_function(self.get_policy)
567 self.server.register_function(self.create_slice)
568 self.server.register_function(self.update_slice)
569 self.server.register_function(self.delete_slice)
570 self.server.register_function(self.start_slice)
571 self.server.register_function(self.stop_slice)
572 self.server.register_function(self.reset_slice)