CSIT-755: Presentation and analytics layer
[csit.git] / resources / tools / presentation / environment.py
1 # Copyright (c) 2017 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 """Environment
15
16 Setting of the environment according to the specification specified in the
17 specification YAML file.
18 """
19
20 import os
21 import shutil
22 import logging
23
24 from errors import PresentationError
25
26
27 class Environment(object):
28     """Setting of the environment:
29     - set environment variables,
30     - create directories.
31     """
32
33     def __init__(self, env, force=False):
34         """Initialization.
35
36         :param env: Environment specification.
37         :param force: If True, remove old build(s) if present.
38         :type env: dict
39         :type force: bool
40         """
41
42         self._env = env
43         self._force = force
44
45     @property
46     def environment(self):
47         """Getter.
48
49         :returns: Environment settings.
50         :rtype: dict
51         """
52         return self._env
53
54     def _set_environment_variables(self):
55         """Set environment variables.
56         """
57         logging.info("Setting the environment variables ...")
58         # logging.debug("Environment variables before:\n{}".format(os.environ))
59
60         count = 1
61
62         for var, value in self._env["configuration"].items():
63             logging.debug("  {:3d} Setting the variable {} = {}".
64                           format(count, var, value))
65             os.environ[var] = str(value)
66             count += 1
67
68         for var, value in self._env["paths"].items():
69             logging.debug("  {:3d} Setting the variable {} = {}".
70                           format(count, var, value))
71             os.environ[var] = str(value)
72             count += 1
73
74         for var, value in self._env["urls"].items():
75             logging.debug("  {:3d} Setting the variable {} = {}".
76                           format(count, var, value))
77             os.environ[var] = str(value)
78             count += 1
79
80         # logging.debug("Environment variables after:\n{}".format(os.environ))
81         logging.info("Done.")
82
83     def _make_dirs(self):
84         """Create the directories specified in the 'make-dirs' part of
85         'environment' section in the specification file.
86
87         :raises: PresentationError if it is not possible to remove or create a
88         directory.
89         """
90
91         if self._force:
92             logging.info("Removing old build(s) ...")
93             for directory in self._env["build-dirs"]:
94                 dir_to_remove = self._env["paths"][directory]
95                 if os.path.isdir(dir_to_remove):
96                     try:
97                         shutil.rmtree(dir_to_remove)
98                         logging.info("  Removed: {}".format(dir_to_remove))
99                     except OSError:
100                         raise PresentationError("Cannot remove the directory "
101                                                 "'{}'".format(dir_to_remove))
102             logging.info("Done.")
103
104         logging.info("Making directories ...")
105
106         for directory in self._env["make-dirs"]:
107             dir_to_make = self._env["paths"][directory]
108             try:
109                 if os.path.isdir(dir_to_make):
110                     logging.warning("The directory '{}' exists, skipping.".
111                                     format(dir_to_make))
112                 else:
113                     os.makedirs(dir_to_make)
114                     logging.info("  Created: {}".format(dir_to_make))
115             except OSError:
116                 raise PresentationError("Cannot make the directory '{}'".
117                                         format(dir_to_make))
118
119         logging.info("Done.")
120
121     def set_environment(self):
122         """Set the environment.
123         """
124
125         self._set_environment_variables()
126         self._make_dirs()
127
128
129 def clean_environment(env):
130     """Clean the environment.
131
132     :param env: Environment specification.
133     :type env: dict
134     :raises: PresentationError if it is not possible to remove a directory.
135     """
136
137     logging.info("Cleaning the environment ...")
138
139     if not env["remove-dirs"]:  # None or empty
140         logging.info("  No directories to remove.")
141         return
142
143     for directory in env["remove-dirs"]:
144         dir_to_remove = env["paths"][directory]
145         logging.info("  Removing the working directory {} ...".
146                      format(dir_to_remove))
147         if os.path.isdir(dir_to_remove):
148             try:
149                 shutil.rmtree(dir_to_remove)
150             except OSError:
151                 raise PresentationError("Cannot remove the directory '{}'".
152                                         format(dir_to_remove))
153         else:
154             logging.warning("The directory '{}' does not exist.".
155                             format(dir_to_remove))
156
157     logging.info("Done.")