PAL improvement: Log repr() of PresentationError
[csit.git] / resources / tools / presentation / pal.py
1 # Copyright (c) 2018 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """CSIT Presentation and analytics layer.
15 """
16
17 import sys
18 import argparse
19 import logging
20
21 from errors import PresentationError
22 from environment import Environment, clean_environment
23 from specification_parser import Specification
24 from input_data_parser import InputData
25 from generator_tables import generate_tables
26 from generator_plots import generate_plots
27 from generator_files import generate_files
28 from static_content import prepare_static_content
29 from generator_report import generate_report
30 from generator_CPTA import generate_cpta
31
32
33 def parse_args():
34     """Parse arguments from cmd line.
35
36     :returns: Parsed arguments.
37     :rtype: ArgumentParser
38     """
39
40     parser = argparse.ArgumentParser(description=__doc__,
41                                      formatter_class=argparse.
42                                      RawDescriptionHelpFormatter)
43     parser.add_argument("-s", "--specification",
44                         required=True,
45                         type=argparse.FileType('r'),
46                         help="Specification YAML file.")
47     parser.add_argument("-r", "--release",
48                         default="master",
49                         type=str,
50                         help="Release string of the product.")
51     parser.add_argument("-v", "--version",
52                         default="0.1",
53                         type=str,
54                         help="Version of the product.")
55     parser.add_argument("-l", "--logging",
56                         choices=["DEBUG", "INFO", "WARNING",
57                                  "ERROR", "CRITICAL"],
58                         default="ERROR",
59                         help="Logging level.")
60     parser.add_argument("-f", "--force",
61                         action='store_true',
62                         help="Force removing the old build(s) if present.")
63
64     return parser.parse_args()
65
66
67 def main():
68     """Main function."""
69
70     log_levels = {"NOTSET": logging.NOTSET,
71                   "DEBUG": logging.DEBUG,
72                   "INFO": logging.INFO,
73                   "WARNING": logging.WARNING,
74                   "ERROR": logging.ERROR,
75                   "CRITICAL": logging.CRITICAL}
76
77     args = parse_args()
78     logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s',
79                         datefmt='%Y/%m/%d %H:%M:%S',
80                         level=log_levels[args.logging])
81
82     logging.info("Application started.")
83     try:
84         spec = Specification(args.specification)
85         spec.read_specification()
86     except PresentationError:
87         logging.critical("Finished with error.")
88         return 1
89
90     if spec.output["output"] not in ("report", "CPTA"):
91         logging.critical("The output '{0}' is not supported.".
92                          format(spec.output["output"]))
93         return 1
94
95     ret_code = 1
96     try:
97         env = Environment(spec.environment, args.force)
98         env.set_environment()
99
100         prepare_static_content(spec)
101
102         data = InputData(spec)
103         data.download_and_parse_data(repeat=2)
104
105         generate_tables(spec, data)
106         generate_plots(spec, data)
107         generate_files(spec, data)
108
109         if spec.output["output"] == "report":
110             generate_report(args.release, spec, args.version)
111             logging.info("Successfully finished.")
112         elif spec.output["output"] == "CPTA":
113             sys.stdout.write(generate_cpta(spec, data))
114             logging.info("Successfully finished.")
115         ret_code = 0
116
117     except (KeyError, ValueError, PresentationError) as err:
118         logging.info("Finished with an error.")
119         logging.critical(repr(err))
120     except Exception as err:
121         logging.info("Finished with an unexpected error.")
122         logging.critical(repr(err))
123     finally:
124         if spec is not None:
125             clean_environment(spec.environment)
126         return ret_code
127
128
129 if __name__ == '__main__':
130     sys.exit(main())