Beispiel #1
0
 def test_tls_simple_with_tls_version(self):
     tls_version = 'TLSv1'
     options = {'--tls': True}
     environment = Environment({'COMPOSE_TLS_VERSION': tls_version})
     result = tls_config_from_options(options, environment)
     assert isinstance(result, docker.tls.TLSConfig)
     assert result.ssl_version == ssl.PROTOCOL_TLSv1
Beispiel #2
0
def containers():
    """
    active containers
    """
    version = API_VERSIONS[V2_0]
    client = docker_client(Environment(), version)
    return client.containers()
Beispiel #3
0
def load_docker_env():
    # TODO: remove this since it is likely no longer needed
    from compose.config.environment import Environment

    environment = os.environ
    # environment.update({key: val for key, val in config["DOCKER_ENV"].items()})
    return Environment(environment)
Beispiel #4
0
    def top_level_cmd(self):
        try:
            compose_files = self.get_compose_files()
            config_path = get_config_path_from_options(
                ".",
                {},
                {"COMPOSE_FILE": compose_files},
            )

            os.environ["COMPOSE_FILE"] = compose_files

            for k, v in self.settings.items():
                if k == "CONFIGURATION_OPTIONAL_SCOPES":
                    continue
                if isinstance(v, bool):
                    v = f"{v}".lower()
                if isinstance(v, int):
                    v = str(v)
                os.environ[k] = v

            env = Environment()
            env.update(os.environ)

            project = get_project(os.getcwd(), config_path, environment=env)
            tlc = TopLevelCommand(project)
            yield tlc
        except Exception:  # noqa: B902
            raise
Beispiel #5
0
    def setUpClass(cls):
        if engine_version_too_low_for_v2():
            version = API_VERSIONS[V1]
        else:
            version = API_VERSIONS[V2_0]

        cls.client = docker_client(Environment(), version)
Beispiel #6
0
 def test_tls_mixed_environment_and_flags(self):
     options = {'--tls': True, '--tlsverify': False}
     environment = Environment({'DOCKER_CERT_PATH': 'tests/fixtures/tls/'})
     result = tls_config_from_options(options, environment)
     assert isinstance(result, docker.tls.TLSConfig)
     assert result.cert == (self.client_cert, self.key)
     assert result.ca_cert == self.ca_cert
     assert result.verify is False
Beispiel #7
0
    def __get_compose_project(self):
        client = docker_client(Environment())
        config_data = config.load(
            config.ConfigDetails(
                self.home_path,
                [config.ConfigFile.from_filename(self.compose_file)]))

        return DockerComposeProject.from_config(name='metal',
                                                client=client,
                                                config_data=config_data)
Beispiel #8
0
 def test_tls_verify_default_cert_path(self):
     environment = Environment({'DOCKER_TLS_VERIFY': '1'})
     options = {'--tls': True}
     with mock.patch('compose.cli.docker_client.default_cert_path') as dcp:
         dcp.return_value = 'tests/fixtures/tls/'
         result = tls_config_from_options(options, environment)
     assert isinstance(result, docker.tls.TLSConfig)
     assert result.verify is True
     assert result.ca_cert == self.ca_cert
     assert result.cert == (self.client_cert, self.key)
    def test_get_simple(self):
        env = Environment({
            'FOO': 'bar',
            'BAR': '1',
            'BAZ': ''
        })

        assert env.get('FOO') == 'bar'
        assert env.get('BAR') == '1'
        assert env.get('BAZ') == ''
def mock_env():
    return Environment({
        'USER': '******',
        'FOO': 'bar',
        'TRUE': 'True',
        'FALSE': 'OFF',
        'POSINT': '50',
        'NEGINT': '-200',
        'FLOAT': '0.145',
        'MODE': '0600',
    })
    def test_get_boolean(self):
        env = Environment({
            'FOO': '',
            'BAR': '0',
            'BAZ': 'FALSE',
            'FOOBAR': 'true',
        })

        assert env.get_boolean('FOO') is False
        assert env.get_boolean('BAR') is False
        assert env.get_boolean('BAZ') is False
        assert env.get_boolean('FOOBAR') is True
        assert env.get_boolean('UNDEFINED') is False
