3 from planetstack.config import Config
6 from openstack.client import OpenStackClient
11 manager_enabled = Config().api_nova_enabled
13 class OpenStackDriver:
15 def __init__(self, config = None, client=None, deployment=None):
17 self.config = Config(config)
19 self.config = Config()
21 self.admin_client = OpenStackClient(deployment=deployment)
22 self.admin_user = self.admin_client.keystone.users.find(name=self.admin_client.keystone.username)
27 self.shell = OpenStackClient(deployment=deployment)
29 self.enabled = manager_enabled
30 self.has_openstack = has_openstack
32 def client_driver(self, caller=None, tenant=None, deployment=None):
34 auth = {'username': caller.email,
35 'password': hashlib.md5(caller.password).hexdigest()[:6],
37 client = OpenStackClient(deployment=deployment, **auth)
39 client = OpenStackClient(tenant=tenant, deployment=deployment)
41 driver = OpenStackDriver(client=client, deployment=deployment)
44 def admin_driver(self, tenant=None, deployment=None):
45 client = OpenStackClient(tenant=tenant, deployment=deployment)
46 driver = OpenStackDriver(client=client, deployment=deployment)
49 def create_role(self, name):
50 roles = self.shell.keystone.roles.findall(name=name)
51 roles_title = self.shell.keystone.roles.findall(name=name.title())
52 roles_found = roles + roles_title
54 role = self.shell.keystone.roles.create(name)
59 def delete_role(self, filter):
60 roles = self.shell.keystone.roles.findall(**filter)
62 self.shell.keystone.roles.delete(role)
65 def create_tenant(self, tenant_name, enabled, description):
66 """Create keystone tenant. Suggested fields: name, description, enabled"""
67 tenants = self.shell.keystone.tenants.findall(name=tenant_name)
69 fields = {'tenant_name': tenant_name, 'enabled': enabled,
70 'description': description}
71 tenant = self.shell.keystone.tenants.create(**fields)
75 # always give the admin user the admin role to any tenant created
77 self.add_user_role(self.admin_user.id, tenant.id, 'admin')
80 def update_tenant(self, id, **kwds):
81 return self.shell.keystone.tenants.update(id, **kwds)
83 def delete_tenant(self, id):
84 ctx = self.shell.nova_db.ctx
85 tenants = self.shell.keystone.tenants.findall(id=id)
86 for tenant in tenants:
87 # nova does not automatically delete the tenant's instances
88 # so we manually delete instances before deleteing the tenant
89 instances = self.shell.nova_db.instance_get_all_by_filters(ctx,
90 {'project_id': tenant.id}, 'id', 'asc')
91 client = OpenStackClient(tenant=tenant.name)
92 driver = OpenStackDriver(client=client)
93 for instance in instances:
94 driver.destroy_instance(instance.id)
95 self.shell.keystone.tenants.delete(tenant)
98 def create_user(self, name, email, password, enabled):
99 users = self.shell.keystone.users.findall(email=email)
101 fields = {'name': name, 'email': email, 'password': password,
103 user = self.shell.keystone.users.create(**fields)
108 def delete_user(self, id):
109 users = self.shell.keystone.users.findall(id=id)
112 keys = self.shell.nova.keypairs.findall()
114 self.shell.nova.keypairs.delete(key)
115 self.shell.keystone.users.delete(user)
118 def get_admin_role(self):
120 for admin_role_name in ['admin', 'Admin']:
121 roles = self.shell.keystone.roles.findall(name=admin_role_name)
127 def add_user_role(self, kuser_id, tenant_id, role_name):
128 user = self.shell.keystone.users.find(id=kuser_id)
129 tenant = self.shell.keystone.tenants.find(id=tenant_id)
130 # admin role can be lowercase or title. Look for both
132 if role_name.lower() == 'admin':
133 role = self.get_admin_role()
135 # look up non admin role or force exception when admin role isnt found
136 role = self.shell.keystone.roles.find(name=role_name)
139 user_roles = user.list_roles(tenant.id)
140 for user_role in user_roles:
141 if user_role.name == role.name:
144 tenant.add_user(user, role)
148 def delete_user_role(self, kuser_id, tenant_id, role_name):
149 user = self.shell.keystone.users.find(id=kuser_id)
150 tenant = self.shell.keystone.tenants.find(id=tenant_id)
151 # admin role can be lowercase or title. Look for both
153 if role_name.lower() == 'admin':
154 role = self.get_admin_role()
156 # look up non admin role or force exception when admin role isnt found
157 role = self.shell.keystone.roles.find(name=role_name)
160 user_roles = user.list_roles(tenant.id)
161 for user_role in user_roles:
162 if user_role.name == role.name:
165 tenant.remove_user(user, role)
169 def update_user(self, id, fields):
170 if 'password' in fields:
171 self.shell.keystone.users.update_password(id, fields['password'])
172 if 'enabled' in fields:
173 self.shell.keystone.users.update_enabled(id, fields['enabled'])
176 def create_router(self, name, set_gateway=True):
177 routers = self.shell.quantum.list_routers(name=name)['routers']
181 router = self.shell.quantum.create_router({'router': {'name': name}})['router']
182 # add router to external network
184 nets = self.shell.quantum.list_networks()['networks']
186 if net['router:external'] == True:
187 self.shell.quantum.add_gateway_router(router['id'],
188 {'network_id': net['id']})
192 def delete_router(self, id):
193 routers = self.shell.quantum.list_routers(id=id)['routers']
194 for router in routers:
195 self.shell.quantum.delete_router(router['id'])
196 # remove router form external network
197 #nets = self.shell.quantum.list_networks()['networks']
199 # if net['router:external'] == True:
200 # self.shell.quantum.remove_gateway_router(router['id'])
202 def add_router_interface(self, router_id, subnet_id):
203 router = self.shell.quantum.show_router(router_id)['router']
204 subnet = self.shell.quantum.show_subnet(subnet_id)['subnet']
205 if router and subnet:
206 self.shell.quantum.add_interface_router(router_id, {'subnet_id': subnet_id})
208 def delete_router_interface(self, router_id, subnet_id):
209 router = self.shell.quantum.show_router(router_id)
210 subnet = self.shell.quantum.show_subnet(subnet_id)
211 if router and subnet:
212 self.shell.quantum.remove_interface_router(router_id, {'subnet_id': subnet_id})
214 def create_network(self, name, shared=False):
215 nets = self.shell.quantum.list_networks(name=name)['networks']
219 net = self.shell.quantum.create_network({'network': {'name': name, 'shared': shared}})['network']
222 def delete_network(self, id):
223 nets = self.shell.quantum.list_networks()['networks']
227 self.delete_network_ports(net['id'])
228 # delete all subnets:
229 for subnet_id in net['subnets']:
230 self.delete_subnet(subnet_id)
231 self.shell.quantum.delete_network(net['id'])
234 def delete_network_ports(self, network_id):
235 ports = self.shell.quantum.list_ports()['ports']
237 if port['network_id'] == network_id:
238 self.shell.quantum.delete_port(port['id'])
241 def delete_subnet_ports(self, subnet_id):
242 ports = self.shell.quantum.list_ports()['ports']
245 for fixed_ip in port['fixed_ips']:
246 if fixed_ip['subnet_id'] == subnet_id:
250 self.shell.quantum.delete_port(port['id'])
253 def create_subnet(self, name, network_id, cidr_ip, ip_version, start, end):
254 #nets = self.shell.quantum.list_networks(name=network_name)['networks']
256 # raise Exception, "No such network: %s" % network_name
260 subnets = self.shell.quantum.list_subnets()['subnets']
262 if snet['cidr'] == cidr_ip and snet['network_id'] == network_id:
266 allocation_pools = [{'start': start, 'end': end}]
267 subnet = {'subnet': {'name': name,
268 'network_id': network_id,
269 'ip_version': ip_version,
271 'dns_nameservers': ['8.8.8.8', '8.8.4.4'],
272 'allocation_pools': allocation_pools}}
273 subnet = self.shell.quantum.create_subnet(subnet)['subnet']
274 self.add_external_route(subnet)
275 # TODO: Add route to external network
276 # e.g. # route add -net 10.0.3.0/24 dev br-ex gw 10.100.0.5
279 def update_subnet(self, id, fields):
280 return self.shell.quantum.update_subnet(id, fields)
282 def delete_subnet(self, id):
283 #return self.shell.quantum.delete_subnet(id=id)
284 # inefficient but fault tolerant
285 subnets = self.shell.quantum.list_subnets()['subnets']
286 for subnet in subnets:
287 if subnet['id'] == id:
288 self.delete_subnet_ports(subnet['id'])
289 self.shell.quantum.delete_subnet(id)
290 self.delete_external_route(subnet)
293 def get_external_routes(self):
294 status, output = commands.getstatusoutput('route')
295 routes = output.split('\n')[3:]
298 def add_external_route(self, subnet, routes=[]):
300 routes = self.get_external_routes()
302 ports = self.shell.quantum.list_ports()['ports']
304 gw_ip = subnet['gateway_ip']
305 subnet_id = subnet['id']
307 # 1. Find the port associated with the subnet's gateway
308 # 2. Find the router associated with that port
309 # 3. Find the port associated with this router and on the external net
310 # 4. Set up route to the subnet through the port from step 3
313 for fixed_ip in port['fixed_ips']:
314 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
316 router_id = gw_port['device_id']
317 router = self.shell.quantum.show_router(router_id)['router']
318 if router and router.get('external_gateway_info'):
319 ext_net = router['external_gateway_info']['network_id']
321 if port['device_id'] == router_id and port['network_id'] == ext_net:
322 ip_address = port['fixed_ips'][0]['ip_address']
325 # check if external route already exists
329 if subnet['cidr'] in route and ip_address in route:
332 cmd = "route add -net %s dev br-ex gw %s" % (subnet['cidr'], ip_address)
333 s, o = commands.getstatusoutput(cmd)
334 #print cmd, "\n", s, o
338 def delete_external_route(self, subnet):
339 ports = self.shell.quantum.list_ports()['ports']
341 gw_ip = subnet['gateway_ip']
342 subnet_id = subnet['id']
344 # 1. Find the port associated with the subnet's gateway
345 # 2. Find the router associated with that port
346 # 3. Find the port associated with this router and on the external net
347 # 4. Set up route to the subnet through the port from step 3
350 for fixed_ip in port['fixed_ips']:
351 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
353 router_id = gw_port['device_id']
354 router = self.shell.quantum.show_router(router_id)['router']
355 ext_net = router['external_gateway_info']['network_id']
357 if port['device_id'] == router_id and port['network_id'] == ext_net:
358 ip_address = port['fixed_ips'][0]['ip_address']
361 cmd = "route delete -net %s" % (subnet['cidr'])
362 commands.getstatusoutput(cmd)
366 def create_keypair(self, name, public_key):
367 keys = self.shell.nova.keypairs.findall(name=name)
371 if key.public_key != public_key:
372 self.delete_keypair(key.id)
373 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
375 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
378 def delete_keypair(self, id):
379 keys = self.shell.nova.keypairs.findall(id=id)
381 self.shell.nova.keypairs.delete(key)
384 def get_private_networks(self, tenant=None):
386 tenant = self.shell.nova.tenant
387 tenant = self.shell.keystone.tenants.find(name=tenant)
388 search_opts = {"tenant_id": tenant.id, "shared": False}
389 private_networks = self.shell.quantum.list_networks(**search_opts)
390 return private_networks
392 def get_shared_networks(self):
393 search_opts = {"shared": True}
394 shared_networks = self.shell.quantum.list_networks(**search_opts)
395 return shared_networks
397 def get_network_subnet(self, network_id):
401 os_networks = self.shell.quantum.list_networks(id=network_id)["networks"]
403 os_network = os_networks[0]
404 if os_network['subnets']:
405 subnet_id = os_network['subnets'][0]
406 os_subnets = self.shell.quantum.list_subnets(id=subnet_id)['subnets']
408 subnet = os_subnets[0]['cidr']
410 return (subnet_id, subnet)
412 def spawn_instance(self, name, key_name=None, hostname=None, image_id=None, security_group=None, pubkeys=[], nics=None, metadata=None):
413 flavor_name = self.config.nova_default_flavor
414 flavor = self.shell.nova.flavors.find(name=flavor_name)
416 # image = self.config.nova_default_imave
417 if not security_group:
418 security_group = self.config.nova_default_security_group
422 # files["/root/.ssh/authorized_keys"] = "\n".join(pubkeys).encode('base64')
424 availability_zone = None
426 availability_zone = 'nova:%s' % hostname.split('.')[0]
427 server = self.shell.nova.servers.create(
432 security_group = security_group,
434 scheduler_hints=hints,
435 availability_zone=availability_zone,
441 def destroy_instance(self, id):
442 if (self.shell.nova.tenant=="admin"):
443 # findall() is implemented as a list() followed by a python search of the
444 # list. Since findall() doesn't accept "all_tenants", we do this using
445 # list() ourselves. This allows us to delete an instance as admin.
446 servers = self.shell.nova.servers.list(search_opts={"all_tenants": True})
448 servers = self.shell.nova.servers.list()
449 for server in servers:
451 result=self.shell.nova.servers.delete(server)
453 def update_instance_metadata(self, id, metadata):
454 servers = self.shell.nova.servers.findall(id=id)
455 for server in servers:
456 self.shell.nova.servers.set_meta(server, metadata)
457 # note: set_meta() returns a broken Server() object. Don't try to
458 # print it in the shell or it will fail in __repr__.
460 def delete_instance_metadata(self, id, metadata):
461 # note: metadata is a dict. Only the keys matter, not the values.
462 servers = self.shell.nova.servers.findall(id=id)
463 for server in servers:
464 self.shell.nova.servers.delete_meta(server, metadata)