7 from util.geniserver import *
8 from util.geniclient import *
9 from util.cert import *
10 from util.trustedroot import *
11 from util.excep import *
12 from util.misc import *
13 from util.config import Config
14 from util.rspec import Rspec
16 class Aggregate(GeniServer):
19 components_file = None
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__(ip, port, keyfile, cert_file)
42 basedir = conf.GENI_BASE_DIR + os.sep
43 server_basedir = basedir + os.sep + "plc" + os.sep
44 self.hrn = conf.GENI_INTERFACE_HRN
45 self.components_file = os.sep.join([server_basedir, 'components', hrn + '.comp'])
46 self.whitelist_file = os.sep.join([server_basedir, 'policy', 'whitelist'])
47 self.blacklist_file = os.sep.join([server_basedir, 'policy', 'blacklist'])
48 self.timestamp_file = os.sep.join([server_basedir, 'components', hrn + '.timestamp'])
49 self.components_ttl = components_ttl
50 self.policy['whitelist'] = []
51 self.policy['blacklist'] = []
53 self.connectRegistry()
55 def connectRegistry(self):
57 Connect to the registry
63 Connect to the plc api interface. First attempt to impor thte shell, if that fails
64 try to connect to the xmlrpc server.
66 self.auth = {'Username': conf.GENI_PLC_USER,
67 'AuthMethod': 'password',
68 'AuthString': conf.GENI_PLC_PASSWORD}
71 # try to import PLC.Shell directly
72 sys.path.append(conf.GENI_PLC_SHELL_PATH)
74 self.shell = PLC.Shell.Shell(globals())
75 self.shell.AuthCheck()
77 # connect to plc api via xmlrpc
78 plc_host = conf.GENI_PLC_HOST
79 plc_port = conf.GENI_PLC_PORT
80 plc_api_path = conf.GENI_PLC_API_PATH
81 url = "https://%(plc_host)s:%(plc_port)s/%(plc_api_path)s/" % locals()
82 self.auth = {'Username': conf.GENI_PLC_USER,
83 'AuthMethod': 'password',
84 'AuthString': conf.GENI_PLC_PASSWORD}
86 self.shell = xmlrpclib.Server(url, verbose = 0, allow_none = True)
87 self.shell.AuthCheck(self.auth)
89 def hostname_to_hrn(self, login_base, hostname):
91 Convert hrn to plantelab name.
93 genihostname = "_".join(hostname.split("."))
94 return ".".join([self.hrn, login_base, genihostname])
96 def slicename_to_hrn(self, slicename):
98 Convert hrn to planetlab name.
100 slicename = slicename.replace("_", ".")
101 return ".".join([self.hrn, slicename])
103 def refresh_components(self):
105 Update the cached list of nodes.
107 # resolve component hostnames
108 nodes = self.shell.GetNodes(self.auth, {}, ['hostname', 'site_id'])
110 # resolve site login_bases
111 site_ids = [node['site_id'] for node in nodes]
112 sites = self.shell.GetSites(self.auth, site_ids, ['site_id', 'login_base'])
115 site_dict[site['site_id']] = site['login_base']
117 # convert plc names to geni hrn
118 self.components = [self.hostname_to_hrn(site_dict[node['site_id']], node['hostname']) for node in nodes]
120 # apply policy. Do not allow nodes found in blacklist, only allow nodes found in whitelist
121 whitelist_policy = lambda node: node in self.policy['whitelist']
122 blacklist_policy = lambda node: node not in self.policy['blacklist']
124 if self.policy['blacklist']:
125 self.components = blacklist_policy(self.components)
126 if self.policy['whitelist']:
127 self.components = whitelist_policy(self.components)
129 # update timestamp and threshold
130 self.timestamp = datetime.datetime.now()
131 delta = datetime.timedelta(hours=self.components_ttl)
132 self.threshold = self.timestamp + delta
134 f = open(self.components_file, 'w')
135 f.write(str(self.components))
137 f = open(self.timestamp_file, 'w')
138 f.write(str(self.threshold))
141 def load_components(self):
143 Read cached list of nodes.
145 # Read component list from cached file
146 if os.path.exists(self.components_file):
147 f = open(self.components_file, 'r')
148 self.components = eval(f.read())
151 time_format = "%Y-%m-%d %H:%M:%S"
152 if os.path.exists(self.timestamp_file):
153 f = open(self.timestamp_file, 'r')
154 timestamp = str(f.read()).split(".")[0]
155 self.timestamp = datetime.datetime.fromtimestamp(time.mktime(time.strptime(timestamp, time_format)))
156 delta = datetime.timedelta(hours=self.components_ttl)
157 self.threshold = self.timestamp + delta
160 def load_policy(self):
162 Read the list of blacklisted and whitelisted nodes.
166 if os.path.exists(self.whitelist_file):
167 f = open(self.whitelist_file, 'r')
168 lines = f.readlines()
171 line = line.strip().replace(" ", "").replace("\n", "")
172 whitelist.extend(line.split(","))
175 if os.path.exists(self.blacklist_file):
176 f = open(self.blacklist_file, 'r')
177 lines = f.readlines()
180 line = line.strip().replace(" ", "").replace("\n", "")
181 blacklist.extend(line.split(","))
183 self.policy['whitelist'] = whitelist
184 self.policy['blacklist'] = blacklist
186 def get_components(self):
188 Return a list of components at this aggregate.
190 # Reload components list
191 now = datetime.datetime.now()
192 #self.load_components()
193 if not self.threshold or not self.timestamp or now > self.threshold:
194 self.refresh_components()
195 elif now < self.threshold and not self.components:
196 self.load_components()
197 return self.components
199 def get_rspec(self, hrn, type):
201 rspec['nodespec'] = {'name': self.conf.GENI_INTERFACE_HRN}
202 rsepc['nodespec']['nodes'] = []
204 nodes = self.shell.GetNodes(self.auth)
205 elif type in ['slice']:
206 slicename = hrn_to_pl_slicename(hrn)
207 slices = self.shell.GetSlices(self.auth, [slicename])
208 node_ids = slices[0]['node_ids']
209 nodes = self.shell.GetNodes(self.auth, node_ids)
211 nodespec = {'name': node['hostname'], 'type': 'std'}
212 elif type in ['aggregate']:
217 def get_resources(self, slice_hrn):
219 Return the current rspec for the specified slice.
221 slicename = hrn_to_plcslicename(slice_hrn)
222 rspec = self.get_rspec(slicenamem, 'slice')
226 def create_slice(self, slice_hrn, rspec, attributes = []):
228 Instantiate the specified slice according to whats defined in the rspec.
230 slicename = self.hrn_to_plcslicename(slice_hrn)
232 nodespecs = spec.getDictsByTagName('NodeSpec')
233 nodes = [nodespec['name'] for nodespec in nodespecs]
234 self.shell.AddSliceToNodes(self.auth, slicename, nodes)
235 for attribute in attributes:
236 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
237 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
239 # XX contact the registry to get the list of users on this slice and
241 #slice_record = self.registry.resolve(slice_hrn)
242 #person_records = slice_record['users']
243 # for person in person_record:
244 # email = person['email']
245 # self.shell.AddPersonToSlice(self.auth, email, slicename)
250 def update_slice(self, slice_hrn, rspec, attributes = []):
252 Update the specified slice.
255 slicename = self.hrn_to_plcslicename(slice_hrn)
256 slices = self.shell.GetSlices(self.auth, [slicename], ['node_ids'])
258 raise RecordNotFound(slice_hrn)
261 # find out where this slice is currently running
262 nodes = self.shell.GetNodes(self.auth, slice['node_ids'], ['hostname'])
263 hostnames = [node['hostname'] for node in nodes]
265 # get netspec details
267 nodespecs = spec.getDictsByTagName('NodeSpec')
268 nodes = [nodespec['name'] for nodespec in nodespecs]
269 # remove nodes not in rspec
270 delete_nodes = set(hostnames).difference(nodes)
271 # add nodes from rspec
272 added_nodes = set(nodes).difference(hostnames)
274 shell.AddSliceToNodes(self.auth, slicename, added_nodes)
275 shell.DeleteSliceFromNodes(self.auth, slicename, deleted_nodes)
277 for attribute in attributes:
278 type, value, node, nodegroup = attribute['type'], attribute['value'], attribute['node'], attribute['nodegroup']
279 shell.AddSliceAttribute(self.auth, slicename, type, value, node, nodegroup)
281 # contact registry to get slice users and add them to the slice
282 # slice_record = self.registry.resolve(slice_hrn)
283 # persons = slice_record['users']
285 #for person in persons:
286 # shell.AddPersonToSlice(person['email'], slice_name)
287 def delete_slice_(self, slice_hrn):
289 Remove this slice from all components it was previouly associated with and
290 free up the resources it was using.
292 slicename = self.hrn_to_plcslicename(slice_hrn)
293 slices = shell.GetSlices(self.auth, [slicename])
295 raise RecordNotFound(slice_hrn)
298 shell.DeleteSliceFromNodes(self.auth, slicename, slice['node_ids'])
301 def start_slice(self, slice_hrn):
303 Stop the slice at plc.
305 slicename = hrn_to_plcslicename(slice_hrn)
306 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
308 raise RecordNotFound(slice_hrn)
310 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
311 attribute_id = attreibutes[0]
312 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "1" )
315 def stop_slice(self, slice_hrn):
317 Stop the slice at plc
319 slicename = hrn_to_plcslicename(slice_hrn)
320 slices = self.shell.GetSlices(self.auth, {'name': slicename}, ['slice_id'])
322 raise RecordNotFound(slice_hrn)
324 atrribtes = self.shell.GetSliceAttributes({'slice_id': slice_id, 'name': 'enabled'}, ['slice_attribute_id'])
325 attribute_id = attreibutes[0]
326 self.shell.UpdateSliceAttribute(self.auth, attribute_id, "0")
330 def reset_slice(self, slice_hrn):
334 slicename = self.hrn_to_plcslicename(slice_hrn)
337 def get_policy(self):
339 Return this aggregates policy.
346 ##############################
347 ## Server methods here for now
348 ##############################
351 return self..get_components()
354 # return self.get_slices()
356 def resources(self, cred, hrn):
357 self.decode_authentication(cred, 'info')
358 self.verify_object_belongs_to_me(hrn)
360 return self.get_resources(hrn)
362 def create(self, cred, hrn, rspec):
363 self.decode_authentication(cred, 'embed')
364 self.verify_object_belongs_to_me(hrn)
365 return self.create(hrn)
367 def update(self, cred, hrn, rspec):
368 self.decode_authentication(cred, 'embed')
369 self.verify_object_belongs_to_me(hrn)
370 return self.update(hrn)
372 def delete(self, cred, hrn):
373 self.decode_authentication(cred, 'embed')
374 self.verify_object_belongs_to_me(hrn)
375 return self.delete_slice(hrn)
377 def start(self, cred, hrn):
378 self.decode_authentication(cred, 'control')
379 return self.start(hrn)
381 def stop(self, cred, hrn):
382 self.decode_authentication(cred, 'control')
383 return self.stop(hrn)
385 def reset(self, cred, hrn):
386 self.decode_authentication(cred, 'control')
387 return self.reset(hrn)
389 def policy(self, cred):
390 self.decode_authentication(cred, 'info')
391 return self.get_policy()
393 def register_functions(self):
394 GeniServer.register_functions(self)
396 # Aggregate interface methods
397 self.server.register_function(self.components)
398 #self.server.register_function(self.slices)
399 self.server.register_function(self.resources)
400 self.server.register_function(self.create)
401 self.server.register_function(self.delete)
402 self.server.register_function(self.start)
403 self.server.register_function(self.stop)
404 self.server.register_function(self.reset)
405 self.server.register_function(self.policy)