Customize the volume list per layer
[validation.git] / bluval / blucon.py
1 #!/usr/bin/python3
2 ##############################################################################
3 # Copyright (c) 2019 AT&T Intellectual Property.                             #
4 # Copyright (c) 2019 Nokia.                                                  #
5 #                                                                            #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may    #
7 # not use this file except in compliance with the License.                   #
8 #                                                                            #
9 # You may obtain a copy of the License at                                    #
10 #       http://www.apache.org/licenses/LICENSE-2.0                           #
11 #                                                                            #
12 # Unless required by applicable law or agreed to in writing, software        #
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT  #
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.           #
15 # See the License for the specific language governing permissions and        #
16 # limitations under the License.                                             #
17 ##############################################################################
18 """This module parses yaml file, reads layers runs container for each layer.
19 """
20
21 import subprocess
22 import sys
23 import traceback
24 from pathlib import Path
25
26 import click
27 import yaml
28
29 from bluutil import BluvalError
30 from bluutil import ShowStopperError
31
32 def get_volumes(layer):
33     """Create a list with volumes to mount in the container for given layer
34     """
35     mypath = Path(__file__).absolute()
36     volume_yaml = yaml.safe_load(mypath.parents[0].joinpath("volumes.yaml").open())
37
38     if layer not in volume_yaml['layers']:
39         return ''
40     if volume_yaml['layers'][layer] is None:
41         return ''
42
43     volume_list = ''
44     for vol in volume_yaml['layers'][layer]:
45         if volume_yaml['volumes'][vol]['local'] == '':
46             continue
47         volume_list = (volume_list + ' -v ' +
48                        volume_yaml['volumes'][vol]['local'] + ':' +
49                        volume_yaml['volumes'][vol]['target'])
50     return volume_list
51
52
53 def invoke_docker(bluprint, layer):
54     """Start docker container for given layer
55     """
56
57     volume_list = get_volumes('common') + get_volumes(layer)
58     cmd = ("docker run" + volume_list +
59            " akraino/validation:{0}-latest"
60            " /bin/sh -c"
61            " 'cd /opt/akraino/validation "
62            "&& python bluval/bluval.py -l {0} {1}'").format(layer, bluprint)
63
64     args = [cmd]
65     try:
66         print('\nInvoking {}'.format(args))
67         subprocess.call(args, shell=True)
68     except OSError:
69         #print('Error while executing {}'.format(args))
70         raise BluvalError(OSError)
71
72
73 def invoke_dockers(yaml_loc, layer, blueprint_name):
74     """Parses yaml file and starts docker container for one/all layers
75     """
76     with open(str(yaml_loc)) as yaml_file:
77         yamldoc = yaml.safe_load(yaml_file)
78     blueprint = yamldoc['blueprint']
79     if layer is None or layer == "all":
80         for each_layer in blueprint['layers']:
81             invoke_docker(blueprint_name, each_layer)
82     else:
83         invoke_docker(blueprint_name, layer)
84
85
86 @click.command()
87 @click.argument('blueprint')
88 @click.option('--layer', '-l')
89 def main(blueprint, layer):
90     """Takes blueprint name and optional layer. Validates inputs and derives
91     yaml location from blueprint name. Invokes validate on blue print.
92     """
93     mypath = Path(__file__).absolute()
94     yaml_loc = mypath.parents[0].joinpath('bluval-{}.yaml'.format(blueprint))
95     if layer is not None:
96         layer = layer.lower()
97     try:
98         invoke_dockers(yaml_loc, layer, blueprint)
99     except ShowStopperError as err:
100         print('ShowStopperError:', err)
101     except BluvalError as err:
102         print('Unexpected BluvalError', err)
103         raise
104     except:
105         print("Exception in user code:")
106         print("-"*60)
107         traceback.print_exc(file=sys.stdout)
108         print("-"*60)
109         raise
110
111
112 if __name__ == "__main__":
113     # pylint: disable=no-value-for-parameter
114     main()