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)
52 role = self.shell.keystone.roles.create(name)
57 def delete_role(self, filter):
58 roles = self.shell.keystone.roles.findall(**filter)
60 self.shell.keystone.roles.delete(role)
63 def create_tenant(self, tenant_name, enabled, description):
64 """Create keystone tenant. Suggested fields: name, description, enabled"""
65 tenants = self.shell.keystone.tenants.findall(name=tenant_name)
67 fields = {'tenant_name': tenant_name, 'enabled': enabled,
68 'description': description}
69 tenant = self.shell.keystone.tenants.create(**fields)
73 # always give the admin user the admin role to any tenant created
75 self.add_user_role(self.admin_user.id, tenant.id, 'admin')
78 def update_tenant(self, id, **kwds):
79 return self.shell.keystone.tenants.update(id, **kwds)
81 def delete_tenant(self, id):
82 ctx = self.shell.nova_db.ctx
83 tenants = self.shell.keystone.tenants.findall(id=id)
84 for tenant in tenants:
85 # nova does not automatically delete the tenant's instances
86 # so we manually delete instances before deleteing the tenant
87 instances = self.shell.nova_db.instance_get_all_by_filters(ctx,
88 {'project_id': tenant.id}, 'id', 'asc')
89 client = OpenStackClient(tenant=tenant.name)
90 driver = OpenStackDriver(client=client)
91 for instance in instances:
92 driver.destroy_instance(instance.id)
93 self.shell.keystone.tenants.delete(tenant)
96 def create_user(self, name, email, password, enabled):
97 users = self.shell.keystone.users.findall(email=email)
99 fields = {'name': name, 'email': email, 'password': password,
101 user = self.shell.keystone.users.create(**fields)
106 def delete_user(self, id):
107 users = self.shell.keystone.users.findall(id=id)
110 keys = self.shell.nova.keypairs.findall()
112 self.shell.nova.keypairs.delete(key)
113 self.shell.keystone.users.delete(user)
116 def add_user_role(self, kuser_id, tenant_id, role_name):
117 user = self.shell.keystone.users.find(id=kuser_id)
118 tenant = self.shell.keystone.tenants.find(id=tenant_id)
119 role = self.shell.keystone.roles.find(name=role_name)
122 user_roles = user.list_roles(tenant.id)
123 for user_role in user_roles:
124 if user_role.name == role.name:
127 tenant.add_user(user, role)
131 def delete_user_role(self, kuser_id, tenant_id, role_name):
132 user = self.shell.keystone.users.find(id=kuser_id)
133 tenant = self.shell.keystone.tenants.find(id=tenant_id)
134 role = self.shell.keystone.roles.find(name=role_name)
137 user_roles = user.list_roles(tenant.id)
138 for user_role in user_roles:
139 if user_role.name == role.name:
142 tenant.remove_user(user, role)
146 def update_user(self, id, fields):
147 if 'password' in fields:
148 self.shell.keystone.users.update_password(id, fields['password'])
149 if 'enabled' in fields:
150 self.shell.keystone.users.update_enabled(id, fields['enabled'])
153 def create_router(self, name, set_gateway=True):
154 routers = self.shell.quantum.list_routers(name=name)['routers']
158 router = self.shell.quantum.create_router({'router': {'name': name}})['router']
159 # add router to external network
161 nets = self.shell.quantum.list_networks()['networks']
163 if net['router:external'] == True:
164 self.shell.quantum.add_gateway_router(router['id'],
165 {'network_id': net['id']})
169 def delete_router(self, id):
170 routers = self.shell.quantum.list_routers(id=id)['routers']
171 for router in routers:
172 self.shell.quantum.delete_router(router['id'])
173 # remove router form external network
174 #nets = self.shell.quantum.list_networks()['networks']
176 # if net['router:external'] == True:
177 # self.shell.quantum.remove_gateway_router(router['id'])
179 def add_router_interface(self, router_id, subnet_id):
180 router = self.shell.quantum.show_router(router_id)['router']
181 subnet = self.shell.quantum.show_subnet(subnet_id)['subnet']
182 if router and subnet:
183 self.shell.quantum.add_interface_router(router_id, {'subnet_id': subnet_id})
185 def delete_router_interface(self, router_id, subnet_id):
186 router = self.shell.quantum.show_router(router_id)
187 subnet = self.shell.quantum.show_subnet(subnet_id)
188 if router and subnet:
189 self.shell.quantum.remove_interface_router(router_id, {'subnet_id': subnet_id})
191 def create_network(self, name, shared=False):
192 nets = self.shell.quantum.list_networks(name=name)['networks']
196 net = self.shell.quantum.create_network({'network': {'name': name, 'shared': shared}})['network']
199 def delete_network(self, id):
200 nets = self.shell.quantum.list_networks()['networks']
204 self.delete_network_ports(net['id'])
205 # delete all subnets:
206 for subnet_id in net['subnets']:
207 self.delete_subnet(subnet_id)
208 self.shell.quantum.delete_network(net['id'])
211 def delete_network_ports(self, network_id):
212 ports = self.shell.quantum.list_ports()['ports']
214 if port['network_id'] == network_id:
215 self.shell.quantum.delete_port(port['id'])
218 def delete_subnet_ports(self, subnet_id):
219 ports = self.shell.quantum.list_ports()['ports']
222 for fixed_ip in port['fixed_ips']:
223 if fixed_ip['subnet_id'] == subnet_id:
227 self.shell.quantum.delete_port(port['id'])
230 def create_subnet(self, name, network_id, cidr_ip, ip_version, start, end):
231 #nets = self.shell.quantum.list_networks(name=network_name)['networks']
233 # raise Exception, "No such network: %s" % network_name
237 subnets = self.shell.quantum.list_subnets()['subnets']
239 if snet['cidr'] == cidr_ip and snet['network_id'] == network_id:
243 allocation_pools = [{'start': start, 'end': end}]
244 subnet = {'subnet': {'name': name,
245 'network_id': network_id,
246 'ip_version': ip_version,
248 'dns_nameservers': ['8.8.8.8', '8.8.4.4'],
249 'allocation_pools': allocation_pools}}
250 subnet = self.shell.quantum.create_subnet(subnet)['subnet']
251 self.add_external_route(subnet)
252 # TODO: Add route to external network
253 # e.g. # route add -net 10.0.3.0/24 dev br-ex gw 10.100.0.5
256 def update_subnet(self, id, fields):
257 return self.shell.quantum.update_subnet(id, fields)
259 def delete_subnet(self, id):
260 #return self.shell.quantum.delete_subnet(id=id)
261 # inefficient but fault tolerant
262 subnets = self.shell.quantum.list_subnets()['subnets']
263 for subnet in subnets:
264 if subnet['id'] == id:
265 self.delete_subnet_ports(subnet['id'])
266 self.shell.quantum.delete_subnet(id)
267 self.delete_external_route(subnet)
270 def get_external_routes(self):
271 status, output = commands.getstatusoutput('route')
272 routes = output.split('\n')[3:]
275 def add_external_route(self, subnet, routes=[]):
277 routes = self.get_external_routes()
279 ports = self.shell.quantum.list_ports()['ports']
281 gw_ip = subnet['gateway_ip']
282 subnet_id = subnet['id']
284 # 1. Find the port associated with the subnet's gateway
285 # 2. Find the router associated with that port
286 # 3. Find the port associated with this router and on the external net
287 # 4. Set up route to the subnet through the port from step 3
290 for fixed_ip in port['fixed_ips']:
291 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
293 router_id = gw_port['device_id']
294 router = self.shell.quantum.show_router(router_id)['router']
295 if router and router.get('external_gateway_info'):
296 ext_net = router['external_gateway_info']['network_id']
298 if port['device_id'] == router_id and port['network_id'] == ext_net:
299 ip_address = port['fixed_ips'][0]['ip_address']
302 # check if external route already exists
306 if subnet['cidr'] in route and ip_address in route:
309 cmd = "route add -net %s dev br-ex gw %s" % (subnet['cidr'], ip_address)
310 s, o = commands.getstatusoutput(cmd)
311 #print cmd, "\n", s, o
315 def delete_external_route(self, subnet):
316 ports = self.shell.quantum.list_ports()['ports']
318 gw_ip = subnet['gateway_ip']
319 subnet_id = subnet['id']
321 # 1. Find the port associated with the subnet's gateway
322 # 2. Find the router associated with that port
323 # 3. Find the port associated with this router and on the external net
324 # 4. Set up route to the subnet through the port from step 3
327 for fixed_ip in port['fixed_ips']:
328 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
330 router_id = gw_port['device_id']
331 router = self.shell.quantum.show_router(router_id)['router']
332 ext_net = router['external_gateway_info']['network_id']
334 if port['device_id'] == router_id and port['network_id'] == ext_net:
335 ip_address = port['fixed_ips'][0]['ip_address']
338 cmd = "route delete -net %s" % (subnet['cidr'])
339 commands.getstatusoutput(cmd)
343 def create_keypair(self, name, public_key):
344 keys = self.shell.nova.keypairs.findall(name=name)
348 if key.public_key != public_key:
349 self.delete_keypair(key.id)
350 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
352 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
355 def delete_keypair(self, id):
356 keys = self.shell.nova.keypairs.findall(id=id)
358 self.shell.nova.keypairs.delete(key)
361 def get_private_networks(self, tenant=None):
363 tenant = self.shell.nova.tenant
364 tenant = self.shell.keystone.tenants.find(name=tenant)
365 search_opts = {"tenant_id": tenant.id, "shared": False}
366 private_networks = self.shell.quantum.list_networks(**search_opts)
367 return private_networks
369 def get_shared_networks(self):
370 search_opts = {"shared": True}
371 shared_networks = self.shell.quantum.list_networks(**search_opts)
372 return shared_networks
374 def get_network_subnet(self, network_id):
378 os_networks = self.shell.quantum.list_networks(id=network_id)["networks"]
380 os_network = os_networks[0]
381 if os_network['subnets']:
382 subnet_id = os_network['subnets'][0]
383 os_subnets = self.shell.quantum.list_subnets(id=subnet_id)['subnets']
385 subnet = os_subnets[0]['cidr']
387 return (subnet_id, subnet)
389 def spawn_instance(self, name, key_name=None, hostname=None, image_id=None, security_group=None, pubkeys=[], nics=None, metadata=None):
390 flavor_name = self.config.nova_default_flavor
391 flavor = self.shell.nova.flavors.find(name=flavor_name)
393 # image = self.config.nova_default_imave
394 if not security_group:
395 security_group = self.config.nova_default_security_group
399 files['/root/.ssh/authorized_keys'] = "\n".join(pubkeys)
402 availability_zone = None
404 availability_zone = 'nova:%s' % hostname
405 server = self.shell.nova.servers.create(
410 security_group = security_group,
412 scheduler_hints=hints,
413 availability_zone=availability_zone,
418 def destroy_instance(self, id):
419 if (self.shell.nova.tenant=="admin"):
420 # findall() is implemented as a list() followed by a python search of the
421 # list. Since findall() doesn't accept "all_tenants", we do this using
422 # list() ourselves. This allows us to delete an instance as admin.
423 servers = self.shell.nova.servers.list(search_opts={"all_tenants": True})
425 servers = self.shell.nova.servers.list()
426 for server in servers:
428 result=self.shell.nova.servers.delete(server)
430 def update_instance_metadata(self, id, metadata):
431 servers = self.shell.nova.servers.findall(id=id)
432 for server in servers:
433 self.shell.nova.servers.set_meta(server, metadata)
434 # note: set_meta() returns a broken Server() object. Don't try to
435 # print it in the shell or it will fail in __repr__.
437 def delete_instance_metadata(self, id, metadata):
438 # note: metadata is a dict. Only the keys matter, not the values.
439 servers = self.shell.nova.servers.findall(id=id)
440 for server in servers:
441 self.shell.nova.servers.delete_meta(server, metadata)