summaryrefslogtreecommitdiffstats
path: root/test/lib/ansible_test/_internal/commands/integration/cloud/cs.py
blob: 0037b423a3d93a750fca2c2721c26455d38b0037 (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
"""CloudStack plugin for integration tests."""
from __future__ import annotations

import json
import configparser
import os
import urllib.parse
import typing as t

from ....util import (
    ApplicationError,
    display,
)

from ....config import (
    IntegrationConfig,
)

from ....docker_util import (
    docker_exec,
)

from ....containers import (
    CleanupMode,
    run_support_container,
    wait_for_file,
)

from . import (
    CloudEnvironment,
    CloudEnvironmentConfig,
    CloudProvider,
)


class CsCloudProvider(CloudProvider):
    """CloudStack cloud provider plugin. Sets up cloud resources before delegation."""
    DOCKER_SIMULATOR_NAME = 'cloudstack-sim'

    def __init__(self, args: IntegrationConfig) -> None:
        super().__init__(args)

        self.image = os.environ.get('ANSIBLE_CLOUDSTACK_CONTAINER', 'quay.io/ansible/cloudstack-test-container:1.4.0')
        self.host = ''
        self.port = 0

        self.uses_docker = True
        self.uses_config = True

    def setup(self) -> None:
        """Setup the cloud resource before delegation and register a cleanup callback."""
        super().setup()

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

    def _setup_static(self) -> None:
        """Configure CloudStack tests for use with static configuration."""
        parser = configparser.ConfigParser()
        parser.read(self.config_static_path)

        endpoint = parser.get('cloudstack', 'endpoint')

        parts = urllib.parse.urlparse(endpoint)

        self.host = parts.hostname

        if not self.host:
            raise ApplicationError('Could not determine host from endpoint: %s' % endpoint)

        if parts.port:
            self.port = parts.port
        elif parts.scheme == 'http':
            self.port = 80
        elif parts.scheme == 'https':
            self.port = 443
        else:
            raise ApplicationError('Could not determine port from endpoint: %s' % endpoint)

        display.info('Read cs host "%s" and port %d from config: %s' % (self.host, self.port, self.config_static_path), verbosity=1)

    def _setup_dynamic(self) -> None:
        """Create a CloudStack simulator using docker."""
        config = self._read_config_template()

        self.port = 8888

        ports = [
            self.port,
        ]

        descriptor = run_support_container(
            self.args,
            self.platform,
            self.image,
            self.DOCKER_SIMULATOR_NAME,
            ports,
            allow_existing=True,
            cleanup=CleanupMode.YES,
        )

        if not descriptor:
            return

        # apply work-around for OverlayFS issue
        # https://github.com/docker/for-linux/issues/72#issuecomment-319904698
        docker_exec(self.args, self.DOCKER_SIMULATOR_NAME, ['find', '/var/lib/mysql', '-type', 'f', '-exec', 'touch', '{}', ';'], capture=True)

        if self.args.explain:
            values = dict(
                HOST=self.host,
                PORT=str(self.port),
            )
        else:
            credentials = self._get_credentials(self.DOCKER_SIMULATOR_NAME)

            values = dict(
                HOST=self.DOCKER_SIMULATOR_NAME,
                PORT=str(self.port),
                KEY=credentials['apikey'],
                SECRET=credentials['secretkey'],
            )

            display.sensitive.add(values['SECRET'])

        config = self._populate_config_template(config, values)

        self._write_config(config)

    def _get_credentials(self, container_name: str) -> dict[str, t.Any]:
        """Wait for the CloudStack simulator to return credentials."""
        def check(value) -> bool:
            """Return True if the given configuration is valid JSON, otherwise return False."""
            # noinspection PyBroadException
            try:
                json.loads(value)
            except Exception:  # pylint: disable=broad-except
                return False  # sometimes the file exists but is not yet valid JSON

            return True

        stdout = wait_for_file(self.args, container_name, '/var/www/html/admin.json', sleep=10, tries=30, check=check)

        return json.loads(stdout)


class CsCloudEnvironment(CloudEnvironment):
    """CloudStack cloud environment plugin. Updates integration test environment after delegation."""
    def get_environment_config(self) -> CloudEnvironmentConfig:
        """Return environment configuration for use in the test environment after delegation."""
        parser = configparser.ConfigParser()
        parser.read(self.config_path)

        config = dict(parser.items('default'))

        env_vars = dict(
            CLOUDSTACK_ENDPOINT=config['endpoint'],
            CLOUDSTACK_KEY=config['key'],
            CLOUDSTACK_SECRET=config['secret'],
            CLOUDSTACK_TIMEOUT=config['timeout'],
        )

        display.sensitive.add(env_vars['CLOUDSTACK_SECRET'])

        ansible_vars = dict(
            cs_resource_prefix=self.resource_prefix,
        )

        return CloudEnvironmentConfig(
            env_vars=env_vars,
            ansible_vars=ansible_vars,
        )