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.trustedroot import TrustedRootList
11 from geni.util.excep import *
12 from geni.util.misc import *
13 from geni.util.config import Config
14 from geni.util.rspec import Rspec
15 from geni.util.specdict import *
16 from geni.util.storage import SimpleStorage
18 class Aggregate(GeniServer):
31 # Create a new aggregate object.
33 # @param ip the ip address to listen on
34 # @param port the port to listen on
35 # @param key_file private key filename of registry
36 # @param cert_file certificate filename containing public key (could be a GID file)
38 def __init__(self, ip, port, key_file, cert_file, config = "/usr/share/geniwrapper/util/geni_config"):
39 GeniServer.__init__(self, ip, port, key_file, cert_file)
40 self.conf = Config(config)
41 basedir = self.conf.GENI_BASE_DIR + os.sep
42 server_basedir = basedir + os.sep + "geni" + os.sep
43 self.hrn = self.conf.GENI_INTERFACE_HRN
45 nodes_file = os.sep.join([server_basedir, 'agg.' + self.hrn + '.components'])
46 self.nodes = SimpleStorage(nodes_file)
48 node_slices_file = os.sep.join([server_basedir, 'agg.' + self.hrn + '.slices'])
49 self.slices = SimpleStorage(node_slices_file)
52 policy_file = os.sep.join([server_basedir, 'policy'])
53 self.policy = SimpleStorage(policy_file, {'whitelist': [], 'blacklist': []})
55 timestamp_file = os.sep.join([server_basedir, 'components', self.hrn + '.timestamp'])
56 self.timestamp = SimpleStorage(timestamp_file)
60 self.connectRegistry()
62 def connectRegistry(self):
64 Connect to the registry
70 Connect to the plc api interface. First attempt to impor thte shell, if that fails
71 try to connect to the xmlrpc server.
73 self.auth = {'Username': self.conf.GENI_PLC_USER,
74 'AuthMethod': 'password',
75 'AuthString': self.conf.GENI_PLC_PASSWORD}
78 # try to import PLC.Shell directly
79 sys.path.append(self.conf.GENI_PLC_SHELL_PATH)
81 self.shell = PLC.Shell.Shell(globals())
82 self.shell.AuthCheck()
84 # connect to plc api via xmlrpc
85 plc_host = self.conf.GENI_PLC_HOST
86 plc_port = self.conf.GENI_PLC_PORT
87 plc_api_path = self.conf.GENI_PLC_API_PATH
88 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
89 self.auth = {'Username': self.conf.GENI_PLC_USER,
90 'AuthMethod': 'password',
91 'AuthString': self.conf.GENI_PLC_PASSWORD}
93 self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
94 self.shell.AuthCheck(self.auth)
96 def hostname_to_hrn(self, login_base, hostname):
98 Convert hrn to plantelab name.
100 genihostname = "_".join(hostname.split("."))
101 return ".".join([self.hrn, login_base, genihostname])
103 def slicename_to_hrn(self, slicename):
105 Convert hrn to planetlab name.
107 slicename = slicename.replace("_", ".")
108 return ".".join([self.hrn, slicename])
110 def refresh_components(self):
112 Update the cached list of nodes.
114 # resolve component hostnames
115 nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
117 # resolve site login_bases
118 site_ids = [node['site_id'] for node in nodes]
119 sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
122 site_dict[site['site_id']] = site['login_base']
124 # convert plc names to geni hrn
127 node_hrn = self.hostname_to_hrn(site_dict[node['site_id']], node['hostname'])
129 # Do not allow nodes found in blacklist, only allow nodes found in whitelist
130 if self.polciy['whitelist'] and node_hrn not in self.polciy['whitelist']:
132 if self.polciy['blacklist'] and node_hrn in self.policy['blacklist']:
134 nodedict[node_hrn] = node['hostname']
136 self.nodes = SimpleStorage(self.nodes.db_filename, nodedict)
139 # update timestamp and threshold
140 self.timestamp['timestamp'] = datetime.datetime.now()
141 delta = datetime.timedelta(hours=self.nodes_ttl)
142 self.threshold = self.timestamp['timestamp'] + delta
143 self.timestamp.write()
145 def load_components(self):
147 Read cached list of nodes.
149 # Read component list from cached file
151 self.timestamp.load()
152 time_format = "%Y-%m-%d %H:%M:%S"
153 timestamp = self.timestamp['timestamp']
154 self.timestamp['timestamp'] = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
155 delta = datetime.timedelta(hours=self.nodes_ttl)
156 self.threshold = self.timestamp['timestamp'] + delta
158 def load_policy(self):
160 Read the list of blacklisted and whitelisted nodes.
165 def get_components(self):
167 Return a list of components at this aggregate.
169 # Reload components list
170 now = datetime.datetime.now()
171 #self.load_components()
172 if not self.threshold or not self.timestamp['timestamp'] or now > self.threshold:
173 self.refresh_components()
174 elif now < self.threshold and not self.nodes.keys():
175 self.load_components()
176 return self.nodes.keys()
178 def get_rspec(self, hrn, type):
180 # Get the required nodes
181 if type in ['aggregate']:
182 nodes = self.shell.GetNodes(self.auth)
183 elif type in ['slice']:
184 slicename = hrn_to_pl_slicename(hrn)
185 slices = self.shell.GetSlices(self.auth, [slicename])
186 node_ids = slices[0]['node_ids']
187 nodes = self.shell.GetNodes(self.auth, node_ids)
189 # Get all network interfaces
192 interface_ids.extend(node['nodenetwork_ids'])
193 interfaces = self.shell.GetNodeNetworks(self.auth, interface_ids)
195 for interface in interfaces:
196 interface_dict[interface['nodenetwork_id']] = interface
198 # join nodes with thier interfaces
200 node['interfaces'] = []
201 for nodenetwork_id in node['nodenetwork_ids']:
202 node['interfaces'].append(interface_dict[nodenetwork_id])
204 # convert and threshold to ints
205 timestamp = self.timestamp['timestamp']
206 start_time = int(self.timestamp['timestamp'].strftime("%s"))
207 end_time = int(self.duration.strftime("%s"))
208 duration = end_time - start_time
210 # create the plc dict
211 networks = {'nodes': nodes, 'name': self.hrn, 'start_time': start_time, 'duration': duration}
212 resources = {'networks': networks, 'start_time': start_time, 'duration': duration}
214 # convert the plc dict to an rspec dict
215 resouceDict = RspecDict(resources)
217 # convert the rspec dict to xml
219 rspec.parseDict(resourceDict)
222 def get_resources(self, slice_hrn):
224 Return the current rspec for the specified slice.
226 slicename = hrn_to_plcslicename(slice_hrn)
227 rspec = self.get_rspec(slicenamem, 'slice')
231 def create_slice(self, slice_hrn, rspec, attributes = []):
233 Instantiate the specified slice according to whats defined in the rspec.
235 slicename = self.hrn_to_plcslicename(slice_hrn)
237 # extract node list from rspec
239 nodespecs = spec.getDictsByTagName('NodeSpec')
240 nodes = [nodespec['name'] for nodespec in nodespecs]
242 # save slice state locally
243 # we can assume that spec object has been validated so its safer to
244 # save this instead of the unvalidated rspec the user gave us
245 self.slices[slice_hrn] = spec.toxml()
248 # add slice to nodes at plc
249 self.shell.AddSliceToNodes(self.auth, slicename, nodes)
250 for attribute in attributes:
251 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
252 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
254 # XX contact the registry to get the list of users on this slice and
256 #slice_record = self.registry.resolve(slice_hrn)
257 #person_records = slice_record['users']
258 # for person in person_record:
259 # email = person['email']
260 # self.shell.AddPersonToSlice(self.auth, email, slicename)
265 def update_slice(self, slice_hrn, rspec, attributes = []):
267 Update the specified slice.
270 slicename = self.hrn_to_plcslicename(slice_hrn)
271 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
273 raise RecordNotFound(slice_hrn)
276 # find out where this slice is currently running
277 nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
278 hostnames = [node['hostname'] for node in nodes]
280 # get netspec details
282 nodespecs = spec.getDictsByTagName('NodeSpec')
283 nodes = [nodespec['name'] for nodespec in nodespecs]
285 # save slice state locally
286 # we can assume that spec object has been validated so its safer to
287 # save this instead of the unvalidated rspec the user gave us
288 self.slices[slice_hrn] = spec.toxml()
291 # remove nodes not in rspec
292 delete_nodes = set(hostnames).difference(nodes)
293 # add nodes from rspec
294 added_nodes = set(nodes).difference(hostnames)
296 shell.AddSliceToNodes(self.auth, slicename, added_nodes)
297 shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
299 for attribute in attributes:
300 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
301 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
303 # contact registry to get slice users and add them to the slice
304 # slice_record = self.registry.resolve(slice_hrn)
305 # persons = slice_record['users']
307 #for person in persons:
308 # shell.AddPersonToSlice(person['email'], slice_name)
311 def delete_slice_(self, slice_hrn):
313 Remove this slice from all components it was previouly associated with and
314 free up the resources it was using.
316 if self.slices.has_key(slice_hrn):
317 self.slices.pop(slice_hrn)
320 slicename = self.hrn_to_plcslicename(slice_hrn)
321 slices = shell.GetSlices(self.auth, [slicename])
323 raise RecordNotFound(slice_hrn)
326 shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
329 def start_slice(self, slice_hrn):
331 Stop the slice at plc.
333 slicename = hrn_to_plcslicename(slice_hrn)
334 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
336 raise RecordNotFound(slice_hrn)
338 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
339 attribute_id = attreibutes[0]
340 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
343 def stop_slice(self, slice_hrn):
345 Stop the slice at plc
347 slicename = hrn_to_plcslicename(slice_hrn)
348 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
350 raise RecordNotFound(slice_hrn)
352 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
353 attribute_id = attreibutes[0]
354 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
358 def reset_slice(self, slice_hrn):
362 slicename = self.hrn_to_plcslicename(slice_hrn)
365 def get_policy(self):
367 Return this aggregates policy.
374 ##############################
375 ## Server methods here for now
376 ##############################
378 def components(self):
379 return self.get_components()
382 # return self.get_slices()
384 def resources(self, cred, hrn):
385 self.decode_authentication(cred, 'info')
386 self.verify_object_belongs_to_me(hrn)
388 return self.get_resources(hrn)
390 def createSlice(self, cred, hrn, rspec):
391 self.decode_authentication(cred, 'embed')
392 self.verify_object_belongs_to_me(hrn)
393 return self.create_slice(hrn)
395 def updateSlice(self, cred, hrn, rspec):
396 self.decode_authentication(cred, 'embed')
397 self.verify_object_belongs_to_me(hrn)
398 return self.update_slice(hrn)
400 def deleteSlice(self, cred, hrn):
401 self.decode_authentication(cred, 'embed')
402 self.verify_object_belongs_to_me(hrn)
403 return self.delete_slice(hrn)
405 def startSlice(self, cred, hrn):
406 self.decode_authentication(cred, 'control')
407 return self.start_slice(hrn)
409 def stopSlice(self, cred, hrn):
410 self.decode_authentication(cred, 'control')
411 return self.stop(hrn)
413 def resetSlice(self, cred, hrn):
414 self.decode_authentication(cred, 'control')
415 return self.reset(hrn)
417 def policy(self, cred):
418 self.decode_authentication(cred, 'info')
419 return self.get_policy()
421 def register_functions(self):
422 GeniServer.register_functions(self)
424 # Aggregate interface methods
425 self.server.register_function(self.components)
426 #self.server.register_function(self.slices)
427 self.server.register_function(self.resources)
428 self.server.register_function(self.createSlice)
429 self.server.register_function(self.deleteSlice)
430 self.server.register_function(self.startSlice)
431 self.server.register_function(self.stopSlice)
432 self.server.register_function(self.resetSlice)
433 self.server.register_function(self.policy)