Move tools.sh to ci/common dir
[joid.git] / ci / genPublicAPIProxyBundle.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5 This script generates a bundle config for the haproxy managing public apis
6
7 Parameters:
8  -l, --lab      : lab config file
9 """
10
11 from jinja2 import Environment, FileSystemLoader
12 from keystoneauth1.identity import v2
13 from keystoneauth1 import session
14 from keystoneclient.v2_0 import client
15 from optparse import OptionParser
16
17 import os
18 import yaml
19
20 #
21 # Parse parameters
22 #
23
24 parser = OptionParser()
25 parser.add_option("-l", "--lab", dest="lab", help="lab config file")
26 (options, args) = parser.parse_args()
27 labconfig_file = options.lab
28
29 #
30 # Set Path and configs path
31 #
32
33 # Capture our current directory
34 TPL_DIR = os.path.dirname(os.path.abspath(__file__))+'/config_tpl'
35
36 #
37 # Local Functions
38 #
39
40
41 def load_yaml(filepath):
42     """Load YAML file"""
43     with open(filepath, 'r') as stream:
44         try:
45             return yaml.load(stream)
46         except yaml.YAMLError as exc:
47             print(exc)
48
49 #
50 # Config import
51 #
52
53 # Load scenario Config
54 config = load_yaml(labconfig_file)
55
56 # Add public api ip to config
57 if 'public_api_ip' in config['lab']['racks'][0]:
58     config['public_api_ip'] = config['lab']['racks'][0]['public_api_ip']
59 else:
60     first_public_ip = config['lab']['racks'][0][
61                         'floating-ip-range'].split(',')[0]
62     # managing ipv6 and ipv4 format
63     sep = ':' if ':' in first_public_ip else '.'
64     api_ip = first_public_ip.split(sep)
65     api_ip[-1] = str(int(api_ip[-1])-1)
66     config['public_api_ip'] = sep.join(api_ip)
67
68 # get endpoint list from keystone
69 username = os.environ['OS_USERNAME']
70 password = os.environ['OS_PASSWORD']
71 tenant_name = os.environ['OS_TENANT_NAME']
72 auth_url = os.environ['OS_AUTH_URL']
73 auth = v2.Password(username=username,
74                    password=password,
75                    tenant_name=tenant_name,
76                    auth_url=auth_url)
77 sess = session.Session(auth=auth)
78 keystone = client.Client(session=sess)
79 services = keystone.services.list()
80 endpoints = keystone.endpoints.list()
81 srv = dict()
82 for service in services:
83     if service.name != 'cinderv2':
84         srv[service.id] = {'name': service.name}
85 for endpoint in endpoints:
86     if endpoint.service_id in srv.keys():
87         internal = endpoint.internalurl.split('/')[2].split(':')
88         srv[endpoint.service_id]['ip'] = ':'.join(internal[:-1])
89         srv[endpoint.service_id]['port'] = internal[-1]
90 config['public_api_services'] = srv
91
92 #
93 # Transform template to deployconfig.yaml according to config
94 #
95
96 # Create the jinja2 environment.
97 env = Environment(loader=FileSystemLoader(TPL_DIR),
98                   trim_blocks=True)
99 template = env.get_template('public-api-proxy.yaml')
100
101 # Render the template
102 output = template.render(**config)
103
104 # Check output syntax
105 try:
106     yaml.load(output)
107 except yaml.YAMLError as exc:
108     print(exc)
109
110 # print output
111 print(output)