summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_internal/cloud/nios.py
blob: c9dae517fd9f4e488916b52eba5cf3e1f143c0aa (plain)
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
"""NIOS plugin for integration tests."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import os

from . import (
    CloudProvider,
    CloudEnvironment,
    CloudEnvironmentConfig,
)

from ..util import (
    find_executable,
    display,
)

from ..docker_util import (
    docker_run,
    docker_rm,
    docker_inspect,
    docker_pull,
    get_docker_container_id,
)


class NiosProvider(CloudProvider):
    """Nios plugin.

    Sets up NIOS mock server for tests.
    """

    DOCKER_SIMULATOR_NAME = 'nios-simulator'

    DOCKER_IMAGE = 'quay.io/ansible/nios-test-container:1.3.0'
    """Default image to run the nios simulator.

    The simulator must be pinned to a specific version
    to guarantee CI passes with the version used.

    It's source source itself resides at:
    https://github.com/ansible/nios-test-container
    """

    def __init__(self, args):
        """Set up container references for provider.

        :type args: TestConfig
        """
        super(NiosProvider, self).__init__(args)

        self.__container_from_env = os.environ.get('ANSIBLE_NIOSSIM_CONTAINER')
        """Overrides target container, might be used for development.

        Use ANSIBLE_NIOSSIM_CONTAINER=whatever_you_want if you want
        to use other image. Omit/empty otherwise.
        """

        self.image = self.__container_from_env or self.DOCKER_IMAGE
        self.container_name = ''

    def filter(self, targets, exclude):
        """Filter out the tests with the necessary config and res unavailable.

        :type targets: tuple[TestTarget]
        :type exclude: list[str]
        """
        docker_cmd = 'docker'
        docker = find_executable(docker_cmd, required=False)

        if docker:
            return

        skip = 'cloud/%s/' % self.platform
        skipped = [target.name for target in targets if skip in target.aliases]

        if skipped:
            exclude.append(skip)
            display.warning(
                'Excluding tests marked "%s" '
                'which require the "%s" command: %s'
                % (skip.rstrip('/'), docker_cmd, ', '.join(skipped))
            )

    def setup(self):
        """Setup cloud resource before delegation and reg cleanup callback."""
        super(NiosProvider, self).setup()

        if self._use_static_config():
            self._setup_static()
        else:
            self._setup_dynamic()

    def get_docker_run_options(self):
        """Get additional options needed when delegating tests to a container.

        :rtype: list[str]
        """
        return ['--link', self.DOCKER_SIMULATOR_NAME] if self.managed else []

    def cleanup(self):
        """Clean up the resource and temporary configs files after tests."""
        if self.container_name:
            docker_rm(self.args, self.container_name)

        super(NiosProvider, self).cleanup()

    def _setup_dynamic(self):
        """Spawn a NIOS simulator within docker container."""
        nios_port = 443
        container_id = get_docker_container_id()

        if container_id:
            display.info(
                'Running in docker container: %s' % container_id,
                verbosity=1,
            )

        self.container_name = self.DOCKER_SIMULATOR_NAME

        results = docker_inspect(self.args, self.container_name)

        if results and not results[0].get('State', {}).get('Running'):
            docker_rm(self.args, self.container_name)
            results = []

        display.info(
            '%s NIOS simulator docker container.'
            % ('Using the existing' if results else 'Starting a new'),
            verbosity=1,
        )

        if not results:
            if self.args.docker or container_id:
                publish_ports = []
            else:
                # publish the simulator ports when not running inside docker
                publish_ports = [
                    '-p', ':'.join((str(nios_port), ) * 2),
                ]

            if not self.__container_from_env:
                docker_pull(self.args, self.image)

            docker_run(
                self.args,
                self.image,
                ['-d', '--name', self.container_name] + publish_ports,
            )

        if self.args.docker:
            nios_host = self.DOCKER_SIMULATOR_NAME
        elif container_id:
            nios_host = self._get_simulator_address()
            display.info(
                'Found NIOS simulator container address: %s'
                % nios_host, verbosity=1
            )
        else:
            nios_host = 'localhost'

        self._set_cloud_config('NIOS_HOST', nios_host)

    def _get_simulator_address(self):
        results = docker_inspect(self.args, self.container_name)
        ip_address = results[0]['NetworkSettings']['IPAddress']
        return ip_address

    def _setup_static(self):
        raise NotImplementedError


class NiosEnvironment(CloudEnvironment):
    """NIOS environment plugin.

    Updates integration test environment after delegation.
    """
    def get_environment_config(self):
        """
        :rtype: CloudEnvironmentConfig
        """
        ansible_vars = dict(
            nios_provider=dict(
                host=self._get_cloud_config('NIOS_HOST'),
                username='admin',
                password='infoblox',
            ),
        )

        return CloudEnvironmentConfig(
            ansible_vars=ansible_vars,
        )