Beispiel #12
0
    def test_tls_verify_flag_no_override(self):
        environment = Environment({
            'DOCKER_TLS_VERIFY': 'true',
            'COMPOSE_TLS_VERSION': 'TLSv1'
        })
        options = {'--tls': True, '--tlsverify': False}

        result = tls_config_from_options(options, environment)
        assert isinstance(result, docker.tls.TLSConfig)
        assert result.ssl_version == ssl.PROTOCOL_TLSv1
        # verify is a special case - since `--tlsverify` = False means it
        # wasn't used, we set it if either the environment or the flag is True
        # see https://github.com/docker/compose/issues/5632
        assert result.verify is True
Beispiel #13
0
    def test_tls_flags_override_environment(self):
        environment = Environment({
            'DOCKER_CERT_PATH': '/completely/wrong/path',
            'DOCKER_TLS_VERIFY': 'false'
        })
        options = {
            '--tlscacert': '"{}"'.format(self.ca_cert),
            '--tlscert': '"{}"'.format(self.client_cert),
            '--tlskey': '"{}"'.format(self.key),
            '--tlsverify': True
        }

        result = tls_config_from_options(options, environment)
        assert isinstance(result, docker.tls.TLSConfig)
        assert result.cert == (self.client_cert, self.key)
        assert result.ca_cert == self.ca_cert
        assert result.verify is True
Beispiel #14
0
def build(filename, env_dict=None, output_path=None):
    """
    Build docker-compose.yml file from services & env.
    """

    path = os.path.dirname(filename)
    conf_file = ConfigFile.from_filename(filename)
    env = Environment(env_dict) if env_dict else None
    conf = load(ConfigDetails(path, [conf_file], env))

    output_path = output_path if output_path else path + '/docker-compose.yml'

    # try to make directory
    if os.path.dirname(output_path):
        os.makedirs(os.path.dirname(output_path))

    out = open(output_path, 'w')
    out.write(serialize_config(conf))
    out.close()

    return output_path
def variable_mapping():
    return Environment({'FOO': 'first', 'BAR': ''})
Beispiel #16
0
def client():
    """
    docker client
    """
    return docker_client(Environment(), API_VERSIONS[COMPOSEFILE_V3_0])
Beispiel #17
0
def client():
    """
    docker client
    """
    return docker_client(Environment(), API_VERSIONS[COMPOSE_SPEC])
Beispiel #18
0
 def test_tls_verify_env_falsy_value(self):
     environment = Environment({'DOCKER_TLS_VERIFY': '0'})
     options = {'--tls': True}
     assert tls_config_from_options(options, environment) is True
Beispiel #19
0
def client():
    return docker_client(Environment(), API_VERSIONS[V2_0])
Beispiel #20
0
    def test_build_native_args_propagated(self, cli_build):
        options = {
            '--build-arg': ['MYVAR', 'ARG=123'],
            '--no-cache': True,
            '--pull': True,
            '--force-rm': True,
            '--memory': True,
            '--compress': True,
            '--parallel': True,
            '--quiet': True,
            '--progress': 'progress',
            'SERVICE': ['service'],
            'COMMAND': 'build',
        }
        env = Environment({
            'MYVAR': 'MYVALUE',
        })
        if cli_build:
            env['COMPOSE_DOCKER_CLI_BUILD'] = '1'
        with mock.patch('compose.cli.main.TopLevelCommand.toplevel_environment', new=env), \
                mock.patch('compose.cli.main.Environment.from_env_file', return_value=env), \
                mock.patch('compose.project.Project.build') as mock_build, \
                mock.patch('compose.cli.command.config.find') as mock_config_find, \
                mock.patch('compose.cli.command.config.load') as mock_config_load:
            mock_config_find.return_value = ConfigDetails(
                working_dir='working_dir',
                config_files=[ConfigFile(filename='config_file', config={})],
                environment=env,
            )
            mock_config_load.return_value = Config(
                version=COMPOSEFILE_V3_4,
                services=[],
                volumes={},
                networks={},
                secrets={},
                configs={},
            )
            project = [None]

            def handler(command, options):
                project[0] = command.project
                command.build(options)

            perform_command(options, handler=handler, command_options=options)
            assert mock_build.call_args == mock.call(
                service_names=['service'],
                no_cache=True,
                pull=True,
                force_rm=True,
                memory=True,
                rm=True,
                build_args={
                    'MYVAR': 'MYVALUE',
                    'ARG': '123'
                },
                gzip=True,
                parallel_build=True,
                silent=True,
                progress='progress',
            )
            assert project[0].native_build_enabled == bool(cli_build)
