Add a new parameter to blucon script
[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 _SUBNET = ""
34
35 def get_volumes(layer):
36     """Create a list with volumes to mount in the container for given layer
37     """
38     mypath = Path(__file__).absolute()
39     volume_yaml = yaml.safe_load(mypath.parents[0].joinpath("volumes.yaml").open())
40
41     if layer not in volume_yaml['layers']:
42         return ''
43     if volume_yaml['layers'][layer] is None:
44         return ''
45
46     volume_list = ''
47     for vol in volume_yaml['layers'][layer]:
48         if volume_yaml['volumes'][vol]['local'] == '':
49             continue
50         volume_list = (volume_list + ' -v ' +
51                        volume_yaml['volumes'][vol]['local'] + ':' +
52                        volume_yaml['volumes'][vol]['target'])
53     return volume_list
54
55
56 def invoke_docker(bluprint, layer):
57     """Start docker container for given layer
58     """
59     volume_list = get_volumes('common') + get_volumes(layer)
60     cmd = ("docker run" + volume_list + _SUBNET +
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('--network', '-n')
93 @click.option('--optional_also', '-o', is_flag=True)
94 def main(blueprint, layer, network, optional_also):
95     """Takes blueprint name and optional layer. Validates inputs and derives
96     yaml location from blueprint name. Invokes validate on blue print.
97     """
98     global _OPTIONAL_ALSO  # pylint: disable=global-statement
99     global _SUBNET # pylint: disable=global-statement
100     mypath = Path(__file__).absolute()
101     yaml_loc = mypath.parents[0].joinpath('bluval-{}.yaml'.format(blueprint))
102     if layer is not None:
103         layer = layer.lower()
104     if optional_also:
105         _OPTIONAL_ALSO = True
106         print("_OPTIONAL_ALSO {}".format(_OPTIONAL_ALSO))
107     if network is not None:
108         _SUBNET = " --net=" + network
109         print("Using", _SUBNET)
110     try:
111         invoke_dockers(yaml_loc, layer, blueprint)
112     except ShowStopperError as err:
113         print('ShowStopperError:', err)
114     except BluvalError as err:
115         print('Unexpected BluvalError', err)
116         raise
117     except:
118         print("Exception in user code:")
119         print("-"*60)
120         traceback.print_exc(file=sys.stdout)
121         print("-"*60)
122         raise
123
124
125 if __name__ == "__main__":
126     # pylint: disable=no-value-for-parameter
127     main()