blob: b5d5f04b9e570a654cbb2a6503ac00be8d15e9f8 [file] [log] [blame]
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +02001# 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
Dmitry Tyzhnenkob8641832017-11-07 17:02:47 +020015import netaddr
16
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030017from collections import defaultdict
18
19from datetime import datetime
Dennis Dmitrievb8115f52017-12-15 13:09:56 +020020from pepper import libpepper
21from tcp_tests.helpers import utils
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030022from tcp_tests import logger
Dmitry Tyzhnenko35413c02018-03-05 14:12:37 +020023from tcp_tests import settings
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030024from tcp_tests.managers.execute_commands import ExecuteCommandsMixin
25
26LOG = logger.logger
27
28
29class SaltManager(ExecuteCommandsMixin):
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +020030 """docstring for SaltManager"""
31
Dmitry Tyzhnenkobc0f8262017-04-28 15:39:26 +030032 __config = None
33 __underlay = None
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030034 _map = {
35 'enforceState': 'enforce_state',
36 'enforceStates': 'enforce_states',
37 'runState': 'run_state',
38 'runStates': 'run_states',
39 }
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +020040
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020041 def __init__(self, config, underlay, host=None, port='6969',
42 username=None, password=None):
Dmitry Tyzhnenkobc0f8262017-04-28 15:39:26 +030043 self.__config = config
44 self.__underlay = underlay
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030045 self.__port = port
46 self.__host = host
47 self.__api = None
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020048 self.__user = username or settings.SALT_USER
49 self.__password = password or settings.SALT_PASSWORD
Dennis Dmitrieveac3aab2017-07-12 16:36:41 +030050 self._salt = self
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +020051
Dmitry Tyzhnenkobc0f8262017-04-28 15:39:26 +030052 super(SaltManager, self).__init__(config=config, underlay=underlay)
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +020053
54 def install(self, commands):
Dina Belovae6fdffb2017-09-19 13:58:34 -070055 # if self.__config.salt.salt_master_host == '0.0.0.0':
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030056 # # Temporary workaround. Underlay should be extended with roles
57 # salt_nodes = self.__underlay.node_names()
58 # self.__config.salt.salt_master_host = \
59 # self.__underlay.host_by_node_name(salt_nodes[0])
Dennis Dmitriev010f4cd2016-11-01 20:43:51 +020060
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030061 self.execute_commands(commands=commands,
62 label="Install and configure salt")
63
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020064 def change_creds(self, username, password):
65 self.__user = username
66 self.__password = password
67
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030068 @property
69 def port(self):
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030070 return self.__port
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030071
72 @property
73 def host(self):
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030074 if self.__host:
75 return self.__host
76 else:
Dina Belovae6fdffb2017-09-19 13:58:34 -070077 # TODO(ddmitriev): consider to add a check and raise
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030078 # exception if 'salt_master_host' is not initialized.
79 return self.__config.salt.salt_master_host
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030080
81 @property
82 def api(self):
83 def login():
84 LOG.info("Authentication in Salt API")
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030085 self.__api.login(
86 username=self.__user,
87 password=self.__password,
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030088 eauth='pam')
89 return datetime.now()
90
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030091 if self.__api:
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030092 if (datetime.now() - self.__session_start).seconds < 5 * 60:
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030093 return self.__api
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030094 else:
95 # FIXXME: Change to debug
96 LOG.info("Session's expired")
97 self.__session_start = login()
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +030098 return self.__api
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +030099
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300100 url = "http://{host}:{port}".format(
101 host=self.host, port=self.port)
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +0300102 LOG.info("Connecting to Salt API {0}".format(url))
Dennis Dmitrievb8115f52017-12-15 13:09:56 +0200103 self.__api = libpepper.Pepper(url)
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300104 self.__session_start = login()
Dennis Dmitriev2d60c8e2017-05-12 18:34:01 +0300105 return self.__api
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300106
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000107 def local(self, tgt, fun, args=None, kwargs=None):
108 return self.api.local(tgt, fun, args, kwargs, expr_form='compound')
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300109
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000110 def local_async(self, tgt, fun, args=None, kwargs=None):
111 return self.api.local_async(tgt, fun, args, kwargs)
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300112
113 def lookup_result(self, jid):
114 return self.api.lookup_jid(jid)
115
116 def check_result(self, r):
117 if len(r.get('return', [])) == 0:
118 raise LookupError("Result is empty or absent")
119
120 result = r['return'][0]
Dmitry Tyzhnenkobc0f8262017-04-28 15:39:26 +0300121 if len(result) == 0:
122 raise LookupError("Result is empty or absent")
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300123 LOG.info("Job has result for %s nodes", result.keys())
124 fails = defaultdict(list)
125 for h in result:
126 host_result = result[h]
127 LOG.info("On %s executed:", h)
128 if isinstance(host_result, list):
129 fails[h].append(host_result)
130 continue
131 for t in host_result:
132 task = host_result[t]
133 if task['result'] is False:
134 fails[h].append(task)
135 LOG.error("%s - %s", t, task['result'])
136 else:
137 LOG.info("%s - %s", t, task['result'])
138
139 return fails if fails else None
140
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000141 def enforce_state(self, tgt, state, args=None, kwargs=None):
142 r = self.local(tgt=tgt, fun='state.sls', args=state)
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300143 f = self.check_result(r)
144 return r, f
145
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000146 def enforce_states(self, tgt, state, args=None, kwargs=None):
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300147 rets = []
148 for s in state:
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000149 r = self.enforce_state(tgt=tgt, state=s)
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300150 rets.append(r)
151 return rets
152
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000153 def run_state(self, tgt, state, args=None, kwargs=None):
154 return self.local(tgt=tgt, fun=state, args=args, kwargs=kwargs), None
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300155
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000156 def run_states(self, tgt, state, args=None, kwargs=None):
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300157 rets = []
158 for s in state:
Dennis Dmitriev6d52a452018-09-26 11:06:32 +0000159 r = self.run_state(tgt=tgt, state=s, args=args, kwargs=kwargs)
Dmitry Tyzhnenko2b730a02017-04-07 19:31:32 +0300160 rets.append(r)
161 return rets
Artem Panchenko0594cd72017-06-12 13:25:26 +0300162
163 def get_pillar(self, tgt, pillar):
164 result = self.local(tgt=tgt, fun='pillar.get', args=pillar)
165 return result['return']
Dmitry Tyzhnenkob8641832017-11-07 17:02:47 +0200166
Dennis Dmitriev2d643bc2017-12-04 12:23:47 +0200167 def get_grains(self, tgt, grains):
168 result = self.local(tgt=tgt, fun='grains.get', args=grains)
169 return result['return']
170
Dmitry Tyzhnenkob8641832017-11-07 17:02:47 +0200171 def get_ssh_data(self):
172 """Generate ssh config for Underlay
173
174 :param roles: list of strings
175 """
176
177 pool_name = self.__config.underlay.net_mgmt
178 pool_net = netaddr.IPNetwork(self.__config.underlay.address_pools[
179 self.__config.underlay.net_mgmt])
180 hosts = self.local('*', 'grains.item', ['host', 'ipv4'])
181
182 if len(hosts.get('return', [])) == 0:
183 raise LookupError("Hosts is empty or absent")
184 hosts = hosts['return'][0]
185 if len(hosts) == 0:
186 raise LookupError("Hosts is empty or absent")
187
188 def host(node_name, ip):
189 return {
190 'roles': ['salt_minion'],
191 'keys': [
192 k['private'] for k in self.__config.underlay.ssh_keys
193 ],
194 'node_name': node_name,
195 'host': ip,
196 'address_pool': pool_name,
197 'login': settings.SSH_NODE_CREDENTIALS['login'],
198 'password': settings.SSH_NODE_CREDENTIALS['password']
199 }
200
Dmitry Tyzhnenkob610afd2018-02-19 15:43:45 +0200201 try:
202 ret = [
203 host(k, next(i for i in v['ipv4'] if i in pool_net))
204 for k, v in hosts.items()
205 if next(i for i in v['ipv4'] if i in pool_net)]
206 LOG.debug("Fetched ssh data from salt grains - {}".format(ret))
207 return ret
208 except StopIteration:
209 msg = ("Can't match nodes ip address with network cidr\n"
210 "Managment network - {net}\n"
211 "Host with address - {host_list}".format(
212 net=pool_net,
213 host_list={k: v['ipv4'] for k, v in hosts.items()}))
214 raise StopIteration(msg)
Dennis Dmitriev2d643bc2017-12-04 12:23:47 +0200215
216 def service_status(self, tgt, service):
217 result = self.local(tgt=tgt, fun='service.status', args=service)
218 return result['return']
219
220 def service_restart(self, tgt, service):
221 result = self.local(tgt=tgt, fun='service.restart', args=service)
222 return result['return']
223
224 def service_stop(self, tgt, service):
225 result = self.local(tgt=tgt, fun='service.stop', args=service)
226 return result['return']
Dennis Dmitrievb8115f52017-12-15 13:09:56 +0200227
228 @utils.retry(3, exception=libpepper.PepperException)
229 def sync_time(self, tgt='*'):
230 LOG.info("NTP time sync on the salt minions '{0}'".format(tgt))
231 # Force authentication update on the next API access
232 # because previous authentication most probably is not valid
233 # before or after time sync.
234 self.__api = None
235 self.run_state(
236 tgt,
Dmitry Tyzhnenko35413c02018-03-05 14:12:37 +0200237 'cmd.run', 'service ntp stop; if [ -x /usr/sbin/ntpdate ]; then ntpdate -s ntp.ubuntu.com; else ntpd -gq ; fi; service ntp start') # noqa
Dennis Dmitrievb8115f52017-12-15 13:09:56 +0200238 new_time_res = self.run_state(tgt, 'cmd.run', 'date')
239 for node_name, time in sorted(new_time_res[0]['return'][0].items()):
240 LOG.info("{0}: {1}".format(node_name, time))
241 self.__api = None