Add example script creating an instance
[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="functest-vm",
195                     confdrive=True,
196                     userdata=None):
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     if userdata is None:
206         instance = nova_client.servers.create(
207             name=instance_name,
208             flavor=flavor,
209             image=image_id,
210             nics=[{"net-id": network_id}]
211         )
212     else:
213         instance = nova_client.servers.create(
214             name=instance_name,
215             flavor=flavor,
216             image=image_id,
217             nics=[{"net-id": network_id}],
218             config_drive=confdrive,
219             userdata=userdata
220         )
221     return instance
222
223
224 def create_instance_and_wait_for_active(flavor_name,
225                                         image_id,
226                                         network_id,
227                                         instance_name="",
228                                         config_drive=False,
229                                         userdata=""):
230     SLEEP = 3
231     VM_BOOT_TIMEOUT = 180
232     nova_client = get_nova_client()
233     instance = create_instance(flavor_name,
234                                image_id,
235                                network_id,
236                                instance_name,
237                                config_drive,
238                                userdata)
239
240     count = VM_BOOT_TIMEOUT / SLEEP
241     for n in range(count, -1, -1):
242         status = get_instance_status(nova_client, instance)
243         if status.lower() == "active":
244             return instance
245         elif status.lower() == "error":
246             print("The instance %s went to ERROR status." % instance_name)
247             return None
248         time.sleep(SLEEP)
249     print("Timeout booting the instance %s." % instance_name)
250     return None
251
252
253 def create_floating_ip(neutron_client):
254     extnet_id = get_external_net_id(neutron_client)
255     props = {'floating_network_id': extnet_id}
256     try:
257         ip_json = neutron_client.create_floatingip({'floatingip': props})
258         fip_addr = ip_json['floatingip']['floating_ip_address']
259         fip_id = ip_json['floatingip']['id']
260     except Exception, e:
261         print "Error [create_floating_ip(neutron_client)]:", e
262         return None
263     return {'fip_addr': fip_addr, 'fip_id': fip_id}
264
265
266 def add_floating_ip(nova_client, server_id, floatingip_id):
267     try:
268         nova_client.servers.add_floating_ip(server_id, floatingip_id)
269         return True
270     except Exception, e:
271         print ("Error [add_floating_ip(nova_client, '%s', '%s')]:" %
272                (server_id, floatingip_id)), e
273         return False
274
275
276 def delete_instance(nova_client, instance_id):
277     try:
278         nova_client.servers.force_delete(instance_id)
279         return True
280     except Exception, e:
281         print "Error [delete_instance(nova_client, '%s')]:" % instance_id, e
282         return False
283
284
285 def delete_floating_ip(nova_client, floatingip_id):
286     try:
287         nova_client.floating_ips.delete(floatingip_id)
288         return True
289     except Exception, e:
290         print ("Error [delete_floating_ip(nova_client, '%s')]:" %
291                floatingip_id), e
292         return False
293
294
295 # *********************************************
296 #   NEUTRON
297 # *********************************************
298 def get_network_list(neutron_client):
299     network_list = neutron_client.list_networks()['networks']
300     if len(network_list) == 0:
301         return None
302     else:
303         return network_list
304
305
306 def get_router_list(neutron_client):
307     router_list = neutron_client.list_routers()['routers']
308     if len(router_list) == 0:
309         return None
310     else:
311         return router_list
312
313
314 def get_port_list(neutron_client):
315     port_list = neutron_client.list_ports()['ports']
316     if len(port_list) == 0:
317         return None
318     else:
319         return port_list
320
321
322 def get_network_id(neutron_client, network_name):
323     networks = neutron_client.list_networks()['networks']
324     id = ''
325     for n in networks:
326         if n['name'] == network_name:
327             id = n['id']
328             break
329     return id
330
331
332 def get_subnet_id(neutron_client, subnet_name):
333     subnets = neutron_client.list_subnets()['subnets']
334     id = ''
335     for s in subnets:
336         if s['name'] == subnet_name:
337             id = s['id']
338             break
339     return id
340
341
342 def get_router_id(neutron_client, router_name):
343     routers = neutron_client.list_routers()['routers']
344     id = ''
345     for r in routers:
346         if r['name'] == router_name:
347             id = r['id']
348             break
349     return id
350
351
352 def get_private_net(neutron_client):
353     # Checks if there is an existing shared private network
354     networks = neutron_client.list_networks()['networks']
355     if len(networks) == 0:
356         return None
357     for net in networks:
358         if (net['router:external'] is False) and (net['shared'] is True):
359             return net
360     return None
361
362
363 def get_external_net(neutron_client):
364     for network in neutron_client.list_networks()['networks']:
365         if network['router:external']:
366             return network['name']
367     return False
368
369
370 def get_external_net_id(neutron_client):
371     for network in neutron_client.list_networks()['networks']:
372         if network['router:external']:
373             return network['id']
374     return False
375
376
377 def check_neutron_net(neutron_client, net_name):
378     for network in neutron_client.list_networks()['networks']:
379         if network['name'] == net_name:
380             for subnet in network['subnets']:
381                 return True
382     return False
383
384
385 def create_neutron_net(neutron_client, name):
386     json_body = {'network': {'name': name,
387                              'admin_state_up': True}}
388     try:
389         network = neutron_client.create_network(body=json_body)
390         network_dict = network['network']
391         return network_dict['id']
392     except Exception, e:
393         print "Error [create_neutron_net(neutron_client, '%s')]:" % name, e
394         return False
395
396
397 def create_neutron_subnet(neutron_client, name, cidr, net_id):
398     json_body = {'subnets': [{'name': name, 'cidr': cidr,
399                               'ip_version': 4, 'network_id': net_id}]}
400     try:
401         subnet = neutron_client.create_subnet(body=json_body)
402         return subnet['subnets'][0]['id']
403     except Exception, e:
404         print ("Error [create_neutron_subnet(neutron_client, '%s', '%s', "
405                "'%s')]:" % (name, cidr, net_id)), e
406         return False
407
408
409 def create_neutron_router(neutron_client, name):
410     json_body = {'router': {'name': name, 'admin_state_up': True}}
411     try:
412         router = neutron_client.create_router(json_body)
413         return router['router']['id']
414     except Exception, e:
415         print "Error [create_neutron_router(neutron_client, '%s')]:" % name, e
416         return False
417
418
419 def create_neutron_port(neutron_client, name, network_id, ip):
420     json_body = {'port': {
421                  'admin_state_up': True,
422                  'name': name,
423                  'network_id': network_id,
424                  'fixed_ips': [{"ip_address": ip}]
425                  }}
426     try:
427         port = neutron_client.create_port(body=json_body)
428         return port['port']['id']
429     except Exception, e:
430         print ("Error [create_neutron_port(neutron_client, '%s', '%s', "
431                "'%s')]:" % (name, network_id, ip)), e
432         return False
433
434
435 def update_neutron_net(neutron_client, network_id, shared=False):
436     json_body = {'network': {'shared': shared}}
437     try:
438         neutron_client.update_network(network_id, body=json_body)
439         return True
440     except Exception, e:
441         print ("Error [update_neutron_net(neutron_client, '%s', '%s')]:" %
442                (network_id, str(shared))), e
443         return False
444
445
446 def update_neutron_port(neutron_client, port_id, device_owner):
447     json_body = {'port': {
448                  'device_owner': device_owner,
449                  }}
450     try:
451         port = neutron_client.update_port(port=port_id,
452                                           body=json_body)
453         return port['port']['id']
454     except Exception, e:
455         print ("Error [update_neutron_port(neutron_client, '%s', '%s')]:" %
456                (port_id, device_owner)), e
457         return False
458
459
460 def add_interface_router(neutron_client, router_id, subnet_id):
461     json_body = {"subnet_id": subnet_id}
462     try:
463         neutron_client.add_interface_router(router=router_id, body=json_body)
464         return True
465     except Exception, e:
466         print ("Error [add_interface_router(neutron_client, '%s', '%s')]:" %
467                (router_id, subnet_id)), e
468         return False
469
470
471 def add_gateway_router(neutron_client, router_id):
472     ext_net_id = get_external_net_id(neutron_client)
473     router_dict = {'network_id': ext_net_id}
474     try:
475         neutron_client.add_gateway_router(router_id, router_dict)
476         return True
477     except Exception, e:
478         print ("Error [add_gateway_router(neutron_client, '%s')]:" %
479                router_id), e
480         return False
481
482
483 def delete_neutron_net(neutron_client, network_id):
484     try:
485         neutron_client.delete_network(network_id)
486         return True
487     except Exception, e:
488         print ("Error [delete_neutron_net(neutron_client, '%s')]:" %
489                network_id), e
490         return False
491
492
493 def delete_neutron_subnet(neutron_client, subnet_id):
494     try:
495         neutron_client.delete_subnet(subnet_id)
496         return True
497     except Exception, e:
498         print ("Error [delete_neutron_subnet(neutron_client, '%s')]:" %
499                subnet_id), e
500         return False
501
502
503 def delete_neutron_router(neutron_client, router_id):
504     try:
505         neutron_client.delete_router(router=router_id)
506         return True
507     except Exception, e:
508         print ("Error [delete_neutron_router(neutron_client, '%s')]:" %
509                router_id), e
510         return False
511
512
513 def delete_neutron_port(neutron_client, port_id):
514     try:
515         neutron_client.delete_port(port_id)
516         return True
517     except Exception, e:
518         print "Error [delete_neutron_port(neutron_client, '%s')]:" % port_id, e
519         return False
520
521
522 def remove_interface_router(neutron_client, router_id, subnet_id):
523     json_body = {"subnet_id": subnet_id}
524     try:
525         neutron_client.remove_interface_router(router=router_id,
526                                                body=json_body)
527         return True
528     except Exception, e:
529         print ("Error [remove_interface_router(neutron_client, '%s', '%s')]:" %
530                (router_id, subnet_id)), e
531         return False
532
533
534 def remove_gateway_router(neutron_client, router_id):
535     try:
536         neutron_client.remove_gateway_router(router_id)
537         return True
538     except Exception, e:
539         print ("Error [remove_gateway_router(neutron_client, '%s')]:" %
540                router_id), e
541         return False
542
543
544 def create_network_full(logger,
545                         neutron_client,
546                         net_name,
547                         subnet_name,
548                         router_name,
549                         cidr):
550
551     # Check if the network already exists
552     network_id = get_network_id(neutron_client, net_name)
553     subnet_id = get_subnet_id(neutron_client, subnet_name)
554     router_id = get_router_id(neutron_client, router_name)
555
556     if network_id != '' and subnet_id != '' and router_id != '':
557         logger.info("A network with name '%s' already exists..." % net_name)
558     else:
559         neutron_client.format = 'json'
560         logger.info('Creating neutron network %s...' % net_name)
561         network_id = create_neutron_net(neutron_client, net_name)
562
563         if not network_id:
564             return False
565
566         logger.debug("Network '%s' created successfully" % network_id)
567         logger.debug('Creating Subnet....')
568         subnet_id = create_neutron_subnet(neutron_client, subnet_name,
569                                           cidr, network_id)
570         if not subnet_id:
571             return False
572
573         logger.debug("Subnet '%s' created successfully" % subnet_id)
574         logger.debug('Creating Router...')
575         router_id = create_neutron_router(neutron_client, router_name)
576
577         if not router_id:
578             return False
579
580         logger.debug("Router '%s' created successfully" % router_id)
581         logger.debug('Adding router to subnet...')
582
583         if not add_interface_router(neutron_client, router_id, subnet_id):
584             return False
585
586         logger.debug("Interface added successfully.")
587
588         logger.debug('Adding gateway to router...')
589         if not add_gateway_router(neutron_client, router_id):
590             return False
591
592         logger.debug("Gateway added successfully.")
593
594     network_dic = {'net_id': network_id,
595                    'subnet_id': subnet_id,
596                    'router_id': router_id}
597     return network_dic
598
599
600 # *********************************************
601 #   SEC GROUPS
602 # *********************************************
603 def get_security_groups(neutron_client):
604     try:
605         security_groups = neutron_client.list_security_groups()[
606             'security_groups']
607         return security_groups
608     except Exception, e:
609         print "Error [get_security_groups(neutron_client)]:", e
610         return None
611
612
613 def get_security_group_id(neutron_client, sg_name):
614     security_groups = get_security_groups(neutron_client)
615     id = ''
616     for sg in security_groups:
617         if sg['name'] == sg_name:
618             id = sg['id']
619             break
620     return id
621
622
623 def create_security_group(neutron_client, sg_name, sg_description):
624     json_body = {'security_group': {'name': sg_name,
625                                     'description': sg_description}}
626     try:
627         secgroup = neutron_client.create_security_group(json_body)
628         return secgroup['security_group']
629     except Exception, e:
630         print ("Error [create_security_group(neutron_client, '%s', '%s')]:" %
631                (sg_name, sg_description)), e
632         return False
633
634
635 def create_secgroup_rule(neutron_client, sg_id, direction, protocol,
636                          port_range_min=None, port_range_max=None):
637     if port_range_min is None and port_range_max is None:
638         json_body = {'security_group_rule': {'direction': direction,
639                                              'security_group_id': sg_id,
640                                              'protocol': protocol}}
641     elif port_range_min is not None and port_range_max is not None:
642         json_body = {'security_group_rule': {'direction': direction,
643                                              'security_group_id': sg_id,
644                                              'port_range_min': port_range_min,
645                                              'port_range_max': port_range_max,
646                                              'protocol': protocol}}
647     else:
648         print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
649                "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
650                                               port_range_min, port_range_max,
651                                               protocol),
652                " Invalid values for port_range_min, port_range_max")
653         return False
654     try:
655         neutron_client.create_security_group_rule(json_body)
656         return True
657     except Exception, e:
658         print ("Error [create_secgroup_rule(neutron_client, '%s', '%s', "
659                "'%s', '%s', '%s', '%s')]:" % (neutron_client, sg_id, direction,
660                                               port_range_min, port_range_max,
661                                               protocol)), e
662         return False
663
664
665 def create_security_group_full(logger, neutron_client,
666                                sg_name, sg_description):
667     sg_id = get_security_group_id(neutron_client, sg_name)
668     if sg_id != '':
669         logger.info("Using existing security group '%s'..." % sg_name)
670     else:
671         logger.info("Creating security group  '%s'..." % sg_name)
672         SECGROUP = create_security_group(neutron_client,
673                                          sg_name,
674                                          sg_description)
675         if not SECGROUP:
676             logger.error("Failed to create the security group...")
677             return False
678
679         sg_id = SECGROUP['id']
680
681         logger.debug("Security group '%s' with ID=%s created successfully."
682                      % (SECGROUP['name'], sg_id))
683
684         logger.debug("Adding ICMP rules in security group '%s'..."
685                      % sg_name)
686         if not create_secgroup_rule(neutron_client, sg_id,
687                                     'ingress', 'icmp'):
688             logger.error("Failed to create the security group rule...")
689             return False
690
691         logger.debug("Adding SSH rules in security group '%s'..."
692                      % sg_name)
693         if not create_secgroup_rule(
694                 neutron_client, sg_id, 'ingress', 'tcp', '22', '22'):
695             logger.error("Failed to create the security group rule...")
696             return False
697
698         if not create_secgroup_rule(
699                 neutron_client, sg_id, 'egress', 'tcp', '22', '22'):
700             logger.error("Failed to create the security group rule...")
701             return False
702     return sg_id
703
704
705 def add_secgroup_to_instance(nova_client, instance_id, secgroup_id):
706     try:
707         nova_client.servers.add_security_group(instance_id, secgroup_id)
708         return True
709     except Exception, e:
710         print ("Error [add_secgroup_to_instance(nova_client, '%s', '%s')]: " %
711                (instance_id, secgroup_id)), e
712         return False
713
714
715 def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota):
716     json_body = {"quota": {
717         "security_group": sg_quota,
718         "security_group_rule": sg_rule_quota
719     }}
720
721     try:
722         neutron_client.update_quota(tenant_id=tenant_id,
723                                     body=json_body)
724         return True
725     except Exception, e:
726         print ("Error [update_sg_quota(neutron_client, '%s', '%s', "
727                "'%s')]:" % (tenant_id, sg_quota, sg_rule_quota)), e
728         return False
729
730
731 def delete_security_group(neutron_client, secgroup_id):
732     try:
733         neutron_client.delete_security_group(secgroup_id)
734         return True
735     except Exception, e:
736         print ("Error [delete_security_group(neutron_client, '%s')]:" %
737                secgroup_id), e
738         return False
739
740
741 # *********************************************
742 #   GLANCE
743 # *********************************************
744 def get_images(nova_client):
745     try:
746         images = nova_client.images.list()
747         return images
748     except Exception, e:
749         print "Error [get_images]:", e
750         return None
751
752
753 def get_image_id(glance_client, image_name):
754     images = glance_client.images.list()
755     id = ''
756     for i in images:
757         if i.name == image_name:
758             id = i.id
759             break
760     return id
761
762
763 def create_glance_image(glance_client, image_name, file_path, disk="qcow2",
764                         container="bare", public=True, logger=None):
765     if not os.path.isfile(file_path):
766         print "Error: file " + file_path + " does not exist."
767         return False
768     try:
769         image_id = get_image_id(glance_client, image_name)
770         if image_id != '':
771             if logger:
772                 logger.info("Image %s already exists." % image_name)
773         else:
774             if logger:
775                 logger.info("Creating image '%s' from '%s'..." % (image_name,
776                                                                   file_path))
777             with open(file_path) as fimage:
778                 image = glance_client.images.create(name=image_name,
779                                                     is_public=public,
780                                                     disk_format=disk,
781                                                     container_format=container,
782                                                     data=fimage)
783             image_id = image.id
784         return image_id
785     except Exception, e:
786         print ("Error [create_glance_image(glance_client, '%s', '%s', "
787                "'%s')]:" % (image_name, file_path, str(public))), e
788         return False
789
790
791 def delete_glance_image(nova_client, image_id):
792     try:
793         nova_client.images.delete(image_id)
794         return True
795     except Exception, e:
796         print ("Error [delete_glance_image(nova_client, '%s')]:" % image_id), e
797         return False
798
799
800 # *********************************************
801 #   CINDER
802 # *********************************************
803 def get_volumes(cinder_client):
804     try:
805         volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1})
806         return volumes
807     except Exception, e:
808         print "Error [get_volumes(cinder_client)]:", e
809         return None
810
811
812 def list_volume_types(cinder_client, public=True, private=True):
813     try:
814         volume_types = cinder_client.volume_types.list()
815         if not public:
816             volume_types = [vt for vt in volume_types if not vt.is_public]
817         if not private:
818             volume_types = [vt for vt in volume_types if vt.is_public]
819         return volume_types
820     except Exception, e:
821         print "Error [list_volume_types(cinder_client)]:", e
822         return None
823
824
825 def create_volume_type(cinder_client, name):
826     try:
827         volume_type = cinder_client.volume_types.create(name)
828         return volume_type
829     except Exception, e:
830         print "Error [create_volume_type(cinder_client, '%s')]:" % name, e
831         return None
832
833
834 def update_cinder_quota(cinder_client, tenant_id, vols_quota,
835                         snapshots_quota, gigabytes_quota):
836     quotas_values = {"volumes": vols_quota,
837                      "snapshots": snapshots_quota,
838                      "gigabytes": gigabytes_quota}
839
840     try:
841         cinder_client.quotas.update(tenant_id, **quotas_values)
842         return True
843     except Exception, e:
844         print ("Error [update_cinder_quota(cinder_client, '%s', '%s', '%s'"
845                "'%s')]:" % (tenant_id, vols_quota,
846                             snapshots_quota, gigabytes_quota)), e
847         return False
848
849
850 def delete_volume(cinder_client, volume_id, forced=False):
851     try:
852         if forced:
853             try:
854                 cinder_client.volumes.detach(volume_id)
855             except:
856                 print "Error:", sys.exc_info()[0]
857             cinder_client.volumes.force_delete(volume_id)
858         else:
859             cinder_client.volumes.delete(volume_id)
860         return True
861     except Exception, e:
862         print ("Error [delete_volume(cinder_client, '%s', '%s')]:" %
863                (volume_id, str(forced))), e
864         return False
865
866
867 def delete_volume_type(cinder_client, volume_type):
868     try:
869         cinder_client.volume_types.delete(volume_type)
870         return True
871     except Exception, e:
872         print ("Error [delete_volume_type(cinder_client, '%s')]:" %
873                volume_type), e
874         return False
875
876
877 # *********************************************
878 #   KEYSTONE
879 # *********************************************
880 def get_tenants(keystone_client):
881     try:
882         tenants = keystone_client.tenants.list()
883         return tenants
884     except Exception, e:
885         print "Error [get_tenants(keystone_client)]:", e
886         return None
887
888
889 def get_users(keystone_client):
890     try:
891         users = keystone_client.users.list()
892         return users
893     except Exception, e:
894         print "Error [get_users(keystone_client)]:", e
895         return None
896
897
898 def get_tenant_id(keystone_client, tenant_name):
899     tenants = keystone_client.tenants.list()
900     id = ''
901     for t in tenants:
902         if t.name == tenant_name:
903             id = t.id
904             break
905     return id
906
907
908 def get_user_id(keystone_client, user_name):
909     users = keystone_client.users.list()
910     id = ''
911     for u in users:
912         if u.name == user_name:
913             id = u.id
914             break
915     return id
916
917
918 def get_role_id(keystone_client, role_name):
919     roles = keystone_client.roles.list()
920     id = ''
921     for r in roles:
922         if r.name == role_name:
923             id = r.id
924             break
925     return id
926
927
928 def create_tenant(keystone_client, tenant_name, tenant_description):
929     try:
930         tenant = keystone_client.tenants.create(tenant_name,
931                                                 tenant_description,
932                                                 enabled=True)
933         return tenant.id
934     except Exception, e:
935         print ("Error [create_tenant(cinder_client, '%s', '%s')]:" %
936                (tenant_name, tenant_description)), e
937         return False
938
939
940 def create_user(keystone_client, user_name, user_password,
941                 user_email, tenant_id):
942     try:
943         user = keystone_client.users.create(user_name, user_password,
944                                             user_email, tenant_id,
945                                             enabled=True)
946         return user.id
947     except Exception, e:
948         print ("Error [create_user(keystone_client, '%s', '%s', '%s'"
949                "'%s')]:" % (user_name, user_password, user_email, tenant_id),
950                e)
951         return False
952
953
954 def add_role_user(keystone_client, user_id, role_id, tenant_id):
955     try:
956         keystone_client.roles.add_user_role(user_id, role_id, tenant_id)
957         return True
958     except Exception, e:
959         print ("Error [add_role_user(keystone_client, '%s', '%s'"
960                "'%s')]:" % (user_id, role_id, tenant_id)), e
961         return False
962
963
964 def delete_tenant(keystone_client, tenant_id):
965     try:
966         keystone_client.tenants.delete(tenant_id)
967         return True
968     except Exception, e:
969         print "Error [delete_tenant(keystone_client, '%s')]:" % tenant_id, e
970         return False
971
972
973 def delete_user(keystone_client, user_id):
974     try:
975         keystone_client.users.delete(user_id)
976         return True
977     except Exception, e:
978         print "Error [delete_user(keystone_client, '%s')]:" % user_id, e
979         return False