-
Notifications
You must be signed in to change notification settings - Fork 656
/
scenario.py
270 lines (220 loc) · 7.96 KB
/
scenario.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import shutil
import os
import fnmatch
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path
from molecule import logger
from molecule import scenarios
from molecule import util
LOG = logger.get_logger(__name__)
class Scenario(object):
"""
A scenario allows Molecule test a role in a particular way, this is a
fundamental change from Molecule v1.
A scenario is a self-contained directory containing everything necessary
for testing the role in a particular way. The default scenario is named
``default``, and every role should contain a default scenario.
Unless mentioned explicitly, the scenario name will be the directory name
hosting the files.
Any option set in this section will override the defaults.
.. code-block:: yaml
scenario:
name: default # optional
create_sequence:
- dependency
- create
- prepare
check_sequence:
- dependency
- cleanup
- destroy
- create
- prepare
- converge
- check
- destroy
converge_sequence:
- dependency
- create
- prepare
- converge
destroy_sequence:
- dependency
- cleanup
- destroy
test_sequence:
- dependency
- lint
- cleanup
- destroy
- syntax
- create
- prepare
- converge
- idempotence
- side_effect
- verify
- cleanup
- destroy
""" # noqa
def __init__(self, config):
"""
Initialize a new scenario class and returns None.
:param config: An instance of a Molecule config.
:return: None
"""
self.config = config
self._setup()
def _remove_scenario_state_directory(self):
"""Remove scenario cached disk stored state.
:return: None
"""
directory = str(Path(self.ephemeral_directory).parent)
LOG.info('Removing {}'.format(directory))
shutil.rmtree(directory)
def prune(self):
"""
Prune the scenario ephemeral directory files and returns None.
"safe files" will not be pruned, including the ansible configuration
and inventory used by this scenario, the scenario state file, and
files declared as "safe_files" in the ``driver`` configuration
declared in ``molecule.yml``.
:return: None
"""
LOG.info('Pruning extra files from scenario ephemeral directory')
safe_files = [
self.config.provisioner.config_file,
self.config.provisioner.inventory_file,
self.config.state.state_file,
] + self.config.driver.safe_files
files = util.os_walk(self.ephemeral_directory, '*')
for f in files:
if not any(sf for sf in safe_files if fnmatch.fnmatch(f, sf)):
os.remove(f)
# Remove empty directories.
for dirpath, dirs, files in os.walk(self.ephemeral_directory, topdown=False):
if not dirs and not files:
os.removedirs(dirpath)
@property
def name(self):
return self.config.config['scenario']['name']
@property
def directory(self):
if self.config.molecule_file:
return os.path.dirname(self.config.molecule_file)
else:
return os.getcwd()
@property
def ephemeral_directory(self):
_ephemeral_directory = os.getenv('MOLECULE_EPHEMERAL_DIRECTORY')
if _ephemeral_directory:
return _ephemeral_directory
project_directory = os.path.basename(self.config.project_directory)
if self.config.is_parallel:
project_directory = '{}-{}'.format(project_directory, self.config._run_uuid)
project_scenario_directory = os.path.join(
self.config.cache_directory, project_directory, self.name
)
path = ephemeral_directory(project_scenario_directory)
return ephemeral_directory(path)
@property
def inventory_directory(self):
return os.path.join(self.ephemeral_directory, "inventory")
@property
def check_sequence(self):
return self.config.config['scenario']['check_sequence']
@property
def cleanup_sequence(self):
return self.config.config['scenario']['cleanup_sequence']
@property
def converge_sequence(self):
return self.config.config['scenario']['converge_sequence']
@property
def create_sequence(self):
return self.config.config['scenario']['create_sequence']
@property
def dependency_sequence(self):
return ['dependency']
@property
def destroy_sequence(self):
return self.config.config['scenario']['destroy_sequence']
@property
def idempotence_sequence(self):
return ['idempotence']
@property
def lint_sequence(self):
# see https://github.com/ansible/molecule/issues/2216
return ['dependency', 'lint']
@property
def prepare_sequence(self):
return ['prepare']
@property
def side_effect_sequence(self):
return ['side_effect']
@property
def syntax_sequence(self):
return ['syntax']
@property
def test_sequence(self):
return self.config.config['scenario']['test_sequence']
@property
def verify_sequence(self):
return ['verify']
@property
def sequence(self):
"""
Select the sequence based on scenario and subcommand of the provided
scenario object and returns a list.
:param scenario: A scenario object.
:param skipped: An optional bool to include skipped scenarios.
:return: list
"""
s = scenarios.Scenarios([self.config])
matrix = s._get_matrix()
try:
return matrix[self.name][self.config.subcommand]
except KeyError:
# TODO(retr0h): May change this handling in the future.
return []
def _setup(self):
"""
Prepare the scenario for Molecule and returns None.
:return: None
"""
if not os.path.isdir(self.inventory_directory):
os.makedirs(self.inventory_directory)
def ephemeral_directory(path=None):
"""
Returns temporary directory to be used by molecule. Molecule users should
not make any assumptions about its location, permissions or its content as
this may change in future release.
"""
d = os.getenv('MOLECULE_EPHEMERAL_DIRECTORY')
if not d:
d = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
d = os.path.abspath(os.path.join(d, path if path else 'molecule'))
if not os.path.isdir(d):
os.umask(0o077)
Path(d).mkdir(mode=0o700, parents=True, exist_ok=True)
return d