Merge "Add Robot test for validating Helm charts"
[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 _OPTIONAL_ALSO = False
33
34 def get_volumes(layer):
35     """Create a list with volumes to mount in the container for given layer
36     """
37     mypath = Path(__file__).absolute()
38     volume_yaml = yaml.safe_load(mypath.parents[0].joinpath("volumes.yaml").open())
39
40     if layer not in volume_yaml['layers']:
41         return ''
42     if volume_yaml['layers'][layer] is None:
43         return ''
44
45     volume_list = ''
46     for vol in volume_yaml['layers'][layer]:
47         if volume_yaml['volumes'][vol]['local'] == '':
48             continue
49         volume_list = (volume_list + ' -v ' +
50                        volume_yaml['volumes'][vol]['local'] + ':' +
51                        volume_yaml['volumes'][vol]['target'])
52     return volume_list
53
54
55 def invoke_docker(bluprint, layer):
56     """Start docker container for given layer
57     """
58
59     volume_list = get_volumes('common') + get_volumes(layer)
60     cmd = ("docker run" + volume_list +
61            " akraino/validation:{0}-latest"
62            " /bin/sh -c"
63            " 'cd /opt/akraino/validation "
64            "&& python bluval/bluval.py -l {0} {1} {2}'"
65            .format(layer, ("-o" if _OPTIONAL_ALSO else ""), bluprint))
66
67     args = [cmd]
68     try:
69         print('\nInvoking {}'.format(args))
70         subprocess.call(args, shell=True)
71     except OSError:
72         #print('Error while executing {}'.format(args))
73         raise BluvalError(OSError)
74
75
76 def invoke_dockers(yaml_loc, layer, blueprint_name):
77     """Parses yaml file and starts docker container for one/all layers
78     """
79     with open(str(yaml_loc)) as yaml_file:
80         yamldoc = yaml.safe_load(yaml_file)
81     blueprint = yamldoc['blueprint']
82     if layer is None or layer == "all":
83         for each_layer in blueprint['layers']:
84             invoke_docker(blueprint_name, each_layer)
85     else:
86         invoke_docker(blueprint_name, layer)
87
88
89 @click.command()
90 @click.argument('blueprint')
91 @click.option('--layer', '-l')
92 @click.option('--optional_also', '-o', is_flag=True)
93 def main(blueprint, layer, optional_also):
94     """Takes blueprint name and optional layer. Validates inputs and derives
95     yaml location from blueprint name. Invokes validate on blue print.
96     """
97     global _OPTIONAL_ALSO  # pylint: disable=global-statement
98     mypath = Path(__file__).absolute()
99     yaml_loc = mypath.parents[0].joinpath('bluval-{}.yaml'.format(blueprint))
100     if layer is not None:
101         layer = layer.lower()
102     if optional_also:
103         _OPTIONAL_ALSO = True
104         print("_OPTIONAL_ALSO {}".format(_OPTIONAL_ALSO))
105     try:
106         invoke_dockers(yaml_loc, layer, blueprint)
107     except ShowStopperError as err:
108         print('ShowStopperError:', err)
109     except BluvalError as err:
110         print('Unexpected BluvalError', err)
111         raise
112     except:
113         print("Exception in user code:")
114         print("-"*60)
115         traceback.print_exc(file=sys.stdout)
116         print("-"*60)
117         raise
118
119
120 if __name__ == "__main__":
121     # pylint: disable=no-value-for-parameter
122     main()