File: test_host_select.py

package info (click to toggle)
cylc-flow 8.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,368 kB
  • sloc: python: 87,751; sh: 17,109; sql: 233; xml: 171; javascript: 78; lisp: 55; makefile: 11
file content (231 lines) | stat: -rw-r--r-- 7,238 bytes parent folder | download
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
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Test the cylc.flow.host_select module.

NOTE: these are functional tests, for unit tests see the docstrings in
      the host_select module.

"""
import logging
from secrets import token_hex
import socket

import pytest

from cylc.flow import CYLC_LOG
from cylc.flow.exceptions import HostSelectException
from cylc.flow.host_select import (
    _get_metrics,
    select_host,
    select_workflow_host,
)
from cylc.flow.hostuserutil import get_fqdn_by_host
from cylc.flow.parsec.exceptions import ListValueError


localhost, localhost_aliases, _ = socket.gethostbyname_ex('localhost')
localhost_fqdn = get_fqdn_by_host(localhost)


# NOTE: ensure that all localhost aliases are actually aliases of localhost,
#       it would appear that this is not always the case
#       on Travis-CI on of the aliases has a different fqdn from the fqdn
#       of the host it is an alias of
localhost_aliases = [
    alias
    for alias in localhost_aliases
    if get_fqdn_by_host(alias) == localhost_fqdn
]


def test_localhost():
    """Basic test with one host to choose from."""
    assert select_host([localhost]) == (
        localhost,
        localhost_fqdn
    )


def test_unique():
    """Basic test choosing from multiple forms of localhost"""
    name, fqdn = select_host(
        localhost_aliases + [localhost]
    )
    assert name in localhost_aliases + [localhost]
    assert fqdn == localhost_fqdn


def test_filter():
    """Test that hosts are filtered out if specified."""
    message = 'Localhost not allowed'
    with pytest.raises(HostSelectException) as excinfo:
        select_host(
            [localhost],
            blacklist=[localhost],
            blacklist_name=message
        )
    assert message in str(excinfo.value)


def test_filter_invalid_blacklist(log_filter):
    """Test that invalid blacklist doesn't bring down the program."""
    result = select_host(
        [localhost], blacklist=[f'non_exist_{token_hex(4)}']
    )
    assert result[0] == localhost
    assert log_filter(logging.WARNING, "Could not resolve blacklisted host")


def test_rankings():
    """Positive test that rankings are evaluated.

    (doesn't prove anything by itself hence test_unreasonable_rankings)
    """
    assert select_host(
        [localhost],
        ranking_string='''
            # if this test fails due to race conditions
            # then you have bigger issues than a test failure
            virtual_memory().available > 1
            getloadavg()[0] < 500
            cpu_count() > 1
            disk_usage('/').free > 1
        '''
    ) == (localhost, localhost_fqdn)


def test_unreasonable_rankings():
    """Negative test that rankings are evaluated.

    (doesn't prove anything by itself hence test_rankings)
    """
    with pytest.raises(HostSelectException) as excinfo:
        select_host(
            [localhost],
            ranking_string='''
                # if this test fails due to race conditions
                # then you are very lucky
                virtual_memory().available > 123456789123456789
                getloadavg()[0] < 1
                cpu_count() > 512
                disk_usage('/').free > 123456789123456789
            '''
        )
    assert (
        'virtual_memory().available > 123456789123456789: False'
    ) in str(excinfo.value)


def test_metric_command_failure():
    """If the psutil command (or SSH) fails ensure the host is excluded."""
    with pytest.raises(HostSelectException) as excinfo:
        select_host(
            [localhost],
            ranking_string='''
                # elephant is not a psutil attribute
                # so will cause the command to fail
                elephant
            '''
        )
    # we should expect the special (2) returncode
    # (i.e. the command ran fine but there was something wrong with the
    # provided expression)
    assert excinfo.value.data[localhost_fqdn]['returncode'] == 2


def test_workflow_host_select(mock_glbl_cfg):
    """Run the workflow_host_select mechanism."""
    mock_glbl_cfg(
        'cylc.flow.host_select.glbl_cfg',
        f'''
            [scheduler]
                [[run hosts]]
                    available= {localhost}
        '''
    )
    assert select_workflow_host() == (localhost, localhost_fqdn)


def test_workflow_host_select_default(mock_glbl_cfg):
    """Ensure "localhost" is provided as a default host."""
    mock_glbl_cfg(
        'cylc.flow.host_select.glbl_cfg',
        '''
            [scheduler]
                [[run hosts]]
                    available =
        '''
    )
    hostname, host_fqdn = select_workflow_host()
    assert hostname in localhost_aliases + [localhost]
    assert host_fqdn == localhost_fqdn


# NOTE: on Travis-CI the fqdn of `localhost` is `localhost`
@pytest.mark.skipif(
    localhost == localhost_fqdn,
    reason='Cannot condemn a host unless is has a safe unique fqdn.'
)
def test_workflow_host_select_condemned(mock_glbl_cfg):
    """Ensure condemned hosts are filtered out."""
    mock_glbl_cfg(
        'cylc.flow.host_select.glbl_cfg',
        f'''
            [scheduler]
                [[run hosts]]
                    available = {localhost}
                    condemned = {localhost_fqdn}
        '''
    )
    with pytest.raises(HostSelectException) as excinfo:
        select_workflow_host()
    assert 'blacklisted' in str(excinfo.value)
    assert 'condemned host' in str(excinfo.value)


def test_condemned_host_ambiguous(mock_glbl_cfg):
    """Test the [scheduler]condemend host coercer

    Not actually host_select code but related functionality.
    """
    with pytest.raises(ListValueError) as excinfo:
        mock_glbl_cfg(
            'cylc.flow.host_select.glbl_cfg',
            f'''
                [scheduler]
                    [[run hosts]]
                        available = {localhost}
                        condemned = {localhost}
            '''
        )
    assert 'ambiguous host' in excinfo.value.msg


def test_get_metrics_no_hosts_error(caplog):
    """It should handle SSH errors.

    If a host is not contactable then it should be shipped.
    """
    caplog.set_level(logging.WARN, CYLC_LOG)
    data = {}
    host_stats = _get_metrics(['not-a-host'], None, data)
    # a warning should be logged
    assert len(caplog.records) == 1
    # no data for the host should be returned
    assert not host_stats
    # the return code should be recorded
    assert data == {'not-a-host': {'returncode': 255}}