Beispiel #21
0
    def test_build_native_builder_called(self, cli_build):
        options = {
            '--build-arg': ['MYVAR', 'ARG=123'],
            '--no-cache': True,
            '--pull': True,
            '--force-rm': False,
            '--memory': True,
            '--compress': False,
            '--parallel': False,
            '--quiet': True,
            '--progress': 'progress',
            'SERVICE': ['service'],
            'COMMAND': 'build',
        }
        env = Environment({
            'MYVAR': 'MYVALUE',
        })

        if cli_build:
            env['COMPOSE_DOCKER_CLI_BUILD'] = '1'
            env['COMPOSE_DOCKER_CLI_BUILD_EXTRA_ARGS'] = '--extra0 --extra1=1'

        iidfile = [None]

        def mock_mktemp():
            iidfile[0] = tempfile.mktemp()
            with open(iidfile[0], 'w') as f:
                f.write(':12345')
            return iidfile[0]

        with mock.patch('compose.cli.main.TopLevelCommand.toplevel_environment', new=env), \
                mock.patch('compose.cli.main.Environment.from_env_file', return_value=env), \
                mock.patch('compose.service.subprocess.Popen') as mock_subprocess_popen, \
                mock.patch('compose.service.tempfile', new=mock.Mock(mktemp=mock_mktemp)), \
                mock.patch('compose.cli.command.get_client') as mock_get_client, \
                mock.patch('compose.cli.command.config.find') as mock_config_find, \
                mock.patch('compose.cli.command.config.load') as mock_config_load:
            mock_config_find.return_value = ConfigDetails(
                working_dir='working_dir',
                config_files=[ConfigFile(filename='config_file', config={})],
                environment=env,
            )
            mock_config_load.return_value = Config(
                version=COMPOSEFILE_V3_4,
                services=[{
                    'name': 'service',
                    'build': {
                        'context': '.',
                    },
                }],
                volumes={},
                networks={},
                secrets={},
                configs={},
            )
            mock_get_client.return_value.api_version = '1.35'
            mock_build = mock_get_client.return_value.build
            mock_build.return_value = \
                mock_subprocess_popen.return_value.__enter__.return_value.stdout = \
                io.StringIO('{"stream": "Successfully built 12345"}')

            project = [None]

            def handler(command, options):
                project[0] = command.project
                command.build(options)

            perform_command(options, handler=handler, command_options=options)
            if not cli_build:
                assert mock_build.called
                assert mock_build.call_args[1]['buildargs'] == {
                    'MYVAR': 'MYVALUE',
                    'ARG': '123'
                }
                assert mock_build.call_args[1]['pull']
                assert mock_build.call_args[1]['nocache']
                assert not mock_build.call_args[1]['forcerm']
                assert not mock_build.call_args[1]['gzip']
                assert not project[0].native_build_enabled
            else:
                assert mock_subprocess_popen.call_args[0][0] == [
                    'docker',
                    'build',
                    '--build-arg',
                    'MYVAR=MYVALUE',
                    '--build-arg',
                    'ARG=123',
                    '--memory',
                    'True',
                    '--no-cache',
                    '--progress',
                    'progress',
                    '--pull',
                    '--tag',
                    'working_dir_service',
                    '--iidfile',
                    iidfile[0],
                    '--extra0',
                    '--extra1=1',
                    '.',
                ]
                assert project[0].native_build_enabled
Beispiel #22
0
def load_docker_env():
    environment = os.environ
    environment.update({key: val for key, val in config["DOCKER_ENV"].items()})
    return Environment(environment)
Beispiel #23
0
def mock_env():
    return Environment({'USER': '******', 'FOO': 'bar'})
 def test_get_undefined(self):
     env = Environment({
         'FOO': 'bar'
     })
     assert env.get('FOOBAR') is None
Beispiel #25
0
 def compose_project(cls):
     env = Environment(os.environ.copy())
     env.update(cls.COMPOSE_ENV)
     return get_project(cls.find_compose_path(),
                        project_name=cls.compose_project_name(),
                        environment=env)
Beispiel #26
0
 def setUpClass(cls):
     version = API_VERSIONS[engine_max_version()]
     cls.client = docker_client(Environment(), version)
 def get_project(self):
     # Dont reuse the client to fix this bug : https://github.com/docker/compose/issues/1275
     client = docker_client(Environment())
     project = Project.from_config(self.name, self.cd, client)
     return project