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.conf = Config(config)
47 self.basedir = self.conf.GENI_BASE_DIR + os.sep
48 self.server_basedir = self.basedir + os.sep + "geni" + os.sep
49 self.hrn = self.conf.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.policy'])
60 self.policy = SimpleStorage(policy_file)
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.conf.GENI_PLC_USER,
89 'AuthMethod': 'password',
90 'AuthString': self.conf.GENI_PLC_PASSWORD}
93 # try to import PLC.Shell directly
94 sys.path.append(self.conf.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.conf.GENI_PLC_HOST
101 plc_port = self.conf.GENI_PLC_PORT
102 plc_api_path = self.conf.GENI_PLC_API_PATH
103 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
104 self.auth = {'Username': self.conf.GENI_PLC_USER,
105 'AuthMethod': 'password',
106 'AuthString': self.conf.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)
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.
154 # resolve component hostnames
155 nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
157 # resolve site login_bases
158 site_ids = [node['site_id'] for node in nodes]
159 sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
162 site_dict[site['site_id']] = site['login_base']
164 # convert plc names to geni hrn
167 node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
169 # Do not allow nodes found in blacklist, only allow nodes found in whitelist
170 if self.polciy['whitelist'] and node_hrn not in self.polciy['whitelist']:
172 if self.polciy['blacklist'] and node_hrn in self.policy['blacklist']:
174 nodedict[node_hrn] = node['hostname']
176 self.nodes = SimpleStorage(self.nodes.db_filename, nodedict)
179 # update timestamp and threshold
180 self.timestamp['timestamp'] = datetime.datetime.now()
181 delta = datetime.timedelta(hours=self.nodes_ttl)
182 self.threshold = self.timestamp['timestamp'] + delta
183 self.timestamp.write()
185 def load_components(self):
187 Read cached list of nodes.
189 # Read component list from cached file
191 self.timestamp.load()
192 time_format = "%Y-%m-%d %H:%M:%S"
193 timestamp = self.timestamp['timestamp']
194 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
195 delta = datetime.timedelta(hours=self.nodes_ttl)
196 self.threshold = self.timestamp['timestamp'] + delta
198 def load_policy(self):
200 Read the list of blacklisted and whitelisted nodes.
205 def get_components(self):
207 Return a list of components at this aggregate.
209 # Reload components list
210 now = datetime.datetime.now()
211 #self.load_components()
212 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
213 self.refresh_components()
214 elif now < self.threshold and not self.nodes.keys():
215 self.load_components()
216 return self.nodes.keys()
218 def get_rspec(self, hrn, type):
220 Get resource information from PLC
223 # Get the required nodes
224 if type in ['aggregate']:
225 nodes = self.shell.GetNodes(self.auth)
226 elif type in ['slice']:
227 slicename = hrn_to_pl_slicename(hrn)
228 slices = self.shell.GetSlices(self.auth, [slicename])
229 node_ids = slices[0]['node_ids']
230 nodes = self.shell.GetNodes(self.auth, node_ids)
232 # Get all network interfaces
235 interface_ids.extend(node['nodenetwork_ids'])
236 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
238 for interface in interfaces:
239 interface_dict[interface['nodenetwork_id']] = interface
241 # join nodes with thier interfaces
243 node['interfaces'] = []
244 for nodenetwork_id in node['nodenetwork_ids']:
245 node['interfaces'].append(interface_dict[nodenetwork_id])
247 # convert and threshold to ints
248 timestamp = self.timestamp['timestamp']
249 start_time = int(self.timestamp['timestamp'].strftime("%s"))
250 end_time = int(self.threshold.strftime("%s"))
251 duration = end_time - start_time
253 # create the plc dict
254 networks = {'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}
255 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
257 # convert the plc dict to an rspec dict
258 resouceDict = RspecDict(resources)
260 # convert the rspec dict to xml
262 rspec.parseDict(resourceDict)
265 def get_resources(self, slice_hrn):
267 Return the current rspec for the specified slice.
269 slicename = hrn_to_plcslicename(slice_hrn)
270 rspec = self.get_rspec(slicenamem, 'slice')
274 def create_slice(self, slice_hrn, rspec, attributes = []):
276 Instantiate the specified slice according to whats defined in the rspec.
279 # save slice state locally
280 # we can assume that spec object has been validated so its safer to
281 # save this instead of the unvalidated rspec the user gave us
282 self.slices[slice_hrn] = spec.toxml()
285 # extract node list from rspec
286 slicename = self.hrn_to_plcslicename(slice_hrn)
288 nodespecs = spec.getDictsByTagName('NodeSpec')
289 nodes = [nodespec['name'] for nodespec in nodespecs]
291 # add slice to nodes at plc
292 self.shell.AddSliceToNodes(self.auth, slicename, nodes)
293 for attribute in attributes:
294 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
295 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
297 # XX contact the registry to get the list of users on this slice and
299 slice_record = self.registry.resolve(self.credential, slice_hrn)
300 #person_records = slice_record['users']
301 # for person in person_record:
302 # email = person['email']
303 # self.shell.AddPersonToSlice(self.auth, email, slicename)
308 def update_slice(self, slice_hrn, rspec, attributes = []):
310 Update the specified slice.
313 slicename = self.hrn_to_plcslicename(slice_hrn)
314 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
316 raise RecordNotFound(slice_hrn)
319 # find out where this slice is currently running
320 nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
321 hostnames = [node['hostname'] for node in nodes]
323 # get netspec details
325 nodespecs = spec.getDictsByTagName('NodeSpec')
326 nodes = [nodespec['name'] for nodespec in nodespecs]
328 # save slice state locally
329 # we can assume that spec object has been validated so its safer to
330 # save this instead of the unvalidated rspec the user gave us
331 self.slices[slice_hrn] = spec.toxml()
334 # remove nodes not in rspec
335 delete_nodes = set(hostnames).difference(nodes)
336 # add nodes from rspec
337 added_nodes = set(nodes).difference(hostnames)
339 shell.AddSliceToNodes(self.auth, slicename, added_nodes)
340 shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
342 for attribute in attributes:
343 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
344 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
346 # contact registry to get slice users and add them to the slice
347 slice_record = self.registry.resolve(self.credential, slice_hrn)
348 # persons = slice_record['users']
350 #for person in persons:
351 # shell.AddPersonToSlice(person['email'], slice_name)
354 def delete_slice_(self, slice_hrn):
356 Remove this slice from all components it was previouly associated with and
357 free up the resources it was using.
359 if self.slices.has_key(slice_hrn):
360 self.slices.pop(slice_hrn)
363 slicename = self.hrn_to_plcslicename(slice_hrn)
364 slices = shell.GetSlices(self.auth, [slicename])
369 shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
372 def start_slice(self, slice_hrn):
374 Stop the slice at plc.
376 slicename = hrn_to_plcslicename(slice_hrn)
377 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
379 #raise RecordNotFound(slice_hrn)
382 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
383 attribute_id = attreibutes[0]
384 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
387 def stop_slice(self, slice_hrn):
389 Stop the slice at plc
391 slicename = hrn_to_plcslicename(slice_hrn)
392 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
394 #raise RecordNotFound(slice_hrn)
397 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
398 attribute_id = attreibutes[0]
399 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
403 def reset_slice(self, slice_hrn):
407 # XX not yet implemented
410 def get_policy(self):
412 Return this aggregates policy.
419 ##############################
420 ## Server methods here for now
421 ##############################
423 def components(self):
424 return self.get_components()
427 # return self.get_slices()
429 def resources(self, cred, hrn):
430 self.decode_authentication(cred, 'info')
431 self.verify_object_belongs_to_me(hrn)
433 return self.get_resources(hrn)
435 def createSlice(self, cred, hrn, rspec):
436 self.decode_authentication(cred, 'embed')
437 self.verify_object_belongs_to_me(hrn)
438 return self.create_slice(hrn)
440 def updateSlice(self, cred, hrn, rspec):
441 self.decode_authentication(cred, 'embed')
442 self.verify_object_belongs_to_me(hrn)
443 return self.update_slice(hrn)
445 def deleteSlice(self, cred, hrn):
446 self.decode_authentication(cred, 'embed')
447 self.verify_object_belongs_to_me(hrn)
448 return self.delete_slice(hrn)
450 def startSlice(self, cred, hrn):
451 self.decode_authentication(cred, 'control')
452 return self.start_slice(hrn)
454 def stopSlice(self, cred, hrn):
455 self.decode_authentication(cred, 'control')
456 return self.stop(hrn)
458 def resetSlice(self, cred, hrn):
459 self.decode_authentication(cred, 'control')
460 return self.reset(hrn)
462 def policy(self, cred):
463 self.decode_authentication(cred, 'info')
464 return self.get_policy()
466 def register_functions(self):
467 GeniServer.register_functions(self)
469 # Aggregate interface methods
470 self.server.register_function(self.components)
471 #self.server.register_function(self.slices)
472 self.server.register_function(self.resources)
473 self.server.register_function(self.createSlice)
474 self.server.register_function(self.deleteSlice)
475 self.server.register_function(self.startSlice)
476 self.server.register_function(self.stopSlice)
477 self.server.register_function(self.resetSlice)
478 self.server.register_function(self.policy)