cleanup task.
[joid.git] / ci / genDeploymentConfig.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5 This script generates a deployment config based on lab config file.
6
7 Parameters:
8  -l, --lab      : lab config file
9 """
10
11 from optparse import OptionParser
12 from jinja2 import Environment, FileSystemLoader
13 from distutils.version import LooseVersion, StrictVersion
14 import os
15 import yaml
16 import subprocess
17 import socket
18 import fcntl
19 import struct
20
21 #
22 # Parse parameters
23 #
24
25 parser = OptionParser()
26 parser.add_option("-l", "--lab", dest="lab", help="lab config file")
27 (options, args) = parser.parse_args()
28 labconfig_file = options.lab
29
30 #
31 # Set Path and configs path
32 #
33
34 # Capture our current directory
35 jujuver = subprocess.check_output(["juju", "--version"])
36
37 if LooseVersion(jujuver) >= LooseVersion('2'):
38     TPL_DIR = os.path.dirname(os.path.abspath(__file__))+'/config_tpl/juju2'
39 else:
40     TPL_DIR = os.path.dirname(os.path.abspath(__file__))+'/config_tpl'
41
42 HOME = os.environ['HOME']
43 USER = os.environ['USER']
44
45 #
46 # Prepare variables
47 #
48
49 # Prepare a storage for passwords
50 passwords_store = dict()
51
52 #
53 # Local Functions
54 #
55
56
57 def load_yaml(filepath):
58     """Load YAML file"""
59     with open(filepath, 'r') as stream:
60         try:
61             return yaml.load(stream)
62         except yaml.YAMLError as exc:
63             print(exc)
64
65
66 def get_ip_address(ifname):
67     """Get local IP"""
68     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
69     return socket.inet_ntoa(fcntl.ioctl(
70         s.fileno(),
71         0x8915,  # SIOCGIFADDR
72         struct.pack('256s', bytes(ifname.encode('utf-8')[:15]))
73     )[20:24])
74
75
76 #
77 # Config import
78 #
79
80 #
81 # Config import
82 #
83
84 # Load scenario Config
85 config = load_yaml(labconfig_file)
86
87 # Set a dict copy of opnfv/spaces
88 config['opnfv']['spaces_dict'] = dict()
89 for space in config['opnfv']['spaces']:
90     config['opnfv']['spaces_dict'][space['type']] = space
91
92 # Set a dict copy of opnfv/storage
93 config['opnfv']['storage_dict'] = dict()
94 for storage in config['opnfv']['storage']:
95     config['opnfv']['storage_dict'][storage['type']] = storage
96
97 # Add some OS environment variables
98 config['os'] = {'home': HOME,
99                 'user': USER,
100                 'brAdmIP': get_ip_address(config['opnfv']['spaces_dict']
101                                                 ['admin']['bridge'])}
102
103 # Prepare interface-enable, more easy to do it here
104 ifnamelist = set()
105 for node in config['lab']['racks'][0]['nodes']:
106     for nic in node['nics']:
107         if 'admin' not in nic['spaces']:
108             ifnamelist.add(nic['ifname'])
109 config['lab']['racks'][0]['ifnamelist'] = ','.join(ifnamelist)
110
111 #
112 # Transform template to deployconfig.yaml according to config
113 #
114
115 # Create the jinja2 environment.
116 env = Environment(loader=FileSystemLoader(TPL_DIR),
117                   trim_blocks=True)
118 template = env.get_template('deployconfig.yaml')
119
120 # Render the template
121 output = template.render(**config)
122
123 # Check output syntax
124 try:
125     yaml.load(output)
126 except yaml.YAMLError as exc:
127     print(exc)
128
129 # print output
130 print(output)