blob: b3cf7b1b48e1bb93d9568fd0be138c70a85dcf14 [file] [log] [blame]
Matteo Scandolof0441032017-08-08 13:05:26 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Scott Bakerb63ea792016-08-11 10:24:48 -070017import commands
18import hashlib
Matteo Scandoloceccb1f2017-06-05 10:35:44 -070019from xosconfig import Config
Scott Bakeraf599eb2017-03-21 12:43:26 -070020from synchronizers.new_base.modelaccessor import *
Scott Bakerb63ea792016-08-11 10:24:48 -070021
22try:
Scott Baker04a37f52016-08-11 10:52:21 -070023 from synchronizers.openstack.client import OpenStackClient
Scott Bakerb63ea792016-08-11 10:24:48 -070024 has_openstack = True
25except:
26 has_openstack = False
27
Matteo Scandoloceccb1f2017-06-05 10:35:44 -070028manager_enabled = Config.get("nova.enabled")
Scott Bakerb63ea792016-08-11 10:24:48 -070029
30class OpenStackDriver:
31
32 def __init__(self, config = None, client=None):
Scott Bakerb63ea792016-08-11 10:24:48 -070033
34 if client:
35 self.shell = client
36
37 self.enabled = manager_enabled
38 self.has_openstack = has_openstack
39 self.controller = None
40 self.admin_user = None
41
42 def client_driver(self, caller=None, tenant=None, controller=None):
43 if caller:
44 auth = {'username': caller.email,
45 'password': hashlib.md5(caller.password).hexdigest()[:6],
46 'tenant': tenant}
Matteo Scandoloceccb1f2017-06-05 10:35:44 -070047 client = OpenStackClient(controller=controller, cacert=Config.get("nova.ca_ssl_cert"), **auth)
Scott Bakerb63ea792016-08-11 10:24:48 -070048 else:
49 admin_driver = self.admin_driver(tenant=tenant, controller=controller)
50 client = OpenStackClient(tenant=tenant, controller=admin_driver.controller)
51
52 driver = OpenStackDriver(client=client)
53 #driver.admin_user = admin_driver.admin_user
54 #driver.controller = admin_driver.controller
55 return driver
56
57 def admin_driver(self, tenant=None, controller=None):
58 if isinstance(controller, int):
59 controller = Controller.objects.get(id=controller.id)
60 if not tenant:
61 tenant = controller.admin_tenant
Matteo Scandoloceccb1f2017-06-05 10:35:44 -070062 client = OpenStackClient(tenant=tenant, controller=controller, cacert=Config.get("nova.ca_ssl_cert"))
Scott Bakerb63ea792016-08-11 10:24:48 -070063 driver = OpenStackDriver(client=client)
64 driver.admin_user = client.keystone.users.find(name=controller.admin_user)
65 driver.controller = controller
66 return driver
67
68 def create_role(self, name):
69 roles = self.shell.keystone.roles.findall(name=name)
70 roles_title = self.shell.keystone.roles.findall(name=name.title())
71 roles_found = roles + roles_title
72 if not roles_found:
73 role = self.shell.keystone.roles.create(name)
74 else:
75 role = roles_found[0]
76 return role
77
78 def delete_role(self, filter):
79 roles = self.shell.keystone.roles.findall(**filter)
80 for role in roles:
81 self.shell.keystone.roles.delete(role)
82 return 1
83
84 def create_tenant(self, tenant_name, enabled, description):
85 """Create keystone tenant. Suggested fields: name, description, enabled"""
86 tenants = self.shell.keystone.tenants.findall(name=tenant_name)
87 if not tenants:
88 fields = {'tenant_name': tenant_name, 'enabled': enabled,
89 'description': description}
90 tenant = self.shell.keystone.tenants.create(**fields)
91 else:
92 tenant = tenants[0]
93
94 # always give the admin user the admin role to any tenant created
95 # by the driver.
96 self.add_user_role(self.admin_user.id, tenant.id, 'admin')
97 return tenant
98
99 def update_tenant(self, id, **kwds):
100 return self.shell.keystone.tenants.update(id, **kwds)
101
102 def delete_tenant(self, id):
103 # FIXME: nova_db is commented out in clients.py, throws errors.
104 # Commenting this out for the time being until actually fixed
105
106 #ctx = self.shell.nova_db.ctx
107 tenants = self.shell.keystone.tenants.findall(id=id)
108 for tenant in tenants:
109 # nova does not automatically delete the tenant's instances
110 # so we manually delete instances before deleting the tenant
111 #instances = self.shell.nova_db.instance_get_all_by_filters(ctx,
112 # {'project_id': tenant.id}, 'id', 'asc')
113 #client = OpenStackClient(tenant=tenant.name)
114 #driver = OpenStackDriver(client=client)
115 #for instance in instances:
116 # driver.destroy_instance(instance.id)
117 self.shell.keystone.tenants.delete(tenant)
118 return 1
119
120 def create_user(self, name, email, password, enabled):
121 users = self.shell.keystone.users.findall(email=email)
122 if not users:
123 fields = {'name': name, 'email': email, 'password': password,
124 'enabled': enabled}
125 user = self.shell.keystone.users.create(**fields)
126 else:
127 user = users[0]
128 return user
129
130 def delete_user(self, id):
131 users = self.shell.keystone.users.findall(id=id)
132 for user in users:
133 # delete users keys
134 keys = self.shell.nova.keypairs.findall()
135 for key in keys:
136 self.shell.nova.keypairs.delete(key)
137 self.shell.keystone.users.delete(user)
138 return 1
139
140 def get_admin_role(self):
141 role = None
142 for admin_role_name in ['admin', 'Admin']:
143 roles = self.shell.keystone.roles.findall(name=admin_role_name)
144 if roles:
145 role = roles[0]
146 break
147 return role
148
149 def add_user_role(self, kuser_id, tenant_id, role_name):
150 user = self.shell.keystone.users.find(id=kuser_id)
151 tenant = self.shell.keystone.tenants.find(id=tenant_id)
152 # admin role can be lowercase or title. Look for both
153 role = None
154 if role_name.lower() == 'admin':
155 role = self.get_admin_role()
156 else:
157 # look up non admin role or force exception when admin role isnt found
158 role = self.shell.keystone.roles.find(name=role_name)
159
160 role_found = False
161 user_roles = user.list_roles(tenant.id)
162 for user_role in user_roles:
163 if user_role.name == role.name:
164 role_found = True
165 if not role_found:
166 tenant.add_user(user, role)
167
168 return 1
169
170 def delete_user_role(self, kuser_id, tenant_id, role_name):
171 user = self.shell.keystone.users.find(id=kuser_id)
172 tenant = self.shell.keystone.tenants.find(id=tenant_id)
173 # admin role can be lowercase or title. Look for both
174 role = None
175 if role_name.lower() == 'admin':
176 role = self.get_admin_role()
177 else:
178 # look up non admin role or force exception when admin role isnt found
179 role = self.shell.keystone.roles.find(name=role_name)
180
181 role_found = False
182 user_roles = user.list_roles(tenant.id)
183 for user_role in user_roles:
184 if user_role.name == role.name:
185 role_found = True
186 if role_found:
187 tenant.remove_user(user, role)
188
189 return 1
190
191 def update_user(self, id, fields):
192 if 'password' in fields:
193 self.shell.keystone.users.update_password(id, fields['password'])
194 if 'enabled' in fields:
195 self.shell.keystone.users.update_enabled(id, fields['enabled'])
196 return 1
197
198 def create_router(self, name, set_gateway=True):
199 routers = self.shell.neutron.list_routers(name=name)['routers']
200 if routers:
201 router = routers[0]
202 else:
203 router = self.shell.neutron.create_router({'router': {'name': name}})['router']
204 # add router to external network
205 if set_gateway:
206 nets = self.shell.neutron.list_networks()['networks']
207 for net in nets:
208 if net['router:external'] == True:
209 self.shell.neutron.add_gateway_router(router['id'],
210 {'network_id': net['id']})
211
212 return router
213
214 def delete_router(self, id):
215 routers = self.shell.neutron.list_routers(id=id)['routers']
216 for router in routers:
217 self.shell.neutron.delete_router(router['id'])
218 # remove router form external network
219 #nets = self.shell.neutron.list_networks()['networks']
220 #for net in nets:
221 # if net['router:external'] == True:
222 # self.shell.neutron.remove_gateway_router(router['id'])
223
224 def add_router_interface(self, router_id, subnet_id):
225 router = self.shell.neutron.show_router(router_id)['router']
226 subnet = self.shell.neutron.show_subnet(subnet_id)['subnet']
227 if router and subnet:
228 self.shell.neutron.add_interface_router(router_id, {'subnet_id': subnet_id})
229
230 def delete_router_interface(self, router_id, subnet_id):
231 router = self.shell.neutron.show_router(router_id)
232 subnet = self.shell.neutron.show_subnet(subnet_id)
233 if router and subnet:
234 self.shell.neutron.remove_interface_router(router_id, {'subnet_id': subnet_id})
235
236 def create_network(self, name, shared=False):
237 nets = self.shell.neutron.list_networks(name=name)['networks']
238 if nets:
239 net = nets[0]
240 else:
241 net = self.shell.neutron.create_network({'network': {'name': name, 'shared': shared}})['network']
242 return net
243
244 def delete_network(self, id):
245 nets = self.shell.neutron.list_networks()['networks']
246 for net in nets:
247 if net['id'] == id:
248 # delete_all ports
249 self.delete_network_ports(net['id'])
250 # delete all subnets:
251 for subnet_id in net['subnets']:
252 self.delete_subnet(subnet_id)
253 self.shell.neutron.delete_network(net['id'])
254 return 1
255
256 def delete_network_ports(self, network_id):
257 ports = self.shell.neutron.list_ports()['ports']
258 for port in ports:
259 if port['network_id'] == network_id:
260 self.shell.neutron.delete_port(port['id'])
261 return 1
262
263 def delete_subnet_ports(self, subnet_id):
264 ports = self.shell.neutron.list_ports()['ports']
265 for port in ports:
266 delete = False
267 for fixed_ip in port['fixed_ips']:
268 if fixed_ip['subnet_id'] == subnet_id:
269 delete=True
270 break
271 if delete:
272 self.shell.neutron.delete_port(port['id'])
273 return 1
274
275 def create_subnet(self, name, network_id, cidr_ip, ip_version, start, end):
276 #nets = self.shell.neutron.list_networks(name=network_name)['networks']
277 #if not nets:
278 # raise Exception, "No such network: %s" % network_name
279 #net = nets[0]
280
281 subnet = None
282 subnets = self.shell.neutron.list_subnets()['subnets']
283 for snet in subnets:
284 if snet['cidr'] == cidr_ip and snet['network_id'] == network_id:
285 subnet = snet
286
287 if not subnet:
288 # HACK: Add metadata route -- Neutron does not reliably supply this
289 metadata_ip = cidr_ip.replace("0/24", "3")
290
291 allocation_pools = [{'start': start, 'end': end}]
292 subnet = {'subnet': {'name': name,
293 'network_id': network_id,
294 'ip_version': ip_version,
295 'cidr': cidr_ip,
296 #'dns_nameservers': ['8.8.8.8', '8.8.4.4'],
297 'host_routes': [{'destination':'169.254.169.254/32','nexthop':metadata_ip}],
298 'gateway_ip': None,
299 'allocation_pools': allocation_pools}}
300 subnet = self.shell.neutron.create_subnet(subnet)['subnet']
301 # self.add_external_route(subnet)
302
303 return subnet
304
305 def update_subnet(self, id, fields):
306 return self.shell.neutron.update_subnet(id, fields)
307
308 def delete_subnet(self, id):
309 #return self.shell.neutron.delete_subnet(id=id)
310 # inefficient but fault tolerant
311 subnets = self.shell.neutron.list_subnets()['subnets']
312 for subnet in subnets:
313 if subnet['id'] == id:
314 self.delete_subnet_ports(subnet['id'])
315 self.shell.neutron.delete_subnet(id)
316 self.delete_external_route(subnet)
317 return 1
318
319 def get_external_routes(self):
320 status, output = commands.getstatusoutput('route')
321 routes = output.split('\n')[3:]
322 return routes
323
324 def add_external_route(self, subnet, routes=[]):
325 if not routes:
326 routes = self.get_external_routes()
327
328 ports = self.shell.neutron.list_ports()['ports']
329
330 gw_ip = subnet['gateway_ip']
331 subnet_id = subnet['id']
332
333 # 1. Find the port associated with the subnet's gateway
334 # 2. Find the router associated with that port
335 # 3. Find the port associated with this router and on the external net
336 # 4. Set up route to the subnet through the port from step 3
337 ip_address = None
338 for port in ports:
339 for fixed_ip in port['fixed_ips']:
340 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
341 gw_port = port
342 router_id = gw_port['device_id']
343 router = self.shell.neutron.show_router(router_id)['router']
344 if router and router.get('external_gateway_info'):
345 ext_net = router['external_gateway_info']['network_id']
346 for port in ports:
347 if port['device_id'] == router_id and port['network_id'] == ext_net:
348 ip_address = port['fixed_ips'][0]['ip_address']
349
350 if ip_address:
351 # check if external route already exists
352 route_exists = False
353 if routes:
354 for route in routes:
355 if subnet['cidr'] in route and ip_address in route:
356 route_exists = True
357 if not route_exists:
358 cmd = "route add -net %s dev br-ex gw %s" % (subnet['cidr'], ip_address)
359 s, o = commands.getstatusoutput(cmd)
360 #print cmd, "\n", s, o
361
362 return 1
363
364 def delete_external_route(self, subnet):
365 ports = self.shell.neutron.list_ports()['ports']
366
367 gw_ip = subnet['gateway_ip']
368 subnet_id = subnet['id']
369
370 # 1. Find the port associated with the subnet's gateway
371 # 2. Find the router associated with that port
372 # 3. Find the port associated with this router and on the external net
373 # 4. Set up route to the subnet through the port from step 3
374 ip_address = None
375 for port in ports:
376 for fixed_ip in port['fixed_ips']:
377 if fixed_ip['subnet_id'] == subnet_id and fixed_ip['ip_address'] == gw_ip:
378 gw_port = port
379 router_id = gw_port['device_id']
380 router = self.shell.neutron.show_router(router_id)['router']
381 ext_net = router['external_gateway_info']['network_id']
382 for port in ports:
383 if port['device_id'] == router_id and port['network_id'] == ext_net:
384 ip_address = port['fixed_ips'][0]['ip_address']
385
386 if ip_address:
387 cmd = "route delete -net %s" % (subnet['cidr'])
388 commands.getstatusoutput(cmd)
389
390 return 1
391
392 def create_keypair(self, name, public_key):
393 keys = self.shell.nova.keypairs.findall(name=name)
394 if keys:
395 key = keys[0]
396 # update key
397 if key.public_key != public_key:
398 self.delete_keypair(key.id)
399 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
400 else:
401 key = self.shell.nova.keypairs.create(name=name, public_key=public_key)
402 return key
403
404 def delete_keypair(self, id):
405 keys = self.shell.nova.keypairs.findall(id=id)
406 for key in keys:
407 self.shell.nova.keypairs.delete(key)
408 return 1
409
410 def get_private_networks(self, tenant=None):
411 if not tenant:
412 tenant = self.shell.nova.tenant
413 tenant = self.shell.keystone.tenants.find(name=tenant)
414 search_opts = {"tenant_id": tenant.id, "shared": False}
415 private_networks = self.shell.neutron.list_networks(**search_opts)
416 return private_networks
417
418 def get_shared_networks(self):
419 search_opts = {"shared": True}
420 shared_networks = self.shell.neutron.list_networks(**search_opts)
421 return shared_networks
422
423 def get_network_subnet(self, network_id):
424 subnet_id = None
425 subnet = None
426 if network_id:
427 os_networks = self.shell.neutron.list_networks(id=network_id)["networks"]
428 if os_networks:
429 os_network = os_networks[0]
430 if os_network['subnets']:
431 subnet_id = os_network['subnets'][0]
432 os_subnets = self.shell.neutron.list_subnets(id=subnet_id)['subnets']
433 if os_subnets:
434 subnet = os_subnets[0]['cidr']
435
436 return (subnet_id, subnet)
437
438 def spawn_instance(self, name, key_name=None, availability_zone=None, hostname=None, image_id=None, security_group=None, pubkeys=[], nics=None, metadata=None, userdata=None, flavor_name=None):
439 if not flavor_name:
Matteo Scandoloceccb1f2017-06-05 10:35:44 -0700440 flavor_name = Config.get("nova.default_flavor")
Scott Bakerb63ea792016-08-11 10:24:48 -0700441
442 flavor = self.shell.nova.flavors.find(name=flavor_name)
443
444 if not security_group:
Matteo Scandoloceccb1f2017-06-05 10:35:44 -0700445 security_group = Config.get("nova.default_security_group")
Scott Bakerb63ea792016-08-11 10:24:48 -0700446
447 files = {}
448 #if pubkeys:
449 # files["/root/.ssh/authorized_keys"] = "\n".join(pubkeys).encode('base64')
450 hints = {}
451
452 # determine availability zone and compute host
453 availability_zone_filter = None
454 if availability_zone is None or not availability_zone:
455 availability_zone_filter = 'nova'
456 else:
457 availability_zone_filter = availability_zone
458 if hostname:
459 availability_zone_filter += ':%s' % hostname
460
461 server = self.shell.nova.servers.create(
462 name=name,
463 key_name = key_name,
464 flavor=flavor.id,
465 image=image_id,
466 security_group = security_group,
467 #files = files,
468 scheduler_hints=hints,
469 availability_zone=availability_zone_filter,
470 nics=nics,
471 networks=nics,
472 meta=metadata,
473 userdata=userdata)
474 return server
475
476 def destroy_instance(self, id):
477 if (self.shell.nova.tenant=="admin"):
478 # findall() is implemented as a list() followed by a python search of the
479 # list. Since findall() doesn't accept "all_tenants", we do this using
480 # list() ourselves. This allows us to delete an instance as admin.
481 servers = self.shell.nova.servers.list(search_opts={"all_tenants": True})
482 else:
483 servers = self.shell.nova.servers.list()
484 for server in servers:
485 if server.id == id:
486 result=self.shell.nova.servers.delete(server)
487
488 def update_instance_metadata(self, id, metadata):
489 servers = self.shell.nova.servers.findall(id=id)
490 for server in servers:
491 self.shell.nova.servers.set_meta(server, metadata)
492 # note: set_meta() returns a broken Server() object. Don't try to
493 # print it in the shell or it will fail in __repr__.
494
495 def delete_instance_metadata(self, id, metadata):
496 # note: metadata is a dict. Only the keys matter, not the values.
497 servers = self.shell.nova.servers.findall(id=id)
498 for server in servers:
499 self.shell.nova.servers.delete_meta(server, metadata)
500