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