blob: 9461c7187d1facea1f82a4c9e5c7b2abe2d0a48c [file] [log] [blame]
Dennis Dmitriev6f59add2016-10-18 13:45:27 +03001# Copyright 2016 Mirantis, Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may
4# not use this file except in compliance with the License. You may obtain
5# a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations
13# under the License.
14
15import os
16
17from devops import error
18from devops.helpers import helpers
19from devops import models
20from django import db
21from oslo_config import cfg
22
23from tcp_tests import settings
24from tcp_tests import settings_oslo
25from tcp_tests.helpers import env_config
26from tcp_tests.helpers import ext
27from tcp_tests.helpers import exceptions
28from tcp_tests import logger
29
30LOG = logger.logger
31
32
33class EnvironmentManager(object):
34 """Class-helper for creating VMs via devops environments"""
35
36 __config = None
37
38 def __init__(self, config=None):
39 """Initializing class instance and create the environment
40
41 :param config: oslo.config object
42 :param config.hardware.conf_path: path to devops YAML template
43 :param config.hardware.current_snapshot: name of the snapshot that
44 descriebe environment status.
45 """
46 self.__devops_config = env_config.EnvironmentConfig()
47 self._env = None
48 self.__config = config
49
50 if config.hardware.conf_path is not None:
51 self._devops_config.load_template(config.hardware.conf_path)
52 else:
53 raise Exception("Devops YAML template is not set in config object")
54
55 try:
56 self._get_env_by_name(self._d_env_name)
57 if not self.has_snapshot(config.hardware.current_snapshot):
58 raise exceptions.EnvironmentSnapshotMissing(
59 self._d_env_name, config.hardware.current_snapshot)
60 except error.DevopsObjNotFound:
61 LOG.info("Environment doesn't exist, creating a new one")
62 self._create_environment()
63 self.set_dns_config()
64
65 @property
66 def _devops_config(self):
67 return self.__devops_config
68
69 @_devops_config.setter
70 def _devops_config(self, conf):
71 """Setter for self.__devops_config
72
73 :param conf: tcp_tests.helpers.env_config.EnvironmentConfig
74 """
75 if not isinstance(conf, env_config.EnvironmentConfig):
76 msg = ("Unexpected type of devops config. Got '{0}' " +
77 "instead of '{1}'")
78 raise TypeError(
79 msg.format(
80 type(conf).__name__,
81 env_config.EnvironmentConfig.__name__
82 )
83 )
84 self.__devops_config = conf
85
86 def lvm_storages(self):
87 """Returns a dict object of lvm storages in current environment
88
89 returned data example:
90 {
91 "master": {
92 "id": "virtio-bff72959d1a54cb19d08"
93 },
94 "slave-0": {
95 "id": "virtio-5e33affc8fe44503839f"
96 },
97 "slave-1": {
98 "id": "virtio-10b6a262f1ec4341a1ba"
99 },
100 }
101
102 :rtype: dict
103 """
104 result = {}
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300105 for node in self._env.get_nodes(role__in=ext.UNDERLAY_NODE_ROLES):
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300106 lvm = filter(lambda x: x.volume.name == 'lvm', node.disk_devices)
107 if len(lvm) == 0:
108 continue
109 lvm = lvm[0]
110 result[node.name] = {}
111 result_node = result[node.name]
112 result_node['id'] = "{bus}-{serial}".format(
113 bus=lvm.bus,
114 serial=lvm.volume.serial[:20])
115 LOG.info("Got disk-id '{}' for node '{}'".format(
116 result_node['id'], node.name))
117 return result
118
119 @property
120 def _d_env_name(self):
121 """Get environment name from fuel devops config
122
123 :rtype: string
124 """
125 return self._devops_config['env_name']
126
127 def _get_env_by_name(self, name):
128 """Set existing environment by name
129
130 :param name: string
131 """
132 self._env = models.Environment.get(name=name)
133
134 def _get_default_node_group(self):
135 return self._env.get_group(name='default')
136
137 def _get_network_pool(self, net_pool_name):
138 default_node_group = self._get_default_node_group()
139 network_pool = default_node_group.get_network_pool(name=net_pool_name)
140 return network_pool
141
142 def get_ssh_data(self, roles=None):
143 """Generate ssh config for Underlay
144
145 :param roles: list of strings
146 """
147 if roles is None:
148 raise Exception("No roles specified for the environment!")
149
150 config_ssh = []
151 for d_node in self._env.get_nodes(role__in=roles):
152 ssh_data = {
153 'node_name': d_node.name,
154 'address_pool': self._get_network_pool(
155 ext.NETWORK_TYPE.public).address_pool.name,
156 'host': self.node_ip(d_node),
157 'login': settings.SSH_NODE_CREDENTIALS['login'],
158 'password': settings.SSH_NODE_CREDENTIALS['password'],
159 }
160 config_ssh.append(ssh_data)
161 return config_ssh
162
163 def create_snapshot(self, name, description=None):
164 """Create named snapshot of current env.
165
166 - Create a libvirt snapshots for all nodes in the environment
167 - Save 'config' object to a file 'config_<name>.ini'
168
169 :name: string
170 """
171 LOG.info("Creating snapshot named '{0}'".format(name))
172 self.__config.hardware.current_snapshot = name
173 LOG.info("current config '{0}'".format(
174 self.__config.hardware.current_snapshot))
175 if self._env is not None:
176 LOG.info('trying to suspend ....')
177 self._env.suspend()
178 LOG.info('trying to snapshot ....')
179 self._env.snapshot(name, description=description, force=True)
180 LOG.info('trying to resume ....')
181 self._env.resume()
182 else:
183 raise exceptions.EnvironmentIsNotSet()
184 settings_oslo.save_config(self.__config, name, self._env.name)
185
186 def _get_snapshot_config_name(self, snapshot_name):
187 """Get config name for the environment"""
188 env_name = self._env.name
189 if env_name is None:
190 env_name = 'config'
191 test_config_path = os.path.join(
192 settings.LOGS_DIR, '{0}_{1}.ini'.format(env_name, snapshot_name))
193 return test_config_path
194
195 def revert_snapshot(self, name):
196 """Revert snapshot by name
197
198 - Revert a libvirt snapshots for all nodes in the environment
199 - Try to reload 'config' object from a file 'config_<name>.ini'
200 If the file not found, then pass with defaults.
201 - Set <name> as the current state of the environment after reload
202
203 :param name: string
204 """
205 LOG.info("Reverting from snapshot named '{0}'".format(name))
206 if self._env is not None:
207 self._env.revert(name=name)
208 LOG.info("Resuming environment after revert")
209 self._env.resume()
210 else:
211 raise exceptions.EnvironmentIsNotSet()
212
213 try:
214 test_config_path = self._get_snapshot_config_name(name)
215 settings_oslo.reload_snapshot_config(self.__config,
216 test_config_path)
217 except cfg.ConfigFilesNotFoundError as conf_err:
218 LOG.error("Config file(s) {0} not found!".format(
219 conf_err.config_files))
220
221 self.__config.hardware.current_snapshot = name
222
223 def _create_environment(self):
224 """Create environment and start VMs.
225
226 If config was provided earlier, we simply create and start VMs,
227 otherwise we tries to generate config from self.config_file,
228 """
229 if self._devops_config.config is None:
230 raise exceptions.DevopsConfigPathIsNotSet()
231 settings = self._devops_config
232 env_name = settings['env_name']
233 LOG.debug(
234 'Preparing to create environment named "{0}"'.format(env_name)
235 )
236 if env_name is None:
237 LOG.error('Environment name is not set!')
238 raise exceptions.EnvironmentNameIsNotSet()
239 try:
240 self._env = models.Environment.create_environment(
241 settings.config
242 )
243 except db.IntegrityError:
244 LOG.error(
245 'Seems like environment {0} already exists.'.format(env_name)
246 )
247 raise exceptions.EnvironmentAlreadyExists(env_name)
248 self._env.define()
249 LOG.info(
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300250 'Environment "{0}" created'.format(env_name)
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300251 )
252
253 def start(self):
254 """Method for start environment
255
256 """
257 if self._env is None:
258 raise exceptions.EnvironmentIsNotSet()
259 self._env.start()
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300260 LOG.info('Environment "{0}" started'.format(self._env.name))
261 for node in self._env.get_nodes(role__in=ext.UNDERLAY_NODE_ROLES):
262 LOG.info("Waiting for SSH on node '{}...'".format(node.name))
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300263 timeout = 360
264 helpers.wait(
265 lambda: helpers.tcp_ping(self.node_ip(node), 22),
266 timeout=timeout,
267 timeout_msg="Node '{}' didn't open SSH in {} sec".format(
268 node.name, timeout
269 )
270 )
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300271 LOG.info('Environment "{0}" ready'.format(self._env.name))
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300272
273 def resume(self):
274 """Resume environment"""
275 if self._env is None:
276 raise exceptions.EnvironmentIsNotSet()
277 self._env.resume()
278
279 def suspend(self):
280 """Suspend environment"""
281 if self._env is None:
282 raise exceptions.EnvironmentIsNotSet()
283 self._env.suspend()
284
285 def stop(self):
286 """Stop environment"""
287 if self._env is None:
288 raise exceptions.EnvironmentIsNotSet()
289 self._env.destroy()
290
291 def has_snapshot(self, name):
292 return self._env.has_snapshot(name)
293
294 def has_snapshot_config(self, name):
295 test_config_path = self._get_snapshot_config_name(name)
296 return os.path.isfile(test_config_path)
297
298 def delete_environment(self):
299 """Delete environment
300
301 """
302 LOG.debug("Deleting environment")
303 self._env.erase()
304
305 def __get_nodes_by_role(self, node_role):
306 """Get node by given role name
307
308 :param node_role: string
309 :rtype: devops.models.Node
310 """
311 LOG.debug('Trying to get nodes by role {0}'.format(node_role))
312 return self._env.get_nodes(role=node_role)
313
314 @property
315 def master_nodes(self):
316 """Get all master nodes
317
318 :rtype: list
319 """
320 nodes = self.__get_nodes_by_role(
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300321 node_role=ext.UNDERLAY_NODE_ROLES.salt_master)
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300322 return nodes
323
324 @property
325 def slave_nodes(self):
326 """Get all slave nodes
327
328 :rtype: list
329 """
330 nodes = self.__get_nodes_by_role(
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300331 node_role=ext.UNDERLAY_NODE_ROLES.salt_minion)
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300332 return nodes
333
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300334 @staticmethod
335 def node_ip(node):
336 """Determine node's IP
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300337
Dennis Dmitriev53d3b772016-10-18 14:31:58 +0300338 :param node: devops.models.Node
339 :return: string
340 """
341 LOG.debug('Trying to determine {0} ip.'.format(node.name))
342 return node.get_ip_address_by_network_name(
343 ext.NETWORK_TYPE.public
344 )
Dennis Dmitriev6f59add2016-10-18 13:45:27 +0300345
346 @property
347 def nameserver(self):
348 return self._env.router(ext.NETWORK_TYPE.public)
349
350 def set_dns_config(self):
351 # Set local nameserver to use by default
352 if not self.__config.underlay.nameservers:
353 self.__config.underlay.nameservers = [self.nameserver]
354 if not self.__config.underlay.upstream_dns_servers:
355 self.__config.underlay.upstream_dns_servers = [self.nameserver]