Initial commit

This commit is contained in:
Jon Ervine
2021-03-03 11:36:53 +08:00
parent a5dc995324
commit 4cdbe9a6d5
137 changed files with 12374 additions and 2 deletions
@@ -0,0 +1,71 @@
import json
import os
import subprocess
import yaml
from tempfile import NamedTemporaryFile
import pytest
@pytest.fixture
def tmp_file_maker():
"""Fixture to return temporary file maker."""
def tmp_file(text):
with NamedTemporaryFile(delete=False) as tempf:
tempf.write(bytes(text, 'UTF-8'))
return tempf.name
return tmp_file
class CompletedProcessProxy(object):
def __init__(self, result):
self.result = result
def __getattr__(self, attr):
return getattr(self.result, attr)
@property
def json(self):
try:
response_json = json.loads(self.stdout)
except json.JSONDecodeError:
pytest.fail(
f"Unable to convert the response to a valid json - stdout: {self.stdout}, stderr: {self.stderr}"
)
return response_json
@property
def yaml(self):
return yaml.safe_load(self.stdout)
@pytest.fixture(scope='function')
def cli(request):
def run(args, *a, **kw):
if not kw.pop('bare', None):
args = ['ansible-runner',] + args
kw['encoding'] = 'utf-8'
if 'check' not in kw:
# By default we want to fail if a command fails to run. Tests that
# want to skip this can pass check=False when calling this fixture
kw['check'] = True
if 'stdout' not in kw:
kw['stdout'] = subprocess.PIPE
if 'stderr' not in kw:
kw['stderr'] = subprocess.PIPE
kw.setdefault('env', os.environ.copy()).update({
'LANG': 'en_US.UTF-8'
})
try:
ret = CompletedProcessProxy(subprocess.run(' '.join(args), shell=True, *a, **kw))
except subprocess.CalledProcessError as err:
pytest.fail(
f"Running {err.cmd} resulted in a non-zero return code: {err.returncode} - stdout: {err.stdout}, stderr: {err.stderr}"
)
return ret
return run
@@ -0,0 +1 @@
localhost
@@ -0,0 +1,38 @@
---
- hosts: localhost
gather_facts: true
vars:
cgroup_search_terms: docker\|lxc\|podman\|oci
is_container: false
is_podman: false
is_docker: false
tasks:
- debug: msg="Test if we are in a container!"
- name: 'Look for container env var defined in /proc/1/environ'
shell: "grep 'container=' /proc/1/environ"
register: container_proc_environ
ignore_errors: true
- name: 'Look for container info defined in /proc/1/cgroup'
shell: "grep '{{ cgroup_search_terms}}' /proc/1/cgroup"
register: container_proc_cgroup
ignore_errors: true
- name: 'Found evidence that we are in docker container'
set_fact:
is_docker: true
when: (('container' in ansible_env and ansible_env.container == 'docker') or ansible_virtualization_type == 'docker')
- name: 'Found evidence that we are in podman container'
set_fact:
is_podman: true
when: ('container' in ansible_env and ansible_env.container == 'podman')
- name: 'Found evidence that we are in a container'
set_fact:
is_container: true
when: is_docker or is_podman or container_proc_environ.rc == 0 or container_proc_cgroup.rc == 0
- fail:
when: not (is_container)
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
import os
import pytest
HERE = os.path.abspath(os.path.dirname(__file__))
@pytest.fixture
def skip_if_no_podman(container_runtime_installed):
if container_runtime_installed != 'podman':
pytest.skip('podman container runtime(s) not available')
@pytest.mark.serial
def test_module_run(cli, skip_if_no_podman):
r = cli(['run', '-m', 'ping','--hosts', 'localhost', os.path.join(HERE, 'priv_data')])
assert '"ping": "pong"' in r.stdout
@pytest.mark.serial
def test_playbook_run(cli, skip_if_no_podman):
r = cli(['run', os.path.join(HERE,'priv_data'), '-p', 'test-container.yml'])
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@pytest.mark.serial
def test_provide_env_var(cli, skip_if_no_podman, test_data_dir):
r = cli(['run', os.path.join(test_data_dir, 'job_env'), '-p', 'printenv.yml'])
assert 'gifmyvqok2' in r.stdout, r.stdout
@pytest.mark.serial
def test_adhoc_localhost_setup(cli, skip_if_no_podman, container_runtime_installed):
r = cli(
[
'adhoc',
'--private-data-dir', os.path.join(HERE,'priv_data'),
'--container-runtime', container_runtime_installed,
'localhost', '-m', 'setup'
]
)
# TODO: look for some fact that indicates we are in container?
assert '"ansible_facts": {' in r.stdout
@pytest.mark.serial
def test_playbook_with_private_data_dir(cli, skip_if_no_podman, container_runtime_installed):
# tests using a private_data_dir in conjunction with an absolute path
r = cli(
[
'playbook',
'--private-data-dir', os.path.join(HERE,'priv_data'),
'--container-runtime', container_runtime_installed,
os.path.join(HERE, 'priv_data/project/test-container.yml')
]
)
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@pytest.mark.serial
def test_playbook_with_relative_path(cli, skip_if_no_podman, container_runtime_installed):
r = cli(
[
'playbook',
'--container-runtime', container_runtime_installed,
'test/integration/containerized/priv_data/project/test-container.yml'
]
)
assert 'PLAY RECAP *******' in r.stdout
assert 'failed=0' in r.stdout
@@ -0,0 +1,72 @@
import os
import shutil
import time
import pytest
from ansible_runner.interface import run
def is_running(cli, container_runtime_installed, container_name):
cmd = [container_runtime_installed, 'ps', '-aq', '--filter', 'name=ansible_runner_foo_bar']
r = cli(cmd, bare=True)
output = '{}{}'.format(r.stdout, r.stderr)
print(' '.join(cmd))
print(output)
return output.strip()
class CancelStandIn:
def __init__(self, runtime, cli, delay=0.2):
self.runtime = runtime
self.cli = cli
self.delay = 0.2
self.checked_running = False
self.start_time = None
def cancel(self):
# Avoid checking for some initial delay to allow container startup
if not self.start_time:
self.start_time = time.time()
if time.time() - self.start_time < self.delay:
return False
# guard against false passes by checking for running container
if not self.checked_running:
for i in range(5):
if is_running(self.cli, self.runtime, 'ansible_runner_foo_bar'):
break
time.sleep(0.2)
else:
print(self.cli([self.runtime, 'ps', '-a'], bare=True).stdout)
raise Exception('Never spawned expected container')
self.checked_running = True
# Established that container was running, now we cancel job
return True
@pytest.mark.serial
def test_cancel_will_remove_container(test_data_dir, container_runtime_installed, cli):
private_data_dir = os.path.join(test_data_dir, 'sleep')
env_dir = os.path.join(private_data_dir, 'env')
if os.path.exists(env_dir):
shutil.rmtree(env_dir)
cancel_standin = CancelStandIn(container_runtime_installed, cli)
res = run(
private_data_dir=private_data_dir,
playbook='sleep.yml',
settings={
'process_isolation_executable': container_runtime_installed,
'process_isolation': True
},
cancel_callback=cancel_standin.cancel,
ident='foo?bar' # question mark invalid char, but should still work
)
assert res.rc == 254, res.stdout.read()
assert res.status == 'canceled'
assert not is_running(
cli, container_runtime_installed, 'ansible_runner_foo_bar'
), 'Found a running container, they should have all been stopped'