blob: 51b6520a748bff09654f9efefe624f299c9e2aca [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 = {}
105# for node in self.k8s_nodes:
106 for node in self.master_nodes + self.slave_nodes:
107 lvm = filter(lambda x: x.volume.name == 'lvm', node.disk_devices)
108 if len(lvm) == 0:
109 continue
110 lvm = lvm[0]
111 result[node.name] = {}
112 result_node = result[node.name]
113 result_node['id'] = "{bus}-{serial}".format(
114 bus=lvm.bus,
115 serial=lvm.volume.serial[:20])
116 LOG.info("Got disk-id '{}' for node '{}'".format(
117 result_node['id'], node.name))
118 return result
119
120 @property
121 def _d_env_name(self):
122 """Get environment name from fuel devops config
123
124 :rtype: string
125 """
126 return self._devops_config['env_name']
127
128 def _get_env_by_name(self, name):
129 """Set existing environment by name
130
131 :param name: string
132 """
133 self._env = models.Environment.get(name=name)
134
135 def _get_default_node_group(self):
136 return self._env.get_group(name='default')
137
138 def _get_network_pool(self, net_pool_name):
139 default_node_group = self._get_default_node_group()
140 network_pool = default_node_group.get_network_pool(name=net_pool_name)
141 return network_pool
142
143 def get_ssh_data(self, roles=None):
144 """Generate ssh config for Underlay
145
146 :param roles: list of strings
147 """
148 if roles is None:
149 raise Exception("No roles specified for the environment!")
150
151 config_ssh = []
152 for d_node in self._env.get_nodes(role__in=roles):
153 ssh_data = {
154 'node_name': d_node.name,
155 'address_pool': self._get_network_pool(
156 ext.NETWORK_TYPE.public).address_pool.name,
157 'host': self.node_ip(d_node),
158 'login': settings.SSH_NODE_CREDENTIALS['login'],
159 'password': settings.SSH_NODE_CREDENTIALS['password'],
160 }
161 config_ssh.append(ssh_data)
162 return config_ssh
163
164 def create_snapshot(self, name, description=None):
165 """Create named snapshot of current env.
166
167 - Create a libvirt snapshots for all nodes in the environment
168 - Save 'config' object to a file 'config_<name>.ini'
169
170 :name: string
171 """
172 LOG.info("Creating snapshot named '{0}'".format(name))
173 self.__config.hardware.current_snapshot = name
174 LOG.info("current config '{0}'".format(
175 self.__config.hardware.current_snapshot))
176 if self._env is not None:
177 LOG.info('trying to suspend ....')
178 self._env.suspend()
179 LOG.info('trying to snapshot ....')
180 self._env.snapshot(name, description=description, force=True)
181 LOG.info('trying to resume ....')
182 self._env.resume()
183 else:
184 raise exceptions.EnvironmentIsNotSet()
185 settings_oslo.save_config(self.__config, name, self._env.name)
186
187 def _get_snapshot_config_name(self, snapshot_name):
188 """Get config name for the environment"""
189 env_name = self._env.name
190 if env_name is None:
191 env_name = 'config'
192 test_config_path = os.path.join(
193 settings.LOGS_DIR, '{0}_{1}.ini'.format(env_name, snapshot_name))
194 return test_config_path
195
196 def revert_snapshot(self, name):
197 """Revert snapshot by name
198
199 - Revert a libvirt snapshots for all nodes in the environment
200 - Try to reload 'config' object from a file 'config_<name>.ini'
201 If the file not found, then pass with defaults.
202 - Set <name> as the current state of the environment after reload
203
204 :param name: string
205 """
206 LOG.info("Reverting from snapshot named '{0}'".format(name))
207 if self._env is not None:
208 self._env.revert(name=name)
209 LOG.info("Resuming environment after revert")
210 self._env.resume()
211 else:
212 raise exceptions.EnvironmentIsNotSet()
213
214 try:
215 test_config_path = self._get_snapshot_config_name(name)
216 settings_oslo.reload_snapshot_config(self.__config,
217 test_config_path)
218 except cfg.ConfigFilesNotFoundError as conf_err:
219 LOG.error("Config file(s) {0} not found!".format(
220 conf_err.config_files))
221
222 self.__config.hardware.current_snapshot = name
223
224 def _create_environment(self):
225 """Create environment and start VMs.
226
227 If config was provided earlier, we simply create and start VMs,
228 otherwise we tries to generate config from self.config_file,
229 """
230 if self._devops_config.config is None:
231 raise exceptions.DevopsConfigPathIsNotSet()
232 settings = self._devops_config
233 env_name = settings['env_name']
234 LOG.debug(
235 'Preparing to create environment named "{0}"'.format(env_name)
236 )
237 if env_name is None:
238 LOG.error('Environment name is not set!')
239 raise exceptions.EnvironmentNameIsNotSet()
240 try:
241 self._env = models.Environment.create_environment(
242 settings.config
243 )
244 except db.IntegrityError:
245 LOG.error(
246 'Seems like environment {0} already exists.'.format(env_name)
247 )
248 raise exceptions.EnvironmentAlreadyExists(env_name)
249 self._env.define()
250 LOG.info(
251 'Environment "{0}" created and started'.format(env_name)
252 )
253
254 def start(self):
255 """Method for start environment
256
257 """
258 if self._env is None:
259 raise exceptions.EnvironmentIsNotSet()
260 self._env.start()
261# for node in self.k8s_nodes:
262 for node in self.master_nodes + self.slave_nodes:
263 LOG.debug("Waiting for SSH on node '{}...'".format(node.name))
264 timeout = 360
265 helpers.wait(
266 lambda: helpers.tcp_ping(self.node_ip(node), 22),
267 timeout=timeout,
268 timeout_msg="Node '{}' didn't open SSH in {} sec".format(
269 node.name, timeout
270 )
271 )
272
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(
321 node_role=ext.UNDERLAY_NODE_ROLE.salt-master)
322 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(
331 node_role=ext.UNDERLAY_NODE_ROLE.salt-minion)
332 return nodes
333
334# @staticmethod
335# def node_ip(node):
336# """Determine node's IP
337#
338# :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# )
345
346# @property
347# def admin_ips(self):
348# """Property to get ip of admin role VMs
349#
350# :return: list
351# """
352# nodes = self.master_nodes
353# return [self.node_ip(node) for node in nodes]
354
355# @property
356# def slave_ips(self):
357# """Property to get ip(s) of slave role VMs
358#
359# :return: list
360# """
361# nodes = self.slave_nodes
362# return [self.node_ip(node) for node in nodes]
363
364 @property
365 def nameserver(self):
366 return self._env.router(ext.NETWORK_TYPE.public)
367
368 def set_dns_config(self):
369 # Set local nameserver to use by default
370 if not self.__config.underlay.nameservers:
371 self.__config.underlay.nameservers = [self.nameserver]
372 if not self.__config.underlay.upstream_dns_servers:
373 self.__config.underlay.upstream_dns_servers = [self.nameserver]