9640fb9b458edf8e20dce8546b618b785a9b9f2f
[functest.git] / utils / openstack_utils.py
1 #!/usr/bin/env python
2 #
3 # jose.lausuch@ericsson.com
4 # valentin.boucher@orange.com
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10
11 import os
12 import os.path
13 import subprocess
14 import sys
15 import time
16
17 from glanceclient import client as glanceclient
18 from keystoneclient.v2_0 import client as keystoneclient
19 from neutronclient.v2_0 import client as neutronclient
20 from novaclient import client as novaclient
21
22
23 # *********************************************
24 #   CREDENTIALS
25 # *********************************************
26 def check_credentials():
27     """
28     Check if the OpenStack credentials (openrc) are sourced
29     """
30     env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD', 'OS_TENANT_NAME']
31     return all(map(lambda v: v in os.environ and os.environ[v], env_vars))
32
33
34 def get_credentials(service):
35     """Returns a creds dictionary filled with the following keys:
36     * username
37     * password/api_key (depending on the service)
38     * tenant_name/project_id (depending on the service)
39     * auth_url
40     :param service: a string indicating the name of the service
41                     requesting the credentials.
42     """
43     creds = {}
44
45     # Check that the env vars exists:
46     envvars = ('OS_USERNAME', 'OS_PASSWORD', 'OS_AUTH_URL', 'OS_TENANT_NAME')
47     for envvar in envvars:
48         if os.getenv(envvar) is None:
49             print("'%s' is not exported as an env variable." % envvar)
50             exit(-1)
51
52     # Unfortunately, each of the OpenStack client will request slightly
53     # different entries in their credentials dict.
54     if service.lower() in ("nova", "cinder"):
55         password = "api_key"
56         tenant = "project_id"
57     else:
58         password = "password"
59         tenant = "tenant_name"
60
61     # The most common way to pass these info to the script is to do it through
62     # environment variables.
63     creds.update({
64         "username": os.environ.get("OS_USERNAME"),
65         password: os.environ.get("OS_PASSWORD"),
66         "auth_url": os.environ.get("OS_AUTH_URL"),
67         tenant: os.environ.get("OS_TENANT_NAME")
68     })
69     cacert = os.environ.get("OS_CACERT")
70     if cacert is not None:
71         # each openstack client uses differnt kwargs for this
72         creds.update({"cacert": cacert,
73                       "ca_cert": cacert,
74                       "https_ca_cert": cacert,
75                       "https_cacert": cacert,
76                       "ca_file": cacert})
77         creds.update({"insecure": "True", "https_insecure": "True"})
78         if not os.path.isfile(cacert):
79             print ("WARNING: The 'OS_CACERT' environment variable is " +
80                    "set to %s but the file does not exist." % cacert)
81     return creds
82
83
84 def source_credentials(rc_file):
85     pipe = subprocess.Popen(". %s; env" % rc_file, stdout=subprocess.PIPE,
86                             shell=True)
87     output = pipe.communicate()[0]
88     env = dict((line.split("=", 1) for line in output.splitlines()))
89     os.environ.update(env)
90     return env
91
92
93 # *********************************************
94 #   CLIENTS
95 # *********************************************
96 def get_keystone_client():
97     creds_keystone = get_credentials("keystone")
98     return keystoneclient.Client(**creds_keystone)
99
100
101 def get_nova_client():
102     creds_nova = get_credentials("nova")
103     return novaclient.Client('2', **creds_nova)
104
105
106 def get_neutron_client():
107     creds_neutron = get_credentials("neutron")
108     return neutronclient.Client(**creds_neutron)
109
110
111 def get_glance_client():
112     keystone_client = get_keystone_client()
113     glance_endpoint = keystone_client.service_catalog.url_for(
114         service_type='image', endpoint_type='publicURL')
115     return glanceclient.Client(1, glance_endpoint,
116                                token=keystone_client.auth_token)
117
118 # *********************************************
119 #   NOVA
120 # *********************************************
121
122
123 def get_instances(nova_client):
124     try:
125         instances = nova_client.servers.list(search_opts={'all_tenants': 1})
126         return instances
127     except Exception, e:
128         print "Error [get_instances(nova_client)]:", e
129         return None
130
131
132 def get_instance_status(nova_client, instance):
133     try:
134         instance = nova_client.servers.get(instance.id)
135         return instance.status
136     except:
137         # print ("Error [get_instance_status(nova_client, '%s')]:" %
138         #        str(instance)), e
139         return None
140
141
142 def get_instance_by_name(nova_client, instance_name):
143     try:
144         instance = nova_client.servers.find(name=instance_name)
145         return instance
146     except Exception, e:
147         print ("Error [get_instance_by_name(nova_client, '%s')]:" %
148                instance_name), e
149         return None
150
151
152 def get_flavor_id(nova_client, flavor_name):
153     flavors = nova_client.flavors.list(detailed=True)
154     id = ''
155     for f in flavors:
156         if f.name == flavor_name:
157             id = f.id
158             break
159     return id
160
161
162 def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram):
163     flavors = nova_client.flavors.list(detailed=True)
164     id = ''
165     for f in flavors:
166         if min_ram <= f.ram and f.ram <= max_ram:
167             id = f.id
168             break
169     return id
170
171
172 def get_floating_ips(nova_client):
173     try:
174         floating_ips = nova_client.floating_ips.list()
175         return floating_ips
176     except Exception, e:
177         print "Error [get_floating_ips(nova_client)]:", e
178         return None
179
180
181 def create_flavor(nova_client, flavor_name, ram, disk, vcpus):
182     try:
183         flavor = nova_client.flavors.create(flavor_name, ram, vcpus, disk)
184     except Exception, e:
185         print ("Error [create_flavor(nova_client, '%s', '%s', '%s', "
186                "'%s')]:" % (flavor_name, ram, disk, vcpus)), e
187         return None
188     return flavor.id
189
190
191 def create_instance(flavor_name,
192                     image_id,
193                     network_id,
194                     instance_name="",
195                     config_drive=False,
196                     userdata=""):
197     nova_client = get_nova_client()
198     try:
199         flavor = nova_client.flavors.find(name=flavor_name)
200     except:
201         print("Error: Flavor '%s' not found. Available flavors are:" %
202               flavor_name)
203         print(nova_client.flavor.list())
204         return -1
205
206     return nova_client.servers.create(
207         name=instance_name,
208         flavor=flavor,
209         image=image_id,
210         config_drive=config_drive,
211         nics=[{"net-id": network_id}]
212     )
213
214
215 def create_instance_and_wait_for_active(flavor_name,
216                                         image_id,
217                                         network_id,
218                                         instance_name="",
219                                         config_drive=False,
220                                         userdata=""):
221     SLEEP = 3
222     VM_BOOT_TIMEOUT = 180
223     nova_client = get_nova_client()
224     instance = create_instance(flavor_name,
225                                image_id,
226                                network_id,
227                                instance_name="",
228                                config_drive=False,
229                                userdata="")
230
231     count = VM_BOOT_TIMEOUT / SLEEP
232     for n in range(count, -1, -1):
233         status = get_instance_status(nova_client, instance)
234         if status.lower() == "active":
235             return instance
236         elif status.lower() == "error":
237             print("The instance %s went to ERROR status." % instance_name)
238             return None
239         time.sleep(SLEEP)
240     print("Timeout booting the instance %s." % instance_name)
241     return None
242
243
244 def create_floating_ip(neutron_client):
245     extnet_id = get_external_net_id(neutron_client)
246     props = {'floating_network_id': extnet_id}
247     try:
248         ip_json = neutron_client.create_floatingip({'floatingip': props})
249         fip_addr = ip_json['floatingip']['floating_ip_address']
250         fip_id = ip_json['floatingip']['id']
251     except Exception, e:
252         print "Error [create_floating_ip(neutron_client)]:", e
253         return None
254     return {'fip_addr': fip_addr, 'fip_id': fip_id}
255
256
257 def add_floating_ip(nova_client, server_id, floatingip_id):
258     try:
259         nova_client.servers.add_floating_ip(server_id, floatingip_id)
260         return True
261     except Exception, e:
262         print ("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
263                (server_id, floatingip_id)), e
264         return False
265
266
267 def delete_instance(nova_client, instance_id):
268     try:
269         nova_client.servers.force_delete(instance_id)
270         return True
271     except Exception, e:
272         print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
273         return False
274
275
276 def delete_floating_ip(nova_client, floatingip_id):
277     try:
278         nova_client.floating_ips.delete(floatingip_id)
279         return True
280     except Exception, e:
281         print ("Error [delete_floating_ip(nova_client, '%s')]:" %
282                floatingip_id), e
283         return False
284
285
286 # *********************************************
287 #   NEUTRON
288 # *********************************************
289 def get_network_list(neutron_client):
290     network_list = neutron_client.list_networks()['networks']
291     if len(network_list) == 0:
292         return None
293     else:
294         return network_list
295
296
297 def get_router_list(neutron_client):
298     router_list = neutron_client.list_routers()['routers']
299     if len(router_list) == 0:
300         return None
301     else:
302         return router_list
303
304
305 def get_port_list(neutron_client):
306     port_list = neutron_client.list_ports()['ports']
307     if len(port_list) == 0:
308         return None
309     else:
310         return port_list
311
312
313 def get_network_id(neutron_client, network_name):
314     networks = neutron_client.list_networks()['networks']
315     id = ''
316     for n in networks:
317         if n['name'] == network_name:
318             id = n['id']
319             break
320     return id
321
322
323 def get_subnet_id(neutron_client, subnet_name):
324     subnets = neutron_client.list_subnets()['subnets']
325     id = ''
326     for s in subnets:
327         if s['name'] == subnet_name:
328             id = s['id']
329             break
330     return id
331
332
333 def get_router_id(neutron_client, router_name):
334     routers = neutron_client.list_routers()['routers']
335     id = ''
336     for r in routers:
337         if r['name'] == router_name:
338             id = r['id']
339             break
340     return id
341
342
343 def get_private_net(neutron_client):
344     # Checks if there is an existing shared private network
345     networks = neutron_client.list_networks()['networks']
346     if len(networks) == 0:
347         return None
348     for net in networks:
349         if (net['router:external'] is False) and (net['shared'] is True):
350             return net
351     return None
352
353
354 def get_external_net(neutron_client):
355     for network in neutron_client.list_networks()['networks']:
356         if network['router:external']:
357             return network['name']
358     return False
359
360
361 def get_external_net_id(neutron_client):
362     for network in neutron_client.list_networks()['networks']:
363         if network['router:external']:
364             return network['id']
365     return False
366
367
368 def check_neutron_net(neutron_client, net_name):
369     for network in neutron_client.list_networks()['networks']:
370         if network['name'] == net_name:
371             for subnet in network['subnets']:
372                 return True
373     return False
374
375
376 def create_neutron_net(neutron_client, name):
377     json_body = {'network': {'name': name,
378                              'admin_state_up': True}}
379     try:
380         network = neutron_client.create_network(body=json_body)
381         network_dict = network['network']
382         return network_dict['id']
383     except Exception, e:
384         print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
385         return False
386
387
388 def create_neutron_subnet(neutron_client, name, cidr, net_id):
389     json_body = {'subnets': [{'name': name, 'cidr': cidr,
390                               'ip_version': 4, 'network_id': net_id}]}
391     try:
392         subnet = neutron_client.create_subnet(body=json_body)
393         return subnet['subnets'][0]['id']
394     except Exception, e:
395         print ("Error [create_neutron_subnet(neutron_client, '%s', '%s', "
396                "'%s')]:" % (name, cidr, net_id)), e
397         return False
398
399
400 def create_neutron_router(neutron_client, name):
401     json_body = {'router': {'name': name, 'admin_state_up': True}}
402     try:
403         router = neutron_client.create_router(json_body)
404         return router['router']['id']
405     except Exception, e:
406         print "Error [create_neutron_router(neutron_client, '%s')]:" % name, e
407         return False
408
409
410 def create_neutron_port(neutron_client, name, network_id, ip):
411     json_body = {'port': {
412                  'admin_state_up': True,
413                  'name': name,
414                  'network_id': network_id,
415                  'fixed_ips': [{"ip_address": ip}]
416                  }}
417     try:
418         port = neutron_client.create_port(body=json_body)
419         return port['port']['id']
420     except Exception, e:
421         print ("Error [create_neutron_port(neutron_client, '%s', '%s', "
422                "'%s')]:" % (name, network_id, ip)), e
423         return False
424
425
426 def update_neutron_net(neutron_client, network_id, shared=False):
427     json_body = {'network': {'shared': shared}}
428     try:
429         neutron_client.update_network(network_id, body=json_body)
430         return True
431     except Exception, e:
432         print ("Error [update_neutron_net(neutron_client, '%s', '%s')]:" %
433                (network_id, str(shared))), e
434         return False
435
436
437 def update_neutron_port(neutron_client, port_id, device_owner):
438     json_body = {'port': {
439                  'device_owner': device_owner,
440                  }}
441     try:
442         port = neutron_client.update_port(port=port_id,
443                                           body=json_body)
444         return port['port']['id']
445     except Exception, e:
446         print ("Error [update_neutron_port(neutron_client, '%s', '%s')]:" %
447                (port_id, device_owner)), e
448         return False
449
450
451 def add_interface_router(neutron_client, router_id, subnet_id):
452     json_body = {"subnet_id": subnet_id}
453     try:
454         neutron_client.add_interface_router(router=router_id, body=json_body)
455         return True
456     except Exception, e:
457         print ("Error [add_interface_router(neutron_client, '%s', '%s')]:" %
458                (router_id, subnet_id)), e
459         return False
460
461
462 def add_gateway_router(neutron_client, router_id):
463     ext_net_id = get_external_net_id(neutron_client)
464     router_dict = {'network_id': ext_net_id}
465     try:
466         neutron_client.add_gateway_router(router_id, router_dict)
467         return True
468     except Exception, e:
469         print ("Error [add_gateway_router(neutron_client, '%s')]:" %
470                router_id), e
471         return False
472
473
474 def delete_neutron_net(neutron_client, network_id):
475     try:
476         neutron_client.delete_network(network_id)
477         return True
478     except Exception, e:
479         print ("Error [delete_neutron_net(neutron_client, '%s')]:" %
480                network_id), e
481         return False
482
483
484 def delete_neutron_subnet(neutron_client, subnet_id):
485     try:
486         neutron_client.delete_subnet(subnet_id)
487         return True
488     except Exception, e:
489         print ("Error [delete_neutron_subnet(neutron_client, '%s')]:" %
490                subnet_id), e
491         return False
492
493
494 def delete_neutron_router(neutron_client, router_id):
495     try:
496         neutron_client.delete_router(router=router_id)
497         return True
498     except Exception, e:
499         print ("Error [delete_neutron_router(neutron_client, '%s')]:" %
500                router_id), e
501         return False
502
503
504 def delete_neutron_port(neutron_client, port_id):
505     try:
506         neutron_client.delete_port(port_id)
507         return True
508     except Exception, e:
509         print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
510         return False
511
512
513 def remove_interface_router(neutron_client, router_id, subnet_id):
514     json_body = {"subnet_id": subnet_id}
515     try:
516         neutron_client.remove_interface_router(router=router_id,
517                                                body=json_body)
518         return True
519     except Exception, e:
520         print ("Error [remove_interface_router(neutron_client, '%s', '%s')]:" %
521                (router_id, subnet_id)), e
522         return False
523
524
525 def remove_gateway_router(neutron_client, router_id):
526     try:
527         neutron_client.remove_gateway_router(router_id)
528         return True
529     except Exception, e:
530         print ("Error [remove_gateway_router(neutron_client, '%s')]:" %
531                router_id), e
532         return False
533
534
535 def create_network_full(logger,
536                         neutron_client,
537                         net_name,
538                         subnet_name,
539                         router_name,
540                         cidr):
541
542     # Check if the network already exists
543     network_id = get_network_id(neutron_client, net_name)
544     subnet_id = get_subnet_id(neutron_client, subnet_name)
545     router_id = get_router_id(neutron_client, router_name)
546
547     if network_id != '' and subnet_id != '' and router_id != '':
548         logger.info("A network with name '%s' already exists..." % net_name)
549     else:
550         neutron_client.format = 'json'
551         logger.info('Creating neutron network %s...' % net_name)
552         network_id = create_neutron_net(neutron_client, net_name)
553
554         if not network_id:
555             return False
556
557         logger.debug("Network '%s' created successfully" % network_id)
558         logger.debug('Creating Subnet....')
559         subnet_id = create_neutron_subnet(neutron_client, subnet_name,
560                                           cidr, network_id)
561         if not subnet_id:
562             return False
563
564         logger.debug("Subnet '%s' created successfully" % subnet_id)
565         logger.debug('Creating Router...')
566         router_id = create_neutron_router(neutron_client, router_name)
567
568         if not router_id:
569             return False
570
571         logger.debug("Router '%s' created successfully" % router_id)
572         logger.debug('Adding router to subnet...')
573
574         if not add_interface_router(neutron_client, router_id, subnet_id):
575             return False
576
577         logger.debug("Interface added successfully.")
578
579         logger.debug('Adding gateway to router...')
580         if not add_gateway_router(neutron_client, router_id):
581             return False
582
583         logger.debug("Gateway added successfully.")
584
585     network_dic = {'net_id': network_id,
586                    'subnet_id': subnet_id,
587                    'router_id': router_id}
588     return network_dic
589
590
591 # *********************************************
592 #   SEC GROUPS
593 # *********************************************
594 def get_security_groups(neutron_client):
595     try:
596         security_groups = neutron_client.list_security_groups()[
597             'security_groups']
598         return security_groups
599     except Exception, e:
600         print "Error [get_security_groups(neutron_client)]:", e
601         return None
602
603
604 def get_security_group_id(neutron_client, sg_name):
605     security_groups = get_security_groups(neutron_client)
606     id = ''
607     for sg in security_groups:
608         if sg['name'] == sg_name:
609             id = sg['id']
610             break
611     return id
612
613
614 def create_security_group(neutron_client, sg_name, sg_description):
615     json_body = {'security_group': {'name': sg_name,
616                                     'description': sg_description}}
617     try:
618         secgroup = neutron_client.create_security_group(json_body)
619         return secgroup['security_group']
620     except Exception, e:
621         print ("Error [create_security_group(neutron_client, '%s', '%s')]:" %
622                (sg_name, sg_description)), e
623         return False
624
625
626 def create_secgroup_rule(neutron_client, sg_id, direction, protocol,
627                          port_range_min=None, port_range_max=None):
628     if port_range_min is None and port_range_max is None:
629         json_body = {'security_group_rule': {'direction': direction,
630                                              'security_group_id': sg_id,
631                                              'protocol': protocol}}
632     elif port_range_min is not None and port_range_max is not None:
633         json_body = {'security_group_rule': {'direction': direction,
634                                              'security_group_id': sg_id,
635                                              'port_range_min': port_range_min,
636                                              'port_range_max': port_range_max,
637                                              'protocol': protocol}}
638     else:
639         print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
640                "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
641                                               port_range_min, port_range_max,
642                                               protocol),
643                " Invalid values for port_range_min, port_range_max")
644         return False
645     try:
646         neutron_client.create_security_group_rule(json_body)
647         return True
648     except Exception, e:
649         print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
650                "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
651                                               port_range_min, port_range_max,
652                                               protocol)), e
653         return False
654
655
656 def add_secgroup_to_instance(nova_client, instance_id, secgroup_id):
657     try:
658         nova_client.servers.add_security_group(instance_id, secgroup_id)
659         return True
660     except Exception, e:
661         print ("Error [add_secgroup_to_instance(nova_client, '%s', '%s')]: " %
662                (instance_id, secgroup_id)), e
663         return False
664
665
666 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
667     json_body = {"quota": {
668         "security_group": sg_quota,
669         "security_group_rule": sg_rule_quota
670     }}
671
672     try:
673         neutron_client.update_quota(tenant_id=tenant_id,
674                                     body=json_body)
675         return True
676     except Exception, e:
677         print ("Error [update_sg_quota(neutron_client, '%s', '%s', "
678                "'%s')]:" % (tenant_id, sg_quota, sg_rule_quota)), e
679         return False
680
681
682 def delete_security_group(neutron_client, secgroup_id):
683     try:
684         neutron_client.delete_security_group(secgroup_id)
685         return True
686     except Exception, e:
687         print ("Error [delete_security_group(neutron_client, '%s')]:" %
688                secgroup_id), e
689         return False
690
691
692 # *********************************************
693 #   GLANCE
694 # *********************************************
695 def get_images(nova_client):
696     try:
697         images = nova_client.images.list()
698         return images
699     except Exception, e:
700         print "Error [get_images]:", e
701         return None
702
703
704 def get_image_id(glance_client, image_name):
705     images = glance_client.images.list()
706     id = ''
707     for i in images:
708         if i.name == image_name:
709             id = i.id
710             break
711     return id
712
713
714 def create_glance_image(glance_client, image_name, file_path, public=True):
715     if not os.path.isfile(file_path):
716         print "Error: file " + file_path + " does not exist."
717         return False
718     try:
719         with open(file_path) as fimage:
720             image = glance_client.images.create(name=image_name,
721                                                 is_public=public,
722                                                 disk_format="qcow2",
723                                                 container_format="bare",
724                                                 data=fimage)
725         return image.id
726     except Exception, e:
727         print ("Error [create_glance_image(glance_client, '%s', '%s', "
728                "'%s')]:" % (image_name, file_path, str(public))), e
729         return False
730
731
732 def delete_glance_image(nova_client, image_id):
733     try:
734         nova_client.images.delete(image_id)
735         return True
736     except Exception, e:
737         print ("Error [delete_glance_image(nova_client, '%s')]:" % image_id), e
738         return False
739
740
741 # *********************************************
742 #   CINDER
743 # *********************************************
744 def get_volumes(cinder_client):
745     try:
746         volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
747         return volumes
748     except Exception, e:
749         print "Error [get_volumes(cinder_client)]:", e
750         return None
751
752
753 def list_volume_types(cinder_client, public=True, private=True):
754     try:
755         volume_types = cinder_client.volume_types.list()
756         if not public:
757             volume_types = [vt for vt in volume_types if not vt.is_public]
758         if not private:
759             volume_types = [vt for vt in volume_types if vt.is_public]
760         return volume_types
761     except Exception, e:
762         print "Error [list_volume_types(cinder_client)]:", e
763         return None
764
765
766 def create_volume_type(cinder_client, name):
767     try:
768         volume_type = cinder_client.volume_types.create(name)
769         return volume_type
770     except Exception, e:
771         print "Error [create_volume_type(cinder_client, '%s')]:" % name, e
772         return None
773
774
775 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
776                         snapshots_quota, gigabytes_quota):
777     quotas_values = {"volumes": vols_quota,
778                      "snapshots": snapshots_quota,
779                      "gigabytes": gigabytes_quota}
780
781     try:
782         cinder_client.quotas.update(tenant_id, **quotas_values)
783         return True
784     except Exception, e:
785         print ("Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'"
786                "'%s')]:" % (tenant_id, vols_quota,
787                             snapshots_quota, gigabytes_quota)), e
788         return False
789
790
791 def delete_volume(cinder_client, volume_id, forced=False):
792     try:
793         if forced:
794             try:
795                 cinder_client.volumes.detach(volume_id)
796             except:
797                 print "Error:", sys.exc_info()[0]
798             cinder_client.volumes.force_delete(volume_id)
799         else:
800             cinder_client.volumes.delete(volume_id)
801         return True
802     except Exception, e:
803         print ("Error [delete_volume(cinder_client, '%s', '%s')]:" %
804                (volume_id, str(forced))), e
805         return False
806
807
808 def delete_volume_type(cinder_client, volume_type):
809     try:
810         cinder_client.volume_types.delete(volume_type)
811         return True
812     except Exception, e:
813         print ("Error [delete_volume_type(cinder_client, '%s')]:" %
814                volume_type), e
815         return False
816
817
818 # *********************************************
819 #   KEYSTONE
820 # *********************************************
821 def get_tenants(keystone_client):
822     try:
823         tenants = keystone_client.tenants.list()
824         return tenants
825     except Exception, e:
826         print "Error [get_tenants(keystone_client)]:", e
827         return None
828
829
830 def get_users(keystone_client):
831     try:
832         users = keystone_client.users.list()
833         return users
834     except Exception, e:
835         print "Error [get_users(keystone_client)]:", e
836         return None
837
838
839 def get_tenant_id(keystone_client, tenant_name):
840     tenants = keystone_client.tenants.list()
841     id = ''
842     for t in tenants:
843         if t.name == tenant_name:
844             id = t.id
845             break
846     return id
847
848
849 def get_user_id(keystone_client, user_name):
850     users = keystone_client.users.list()
851     id = ''
852     for u in users:
853         if u.name == user_name:
854             id = u.id
855             break
856     return id
857
858
859 def get_role_id(keystone_client, role_name):
860     roles = keystone_client.roles.list()
861     id = ''
862     for r in roles:
863         if r.name == role_name:
864             id = r.id
865             break
866     return id
867
868
869 def create_tenant(keystone_client, tenant_name, tenant_description):
870     try:
871         tenant = keystone_client.tenants.create(tenant_name,
872                                                 tenant_description,
873                                                 enabled=True)
874         return tenant.id
875     except Exception, e:
876         print ("Error [create_tenant(cinder_client, '%s', '%s')]:" %
877                (tenant_name, tenant_description)), e
878         return False
879
880
881 def create_user(keystone_client, user_name, user_password,
882                 user_email, tenant_id):
883     try:
884         user = keystone_client.users.create(user_name, user_password,
885                                             user_email, tenant_id,
886                                             enabled=True)
887         return user.id
888     except Exception, e:
889         print ("Error [create_user(keystone_client, '%s', '%s', '%s'"
890                "'%s')]:" % (user_name, user_password, user_email, tenant_id),
891                e)
892         return False
893
894
895 def add_role_user(keystone_client, user_id, role_id, tenant_id):
896     try:
897         keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
898         return True
899     except Exception, e:
900         print ("Error [add_role_user(keystone_client, '%s', '%s'"
901                "'%s')]:" % (user_id, role_id, tenant_id)), e
902         return False
903
904
905 def delete_tenant(keystone_client, tenant_id):
906     try:
907         keystone_client.tenants.delete(tenant_id)
908         return True
909     except Exception, e:
910         print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
911         return False
912
913
914 def delete_user(keystone_client, user_id):
915     try:
916         keystone_client.users.delete(user_id)
917         return True
918     except Exception, e:
919         print "Error [delete_user(keystone_client, '%s')]:" % user_id, e
920         return False