Debian Codegraph @

tests/unit/test_host_select.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Test the cylc.flow.host_select module.
18
19 NOTE: these are functional tests, for unit tests see the docstrings in
20 the host_select module.
21
22 """
23 import logging
24 from secrets import token_hex
25 import socket
26
27 import pytest
28
29 from cylc.flow import CYLC_LOG
30 from cylc.flow.exceptions import HostSelectException
31 from cylc.flow.host_select import (
32 _get_metrics,
33 select_host,
34 select_workflow_host,
35 )
36 from cylc.flow.hostuserutil import get_fqdn_by_host
37 from cylc.flow.parsec.exceptions import ListValueError
38
39
40 localhost, localhost_aliases, _ = socket.gethostbyname_ex('localhost')
41 localhost_fqdn = get_fqdn_by_host(localhost)
42
43
44 # NOTE: ensure that all localhost aliases are actually aliases of localhost,
45 # it would appear that this is not always the case
46 # on Travis-CI on of the aliases has a different fqdn from the fqdn
47 # of the host it is an alias of
48 localhost_aliases = [
49 alias
50 for alias in localhost_aliases
51 if get_fqdn_by_host(alias) == localhost_fqdn
52 ]
53
54
55 def test_localhost():
56 """Basic test with one host to choose from."""
57 assert select_host([localhost]) == (
58 localhost,
59 localhost_fqdn
60 )
61
62
63 def test_unique():
64 """Basic test choosing from multiple forms of localhost"""
65 name, fqdn = select_host(
66 localhost_aliases + [localhost]
67 )
68 assert name in localhost_aliases + [localhost]
69 assert fqdn == localhost_fqdn
70
71
72 def test_filter():
73 """Test that hosts are filtered out if specified."""
74 message = 'Localhost not allowed'
75 with pytest.raises(HostSelectException) as excinfo:
76 select_host(
77 [localhost],
78 blacklist=[localhost],
79 blacklist_name=message
80 )
81 assert message in str(excinfo.value)
82
83
84 def test_filter_invalid_blacklist(log_filter):
85 """Test that invalid blacklist doesn't bring down the program."""
86 result = select_host(
87 [localhost], blacklist=[f'non_exist_{token_hex(4)}']
88 )
89 assert result[0] == localhost
90 assert log_filter(logging.WARNING, "Could not resolve blacklisted host")
91
92
93 def test_rankings():
94 """Positive test that rankings are evaluated.
95
96 (doesn't prove anything by itself hence test_unreasonable_rankings)
97 """
98 assert select_host(
99 [localhost],
100 ranking_string='''
101 # if this test fails due to race conditions
102 # then you have bigger issues than a test failure
103 virtual_memory().available > 1
104 getloadavg()[0] < 500
105 cpu_count() > 1
106 disk_usage('/').free > 1
107 '''
108 ) == (localhost, localhost_fqdn)
109
110
111 def test_unreasonable_rankings():
112 """Negative test that rankings are evaluated.
113
114 (doesn't prove anything by itself hence test_rankings)
115 """
116 with pytest.raises(HostSelectException) as excinfo:
117 select_host(
118 [localhost],
119 ranking_string='''
120 # if this test fails due to race conditions
121 # then you are very lucky
122 virtual_memory().available > 123456789123456789
123 getloadavg()[0] < 1
124 cpu_count() > 512
125 disk_usage('/').free > 123456789123456789
126 '''
127 )
128 assert (
129 'virtual_memory().available > 123456789123456789: False'
130 ) in str(excinfo.value)
131
132
133 def test_metric_command_failure():
134 """If the psutil command (or SSH) fails ensure the host is excluded."""
135 with pytest.raises(HostSelectException) as excinfo:
136 select_host(
137 [localhost],
138 ranking_string='''
139 # elephant is not a psutil attribute
140 # so will cause the command to fail
141 elephant
142 '''
143 )
144 # we should expect the special (2) returncode
145 # (i.e. the command ran fine but there was something wrong with the
146 # provided expression)
147 assert excinfo.value.data[localhost_fqdn]['returncode'] == 2
148
149
150 def test_workflow_host_select(mock_glbl_cfg):
151 """Run the workflow_host_select mechanism."""
152 mock_glbl_cfg(
153 'cylc.flow.host_select.glbl_cfg',
154 f'''
155 [scheduler]
156 [[run hosts]]
157 available= {localhost}
158 '''
159 )
160 assert select_workflow_host() == (localhost, localhost_fqdn)
161
162
163 def test_workflow_host_select_default(mock_glbl_cfg):
164 """Ensure "localhost" is provided as a default host."""
165 mock_glbl_cfg(
166 'cylc.flow.host_select.glbl_cfg',
167 '''
168 [scheduler]
169 [[run hosts]]
170 available =
171 '''
172 )
173 hostname, host_fqdn = select_workflow_host()
174 assert hostname in localhost_aliases + [localhost]
175 assert host_fqdn == localhost_fqdn
176
177
178 # NOTE: on Travis-CI the fqdn of `localhost` is `localhost`
179 @pytest.mark.skipif(
180 localhost == localhost_fqdn,
181 reason='Cannot condemn a host unless is has a safe unique fqdn.'
182 )
183 def test_workflow_host_select_condemned(mock_glbl_cfg):
184 """Ensure condemned hosts are filtered out."""
185 mock_glbl_cfg(
186 'cylc.flow.host_select.glbl_cfg',
187 f'''
188 [scheduler]
189 [[run hosts]]
190 available = {localhost}
191 condemned = {localhost_fqdn}
192 '''
193 )
194 with pytest.raises(HostSelectException) as excinfo:
195 select_workflow_host()
196 assert 'blacklisted' in str(excinfo.value)
197 assert 'condemned host' in str(excinfo.value)
198
199
200 def test_condemned_host_ambiguous(mock_glbl_cfg):
201 """Test the [scheduler]condemend host coercer
202
203 Not actually host_select code but related functionality.
204 """
205 with pytest.raises(ListValueError) as excinfo:
206 mock_glbl_cfg(
207 'cylc.flow.host_select.glbl_cfg',
208 f'''
209 [scheduler]
210 [[run hosts]]
211 available = {localhost}
212 condemned = {localhost}
213 '''
214 )
215 assert 'ambiguous host' in excinfo.value.msg
216
217
218 def test_get_metrics_no_hosts_error(caplog):
219 """It should handle SSH errors.
220
221 If a host is not contactable then it should be shipped.
222 """
223 caplog.set_level(logging.WARN, CYLC_LOG)
224 data = {}
225 host_stats = _get_metrics(['not-a-host'], None, data)
226 # a warning should be logged
227 assert len(caplog.records) == 1
228 # no data for the host should be returned
229 assert not host_stats
230 # the return code should be recorded
231 assert data == {'not-a-host': {'returncode': 255}}