Initial commit

This commit is contained in:
Jon Ervine
2021-03-02 20:53:43 +08:00
parent 89d3a2dfe1
commit f961b728fa
2919 changed files with 388582 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
---
- name: Build AWX Docker Images
hosts: localhost
gather_facts: true
roles:
- {role: dockerfile}
- {role: image_build}
- {role: image_push, when: "docker_registry is defined"}
+6
View File
@@ -0,0 +1,6 @@
---
- name: Render AWX Dockerfile and sources
hosts: localhost
gather_facts: true
roles:
- {role: dockerfile}
@@ -0,0 +1,6 @@
---
build_dev: false
kube_dev: false
dockerfile_dest: '../..'
dockerfile_name: 'Dockerfile'
template_dest: '_build'
@@ -0,0 +1,52 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.19 (Darwin)
mQINBFVfhqABEAC6EEEPv57spTUSQvtgqbVZI7d5ooCTMXEo5KJGVPVSfKtO8+BV
ZTKPukUazbtplDlIe9csfbP7CBaaBn5CtDgIrbROzazxoWv7mIP6hjUaTQSd5tvv
ONDQvnCDD5SKcy+XhqkmALSvREsN9tNtKETGXgNOLwJAlzxcpt8JLXnuiCCbefum
gaDoPQsIkegFa/r6XhY6kLi2lpQOJ3v72IXNDpdau1vtp/xPHclfCI1iQ7gnfEdw
rRJRGeOx1qikyqAVFgXXiI/NAQrsyIsO0ECGSBLQeDna/bGrqpCGKnrbJhfGAIWA
aXUTRCQRemiansk0Whu4ATZz8iM9zJPi1R7CeMXgwe7VtD4KOd1y7UBHKwAhIWdu
4Q4lsOpm2tzYFQUrY6mQ/3BkywDHkdVqmQKTGCuwcNO9PMOBLSE99yCIjxXL04VM
dPWIqMvh15TLjd6UahNFucowX3312z4JpWFHWA075MdkvVVcqfMxohViOLUCYt/C
74xFmT+uZUKnSQFYT/JaGqxFLjkYHmnFrb710fBjniDlaB4Ii3Tft/yXsgx8P9xb
y2cWA/W6yFeRqXM49C3/KA6RhDWU90P55O/MWbYUSGiGu+eYT3rMAV2cI6r4+U7e
YgQvntpc9GbAzab6co8ceJ3lpTHtSl+QZJUhSoPYg5VbSilf0AqZgUSUUQARAQAB
tC5BbnNpYmxlLCBJbmMuIChyZWxlYXNlKSA8c2VjdXJpdHlAYW5zaWJsZS5jb20+
iQI4BBMBAgAiBQJVX4agAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRC4
TjOcRCZnqfN+D/9LvJVLW/zMPcZ4qK+/KpNiD+MXducBpQiUfj2AoEqkR2LwL4/G
v5N3GCpBHSrzK1PBp5uW1+6TcdotBO5ePtmvJlSjVMVxHkcTTBfuzqtErcw/zequ
sNsagllPlCePT1Osi34onGm7zMdillh/uw30bojYRwtDpfXiXJAqPc3vqXrER8EE
r+ZFj4MJcqDGWdIguWX8hnIFkzYZ7Gyvwo4ETWrdRhRfHoIdwyiAawnxkgpMVHxv
2+JlqDb+qqY2Wjffd5WC2uaxK88sCsScJF+aE+WlBIVRA4POu4gZneLfuGzzpg2e
9PSWmtDo5X7ECRnfTIMvAbbpt08x/zSZxwRUwLdQ+F9vN7RZ/ibaXE2rG1xrWOO/
wel8cfhDl7YgZhKw8R/RURliOB5FFJ336zGWm5HTHyhblbiNn+LcUAy8ipYp6y+C
ATLnHzF6J5CtIRpG4Bs5Ar3xePNGUnEHXiLv3wYeq3uUkrFcRpmcMUSBrtk6QHbD
fmJvWpdA4twmoBFBMyvvTJmBb52teNzoqBgeNflXl+SVAMT2eZSezqbvevuHQTOX
uRw0GXsKCQ/hyR9f1fd0yGRMtPqNTRLwBb4lzpU70/rRmU9gHzY4Yhwg3E9Tv+rM
a5Lj3YmlJRax5gUVQN02E1zlBDsiNrGqpmDG1Mxo7YPpbxgu0PFPqeqcFbkCDQRV
X4agARAAwO4MA+7uIRV+oHmyMPLFWqiKp2nFy5McQByJxSQchn93/9qud4JYd1i6
8pIiKN6XJqtpt16UCTewcZHM5oOJQVNwAS8TP9imfg73TfUaoOoUbp0qfGKub/Q4
6Ktnwe940qEqYG1/QsPWNE/4G1O3b/O7m6qlozEEmxep8bRviRChz4/Mw75S1W6i
jlKYI8yZOUco9oiFJcKqyYtaKkgEg18cNuY8uvAlvULezaZyCqVjoVbKGUUAPSVg
CBixqLQ7UmBMA6xxptVuBvaRJAaF0VvvcyBZo4SzybtrHbUD1VWIzmWKKD/sDS2J
MQbnQ0FnhRzTjhvQhAp2LVPeAQVbQNFdG7y+ROCHeE9mqutTZLOilut+CQ8HDWuQ
/eCQU5yV7vh3FL/SVYS0ahZj+FdfTq8rbeIsDT42Z/MjDB54jxB5ajCHLomi4LhC
09zeb7HgwUc5wzoN7nU1OLmmn0AFwKJVD1R5UgySggv2xJym1H/mjJiR0MDweJDc
xj3bf4qGRDLVFRkZcO3cmMDLhL9gb1MIU3zBVotOBt2dig/Je+K6CUFHAA237Vcg
VKUrLIi6OdG3ecAdflGsaNKQ5XPv2mfhbieXu9N/S7HBvjeHIBD2xjWNz9UE1ymu
QPwR6+zTxD4Nx1xIiink0MN1PaCkGJ03YBSsXnHoyiOhqAfceRcAEQEAAYkCHwQY
AQIACQUCVV+GoAIbDAAKCRC4TjOcRCZnqSvGD/wP8y6fz2PsrgspHCraNuWTJaVA
DesQgOxJS6uHskW/jnHkvAMTNzlVhov1hN7g+QjPMISQDCn+913kyqZ0lU3lYmvz
nByPAbgzZvmAaTqb8v79zY6UH4NzbBuz4dhYN65dxhiMpNrXVvMRQjPFRXG0GG5d
7ypM1b9eoRTRlJNAwQ/ONoQxZdzVpmpXjcMOaifs75lkGAfNT0bcG/o/Qh/p4MRF
t/VSmH8tM8jJuHbIPcs8FWP4J8xzum8uhF2ZlKEQsR2C9cBJSBrs5jdOjgMqwFv5
2qCg0PpEKKNQdu9MabapBprFMwJWIl+dOjUE3fdMrOSJBZZusQq9nwtDNAaaLcD7
RwStw7AXi6CxYuB/uikKRviLqRCwASdj5Cdjtu6mohS8DdVkpEYbpuPjEdqc7UyW
fAZQqYMkwIfaxE25/S+FxqISSCFIOCL3QNTk0Q9u2W6Fh+KUACZobtwUL/XytPBz
7Fn5wXeOCPoAbOXoiT7kPsFGvIsFHpF3K7Fy+cMrqr5dqhywGK5ckIKXRKmCAu8H
iDeBqVjBn143WJPZ8uiu+7TiaGLuOqDdiDSchM24W4hs5DbD9zdVYy6IFi1OWSot
HUQyZisiIgD1hSHhkn2LTYrJqIdvJ/q8buMKywB9Avs5fwP/CnsrSP9z+RWJ8HKP
OwWvTVGXCPUZTxHiYg==
=msBf
-----END PGP PUBLIC KEY BLOCK-----
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
if [ `id -u` -ge 500 ]; then
echo "awx:x:`id -u`:`id -g`:,,,:/var/lib/awx:/bin/bash" >> /tmp/passwd
cat /tmp/passwd > /etc/passwd
rm /tmp/passwd
fi
if [ -n "${AWX_KUBE_DEVEL}" ]; then
pushd /awx_devel
make awx-link
popd
export SDB_NOTIFY_HOST=$(ip route | head -n1 | awk '{print $3}')
fi
source /etc/tower/conf.d/environment.sh
ANSIBLE_REMOTE_TEMP=/tmp ANSIBLE_LOCAL_TEMP=/tmp ansible -i "127.0.0.1," -c local -v -m wait_for -a "host=$DATABASE_HOST port=$DATABASE_PORT" all
ANSIBLE_REMOTE_TEMP=/tmp ANSIBLE_LOCAL_TEMP=/tmp ansible -i "127.0.0.1," -c local -v -m postgresql_db --become-user $DATABASE_USER -a "name=$DATABASE_NAME owner=$DATABASE_USER login_user=$DATABASE_USER login_host=$DATABASE_HOST login_password=$DATABASE_PASSWORD port=$DATABASE_PORT" all
awx-manage collectstatic --noinput --clear
unset $(cut -d = -f -1 /etc/tower/conf.d/environment.sh)
supervisord -c /etc/supervisord.conf
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
if [ `id -u` -ge 500 ]; then
echo "awx:x:`id -u`:`id -g`:,,,:/var/lib/awx:/bin/bash" >> /tmp/passwd
cat /tmp/passwd > /etc/passwd
rm /tmp/passwd
fi
if [ -n "${AWX_KUBE_DEVEL}" ]; then
pushd /awx_devel
make awx-link
popd
export SDB_NOTIFY_HOST=$(ip route | head -n1 | awk '{print $3}')
fi
source /etc/tower/conf.d/environment.sh
ANSIBLE_REMOTE_TEMP=/tmp ANSIBLE_LOCAL_TEMP=/tmp ansible -i "127.0.0.1," -c local -v -m wait_for -a "host=$DATABASE_HOST port=$DATABASE_PORT" all
ANSIBLE_REMOTE_TEMP=/tmp ANSIBLE_LOCAL_TEMP=/tmp ansible -i "127.0.0.1," -c local -v -m postgresql_db --become-user $DATABASE_USER -a "name=$DATABASE_NAME owner=$DATABASE_USER login_user=$DATABASE_USER login_host=$DATABASE_HOST login_password=$DATABASE_PASSWORD port=$DATABASE_PORT" all
if [ -z "$AWX_SKIP_MIGRATIONS" ]; then
echo "Running migrations..."
awx-manage migrate --noinput
fi
if [ -z "$AWX_SKIP_PROVISION_INSTANCE" ]; then
awx-manage provision_instance --hostname=$(hostname)
fi
if [ -z "$AWX_SKIP_REGISTERQUEUE" ]; then
awx-manage register_queue --queuename=tower --instance_percent=100
fi
if [ ! -z "$AWX_ADMIN_USER" ]&&[ ! -z "$AWX_ADMIN_PASSWORD" ]; then
echo "from django.contrib.auth.models import User; User.objects.create_superuser('$AWX_ADMIN_USER', 'root@localhost', '$AWX_ADMIN_PASSWORD')" | awx-manage shell
fi
echo 'from django.conf import settings; x = settings.AWX_TASK_ENV; x["HOME"] = "/var/lib/awx"; settings.AWX_TASK_ENV = x' | awx-manage shell
unset $(cut -d = -f -1 /etc/tower/conf.d/environment.sh)
supervisord -c /etc/supervisord_task.conf
@@ -0,0 +1,7 @@
$WorkDirectory /var/lib/awx/rsyslog
$MaxMessageSize 700000
$IncludeConfig /var/lib/awx/rsyslog/conf.d/*.conf
module(load="imuxsock" SysSock.Use="off")
input(type="imuxsock" Socket="/var/run/awx-rsyslog/rsyslog.sock" unlink="on")
template(name="awx" type="string" string="%msg%")
action(type="omfile" file="/dev/null")
@@ -0,0 +1,89 @@
# AWX settings file
import os
def get_secret():
if os.path.exists("/etc/tower/SECRET_KEY"):
return open('/etc/tower/SECRET_KEY', 'rb').read().strip()
ADMINS = ()
STATIC_ROOT = '/var/lib/awx/public/static'
PROJECTS_ROOT = '/var/lib/awx/projects'
AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/awx_ansible_collections'
JOBOUTPUT_ROOT = '/var/lib/awx/job_status'
SECRET_KEY = get_secret()
ALLOWED_HOSTS = ['*']
# Container environments don't like chroots
AWX_PROOT_ENABLED = False
CLUSTER_HOST_ID = "awx"
SYSTEM_UUID = '00000000-0000-0000-0000-000000000000'
CSRF_COOKIE_SECURE = False
SESSION_COOKIE_SECURE = False
###############################################################################
# EMAIL SETTINGS
###############################################################################
SERVER_EMAIL = 'root@localhost'
DEFAULT_FROM_EMAIL = 'webmaster@localhost'
EMAIL_SUBJECT_PREFIX = '[AWX] '
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
LOGGING['handlers']['console'] = {
'()': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'simple',
}
LOGGING['loggers']['django.request']['handlers'] = ['console']
LOGGING['loggers']['rest_framework.request']['handlers'] = ['console']
LOGGING['loggers']['awx']['handlers'] = ['console', 'external_logger']
LOGGING['loggers']['awx.main.commands.run_callback_receiver']['handlers'] = ['console']
LOGGING['loggers']['awx.main.tasks']['handlers'] = ['console', 'external_logger']
LOGGING['loggers']['awx.main.scheduler']['handlers'] = ['console', 'external_logger']
LOGGING['loggers']['django_auth_ldap']['handlers'] = ['console']
LOGGING['loggers']['social']['handlers'] = ['console']
LOGGING['loggers']['system_tracking_migrations']['handlers'] = ['console']
LOGGING['loggers']['rbac_migrations']['handlers'] = ['console']
LOGGING['loggers']['awx.isolated.manager.playbooks']['handlers'] = ['console']
LOGGING['handlers']['callback_receiver'] = {'class': 'logging.NullHandler'}
LOGGING['handlers']['task_system'] = {'class': 'logging.NullHandler'}
LOGGING['handlers']['tower_warnings'] = {'class': 'logging.NullHandler'}
LOGGING['handlers']['rbac_migrations'] = {'class': 'logging.NullHandler'}
LOGGING['handlers']['system_tracking_migrations'] = {'class': 'logging.NullHandler'}
LOGGING['handlers']['management_playbooks'] = {'class': 'logging.NullHandler'}
DATABASES = {
'default': {
'ATOMIC_REQUESTS': True,
'ENGINE': 'awx.main.db.profiled_pg',
'NAME': os.getenv("DATABASE_NAME", None),
'USER': os.getenv("DATABASE_USER", None),
'PASSWORD': os.getenv("DATABASE_PASSWORD", None),
'HOST': os.getenv("DATABASE_HOST", None),
'PORT': os.getenv("DATABASE_PORT", None),
}
}
if os.getenv("DATABASE_SSLMODE", False):
DATABASES['default']['OPTIONS'] = {'sslmode': os.getenv("DATABASE_SSLMODE")}
USE_X_FORWARDED_HOST = True
USE_X_FORWARDED_PORT = True
@@ -0,0 +1,19 @@
---
- name: Create _build directory
file:
path: "{{ dockerfile_dest }}/{{ template_dest }}"
state: directory
- name: Render supervisor configs
template:
src: "{{ item }}.j2"
dest: "{{ dockerfile_dest }}/{{ template_dest }}/{{ item }}"
with_items:
- "supervisor.conf"
- "supervisor_task.conf"
- name: Render Dockerfile
template:
src: Dockerfile.j2
dest: "{{ dockerfile_dest }}/{{ dockerfile_name }}"
@@ -0,0 +1,268 @@
### This file is generated from
### tools/ansible/roles/dockerfile/templates/Dockerfile.j2
###
### DO NOT EDIT
###
# Locations - set globally to be used across stages
ARG COLLECTION_BASE="/var/lib/awx/vendor/awx_ansible_collections"
# Build container
FROM centos:8 as builder
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
USER root
# Install build dependencies
RUN dnf -y module enable 'postgresql:12'
RUN dnf -y update && \
dnf -y install epel-release 'dnf-command(config-manager)' && \
dnf module -y enable 'postgresql:12' && \
dnf config-manager --set-enabled powertools && \
dnf -y install ansible \
gcc \
gcc-c++ \
git-core \
glibc-langpack-en \
libcurl-devel \
libffi-devel \
libtool-ltdl-devel \
make \
nodejs \
nss \
openldap-devel \
patch \
@postgresql:12 \
postgresql-devel \
python3-devel \
python3-pip \
python3-psycopg2 \
python3-setuptools \
swig \
unzip \
xmlsec1-devel \
xmlsec1-openssl-devel
RUN python3 -m ensurepip && pip3 install "virtualenv < 20"
# Install & build requirements
ADD Makefile /tmp/Makefile
RUN mkdir /tmp/requirements
ADD requirements/requirements_ansible.txt \
requirements/requirements_ansible_uninstall.txt \
requirements/requirements_ansible_git.txt \
requirements/requirements.txt \
requirements/requirements_tower_uninstall.txt \
requirements/requirements_git.txt \
requirements/collections_requirements.yml \
/tmp/requirements/
RUN cd /tmp && make requirements_awx requirements_ansible_py3
RUN cd /tmp && make requirements_collections
{% if (build_dev|bool) or (kube_dev|bool) %}
ADD requirements/requirements_dev.txt /tmp/requirements
RUN cd /tmp && make requirements_awx_dev requirements_ansible_dev
{% else %}
# Use the distro provided npm to bootstrap our required version of node
RUN npm install -g n && n 14.15.1 && dnf remove -y nodejs
# Copy source into builder, build sdist, install it into awx venv
COPY . /tmp/src/
WORKDIR /tmp/src/
RUN make sdist && \
/var/lib/awx/venv/awx/bin/pip install dist/awx-$(cat VERSION).tar.gz
{% endif %}
# Final container(s)
FROM centos:8
ARG COLLECTION_BASE
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
USER root
# Install runtime requirements
RUN dnf -y module enable 'postgresql:12'
RUN dnf -y update && \
dnf -y install epel-release 'dnf-command(config-manager)' && \
dnf module -y enable 'postgresql:12' && \
dnf config-manager --set-enabled powertools && \
dnf -y install acl \
ansible \
bubblewrap \
git-core \
git-lfs \
glibc-langpack-en \
krb5-workstation \
libcgroup-tools \
nginx \
@postgresql:12 \
python3-devel \
python3-libselinux \
python3-pip \
python3-psycopg2 \
python3-setuptools \
rsync \
subversion \
sudo \
vim-minimal \
which \
unzip \
xmlsec1-openssl && \
dnf -y install centos-release-stream && dnf -y install "rsyslog >= 8.1911.0" && dnf -y remove centos-release-stream && \
dnf -y clean all
# Install kubectl
RUN curl -L -o /usr/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v1.17.8/bin/linux/{{ kubectl_architecture | default('amd64') }}/kubectl && \
chmod a+x /usr/bin/kubectl
RUN curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 && \
chmod 700 get_helm.sh && \
./get_helm.sh
# Install tini
RUN curl -L -o /usr/bin/tini https://github.com/krallin/tini/releases/download/v0.19.0/tini-{{ tini_architecture | default('amd64') }} && \
chmod +x /usr/bin/tini
RUN python3 -m ensurepip && pip3 install "virtualenv < 20" supervisor {% if build_dev|bool %}flake8{% endif %}
RUN rm -rf /root/.cache && rm -rf /tmp/*
# Install OpenShift CLI
RUN cd /usr/local/bin && \
curl -L https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit.tar.gz | \
tar -xz --strip-components=1 --wildcards --no-anchored 'oc'
{% if (build_dev|bool) or (kube_dev|bool) %}
# Install development/test requirements
RUN dnf -y install \
gdb \
gtk3 \
gettext \
alsa-lib \
libX11-xcb \
libXScrnSaver \
strace \
vim \
nmap-ncat \
nodejs \
nss \
make \
patch \
socat \
tmux \
wget \
diffutils \
unzip && \
npm install -g n && n 14.15.1 && dnf remove -y nodejs
# This package randomly fails to download.
# It is nice to have in the dev env, but not necessary.
# Add it back to the list above if the repo ever straighten up.
RUN dnf --enablerepo=debuginfo -y install python3-debuginfo || :
{% endif %}
# Copy app from builder
COPY --from=builder /var/lib/awx /var/lib/awx
RUN ln -s /var/lib/awx/venv/awx/bin/awx-manage /usr/bin/awx-manage
{%if build_dev|bool %}
RUN openssl req -nodes -newkey rsa:2048 -keyout /etc/nginx/nginx.key -out /etc/nginx/nginx.csr \
-subj "/C=US/ST=North Carolina/L=Durham/O=Ansible/OU=AWX Development/CN=awx.localhost" && \
openssl x509 -req -days 365 -in /etc/nginx/nginx.csr -signkey /etc/nginx/nginx.key -out /etc/nginx/nginx.crt && \
chmod 640 /etc/nginx/nginx.{csr,key,crt}
{% endif %}
# Create default awx rsyslog config
ADD tools/ansible/roles/dockerfile/files/rsyslog.conf /var/lib/awx/rsyslog/rsyslog.conf
## File mappings
{% if build_dev|bool %}
ADD tools/docker-compose/launch_awx.sh /usr/bin/launch_awx.sh
ADD tools/docker-compose/nginx.conf /etc/nginx/nginx.conf
ADD tools/docker-compose/nginx.vh.default.conf /etc/nginx/conf.d/nginx.vh.default.conf
ADD tools/docker-compose/start_tests.sh /start_tests.sh
ADD tools/docker-compose/bootstrap_development.sh /usr/bin/bootstrap_development.sh
ADD tools/docker-compose/entrypoint.sh /entrypoint.sh
{% else %}
ADD tools/ansible/roles/dockerfile/files/launch_awx.sh /usr/bin/launch_awx.sh
ADD tools/ansible/roles/dockerfile/files/launch_awx_task.sh /usr/bin/launch_awx_task.sh
ADD tools/ansible/roles/dockerfile/files/settings.py /etc/tower/settings.py
ADD {{ template_dest }}/supervisor.conf /etc/supervisord.conf
ADD {{ template_dest }}/supervisor_task.conf /etc/supervisord_task.conf
ADD tools/scripts/config-watcher /usr/bin/config-watcher
{% endif %}
{% if (build_dev|bool) or (kube_dev|bool) %}
ADD tools/docker-compose/awx.egg-link /tmp/awx.egg-link
ADD tools/docker-compose/awx-manage /usr/local/bin/awx-manage
ADD tools/scripts/awx-python /usr/bin/awx-python
{% endif %}
# Pre-create things we need to access
RUN for dir in \
/var/lib/awx \
/var/lib/awx/rsyslog \
/var/lib/awx/rsyslog/conf.d \
/var/run/awx-rsyslog \
/var/log/tower \
/var/log/nginx \
/var/lib/postgresql \
/var/run/supervisor \
/var/lib/nginx ; \
do mkdir -m 0775 -p $dir ; chmod g+rw $dir ; chgrp root $dir ; done && \
for file in \
/etc/passwd \
/var/lib/awx/rsyslog/rsyslog.conf ; \
do touch $file ; chmod g+rw $file ; chgrp root $file ; done
# Adjust any remaining permissions
RUN chmod u+s /usr/bin/bwrap ; \
chgrp -R root ${COLLECTION_BASE} ; \
chmod -R g+rw ${COLLECTION_BASE}
{% if (build_dev|bool) or (kube_dev|bool) %}
RUN for dir in \
/var/lib/awx/venv \
/var/lib/awx/venv/awx/lib/python3.6 \
/var/lib/awx/projects \
/var/lib/awx/rsyslog \
/var/run/awx-rsyslog \
/.ansible \
/var/lib/awx/vendor ; \
do mkdir -m 0775 -p $dir ; chmod g+rw $dir ; chgrp root $dir ; done && \
for file in \
/var/run/nginx.pid \
/var/lib/awx/venv/awx/lib/python3.6/site-packages/awx.egg-link ; \
do touch $file ; chmod g+rw $file ; done
{% endif %}
{% if not build_dev|bool %}
RUN ln -sf /dev/stdout /var/log/nginx/access.log && \
ln -sf /dev/stderr /var/log/nginx/error.log
{% endif %}
ENV HOME="/var/lib/awx"
ENV PATH="/usr/pgsql-10/bin:${PATH}"
{% if build_dev|bool %}
EXPOSE 8043 8013 8080 22
ENTRYPOINT ["/entrypoint.sh"]
CMD ["/bin/bash"]
{% else %}
USER 1000
EXPOSE 8052
ENTRYPOINT ["/usr/bin/tini", "--"]
CMD /usr/bin/launch_awx.sh
VOLUME /var/lib/nginx
{% endif %}
@@ -0,0 +1,117 @@
[supervisord]
nodaemon = True
umask = 022
logfile = /dev/stdout
logfile_maxbytes = 0
pidfile = /var/run/supervisor/supervisor.web.pid
[program:nginx]
{% if kube_dev | bool %}
command = make nginx
directory = /awx_devel
{% else %}
command = nginx -g "daemon off;"
{% endif %}
autostart = true
autorestart = true
stopwaitsecs = 5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:uwsgi]
{% if kube_dev | bool %}
command = make uwsgi
directory = /awx_devel
environment =
UWSGI_DEV_RELOAD_COMMAND='supervisorctl -c /etc/supervisord_task.conf restart all; supervisorctl restart tower-processes:daphne tower-processes:wsbroadcast'
{% else %}
command = /var/lib/awx/venv/awx/bin/uwsgi --socket 127.0.0.1:8050 --module=awx.wsgi:application --vacuum --processes=5 --harakiri=120 --no-orphans --master --max-requests=1000 --master-fifo=/var/lib/awx/awxfifo --lazy-apps -b 32768
directory = /var/lib/awx
{% endif %}
autostart = true
autorestart = true
stopwaitsecs = 15
stopasgroup=true
killasgroup=true
stopsignal=KILL
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:daphne]
{% if kube_dev | bool %}
command = make daphne
directory = /awx_devel
{% else %}
command = /var/lib/awx/venv/awx/bin/daphne -b 127.0.0.1 -p 8051 --websocket_timeout -1 awx.asgi:channel_layer
directory = /var/lib/awx
{% endif %}
autostart = true
stopsignal=KILL
autorestart = true
stopwaitsecs = 5
stopasgroup=true
killasgroup=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:wsbroadcast]
{% if kube_dev | bool %}
command = make wsbroadcast
directory = /awx_devel
{% else %}
command = awx-manage run_wsbroadcast
directory = /var/lib/awx
{% endif %}
autostart = true
autorestart = true
stopwaitsecs = 5
stopasgroup=true
killasgroup=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:awx-rsyslogd]
command = rsyslogd -n -i /var/run/awx-rsyslog/rsyslog.pid -f /var/lib/awx/rsyslog/rsyslog.conf
autostart = true
autorestart = true
startretries = 10
stopwaitsecs = 5
stopsignal=TERM
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/dev/stderr
stdout_logfile_maxbytes=0
[group:tower-processes]
programs=nginx,uwsgi,daphne,wsbroadcast,awx-rsyslogd
priority=5
# TODO: Exit Handler
[eventlistener:awx-config-watcher]
command=/usr/bin/config-watcher
stderr_logfile=/dev/stdout
stderr_logfile_maxbytes=0
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
events=TICK_60
priority=0
[unix_http_server]
file=/var/run/supervisor/supervisor.web.sock
[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.web.sock ; use a unix:// URL for a unix socket
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
@@ -0,0 +1,62 @@
[supervisord]
nodaemon = True
umask = 022
logfile = /dev/stdout
logfile_maxbytes = 0
pidfile = /var/run/supervisor/supervisor.pid
[program:dispatcher]
{% if kube_dev | bool %}
command = make dispatcher
directory = /awx_devel
{% else %}
command = awx-manage run_dispatcher
directory = /var/lib/awx
{% endif %}
autostart = true
autorestart = true
stopwaitsecs = 5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:callback-receiver]
{% if kube_dev | bool %}
command = make receiver
directory = /awx_devel
{% else %}
command = awx-manage run_callback_receiver
directory = /var/lib/awx
{% endif %}
autostart = true
autorestart = true
stopwaitsecs = 5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[group:tower-processes]
programs=dispatcher,callback-receiver
priority=5
# TODO: Exit Handler
[eventlistener:awx-config-watcher]
command=/usr/bin/config-watcher
stderr_logfile=/dev/stdout
stderr_logfile_maxbytes=0
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
events=TICK_60
priority=0
[unix_http_server]
file=/var/run/supervisor/supervisor.sock
[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock ; use a unix:// URL for a unix socket
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
@@ -0,0 +1,6 @@
---
create_preload_data: true
# Helper vars to construct the proper download URL for the current architecture
tini_architecture: '{{ { "x86_64": "amd64", "aarch64": "arm64", "armv7": "arm" }[ansible_facts.architecture] }}'
kubectl_architecture: '{{ { "x86_64": "amd64", "aarch64": "arm64", "armv7": "arm" }[ansible_facts.architecture] }}'
@@ -0,0 +1,31 @@
---
- name: Set global version if not provided
set_fact:
awx_version: "{{ lookup('file', playbook_dir + '/../../VERSION') }}"
when: awx_version is not defined
- name: Verify awx-logos directory exists for official install
stat:
path: "../../awx-logos"
register: logosdir
failed_when: logosdir.stat.isdir is not defined or not logosdir.stat.isdir
when: awx_official|default(false)|bool
- name: Copy logos for inclusion in sdist
copy:
src: "../../awx-logos/awx/ui/client/assets/"
dest: "../awx/ui_next/public/static/media/"
when: awx_official|default(false)|bool
- name: Set awx image name
set_fact:
awx_image: "{{ awx_image|default('awx') }}"
# Calling Docker directly because docker-py doesnt support BuildKit
- name: Build AWX image
command: docker build -t {{ awx_image }}:{{ awx_version }} -f ../../{{ dockerfile_name }} ../..
- name: Tag awx images as latest
command: "docker tag {{ item }}:{{ awx_version }} {{ item }}:latest"
with_items:
- "{{ awx_image }}"
@@ -0,0 +1,33 @@
---
- name: Authenticate with Docker registry if registry password given
docker_login:
registry: "{{ docker_registry }}"
username: "{{ docker_registry_username }}"
password: "{{ docker_registry_password }}"
reauthorize: true
when: docker_registry is defined and docker_registry_password is defined
- name: Remove local images to ensure proper push behavior
block:
- name: Remove awx image
docker_image:
name: "{{ docker_registry }}/{{ docker_registry_repository }}/{{ awx_image }}"
tag: "{{ awx_version }}"
state: absent
- name: Tag and Push Container Images
block:
- name: Tag and push awx image to registry
docker_image:
name: "{{ awx_image }}"
repository: "{{ docker_registry }}/{{ docker_registry_repository }}/{{ awx_image }}"
tag: "{{ item }}"
push: true
with_items:
- "latest"
- "{{ awx_version }}"
- name: Set full image path for Registry
set_fact:
awx_docker_actual_image: >-
{{ docker_registry }}/{{ docker_registry_repository }}/{{ awx_image }}:{{ awx_version }}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
echo "---------- requirements.txt --------------"
for each in `cat requirements/requirements.txt| awk -F= '{print $1}' | tr -d "[]"`
do
if [ ! -f docs/licenses/$each.txt ]; then
echo No license for $each
fi
done
echo "---------- end requirements.txt --------------"
echo "---------- requirements_ansible.txt --------------"
for each in `cat requirements/requirements_ansible.txt| awk -F= '{print $1}' | tr -d "[]"`
do
if [ ! -f docs/licenses/$each.txt ]; then
echo No license for $each
fi
done
echo "---------- end requirements_ansible.txt --------------"
+15
View File
@@ -0,0 +1,15 @@
resource small medium Jan2017 jobs1k jobs10k jobs50k jobs100k jobs200k e2e
organizations 50 500 1 1 1 1 1 1 110
users 500 5000 3 3 3 3 3 3 110
teams 200 500 2 2 2 2 2 2 100
projects 150 1000 30 30 30 30 30 30 110
job_templates 300 2000 127 127 127 127 127 127 110
credentials 150 2000 50 50 50 50 50 50 110
inventories 150 2000 6 6 6 6 6 6 110
inventory_groups 700 500 15 15 15 15 15 15 110
inventory_hosts 1100 2500 15 15 15 15 15 15 110
wfjts 50 100 0 0 0 0 0 0 0
nodes 1000 1000 0 0 0 0 0 0 0
labels 1000 1000 0 0 0 0 0 0 0
jobs 2000 5000 157208 1000 10000 50000 100000 200000 1000
job_events 40000 100000 3370942 20000 200000 1000000 2000000 4000000 20000
1 resource small medium Jan2017 jobs1k jobs10k jobs50k jobs100k jobs200k e2e
2 organizations 50 500 1 1 1 1 1 1 110
3 users 500 5000 3 3 3 3 3 3 110
4 teams 200 500 2 2 2 2 2 2 100
5 projects 150 1000 30 30 30 30 30 30 110
6 job_templates 300 2000 127 127 127 127 127 127 110
7 credentials 150 2000 50 50 50 50 50 50 110
8 inventories 150 2000 6 6 6 6 6 6 110
9 inventory_groups 700 500 15 15 15 15 15 15 110
10 inventory_hosts 1100 2500 15 15 15 15 15 15 110
11 wfjts 50 100 0 0 0 0 0 0 0
12 nodes 1000 1000 0 0 0 0 0 0 0
13 labels 1000 1000 0 0 0 0 0 0 0
14 jobs 2000 5000 157208 1000 10000 50000 100000 200000 1000
15 job_events 40000 100000 3370942 20000 200000 1000000 2000000 4000000 20000
+734
View File
@@ -0,0 +1,734 @@
#!/usr/bin/env python
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved
import os
import sys
# Python
from collections import defaultdict
from optparse import make_option, OptionParser
from datetime import datetime
import logging
# Django
import django
from django.utils.timezone import now
base_dir = os.path.abspath( # Convert into absolute path string
os.path.join( # Current file's grandparent directory
os.path.join( # Current file's parent directory
os.path.dirname( # Current file's directory
os.path.abspath(__file__) # Current file path
),
os.pardir
),
os.pardir
)
)
if base_dir not in sys.path:
sys.path.insert(1, base_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "awx.settings.development") # noqa
django.setup() # noqa
from django.db import transaction # noqa
# awx
from awx.main.models import ( # noqa
Credential, CredentialType, Group, Host, Inventory, Job, JobEvent,
JobHostSummary, JobTemplate, Label, Organization, PrimordialModel, Project,
Team, User, WorkflowJobTemplate, WorkflowJobTemplateNode,
batch_role_ancestor_rebuilding,
)
from awx.main.signals import ( # noqa
disable_activity_stream,
disable_computed_fields
)
option_list = [
make_option('--organizations', action='store', type='int', default=3,
help='Number of organizations to create'),
make_option('--users', action='store', type='int', default=10,
help='Number of users to create'),
make_option('--teams', action='store', type='int', default=5,
help='Number of teams to create'),
make_option('--projects', action='store', type='int', default=10,
help='Number of projects to create'),
make_option('--job-templates', action='store', type='int', default=20,
help='Number of job templates to create'),
make_option('--credentials', action='store', type='int', default=5,
help='Number of credentials to create'),
make_option('--inventories', action='store', type='int', default=5,
help='Number of credentials to create'),
make_option('--inventory-groups', action='store', type='int', default=10,
help='Number of credentials to create'),
make_option('--inventory-hosts', action='store', type='int', default=40,
help='number of credentials to create'),
make_option('--wfjts', action='store', type='int', default=15,
help='number of workflow job templates to create'),
make_option('--nodes', action='store', type='int', default=200,
help='number of workflow job template nodes to create'),
make_option('--labels', action='store', type='int', default=100,
help='labels to create, will associate 10x as many'),
make_option('--jobs', action='store', type='int', default=200,
help='number of job entries to create'),
make_option('--job-events', action='store', type='int', default=500,
help='number of job event entries to create'),
make_option('--pretend', action='store_true',
help="Don't commit the data to the database"),
make_option('--preset', action='store', type='string', default='',
help="Preset data set to use"),
make_option('--prefix', action='store', type='string', default='',
help="Prefix generated names with this string"),
#make_option('--spread-bias', action='store', type='string', default='exponential',
# help='"exponential" to bias associations exponentially front loaded for - for ex'),
]
parser = OptionParser(option_list=option_list)
options, remainder = parser.parse_args()
options = vars(options)
if options['preset']:
print(' Using preset data numbers set ' + str(options['preset']))
# Read the numbers of resources from presets file, if provided
presets_filename = os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'presets.tsv'))
with open(presets_filename) as f:
text = f.read()
split_lines = [line.split('\t') for line in text.split('\n')]
keys = split_lines[0][1:]
try:
col = keys.index(options['preset'])
except ValueError:
raise Exception('Preset "%s" dataset not found, options are %s' % (options['preset'], keys))
options.update({cols[0]: cols[col + 1] for cols in split_lines})
if not options['prefix']:
options['prefix'] = options['preset']
n_organizations = int(options['organizations'])
n_users = int(options['users'])
n_teams = int(options['teams'])
n_projects = int(options['projects'])
n_job_templates = int(options['job_templates'])
n_credentials = int(options['credentials'])
n_inventories = int(options['inventories'])
n_inventory_groups = int(options['inventory_groups'])
n_inventory_hosts = int(options['inventory_hosts'])
n_wfjts = int(options['wfjts'])
n_nodes = int(options['nodes'])
n_labels = int(options['labels'])
n_jobs = int(options['jobs'])
n_job_events = int(options['job_events'])
prefix = options['prefix']
organizations = []
users = []
teams = []
projects = []
job_templates = []
credentials = []
inventories = []
inventory_groups = []
inventory_hosts = []
wfjts = []
nodes = []
labels = []
jobs = []
#job_events = []
def spread(n, m):
ret = []
# At least one in each slot, split up the rest exponentially so the first
# buckets contain a lot of entries
for i in range(m):
if n > 0:
ret.append(1)
n -= 1
else:
ret.append(0)
for i in range(m):
n_in_this_slot = n // 2
n-= n_in_this_slot
ret[i] += n_in_this_slot
if n > 0 and len(ret):
ret[0] += n
return ret
ids = defaultdict(lambda: 0)
bulk_data_description = 'From Tower bulk-data script'
# function to cycle through a list
def yield_choice(alist):
ix = 0
while True:
yield alist[ix]
ix += 1
if ix >= len(alist):
ix = 0
class Rollback(Exception):
pass
# Normally the modified_by field is populated by the crum library automatically,
# but since this is ran outside the request-response cycle that won't work.
# It is disaled here.
def mock_save(self, *args, **kwargs):
return super(PrimordialModel, self).save(*args, **kwargs)
def mock_update(self):
return
def mock_computed_fields(self, **kwargs):
pass
PrimordialModel.save = mock_save
Project.update = mock_update
startTime = datetime.now()
def make_the_data():
with disable_activity_stream():
with batch_role_ancestor_rebuilding(), disable_computed_fields():
admin, created = User.objects.get_or_create(username = 'admin', is_superuser=True)
if created:
admin.is_superuser = True
admin.save()
admin.set_password('test')
admin.save()
org_admin, created = User.objects.get_or_create(username = 'org_admin')
if created:
org_admin.set_password('test')
org_admin.save()
org_member, created = User.objects.get_or_create(username = 'org_member')
if created:
org_member.set_password('test')
org_member.save()
prj_admin, created = User.objects.get_or_create(username = 'prj_admin')
if created:
prj_admin.set_password('test')
prj_admin.save()
jt_admin, created = User.objects.get_or_create(username = 'jt_admin')
if created:
jt_admin.set_password('test')
jt_admin.save()
inv_admin, created = User.objects.get_or_create(username = 'inv_admin')
if created:
inv_admin.set_password('test')
inv_admin.save()
print('# Creating %d organizations' % n_organizations)
for i in range(n_organizations):
sys.stdout.write('\r%d ' % (i + 1))
sys.stdout.flush()
org, _ = Organization.objects.get_or_create(name='%s Organization %d' % (prefix, i))
organizations.append(org)
if i == 0:
org.admin_role.members.add(org_admin)
org.member_role.members.add(org_admin)
org.member_role.members.add(org_member)
org.member_role.members.add(prj_admin)
org.member_role.members.add(jt_admin)
org.member_role.members.add(inv_admin)
print('')
print('# Creating %d users' % n_users)
org_idx = 0
for n in spread(n_users, n_organizations):
for i in range(n):
ids['user'] += 1
user_id = ids['user']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, organizations[org_idx].name, i+ 1))
sys.stdout.flush()
user, _ = User.objects.get_or_create(username='%suser-%d' % (prefix, user_id))
organizations[org_idx].member_role.members.add(user)
users.append(user)
org_idx += 1
print('')
creator_gen = yield_choice(users)
for i in range(6):
next(creator_gen)
modifier_gen = yield_choice(users)
print('# Creating %d teams' % n_teams)
org_idx = 0
for n in spread(n_teams, n_organizations):
org = organizations[org_idx]
for i in range(n):
ids['team'] += 1
team_id = ids['team']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, org.name, i+ 1))
sys.stdout.flush()
team, _ = Team.objects.get_or_create(
name='%s Team %d Org %d' % (prefix, team_id, org_idx), organization=org,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen))
)
teams.append(team)
org_idx += 1
print('')
print('# Adding users to teams')
for org in organizations:
org_teams = [t for t in org.teams.all()]
org_users = [u for u in org.member_role.members.all()]
print(' Spreading %d users accross %d teams for %s' % (len(org_users), len(org_teams), org.name))
# Our normal spread for most users
cur_user_idx = 0
cur_team_idx = 0
for n in spread(len(org_users), len(org_teams)):
team = org_teams[cur_team_idx]
for i in range(n):
if cur_user_idx < len(org_users):
user = org_users[cur_user_idx]
team.member_role.members.add(user)
cur_user_idx += 1
cur_team_idx += 1
# First user gets added to all teams
for team in org_teams:
team.member_role.members.add(org_users[0])
print('# Creating %d credentials for users' % (n_credentials - n_credentials // 2))
user_idx = 0
for n in spread(n_credentials - n_credentials // 2, n_users):
user = users[user_idx]
for i in range(n):
ids['credential'] += 1
sys.stdout.write('\r %d ' % (ids['credential']))
sys.stdout.flush()
credential_id = ids['credential']
credential, _ = Credential.objects.get_or_create(
name='%s Credential %d User %d' % (prefix, credential_id, user_idx),
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen)),
credential_type=CredentialType.objects.filter(namespace='ssh').first()
)
credential.admin_role.members.add(user)
credentials.append(credential)
user_idx += 1
print('')
credential_gen = yield_choice(credentials)
print('# Creating %d credentials for teams' % (n_credentials // 2))
team_idx = 0
starting_credential_id = ids['credential']
for n in spread(n_credentials - n_credentials // 2, n_teams):
team = teams[team_idx]
for i in range(n):
ids['credential'] += 1
sys.stdout.write('\r %d ' % (ids['credential'] - starting_credential_id))
sys.stdout.flush()
credential_id = ids['credential']
credential, _ = Credential.objects.get_or_create(
name='%s Credential %d team %d' % (prefix, credential_id, team_idx),
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen)),
credential_type=CredentialType.objects.filter(namespace='ssh').first()
)
credential.admin_role.parents.add(team.member_role)
credentials.append(credential)
team_idx += 1
print('')
print('# Creating %d projects' % n_projects)
org_idx = 0
for n in spread(n_projects, n_organizations):
org = organizations[org_idx]
for i in range(n):
ids['project'] += 1
project_id = ids['project']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, org.name, i+ 1))
sys.stdout.flush()
project, _ = Project.objects.get_or_create(
name='%s Project %d Org %d' % (prefix, project_id, org_idx),
organization=org,
defaults=dict(
created_by=next(creator_gen), modified_by=next(modifier_gen),
scm_url='https://github.com/ansible/test-playbooks.git',
scm_type='git',
playbook_files=[
"check.yml", "debug-50.yml", "debug.yml", "debug2.yml",
"debug_extra_vars.yml", "dynamic_inventory.yml",
"environ_test.yml", "fail_unless.yml", "pass_unless.yml",
"pause.yml", "ping-20.yml", "ping.yml",
"setfact_50.yml", "vault.yml"
])
)
projects.append(project)
if org_idx == 0 and i == 0:
project.admin_role.members.add(prj_admin)
org_idx += 1
print('')
print('# Creating %d inventories' % n_inventories)
org_idx = 0
for n in spread(n_inventories, min(n_inventories // 4 + 1, n_organizations)):
org = organizations[org_idx]
for i in range(n):
ids['inventory'] += 1
inventory_id = ids['inventory']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, org.name, i+ 1))
sys.stdout.flush()
inventory, _ = Inventory.objects.get_or_create(
name='%s Inventory %d Org %d' % (prefix, inventory_id, org_idx),
organization=org,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen)),
variables='{"ansible_connection": "local"}'
)
inventories.append(inventory)
if org_idx == 0 and i == 0:
inventory.admin_role.members.add(inv_admin)
org_idx += 1
print('')
print('# Creating %d inventory_groups' % n_inventory_groups)
inv_idx = 0
for n in spread(n_inventory_groups, n_inventories):
inventory = inventories[inv_idx]
parent_list = [None] * 3
for i in range(n):
ids['group'] += 1
group_id = ids['group']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, inventory.name, i+ 1))
sys.stdout.flush()
group, _ = Group.objects.get_or_create(
name='%s Group %d Inventory %d' % (prefix, group_id, inv_idx),
inventory=inventory,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen))
)
# Have each group have up to 3 parent groups
for parent_n in range(3):
if i // 4 + parent_n < len(parent_list) and parent_list[i // 4 + parent_n]:
group.parents.add(parent_list[i // 4 + parent_n])
if parent_list[i // 4] is None:
parent_list[i // 4] = group
else:
parent_list.append(group)
inventory_groups.append(group)
inv_idx += 1
print('')
print('# Creating %d inventory_hosts' % n_inventory_hosts)
group_idx = 0
for n in spread(n_inventory_hosts, n_inventory_groups):
group = inventory_groups[group_idx]
for i in range(n):
ids['host'] += 1
host_id = ids['host']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, group.name, i+ 1))
sys.stdout.flush()
host, _ = Host.objects.get_or_create(
name='%s.host-%06d.group-%05d.dummy' % (prefix, host_id, group_idx),
inventory=group.inventory,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen))
)
# Add the host to up to 3 groups
host.groups.add(group)
for m in range(2):
if group_idx + m < len(inventory_groups) and group.inventory.id == inventory_groups[group_idx + m].inventory.id:
host.groups.add(inventory_groups[group_idx + m])
inventory_hosts.append(host)
group_idx += 1
print('')
print('# Creating %d job_templates' % n_job_templates)
project_idx = 0
inv_idx = 0
for n in spread(n_job_templates, n_projects):
project = projects[project_idx]
for i in range(n):
ids['job_template'] += 1
job_template_id = ids['job_template']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, project.name, i+ 1))
sys.stdout.flush()
inventory = None
org_inv_count = project.organization.inventories.count()
if org_inv_count > 0:
inventory = project.organization.inventories.all()[inv_idx % org_inv_count]
extra_kwargs = {}
job_template, _ = JobTemplate.objects.get_or_create(
name='%s Job Template %d Project %d' % (prefix, job_template_id, project_idx),
defaults=dict(
inventory=inventory,
project=project,
created_by=next(creator_gen),
modified_by=next(modifier_gen),
playbook="debug.yml",
**extra_kwargs)
)
job_template.credentials.add(next(credential_gen))
if ids['job_template'] % 7 == 0:
job_template.credentials.add(next(credential_gen))
if ids['job_template'] % 5 == 0: # formerly cloud credential
job_template.credentials.add(next(credential_gen))
job_template._is_new = _
job_templates.append(job_template)
inv_idx += 1
if project_idx == 0 and i == 0:
job_template.admin_role.members.add(jt_admin)
project_idx += 1
if n > 0:
print('')
print('# Creating %d Workflow Job Templates' % n_wfjts)
org_idx = 0
for n in spread(n_wfjts, n_organizations):
org = organizations[org_idx]
for i in range(n):
ids['wfjts'] += 1
wfjt_id = ids['wfjts']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, org.name, i+ 1))
sys.stdout.flush()
wfjt, _ = WorkflowJobTemplate.objects.get_or_create(
name='%s WFJT %d Org %d' % (prefix, wfjt_id, org_idx),
description=bulk_data_description,
organization=org,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen))
)
wfjt._is_new = _
wfjts.append(wfjt)
org_idx += 1
if n:
print('')
print('# Creating %d Workflow Job Template nodes' % n_nodes)
wfjt_idx = 0
for n in spread(n_nodes, n_wfjts):
wfjt = wfjts[wfjt_idx]
if not wfjt._is_new:
continue
jt_gen = yield_choice(job_templates)
inv_gen = yield_choice(inventories)
cred_gen = yield_choice(credentials)
parent_idx = 0
wfjt_nodes = []
for i in range(n):
ids['nodes'] += 1
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, wfjt.name, i+ 1))
sys.stdout.flush()
kwargs = dict(
workflow_job_template=wfjt,
unified_job_template=next(jt_gen),
modified=now()
)
if i % 2 == 0:
# only apply inventories for every other node
kwargs['inventory'] = next(inv_gen)
node, _ = WorkflowJobTemplateNode.objects.get_or_create(
**kwargs
)
if i % 3 == 0:
# only apply prompted credential every 3rd node
node.credentials.add(next(cred_gen))
# nodes.append(node)
wfjt_nodes.append(node)
if i <= 3:
continue
parent_node = wfjt_nodes[parent_idx]
if parent_node.workflow_job_template != node.workflow_job_template:
raise Exception("Programming error, associating nodes in different workflows")
elif parent_node == node:
raise Exception("error, self association")
if parent_idx % 2 == 0:
parent_node.always_nodes.add(node)
else:
if (i + 1) % 3 == 0:
parent_node.failure_nodes.add(node)
else:
parent_node.success_nodes.add(node)
parent_idx = (parent_idx + 7) % len(wfjt_nodes)
wfjt_idx += 1
if n:
print('')
print('# Creating %d Labels' % n_labels)
org_idx = 0
for n in spread(n_labels, n_organizations):
org = organizations[org_idx]
for i in range(n):
ids['labels'] += 1
label_id = ids['labels']
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, org.name, i + 1))
sys.stdout.flush()
label, _ = Label.objects.get_or_create(
name='%sL_%do%d' % (prefix, label_id, org_idx),
organization=org,
defaults=dict(created_by=next(creator_gen),
modified_by=next(modifier_gen))
)
labels.append(label)
org_idx += 1
if n:
print('')
label_gen = yield_choice(labels)
print('# Adding labels to job templates')
jt_idx = 0
for n in spread(n_labels * 7, n_job_templates):
if n == 0:
continue
jt = job_templates[jt_idx]
if not jt._is_new:
continue
print(' Giving %d labels to %s JT' % (n, jt.name))
for i in range(n):
jt.labels.add(next(label_gen))
jt_idx += 1
print('# Adding labels to workflow job templates')
wfjt_idx = 0
for n in spread(n_labels * 3, n_wfjts):
wfjt = wfjts[wfjt_idx]
if not jt._is_new:
continue
print(' Giving %d labels to %s WFJT' % (n, wfjt.name))
for i in range(n):
wfjt.labels.add(next(label_gen))
wfjt_idx += 1
# Disable logging here, because it will mess up output format
logger = logging.getLogger('awx.main')
logger.propagate = False
print('# Creating %d jobs' % n_jobs)
group_idx = 0
job_template_idx = 0
job_i = 0
for n in spread(n_jobs, n_job_templates):
job_template = job_templates[job_template_idx]
for i in range(n):
sys.stdout.write('\r Assigning %d to %s: %d ' % (n, job_template.name, i+ 1))
sys.stdout.flush()
if len(jobs) % 4 == 0:
job_stat = 'failed'
elif len(jobs) % 11 == 0:
job_stat = 'canceled'
else:
job_stat = 'successful'
job, _ = Job.objects.get_or_create(
job_template=job_template,
status=job_stat, name="%s-%d" % (job_template.name, job_i),
project=job_template.project, inventory=job_template.inventory,
)
for ec in job_template.credentials.all():
job.credentials.add(ec)
job._is_new = _
jobs.append(job)
job_i += 1
if not job._is_new:
group_idx += 1
continue
if i + 1 == n:
job_template.last_job = job
if job_template.pk % 5 == 0:
job_template.current_job = job
job_template.save()
if job._is_new:
with transaction.atomic():
if job_template.inventory:
inv_groups = [g for g in job_template.inventory.groups.all()]
if len(inv_groups):
JobHostSummary.objects.bulk_create([
JobHostSummary(
job=job, host=h, host_name=h.name, processed=1,
created=now(), modified=now()
)
for h in inv_groups[group_idx % len(inv_groups)].hosts.all()[:100]
])
group_idx += 1
job_template_idx += 1
if n:
print('')
print('# Creating %d job events' % n_job_events)
job_idx = 0
for n in spread(n_job_events, n_jobs):
job = jobs[job_idx]
# Check if job already has events, for idempotence
if not job._is_new:
continue
# Bulk create in chunks with maximum chunk size
MAX_BULK_CREATE = 100
for j in range((n // MAX_BULK_CREATE) + 1):
n_subgroup = MAX_BULK_CREATE
if j == n / MAX_BULK_CREATE:
# on final pass, create the remainder
n_subgroup = n % MAX_BULK_CREATE
sys.stdout.write('\r Creating %d job events for job %d, subgroup: %d' % (n, job.id, j + 1))
sys.stdout.flush()
JobEvent.objects.bulk_create([
JobEvent(
created=now(),
modified=now(),
job=job,
event='runner_on_ok'
)
for i in range(n_subgroup)
])
job_idx += 1
if n:
print('')
if options['pretend']:
with transaction.atomic():
try:
make_the_data()
raise Rollback()
except Rollback:
print('Rolled back changes')
pass
else:
make_the_data()
print('')
print('script execution time: {}'.format(datetime.now() - startTime))
+100
View File
@@ -0,0 +1,100 @@
---
version: '2'
services:
haproxy:
build:
context: ./docker-compose
dockerfile: Dockerfile-haproxy
container_name: tools_haproxy_1
depends_on:
- "awx-1"
- "awx-2"
- "awx-3"
ports:
- "8013:8013"
- "8043:8043"
- "1936:1936"
awx-1:
user: ${CURRENT_UID}
container_name: tools_awx_1_1
privileged: true
image: ${DEV_DOCKER_TAG_BASE}/awx_devel:${TAG}
hostname: awx-1
environment:
CURRENT_UID:
SDB_HOST: 0.0.0.0
SDB_PORT: 5899
AWX_GROUP_QUEUES: alpha,tower
command: launch_awx.sh
working_dir: "/awx_devel"
volumes:
- "../:/awx_devel"
- "./redis/redis_socket_ha_1:/var/run/redis/"
- "./docker-compose/supervisor.conf:/etc/supervisord.conf"
ports:
- "5899-5999:5899-5999"
awx-2:
user: ${CURRENT_UID}
container_name: tools_awx_2_1
privileged: true
image: ${DEV_DOCKER_TAG_BASE}/awx_devel:${TAG}
hostname: awx-2
command: launch_awx.sh
working_dir: "/awx_devel"
environment:
CURRENT_UID:
SDB_HOST: 0.0.0.0
SDB_PORT: 7899
AWX_GROUP_QUEUES: bravo,tower
volumes:
- "../:/awx_devel"
- "./redis/redis_socket_ha_2:/var/run/redis/"
- "./docker-compose/supervisor.conf:/etc/supervisord.conf"
ports:
- "7899-7999:7899-7999"
awx-3:
user: ${CURRENT_UID}
container_name: tools_awx_3_1
privileged: true
image: ${DEV_DOCKER_TAG_BASE}/awx_devel:${TAG}
hostname: awx-3
command: launch_awx.sh
working_dir: "/awx_devel"
environment:
CURRENT_UID:
SDB_HOST: 0.0.0.0
SDB_PORT: 8899
AWX_GROUP_QUEUES: charlie,tower
volumes:
- "../:/awx_devel"
- "./redis/redis_socket_ha_3:/var/run/redis/"
- "./docker-compose/supervisor.conf:/etc/supervisord.conf"
ports:
- "8899-8999:8899-8999"
redis_1:
user: ${CURRENT_UID}
image: redis:latest
container_name: tools_redis_1_1
command: ["/usr/local/etc/redis/redis.conf"]
volumes:
- "./redis/redis.conf:/usr/local/etc/redis/redis.conf"
- "./redis/redis_socket_ha_1:/var/run/redis/"
redis_2:
user: ${CURRENT_UID}
image: redis:latest
container_name: tools_redis_2_1
command: ["/usr/local/etc/redis/redis.conf"]
volumes:
- "./redis/redis.conf:/usr/local/etc/redis/redis.conf"
- "./redis/redis_socket_ha_2:/var/run/redis/"
redis_3:
user: ${CURRENT_UID}
image: redis:latest
container_name: tools_redis_3_1
command: ["/usr/local/etc/redis/redis.conf"]
volumes:
- "./redis/redis.conf:/usr/local/etc/redis/redis.conf"
- "./redis/redis_socket_ha_3:/var/run/redis/"
postgres:
image: postgres:12
container_name: tools_postgres_1
+2
View File
@@ -0,0 +1,2 @@
FROM haproxy:1.6-alpine
COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg
+5
View File
@@ -0,0 +1,5 @@
FROM logstash:5-alpine
COPY logstash.conf /
RUN touch /logstash.log
RUN chown logstash:logstash /logstash.log
CMD ["-f", "/logstash.conf"]
+172
View File
@@ -0,0 +1,172 @@
# Docker Compose for Development
## Overview
Here are the main make targets:
* `docker-compose-build` - used for building the development image, which is used by the `docker-compose` target
* `docker-compose` - make target for development, passes awx_devel image and tag
Notable files:
* `tools/docker-compose/inventory` file - used to configure the local AWX development deploymen
* `migrate.yml` - playbook for migrating data from Local Docker to the Development Environment
### Prerequisites
- [Docker](https://docs.docker.com/engine/installation/) on the host where AWX will be deployed. After installing Docker, the Docker service must be started (depending on your OS, you may have to add the local user that uses Docker to the ``docker`` group, refer to the documentation for details)
- [docker-compose](https://pypi.org/project/docker-compose/) Python module.
+ This also installs the `docker` Python module, which is incompatible with [`docker-py`](https://pypi.org/project/docker-py/). If you have previously installed `docker-py`, please uninstall it.
- [Docker Compose](https://docs.docker.com/compose/install/).
- [Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html) will need to be installed as we use it to template files needed for the docker-compose.
## Configuration
In the [`inventory` file](../inventory), set your `pg_password`, `broadcast_websocket_secret`, `secret_key`, and any other settings you need for your deployment.
AWX requires access to a PostgreSQL database, and by default, one will be created and deployed in a container, and data will be persisted to a docker volume. When the container is stopped, the database files will still exist in the docker volume. An external database can be used by setting the `pg_host`, `pg_hostname`, and `pg_username`.
> If you are coming from a Local Docker installation of AWX, consider migrating your data first, see the [data migration section](#migrating-data-from-local-docker) below.
## Starting the Development Environment
### Build the image
The AWX base container image (defined in the Dockerfile templated from [Dockerfile.j2](./../ansible/roles/dockerfile/templates/Dockerfile.j2)) contains basic OS dependencies and symbolic links into the development environment that make running the services easy.
Run the following to build the image:
```bash
$ make docker-compose-build
```
> The image will need to be rebuilt if there are any changes to Dockerfile.j2 or any of the files used by the templated Dockerfile.
Once the build completes, you will have a `ansible/awx_devel` image in your local image cache. Use the `docker images` command to view it, as follows:
```bash
(host)$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ansible/awx_devel latest ba9ec3e8df74 26 minutes ago 1.42GB
```
> By default, this image will be tagged with your branch name. You can specify a custom tag by setting an environment variable, for example: `DEVEL_IMAGE_NAME=quay.io/your_user/awx_devel:17.0.1`
### Run AWX
##### Start the containers
Run the awx, postgres and redis containers. This utilizes the image built in the previous step, and will automatically start all required services and dependent containers. Once the containers launch, your session will be attached to the awx container, and you'll be able to watch log messages and events in real time. You will see messages from Django and the front end build process.
```bash
$ make docker-compose
```
> The make target assumes that the image you built is tagged with your current branch. This allows you to build images for different contexts or branches. When starting the containers, you can choose a specific branch by setting `COMPOSE_TAG=<branch name> `in your environment. For example, you might be working in a feature branch, but you want to run the containers using the devel image you built previously. To do that, start the containers using the following command: `$ COMPOSE_TAG=devel make docker-compose`
##### Wait for migrations to complete
The first time you start the environment, database migrations need to run in order to build the PostgreSQL database. It will take few moments, but eventually you will see output in your terminal session that looks like the following:
```bash
awx_1 | Operations to perform:
awx_1 | Synchronize unmigrated apps: solo, api, staticfiles, debug_toolbar, messages, channels, django_extensions, ui, rest_framework, polymorphic
awx_1 | Apply all migrations: sso, taggit, sessions, sites, kombu_transport_django, social_auth, contenttypes, auth, conf, main
awx_1 | Synchronizing apps without migrations:
awx_1 | Creating tables...
awx_1 | Running deferred SQL...
awx_1 | Installing custom SQL...
awx_1 | Running migrations:
awx_1 | Rendering model states... DONE
awx_1 | Applying contenttypes.0001_initial... OK
awx_1 | Applying contenttypes.0002_remove_content_type_name... OK
awx_1 | Applying auth.0001_initial... OK
...
```
##### Clean and Build UI
```bash
$ docker exec tools_awx_1 make clean-ui ui-devel
```
See [the ui development documentation](../../awx/ui_next/README.md) for more information on using the frontend development, build, and test tooling.
Once migrations are completed and the UI is built, you can begin using AWX. The UI can be reached in your browser at `https://localhost:8043/#/home`, and the API can be found at `https://localhost:8043/api/v2`.
##### Create an admin user
Before you can log into AWX, you need to create an admin user. With this user you will be able to create more users, and begin configuring the server. From within the container shell, run the following command:
```bash
$ docker exec -ti tools_awx_1 awx-manage createsuperuser
```
> Remember the username and password, as you will use them to log into the web interface for the first time.
##### Load Demo Data
Optionally, you may also want to load some demo data. This will create a demo project, inventory, and job template.
```bash
$ docker exec tools_awx_1 awx-manage create_preload_data
```
> This information will persist in the database running in the `tools_postgres_1` container, until the container is removed. You may periodically need to recreate
this container, and thus the database, if the database schema changes in an upstream commit.
## Migrating Data from Local Docker
If you are migrating data from a Local Docker installation (17.0.1 and prior), you can
migrate your data to the development environment via the migrate.yml playbook using the steps described [here](./docs/data_migration.md).
## Upgrading the Development Environment
Upgrading AWX involves checking out the new source code and re-running the make target. Download a newer release from [https://github.com/ansible/awx/releases](https://github.com/ansible/awx/releases) and re-populate the inventory file with your customized variables.
After updating the inventory file with any custom values, run the make target from the root of your AWX clone.
```bash
$ make docker-compose
```
## Extras
* [Start a shell](#start-a-shell)
* [Start AWX from the container shell](#start-awx-from-the-container-shell)
* [Using Logstash](./docs/logstash.md)
### Start a Shell
To run `awx-manage` commands and modify things inside the container, you will want to start a shell session on the *awx* container. In a new terminal session, use the `docker exec` command to start the shell session:
```bash
(host)$ docker exec -it tools_awx_1 bash
```
This creates a session in the *awx* containers, just as if you were using `ssh`, and allows you execute commands within the running container.
### Start AWX from the container shell
Often times you'll want to start the development environment without immediately starting all of the services in the *awx* container, and instead be taken directly to a shell. You can do this with the following:
```bash
(host)$ make docker-compose-test
```
Using `docker exec`, this will create a session in the running *awx* container, and place you at a command prompt, where you can run shell commands inside the container.
If you want to start and use the development environment, you'll first need to bootstrap it by running the following command:
```bash
(container)# /usr/bin/bootstrap_development.sh
```
The above will do all the setup tasks, including running database migrations, so it may take a couple minutes. Once it's done it
will drop you back to the shell.
In order to launch all developer services:
```bash
(container)# /usr/bin/launch_awx.sh
```
`launch_awx.sh` also calls `bootstrap_development.sh` so if all you are doing is launching the supervisor to start all services, you don't
need to call `bootstrap_development.sh` first.
+7
View File
@@ -0,0 +1,7 @@
---
- name: Migrate data for upgrades and from Local Docker installs
hosts: localhost
gather_facts: true
roles:
- {role: sources}
- {role: migrate}
@@ -0,0 +1,5 @@
---
postgres_data_dir: "~/.awx/pgdocker"
migrate_local_docker: false
old_docker_compose_dir: "~/.awx/awxcompose"
pg_volume_name: "postgres_data"
@@ -0,0 +1,5 @@
---
# Migrate data from a bind-mount to a volume
- import_tasks: migrate-from-local-docker.yml
when: migrate_local_docker
@@ -0,0 +1,53 @@
---
# Migrate data from old Local Docker to a fresh development environment
- name: Remove awx_postgres to ensure consistent start state
shell: |
docker rm -f awx_postgres
ignore_errors: true
- name: Start Local Docker database container
docker_compose:
project_src: "{{ old_docker_compose_dir }}"
services:
- postgres
state: present
recreate: always
- name: Wait for postgres to initialize
wait_for:
timeout: 3
- name: Database dump to local filesystem
shell: |
docker-compose -f {{ old_docker_compose_dir }}/docker-compose.yml exec -T postgres pg_dumpall -U {{ pg_username }} > awx_dump.sql
- name: Stop AWX containers so the old postgres container does not get used
docker_compose:
project_src: "{{ old_docker_compose_dir }}"
state: absent
ignore_errors: true
- name: Start dev env database container
docker_compose:
project_src: "{{ playbook_dir }}/../_sources"
files: "docker-compose.yml"
services:
- postgres
state: present
recreate: always
environment:
COMPOSE_PROJECT_NAME: "tools"
- name: Wait for postgres to initialize
wait_for:
timeout: 3
- name: Restore to new postgres container
shell: |
COMPOSE_PROJECT_NAME=tools docker-compose -f {{ playbook_dir }}/../_sources/docker-compose.yml exec -T postgres psql -U {{ pg_username }} -d {{ pg_database }} -p {{ pg_port }} < awx_dump.sql
- name: Clean up temporary awx db dump
file:
path: awx_dump.sql
state: absent
@@ -0,0 +1,7 @@
---
sources_dest: '../_sources'
compose_name: 'docker-compose.yml'
awx_image: 'quay.io/ansible/awx_devel'
pg_port: 5432
pg_username: 'awx'
pg_database: 'awx'
@@ -0,0 +1,82 @@
---
- name: Create _sources directory
file:
path: "{{ sources_dest }}/secrets"
state: 'directory'
mode: '0700'
- name: Detect secrets
stat:
path: "{{ sources_dest }}/secrets/{{ item }}.yml"
register: secrets
when: not lookup('vars', item, default='')
loop:
- pg_password
- secret_key
- broadcast_websocket_secret
- name: Generate secrets if needed
template:
src: 'secrets.yml.j2'
dest: '{{ sources_dest }}/secrets/{{ item.item }}.yml'
mode: '0600'
when: not lookup('vars', item.item, default='') and not item.stat.exists
loop: "{{ secrets.results }}"
- name: Include generated secrets unless they are explicitly passed in
include_vars: "{{ sources_dest }}/secrets/{{ item.item }}.yml"
no_log: true
when: not lookup('vars', item.item, default='')
loop: "{{ secrets.results }}"
- name: Write out SECRET_KEY
copy:
content: "{{ secret_key }}"
dest: "{{ sources_dest }}/SECRET_KEY"
no_log: true
- name: Render configuration templates
template:
src: "{{ item }}.j2"
dest: "{{ sources_dest }}/{{ item }}"
mode: '0600'
with_items:
- "database.py"
- "websocket_secret.py"
- name: Delete old local_settings.py
file:
path: "{{ playbook_dir }}/../../../awx/settings/local_settings.py"
state: absent
- name: Copy local_settings.py
copy:
src: "local_settings.py"
dest: "{{ sources_dest }}/local_settings.py"
- name: Get OS info for sdb
shell: |
docker info | grep 'Operating System'
register: os_info
changed_when: false
- name: Get user UID
shell: id -u
register: current_user
changed_when: false
- name: Set fact with user UID
set_fact:
user_id: "'{{ current_user.stdout }}'"
- name: Set global version if not provided
set_fact:
awx_image_tag: "{{ lookup('file', playbook_dir + '/../../../VERSION') }}"
when: awx_image_tag is not defined
- name: Render Docker-Compose
template:
src: docker-compose.yml.j2
dest: "{{ sources_dest }}/{{ compose_name }}"
mode: '0600'
@@ -0,0 +1,11 @@
DATABASES = {
'default': {
'ATOMIC_REQUESTS': True,
'ENGINE': 'awx.main.db.profiled_pg',
'NAME': "{{ pg_database }}",
'USER': "{{ pg_username }}",
'PASSWORD': "{{ pg_password }}",
'HOST': "{{ pg_hostname | default('postgres') }}",
'PORT': "{{ pg_port }}",
}
}
@@ -0,0 +1,66 @@
---
version: '2'
services:
# Primary AWX Development Container
awx:
user: "{{ ansible_user_uid }}"
image: "{{ awx_image }}:{{ awx_image_tag }}"
container_name: tools_awx_1
hostname: awx
command: launch_awx.sh
environment:
OS: "{{ os_info.stdout }}"
SDB_HOST: 0.0.0.0
SDB_PORT: 7899
AWX_GROUP_QUEUES: tower
ports:
- "8888:8888"
- "8080:8080"
- "8013:8013"
- "8043:8043"
- "6899:6899" # default port range for sdb-listen
- "7899-7999:7899-7999" # default port range for sdb-listen
links:
- postgres
- redis
working_dir: "/awx_devel"
volumes:
- "../../../:/awx_devel"
- "../../docker-compose/supervisor.conf:/etc/supervisord.conf"
- "../../docker-compose/_sources/database.py:/etc/tower/conf.d/database.py"
- "../../docker-compose/_sources/websocket_secret.py:/etc/tower/conf.d/websocket_secret.py"
- "../../docker-compose/_sources/local_settings.py:/etc/tower/conf.d/local_settings.py"
- "../../docker-compose/_sources/SECRET_KEY:/etc/tower/SECRET_KEY"
- "redis_socket:/var/run/redis/:rw"
privileged: true
tty: true
# A useful container that simply passes through log messages to the console
# helpful for testing awx/tower logging
# logstash:
# build:
# context: ./docker-compose
# dockerfile: Dockerfile-logstash
# Postgres Database Container
postgres:
image: postgres:12
container_name: tools_postgres_1
environment:
POSTGRES_HOST_AUTH_METHOD: trust
POSTGRES_USER: {{ pg_username }}
POSTGRES_DB: {{ pg_database }}
POSTGRES_PASSWORD: {{ pg_password }}
volumes:
- "awx_db:/var/lib/postgresql/data"
redis:
image: redis:latest
container_name: tools_redis_1
volumes:
- "../../redis/redis.conf:/usr/local/etc/redis/redis.conf"
- "redis_socket:/var/run/redis/:rw"
entrypoint: ["redis-server"]
command: ["/usr/local/etc/redis/redis.conf"]
volumes:
awx_db:
redis_socket:
@@ -0,0 +1,10 @@
DATABASE_USER={{ pg_username|quote }}
DATABASE_NAME={{ pg_database|quote }}
DATABASE_HOST={{ pg_hostname|default('postgres')|quote }}
DATABASE_PORT={{ pg_port|default('5432')|quote }}
DATABASE_PASSWORD={{ pg_password|default('awxpass')|quote }}
{% if pg_admin_password is defined %}
DATABASE_ADMIN_PASSWORD={{ pg_admin_password|quote }}
{% endif %}
AWX_ADMIN_USER={{ admin_user|quote }}
AWX_ADMIN_PASSWORD={{ admin_password|quote }}
@@ -0,0 +1,122 @@
#user awx;
worker_processes 1;
pid /tmp/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server_tokens off;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /dev/stdout main;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
sendfile on;
#tcp_nopush on;
#gzip on;
upstream uwsgi {
server 127.0.0.1:8050;
}
upstream daphne {
server 127.0.0.1:8051;
}
{% if ssl_certificate is defined %}
server {
listen 8052 default_server;
server_name _;
# Redirect all HTTP links to the matching HTTPS page
return 301 https://$host$request_uri;
}
{%endif %}
server {
{% if (ssl_certificate is defined) and (ssl_certificate_key is defined) %}
listen 8053 ssl;
ssl_certificate /etc/nginx/awxweb.pem;
ssl_certificate_key /etc/nginx/awxweb_key.pem;
{% elif (ssl_certificate is defined) and (ssl_certificate_key is not defined) %}
listen 8053 ssl;
ssl_certificate /etc/nginx/awxweb.pem;
ssl_certificate_key /etc/nginx/awxweb.pem;
{% else %}
listen 8052 default_server;
{% endif %}
# If you have a domain name, this is where to add it
server_name _;
keepalive_timeout 65;
# HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
add_header Strict-Transport-Security max-age=15768000;
# Protect against click-jacking https://www.owasp.org/index.php/Testing_for_Clickjacking_(OTG-CLIENT-009)
add_header X-Frame-Options "DENY";
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
location /static/ {
alias /var/lib/awx/public/static/;
}
location /favicon.ico { alias /var/lib/awx/public/static/favicon.ico; }
location /websocket {
# Pass request to the upstream alias
proxy_pass http://daphne;
# Require http version 1.1 to allow for upgrade requests
proxy_http_version 1.1;
# We want proxy_buffering off for proxying to websockets.
proxy_buffering off;
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if you use HTTPS:
proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client for the sake of redirects
proxy_set_header Host $http_host;
# We've set the Host header, so we don't need Nginx to muddle
# about with redirects
proxy_redirect off;
# Depending on the request value, set the Upgrade and
# connection headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
location / {
# Add trailing / if missing
rewrite ^(.*)$http_host(.*[^/])$ $1$http_host$2/ permanent;
uwsgi_read_timeout 120s;
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
{%- if extra_nginx_include is defined %}
include {{ extra_nginx_include }};
{%- endif %}
proxy_set_header X-Forwarded-Port 443;
uwsgi_param HTTP_X_FORWARDED_PORT 443;
}
}
}
@@ -0,0 +1 @@
{{ item.item }}: '{{ lookup('vars', item.item, default='') or lookup('password', '/dev/null chars=ascii_letters') }}'
@@ -0,0 +1 @@
BROADCAST_WEBSOCKET_SECRET = "{{ broadcast_websocket_secret | b64encode }}"
+6
View File
@@ -0,0 +1,6 @@
---
- name: Render AWX Dockerfile and sources
hosts: localhost
gather_facts: true
roles:
- {role: sources}
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/awx-python
# EASY-INSTALL-ENTRY-SCRIPT: 'awx','console_scripts','awx-manage'
import sys
from pkg_resources import load_entry_point
__requires__ = 'awx'
if __name__ == '__main__':
sys.exit(
load_entry_point('awx', 'console_scripts', 'awx-manage')()
)
+1
View File
@@ -0,0 +1 @@
/awx_devel
+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
set +x
# Wait for the databases to come up
ansible -i "127.0.0.1," -c local -v -m wait_for -a "host=postgres port=5432" all
ansible -i "127.0.0.1," -c local -v -m wait_for -a "path=/var/run/redis/redis.sock" all
# In case AWX in the container wants to connect to itself, use "docker exec" to attach to the container otherwise
# TODO: FIX
#/etc/init.d/ssh start
# Move to the source directory so we can bootstrap
if [ -f "/awx_devel/manage.py" ]; then
cd /awx_devel
else
echo "Failed to find awx source tree, map your development tree volume"
fi
make awx-link
# AWX bootstrapping
make version_file
make migrate
make init
mkdir -p /awx_devel/awx/public/static
mkdir -p /awx_devel/awx/ui/static
mkdir -p /awx_devel/awx/ui_next/build/static
@@ -0,0 +1,28 @@
# Migrating Data from Local Docker
If you are migrating data from a Local Docker installation (17.0.1 and prior), you can
migrate your data to the development environment via the migrate.yml playbook.
> Note: This will also convert your postgresql bind-mount into a docker volume.
### Migrate data with migrate.yml
First, in the [`inventory` file](../inventory), set your `pg_password`, `broadcast_websocket_secret`, `secret_key`, and any other settings you need for your deployment. **Make sure you use the same values from the `inventory` file in your existing pre-18.0.0 Docker deployment.**
If you used a custom pgdocker or awxcompose location, you will need to set the `postgres_data_dir` and `old_docker_compose_dir` variables.
1. Run the [migrate playbook](../ansible/migrate.yml) to migrate your data to the new postgresql container and convert the data directory to a volume mount.
```bash
$ ansible-playbook -i tools/docker-compose/inventory tools/docker-compose/ansible/migrate.yml -e "migrate_local_docker=true" -e "postgres_data_dir=~/.awx/pgdocker" -e "old_docker_compose_dir=~/.awx/awxcompose"
```
2. Change directory to the top of your awx checkout, and follow the [development environment installation instructions](../README.md) to start your containers:
```bash
$ make docker-compose-build
$ make docker-compose
$ docker exec tools_awx_1 make clean-ui ui-devel
```
3. After ensuring your data has been successfully migrated, you may delete your old data directory (typically stored at `~/.awx/pgdocker`).
4. Note that after migration, the development environment will be available at https://localhost:8043/ (not http://localhost).
+49
View File
@@ -0,0 +1,49 @@
# How to use the logstash container
#### Modify the docker-compose.yml
Uncomment the following lines in the `docker-compose.yml`
```
#- logstash
...
#logstash:
# build:
# context: ./docker-compose
# dockerfile: Dockerfile-logstash
```
POST the following content to `/api/v2/settings/logging/` (this uses
authentication set up inside of the logstash configuration file).
```
{
"LOG_AGGREGATOR_HOST": "http://logstash",
"LOG_AGGREGATOR_PORT": 8085,
"LOG_AGGREGATOR_TYPE": "logstash",
"LOG_AGGREGATOR_USERNAME": "awx_logger",
"LOG_AGGREGATOR_PASSWORD": "workflows",
"LOG_AGGREGATOR_LOGGERS": [
"awx",
"activity_stream",
"job_events",
"system_tracking"
],
"LOG_AGGREGATOR_INDIVIDUAL_FACTS": false,
"LOG_AGGREGATOR_TOWER_UUID": "991ac7e9-6d68-48c8-bbde-7ca1096653c6",
"LOG_AGGREGATOR_ENABLED": true
}
```
> Note: HTTP must be specified in the `LOG_AGGREGATOR_HOST` if you are using the docker development environment.
An example of how to view the most recent logs from the container:
```
docker exec -i -t $(docker ps -aqf "name=tools_logstash_1") tail -n 50 /logstash.log
```
#### How to add logstash plugins
Add any plugins you need in `tools/elastic/logstash/Dockerfile` before running the container.
+14
View File
@@ -0,0 +1,14 @@
#!/bin/bash
if [ `id -u` -ge 500 ] || [ -z "${CURRENT_UID}" ]; then
cat << EOF > /tmp/passwd
root:x:0:0:root:/root:/bin/bash
awx:x:`id -u`:`id -g`:,,,:/tmp:/bin/bash
EOF
cat /tmp/passwd > /etc/passwd
rm /tmp/passwd
fi
exec $@
+48
View File
@@ -0,0 +1,48 @@
global
debug
stats socket /tmp/admin.sock
stats timeout 30s
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000
timeout client 50000
timeout server 50000
frontend localnodes
bind *:8013
mode http
default_backend nodes
frontend localnodes_ssl
bind *:8043
mode tcp
default_backend nodes_ssl
backend nodes
mode http
balance roundrobin
option forwardfor
option http-pretend-keepalive
http-request set-header X-Forwarded-Port %[dst_port]
http-request add-header X-Forwarded-Proto https if { ssl_fc }
option httpchk HEAD / HTTP/1.1\r\nHost:localhost
server awx-1 awx-1:8013 check
server awx-2 awx-2:8013 check
server awx-3 awx-3:8013 check
backend nodes_ssl
mode tcp
balance roundrobin
server awx-1 awx-1:8043
server awx-2 awx-2:8043
server awx-3 awx-3:8043
listen stats
bind *:1936
stats enable
stats uri /
+19
View File
@@ -0,0 +1,19 @@
localhost ansible_connection=local ansible_python_interpreter="/usr/bin/env python3"
[all:vars]
# AWX-Managed Database Settings
# If left blank, these will be generated upon install.
# Values are written out to tools/docker-compose/_sources/secrets/
# pg_password=""
# broadcast_websocket_secret=""
# secret_key=""
# External Database Settings
# pg_host=""
# pg_password=""
# pg_username=""
# pg_hostname=""
# awx_image="ansible/awx"
# migrate_local_docker=false
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
set +x
bootstrap_development.sh
cd /awx_devel
# Start the services
exec tini -- make supervisor
+28
View File
@@ -0,0 +1,28 @@
input {
http {
port => 8085
user => awx_logger
password => "workflows"
}
udp {
port => 8086
}
tcp {
port => 8087
}
}
## Add your filters / logstash plugins configuration here
filter {
json {
source => "message"
}
}
output {
stdout { codec => rubydebug }
file {
path => "/logstash.log"
}
}
+31
View File
@@ -0,0 +1,31 @@
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
server_tokens off;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
sendfile on;
#tcp_nopush on;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
+122
View File
@@ -0,0 +1,122 @@
upstream uwsgi {
server localhost:8050;
}
upstream daphne {
server localhost:8051;
}
# server {
# listen 8013 default_server;
# listen [::]:8013 default_server;
# server_name _;
# return 301 https://$host:8043$request_uri;
# }
server {
listen 8013 default_server;
# If you have a domain name, this is where to add it
server_name _;
keepalive_timeout 65;
# HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
add_header Strict-Transport-Security max-age=15768000;
location /static/ {
root /awx_devel;
try_files /awx/ui/$uri /awx/$uri /awx/public/$uri =404;
access_log off;
sendfile off;
}
location ~ ^/websocket {
# Pass request to the upstream alias
proxy_pass http://daphne;
# Require http version 1.1 to allow for upgrade requests
proxy_http_version 1.1;
# We want proxy_buffering off for proxying to websockets.
proxy_buffering off;
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if you use HTTPS:
proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client for the sake of redirects
proxy_set_header Host $http_host;
# We've set the Host header, so we don't need Nginx to muddle
# about with redirects
proxy_redirect off;
# Depending on the request value, set the Upgrade and
# connection headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
location / {
# Add trailing / if missing
rewrite ^(.*[^/])$ $1/ permanent;
uwsgi_read_timeout 120s;
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
}
server {
listen 8043 default_server ssl;
# If you have a domain name, this is where to add it
server_name _;
keepalive_timeout 65;
ssl_certificate /etc/nginx/nginx.crt;
ssl_certificate_key /etc/nginx/nginx.key;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
# intermediate configuration. tweak to your needs.
ssl_protocols TLSv1.2;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256';
ssl_prefer_server_ciphers on;
# HSTS (ngx_http_headers_module is required) (15768000 seconds = 6 months)
add_header Strict-Transport-Security max-age=15768000;
location /static/ {
root /awx_devel;
try_files /awx/ui/$uri /awx/$uri /awx/public/$uri =404;
access_log off;
sendfile off;
}
location ~ ^/websocket {
# Pass request to the upstream alias
proxy_pass http://daphne;
# Require http version 1.1 to allow for upgrade requests
proxy_http_version 1.1;
# We want proxy_buffering off for proxying to websockets.
proxy_buffering off;
# http://en.wikipedia.org/wiki/X-Forwarded-For
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# enable this if you use HTTPS:
proxy_set_header X-Forwarded-Proto https;
# pass the Host: header from the client for the sake of redirects
proxy_set_header Host $http_host;
# We've set the Host header, so we don't need Nginx to muddle
# about with redirects
proxy_redirect off;
# Depending on the request value, set the Upgrade and
# connection headers
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
location / {
# Add trailing / if missing
rewrite ^(.*[^/])$ $1/ permanent;
uwsgi_read_timeout 120s;
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
}
+9
View File
@@ -0,0 +1,9 @@
#!/bin/bash
set +x
cd /awx_devel
make clean
make awx-link
cp tools/docker-compose/ansible/roles/sources/files/local_settings.py awx/settings/local_settings.py
make "${1:-test}"
+97
View File
@@ -0,0 +1,97 @@
[supervisord]
umask = 022
minfds = 4096
nodaemon=true
[program:awx-dispatcher]
command = make dispatcher
autostart = true
autorestart = true
stopwaitsecs = 1
stopsignal=KILL
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-receiver]
command = make receiver
autostart = true
autorestart = true
stopwaitsecs = 1
stopsignal=KILL
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-wsbroadcast]
command = make wsbroadcast
autostart = true
autorestart = true
stopwaitsecs = 1
stopsignal=KILL
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-uwsgi]
command = make uwsgi
autostart = true
autorestart = true
redirect_stderr=true
stopwaitsecs = 1
stopsignal=KILL
stopasgroup=true
killasgroup=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-daphne]
command = make daphne
autostart = true
autorestart = true
redirect_stderr=true
stopwaitsecs = 1
stopsignal=KILL
stopasgroup=true
killasgroup=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-nginx]
command = make nginx
autostart = true
autorestart = true
redirect_stderr=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[program:awx-rsyslogd]
command = rsyslogd -n -i /var/run/awx-rsyslog/rsyslog.pid -f /var/lib/awx/rsyslog/rsyslog.conf
autostart = true
autorestart = true
stopwaitsecs = 5
stopsignal=TERM
stopasgroup=true
killasgroup=true
redirect_stderr=true
stdout_logfile=/dev/fd/1
stdout_logfile_maxbytes=0
[group:tower-processes]
programs=awx-dispatcher,awx-receiver,awx-uwsgi,awx-daphne,awx-nginx,awx-wsbroadcast,awx-rsyslogd
priority=5
[unix_http_server]
file=/var/run/supervisor/supervisor.sock
[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock ; use a unix:// URL for a unix socket
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
@@ -0,0 +1,31 @@
---
version: '2'
services:
# Primary Tower Development Container link
awx:
links:
- hashivault
- conjur
hashivault:
image: vault
container_name: tools_hashivault_1
ports:
- '8200:8200'
cap_add:
- IPC_LOCK
environment:
VAULT_DEV_ROOT_TOKEN_ID: 'vaultdev'
conjur:
image: cyberark/conjur
container_name: tools_conjur_1
command: server -p 8300
environment:
DATABASE_URL: postgres://awx@postgres/postgres
CONJUR_DATA_KEY: 'dveUwOI/71x9BPJkIgvQRRBF3SdASc+HP4CUGL7TKvM='
depends_on:
- postgres
links:
- postgres
ports:
- "8300:8300"
+17
View File
@@ -0,0 +1,17 @@
---
version: '2'
services:
# Primary Tower Development Container link
awx:
environment:
AWX_GROUP_QUEUES: tower,thepentagon
links:
- isolated
# Isolated Rampart Container
isolated:
image: ${DEV_DOCKER_TAG_BASE}/awx_isolated:${TAG}
container_name: tools_isolated_1
hostname: isolated
volumes:
- "../awx/main/isolated:/awx_devel"
privileged: true
+20
View File
@@ -0,0 +1,20 @@
ARG TAG=latest
FROM ansible/awx_devel:${TAG}
RUN dnf install -y gcc python36-devel openssh-server
RUN python3 -m ensurepip && pip3 install "virtualenv < 20" ansible-runner
RUN dnf remove -y gcc python36-devel && rm -rf /var/cache/dnf
RUN rm -f /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_rsa_key
RUN ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_ecdsa_key
RUN ssh-keygen -q -N "" -t rsa -f /etc/ssh/ssh_host_rsa_key
RUN sed -i "s/#UsePrivilegeSeparation.*/UsePrivilegeSeparation no/g" /etc/ssh/sshd_config
RUN sed -i "s/UsePAM.*/UsePAM yes/g" /etc/ssh/sshd_config
RUN sed -i "s/#StrictModes.*/StrictModes no/g" /etc/ssh/sshd_config
RUN mkdir -p /root/.ssh
RUN ln -s /awx_devel/authorized_keys /root/.ssh/authorized_keys
ENTRYPOINT ["tini", "--"]
CMD ["/usr/sbin/sshd", "-D"]
EXPOSE 22
+67
View File
@@ -0,0 +1,67 @@
## Instructions on using an isolated node
The building of the isolated node is done in the `make docker-compose-build`
target. Its image uses a different tag from the tools_awx container.
Given that the images are built, you can run the combined docker compose target. This uses
the base `docker-compose.yml` with modifications found in `docker-isolated-override.yml`.
You will still need to give COMPOSE_TAG with whatever your intended
base branch is. For example:
```bash
make docker-isolated COMPOSE_TAG=devel
```
This will automatically exchange the keys in order for the `tools_awx_1`
container to access the `tools_isolated_1` container over ssh.
After that, it will bring up all the containers like the normal docker-compose
workflow.
### Running a job on the Isolated Node
Create a job template that runs normally. Add the id of the instance
group named `thepentagon` to the JT's instance groups. To do this, POST
the id (probably id=2) to `/api/v2/job_templates/N/instance_groups/`.
After that, run the job template.
The models are automatically created when running the Makefile target,
and they are structured as follows:
+-------+ +-------------+
| tower |<----+ thepentagon |
+-------+ +-------------+
^ ^
| |
| |
+---+---+ +-----+----+
| tower | | isolated |
+-------+ +----------+
The `controller` for the group "thepentagon" and all hosts therein is
determined by a ForeignKey within the instance group.
### Run a playbook
In order to run an isolated job, associate the instance group `thepentagon` with
a job template, inventory, or organization, then run a job that derives from
that resource. You should be able to confirm success by inspecting the
`instance_group` of the job.
#### Advanced Manual Testing
If you want to run a job manually inside of the isolated container with this
tooling, you need a private data directory. Normal isolated job runs will
clean up their private data directory, but you can temporarily disable this
by disabling some parts of the cleanup_isolated.yml playbook.
Example location of a private data directory:
`/tmp/awx_29_OM6Mnx/`
The following command would run the playbook corresponding to that job.
```bash
ansible-runner start /tmp/awx_29_OM6Mnx/ -p some_playbook.yml
```
Other ansible-runner commands include `start`, `is-alive`, and `stop`.
+121
View File
@@ -0,0 +1,121 @@
# Docker ELK / Elastic Stack Development Tools
These are tools to run a containerized version of ELK stack, comprising
of Logstash, Elastic Search, and Kibana.
A copy of the license is in `docs/licenses/docker-elk.txt`
## Instructions
Due to complex requirements from the elastic search container upstream, there
is a prerequisite to get the containers running. The docker _host_ machine
must have the `max_map_count` variable increased. For a developer using
docker-machine with something like VirtualBox of VMWare, this can be
done by getting via bash in the running Docker machine. Example:
```bash
docker-machine ssh default sudo sysctl -w vm.max_map_count=262144
```
> Note: If you are running docker natively on linux, you need only run `sysctl -w vm.max_map_count=262144`
After this, the containers can be started up with commands like:
```bash
make docker-compose-elk
```
```bash
make docker-compose-cluster-elk
```
These are ran from the root folder of the ansible-tower repository.
Kibana is the visualization service, and it can be accessed in a web browser
by going to `{server address}:5601`.
### Authentication
The default HTTPS logstash configuration makes use of basic auth, so a username
and password is needed in HTTPS configuration, in addition to the other
parameters. The following settings are supported:
```
{
"LOG_AGGREGATOR_HOST": "logstash",
"LOG_AGGREGATOR_PORT": 8085,
"LOG_AGGREGATOR_TYPE": "logstash",
"LOG_AGGREGATOR_USERNAME": "awx_logger",
"LOG_AGGREGATOR_PASSWORD": "workflows",
"LOG_AGGREGATOR_LOGGERS": [
"awx",
"activity_stream",
"job_events",
"system_tracking"
],
"LOG_AGGREGATOR_INDIVIDUAL_FACTS": false,
"LOG_AGGREGATOR_ENABLED": true,
"LOG_AGGREGATOR_PROTOCOL": "https",
"LOG_AGGREGATOR_TCP_TIMEOUT": 5
}
```
and
```
{
"LOG_AGGREGATOR_HOST": "logstash",
"LOG_AGGREGATOR_PORT": 8086,
"LOG_AGGREGATOR_TYPE": "logstash",
"LOG_AGGREGATOR_LOGGERS": [
"awx",
"activity_stream",
"job_events",
"system_tracking"
],
"LOG_AGGREGATOR_INDIVIDUAL_FACTS": false,
"LOG_AGGREGATOR_ENABLED": true,
"LOG_AGGREGATOR_PROTOCOL": "udp",
"LOG_AGGREGATOR_TCP_TIMEOUT": 5
}
```
and
```
{
"LOG_AGGREGATOR_HOST": "logstash",
"LOG_AGGREGATOR_PORT": 8087,
"LOG_AGGREGATOR_TYPE": "logstash",
"LOG_AGGREGATOR_LOGGERS": [
"awx",
"activity_stream",
"job_events",
"system_tracking"
],
"LOG_AGGREGATOR_INDIVIDUAL_FACTS": false,
"LOG_AGGREGATOR_ENABLED": true,
"LOG_AGGREGATOR_PROTOCOL": "tcp",
"LOG_AGGREGATOR_TCP_TIMEOUT": 5
}
```
These can be entered via Configure-Tower-in-Tower by making a POST to
`/api/v2/settings/logging/`.
### Connecting Logstash to 3rd Party Receivers
In order to send these logs to an external consumer of logstash format
messages, replace the output variables in the logstash.conf file.
```
output {
elasticsearch {
hosts => "elasticsearch:9200"
}
}
```
## Changelog
Current branch point `a776151221182dcfaec7df727459e208c895d25b`
Nov 18, 2016
- Original branch point `b5a4deee142b152d4f9232ebac5bbabb2d2cef3c`
Sep 25, 2016, before X-Pack support
@@ -0,0 +1,49 @@
---
# Structure for the Elastic Stack docker configuration came from docker-elk:
# https://github.com/deviantony/docker-elk
# docker-elk is under the MIT License,
# a copy of its license is provided in docs/licenses/docker-elk.txt
# contents modified
version: '2'
services:
# Components of ELK stack for logging
elasticsearch:
build: ../../elastic/elasticsearch/
ports:
- "9200:9200"
- "9300:9300"
environment:
ES_JAVA_OPTS: "-Xms1g -Xmx1g"
# networks: # add back in when a connection to tower_tools is possible
# - docker_elk
logstash:
build: ../../elastic/logstash/
command: -f /etc/logstash/conf.d/
volumes:
- ../../elastic/logstash/config:/etc/logstash/conf.d
ports:
- "8085:8085"
links:
- elasticsearch
# networks:
# - docker_elk
depends_on:
- elasticsearch
kibana:
build: ../../elastic/kibana/
volumes:
- ../../elastic/kibana/config/:/opt/kibana/config/
ports:
- "5601:5601"
links:
- elasticsearch
# networks:
# - docker_elk
depends_on:
- elasticsearch
# networks:
# docker_elk:
# driver: bridge
@@ -0,0 +1,13 @@
---
version: '2'
services:
# Tower Development Cluster
tower_1:
links:
- logstash
tower_2:
links:
- logstash
tower_3:
links:
- logstash
@@ -0,0 +1,7 @@
---
version: '2'
services:
# Primary AWX Development Container
awx:
links:
- logstash
+5
View File
@@ -0,0 +1,5 @@
FROM elasticsearch:5
ENV ES_JAVA_OPTS="-Des.path.conf=/etc/elasticsearch"
CMD ["-E", "network.host=0.0.0.0", "-E", "discovery.zen.minimum_master_nodes=1"]
@@ -0,0 +1 @@
Ensure the existence of the parent folder.
+1
View File
@@ -0,0 +1 @@
FROM kibana:5
+93
View File
@@ -0,0 +1,93 @@
---
# Kibana is served by a back end server. This setting specifies the port to use.
server.port: 5601
# This setting specifies the IP address of the back end server.
server.host: "0.0.0.0"
# Enables you to specify a path to mount Kibana at if you are running behind a proxy. This setting
# cannot end in a slash.
# server.basePath: ""
# The maximum payload size in bytes for incoming server requests.
# server.maxPayloadBytes: 1048576
# The Kibana server's name. This is used for display purposes.
# server.name: "your-hostname"
# The URL of the Elasticsearch instance to use for all your queries.
elasticsearch.url: "http://elasticsearch:9200"
# When this setting’s value is true Kibana uses the hostname specified in the server.host
# setting. When the value of this setting is false, Kibana uses the hostname of the host
# that connects to this Kibana instance.
# elasticsearch.preserveHost: true
# Kibana uses an index in Elasticsearch to store saved searches, visualizations and
# dashboards. Kibana creates a new index if the index doesn’t already exist.
# kibana.index: ".kibana"
# The default application to load.
# kibana.defaultAppId: "discover"
# If your Elasticsearch is protected with basic authentication, these settings provide
# the username and password that the Kibana server uses to perform maintenance on the Kibana
# index at startup. Your Kibana users still need to authenticate with Elasticsearch, which
# is proxied through the Kibana server.
# elasticsearch.username: "user"
# elasticsearch.password: "pass"
# Paths to the PEM-format SSL certificate and SSL key files, respectively. These
# files enable SSL for outgoing requests from the Kibana server to the browser.
# server.ssl.cert: /path/to/your/server.crt
# server.ssl.key: /path/to/your/server.key
# Optional settings that provide the paths to the PEM-format SSL certificate and key files.
# These files validate that your Elasticsearch backend uses the same key files.
# elasticsearch.ssl.cert: /path/to/your/client.crt
# elasticsearch.ssl.key: /path/to/your/client.key
# Optional setting that enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
# elasticsearch.ssl.ca: /path/to/your/CA.pem
# To disregard the validity of SSL certificates, change this setting’s value to false.
# elasticsearch.ssl.verify: true
# Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
# the elasticsearch.requestTimeout setting.
# elasticsearch.pingTimeout: 1500
# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
# elasticsearch.requestTimeout: 30000
# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
# elasticsearch.requestHeadersWhitelist: [ authorization ]
# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
# elasticsearch.shardTimeout: 0
# Time in milliseconds to wait for Elasticsearch at Kibana startup before retrying.
# elasticsearch.startupTimeout: 5000
# Specifies the path where Kibana creates the process ID file.
# pid.file: /var/run/kibana.pid
# Enables you specify a file where Kibana stores log output.
# logging.dest: stdout
# Set the value of this setting to true to suppress all logging output.
# logging.silent: false
# Set the value of this setting to true to suppress all logging output other than error messages.
# logging.quiet: false
# Set the value of this setting to true to log all events, including system usage information
# and all requests.
# logging.verbose: false
# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 10000.
# ops.interval: 10000
+4
View File
@@ -0,0 +1,4 @@
FROM logstash:5
# Add your logstash plugins setup here
# Example: RUN logstash-plugin install logstash-filter-json
@@ -0,0 +1,21 @@
input {
http {
port => 8085
user => awx_logger
password => "workflows"
}
}
## Add your filters / logstash plugins configuration here
filter {
json {
source => "message"
}
}
output {
elasticsearch {
hosts => "elasticsearch:9200"
}
}
+1
View File
@@ -0,0 +1 @@
./data
+46
View File
@@ -0,0 +1,46 @@
---
# prometheus.yml
# my global config
global:
scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.
static_configs:
- targets: ['127.0.0.1:9090']
- job_name: 'awx'
tls_config:
insecure_skip_verify: true
metrics_path: /api/v2/metrics
scrape_interval: 5s
scheme: http
params:
format: ['txt']
basic_auth:
username: admin
password: password
# bearer_token: oauth-token
static_configs:
- targets:
- awxweb:8013
+10
View File
@@ -0,0 +1,10 @@
unixsocket /var/run/redis/redis.sock
unixsocketperm 770
port 0
# Do not actually listen to any tcp port
# but include the bind directive because without it redis will
# listen on the public interface. Port 0 causes it to NOT listen on
# the public interface. Adding the below line is an extra precaution.
# If a developer comes by later and wants to listen on a tcp port and changes
# the above port, it will ONLY listen on the local interface.
bind 127.0.0.1
@@ -0,0 +1 @@
This dir must pre-exist and be owned by the user you are launching awx dev env as. If the dir does not exist before launching the awx dev environment then docker will create the dir and it will be owned by root. Since we start our awx dev environment with user: ${CURRENT_UID} the redis container will be unable to create a socket file in a directory owned by root.
@@ -0,0 +1 @@
This dir must pre-exist and be owned by the user you are launching awx dev env as. If the dir does not exist before launching the awx dev environment then docker will create the dir and it will be owned by root. Since we start our awx dev environment with user: ${CURRENT_UID} the redis container will be unable to create a socket file in a directory owned by root.
@@ -0,0 +1 @@
This dir must pre-exist and be owned by the user you are launching awx dev env as. If the dir does not exist before launching the awx dev environment then docker will create the dir and it will be owned by root. Since we start our awx dev environment with user: ${CURRENT_UID} the redis container will be unable to create a socket file in a directory owned by root.
+1
View File
@@ -0,0 +1 @@
This dir must pre-exist and be owned by the user you are launching awx dev env as. If the dir does not exist before launching the awx dev environment then docker will create the dir and it will be owned by root. Since we start our awx dev environment with user: ${CURRENT_UID} the rsyslog process will be unable to create a config file in a directory owned by root.
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
if [ -f /etc/sysconfig/ansible-tower ]; then
source /etc/sysconfig/ansible-tower
fi
case "$1" in
start|stop|restart)
exec systemctl $1 ansible-tower.service
;;
status)
exec systemctl status ansible-tower.service $TOWER_SERVICES
;;
*)
echo "Usage: ansible-tower-service start|stop|restart|status"
exit 1
;;
esac
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
exec /var/lib/awx/setup/setup.sh "$@"
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Enable Tower virtualenv
for venv_path in /var/lib/awx/venv/awx; do
if [ -f $venv_path/bin/activate ]; then
. $venv_path/bin/activate
fi
done
# Run the requested Python command, using the interpreter from the path
exec python3 "$@"
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python
#
# This script is based on https://github.com/django/django/blob/master/django/core/management/commands/compilemessages.py
# It has been modified to run without Django, because the virtual environment
# is not available when `make languages` is invoked.
#
import codecs
import datetime
import locale
import os
import sys
from decimal import Decimal
from subprocess import PIPE, Popen
def is_writable(path):
# Known side effect: updating file access/modified time to current time if
# it is writable.
try:
with open(path, 'a'):
os.utime(path, None)
except (IOError, OSError):
return False
return True
def has_bom(fn):
with open(fn, 'rb') as f:
sample = f.read(4)
return sample.startswith((codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))
def popen_wrapper(args, os_err_exc_type=Exception, stdout_encoding='utf-8'):
"""
Friendly wrapper around Popen.
Returns stdout output, stderr output and OS status code.
"""
try:
p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
except OSError as e:
strerror = force_text(e.strerror, DEFAULT_LOCALE_ENCODING, strings_only=True)
raise Exception(os_err_exc_type, os_err_exc_type('Error executing %s: %s' %
(args[0], strerror)), sys.exc_info()[2])
output, errors = p.communicate()
return (
force_text(output, stdout_encoding, strings_only=True, errors='strict'),
force_text(errors, DEFAULT_LOCALE_ENCODING, strings_only=True, errors='replace'),
p.returncode
)
def get_system_encoding():
"""
The encoding of the default system locale but falls back to the given
fallback encoding if the encoding is unsupported by python or could
not be determined. See tickets #10335 and #5846
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
codecs.lookup(encoding)
except Exception:
encoding = 'ascii'
return encoding
_PROTECTED_TYPES = (
type(None), int, float, Decimal, datetime.datetime, datetime.date, datetime.time,
)
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, _PROTECTED_TYPES)
DEFAULT_LOCALE_ENCODING = get_system_encoding()
def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first for performance reasons.
if issubclass(type(s), str):
return s
if strings_only and is_protected_type(s):
return s
try:
if not issubclass(type(s), str):
if isinstance(s, bytes):
s = str(s, encoding, errors)
else:
s = str(s)
else:
# Note: We use .decode() here, instead of str(s, encoding,
# errors), so that if s is a SafeBytes, it ends up being a
# SafeText at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise Exception(s, *e.args)
else:
# If we get to here, the caller has passed in an Exception
# subclass populated with non-ASCII bytestring data without a
# working unicode method. Try to handle this without raising a
# further exception by individually forcing the exception args
# to unicode.
s = ' '.join(force_text(arg, encoding, strings_only, errors)
for arg in s)
return s
if __name__ == "__main__":
basedirs = [os.path.join('conf', 'locale'), 'locale']
# Walk entire tree, looking for locale directories
for dirpath, dirnames, filenames in os.walk('.', topdown=True):
for dirname in dirnames:
if dirname == 'locale':
basedirs.append(os.path.join(dirpath, dirname))
basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs)))
for basedir in basedirs:
dirs = [basedir]
locations = []
for ldir in dirs:
for dirpath, dirnames, filenames in os.walk(ldir):
locations.extend((dirpath, f) for f in filenames if f.endswith('.po'))
if locations:
program = 'msgfmt'
program_options = ['--check-format']
for i, (dirpath, f) in enumerate(locations):
print('processing file %s in %s\n' % (f, dirpath))
po_path = os.path.join(dirpath, f)
if has_bom(po_path):
raise Exception("The %s file has a BOM (Byte Order Mark). "
"Django only supports .po files encoded in "
"UTF-8 and without any BOM." % po_path)
base_path = os.path.splitext(po_path)[0]
# Check writability on first location
if i == 0 and not is_writable((base_path + '.mo')):
raise Exception("The po files under %s are in a seemingly not writable location. "
"mo files will not be updated/created." % dirpath)
args = [program] + program_options + [
'-o', (base_path + '.mo'), (base_path + '.po')
]
output, errors, status = popen_wrapper(args)
if status:
if errors:
msg = "Execution of %s failed: %s" % (program, errors)
else:
msg = "Execution of %s failed" % program
raise Exception(msg)
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
import os
import sys
import hashlib
from supervisor import childutils
def hash(f):
s = hashlib.sha1()
with open(f, "rb") as fd:
for chunk in iter(lambda: fd.read(4096), b""):
s.update(chunk)
return s.hexdigest()
def last_hash(f):
with open(f, "r") as fd:
return fd.read().strip()
def write_hash(f, h):
with open(f, "w") as fd:
fd.write(h)
def main():
settings_file = "/etc/tower/settings.py"
hash_file = "/var/lib/awx/.configsha"
while 1:
rpc = childutils.getRPCInterface(os.environ)
headers, payload = childutils.listener.wait(sys.stdin, sys.stdout)
if not headers['eventname'].startswith('TICK'):
childutils.listener.ok(sys.stdout)
continue
try:
current_hash = hash(settings_file)
except:
sys.stderr.write("Could not open settings.py, skipping config watcher")
childutils.listener.ok(sys.stdout)
continue
try:
if current_hash == last_hash(hash_file):
childutils.listener.ok(sys.stdout)
continue
else:
sys.stderr.write("Config changed, reloading services")
for proc in rpc.supervisor.getAllProcessInfo():
group = proc['group']
name = proc['name']
program = "{}:{}".format(group, name)
if group == "tower-processes":
sys.stderr.write('Restarting %s\n' % program)
rpc.supervisor.stopProcess(program)
rpc.supervisor.startProcess(program)
except:
sys.stderr.write("No previous hash found")
write_hash(hash_file, current_hash)
childutils.listener.ok(sys.stdout)
if __name__ == '__main__':
main()
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/awx-python
import sys
import os
import signal
def write_stdout(s):
sys.stdout.write(s)
sys.stdout.flush()
def write_stderr(s):
sys.stderr.write(s)
sys.stderr.flush()
def main():
while 1:
write_stdout('READY\n')
line = sys.stdin.readline()
headers = dict([ x.split(':') for x in line.split() ])
headers.update(dict([ x.split(':') for x in sys.stdin.read(int(headers['len'])).split()]))
if headers['eventname'] == 'PROCESS_STATE_FATAL':
os.kill(os.getppid(), signal.SIGTERM)
write_stdout('RESULT 2\nOK')
if __name__ == "__main__":
main()
+326
View File
@@ -0,0 +1,326 @@
#! /usr/bin/env awx-python
#
# !!! READ BEFORE POINTING THIS AT YOUR FOOT !!!
#
# This script attempts to connect to an AWX database and insert (by default)
# a billion main_jobevent rows as screamingly fast as possible.
#
# tl;dr for best results, feed it high IOPS.
#
# this script exists *solely* for the purpose of generating *test* data very
# quickly; do *not* point this at a production installation or you *will* be
# very unhappy
#
# Before running this script, you should give postgres *GOBS* of memory
# and disk so it can create indexes and constraints as quickly as possible.
# In fact, it's probably not smart to attempt this on anything less than 8 core,
# 32GB of RAM, and tens of thousands of IOPS.
#
# Also, a billion events is a *lot* of data; make sure you've
# provisioned *at least* 750GB of disk space
#
# if you want this script to complete in a few hours, a good starting point
# is something like m5.4xlarge w/ 1TB provisioned IOPS SSD (io1)
#
import argparse
import datetime
import itertools
import json
import multiprocessing
import pkg_resources
import random
import subprocess
import sys
from io import StringIO
from time import time
from uuid import uuid4
import psycopg2
from django import setup as setup_django
from django.db import connection
from django.db.models.sql import InsertQuery
from django.utils.timezone import now
db = json.loads(
subprocess.check_output(
['awx-manage', 'print_settings', 'DATABASES', '--format', 'json']
)
)
name = db['DATABASES']['default']['NAME']
user = db['DATABASES']['default']['USER']
pw = db['DATABASES']['default']['PASSWORD']
host = db['DATABASES']['default']['HOST']
dsn = f'dbname={name} user={user} password={pw} host={host}'
u = str(uuid4())
STATUS_OPTIONS = ('successful', 'failed', 'error', 'canceled')
EVENT_OPTIONS = ('runner_on_ok', 'runner_on_failed', 'runner_on_changed', 'runner_on_skipped', 'runner_on_unreachable')
MODULE_OPTIONS = ('yup', 'stonchronize', 'templotz', 'deboog')
class YieldedRows(StringIO):
def __init__(self, job_id, rows, created_stamp, modified_stamp, *args, **kwargs):
self.rows = rows
self.rowlist = []
for (event, module) in itertools.product(EVENT_OPTIONS, MODULE_OPTIONS):
event_data_json = {
"task_action": module,
"name": "Do a {} thing".format(module),
"task": "Do a {} thing".format(module)
}
row = "\t".join([
f"{created_stamp}",
f"{modified_stamp}",
event,
json.dumps(event_data_json),
str(event in ('runner_on_failed', 'runner_on_unreachable')),
str(event == 'runner_on_changed'),
"localhost",
"Example Play",
"Hello World",
"",
"0",
"1",
job_id,
u,
"",
"1",
"hello_world.yml",
"0",
"X",
"1",
]) + '\n'
self.rowlist.append(row)
def read(self, x):
if self.rows <= 0:
self.close()
return ''
self.rows -= 1000
return self.rowlist[random.randrange(len(self.rowlist))] * 1000
def firehose(job, count, created_stamp, modified_stamp):
conn = psycopg2.connect(dsn)
f = YieldedRows(job, count, created_stamp, modified_stamp)
with conn.cursor() as cursor:
cursor.copy_expert((
'COPY '
'main_jobevent('
'created, modified, event, event_data, failed, changed, '
'host_name, play, role, task, counter, host_id, job_id, uuid, '
'parent_uuid, end_line, playbook, start_line, stdout, verbosity'
') '
'FROM STDIN'
), f, size=1024 * 1000)
conn.commit()
conn.close()
def cleanup(sql):
print(sql)
conn = psycopg2.connect(dsn)
with conn.cursor() as cursor:
cursor.execute(sql)
conn.commit()
conn.close()
def generate_jobs(jobs, batch_size, time_delta):
print(f'inserting {jobs} job(s)')
sys.path.insert(0, pkg_resources.get_distribution('awx').module_path)
from awx import prepare_env
prepare_env()
setup_django()
from awx.main.models import UnifiedJob, Job, JobTemplate
fields = list(set(Job._meta.fields) - set(UnifiedJob._meta.fields))
job_field_names = set([f.attname for f in fields])
# extra unified job field names from base class
for field_name in ('name', 'created_by_id', 'modified_by_id'):
job_field_names.add(field_name)
jt_count = JobTemplate.objects.count()
def make_batch(N, jt_pos=0):
jt = None
while not jt:
try:
jt = JobTemplate.objects.all()[jt_pos % jt_count]
except IndexError as e:
# seems to happen every now and then due to some race condition
print('Warning: IndexError on {} JT, error: {}'.format(
jt_pos % jt_count, e
))
jt_pos += 1
jt_defaults = dict(
(f.attname, getattr(jt, f.attname))
for f in JobTemplate._meta.get_fields()
if f.concrete and f.attname in job_field_names and getattr(jt, f.attname)
)
jt_defaults['job_template_id'] = jt.pk
jt_defaults['unified_job_template_id'] = jt.pk # populated by save method
jobs = [
Job(
status=STATUS_OPTIONS[i % len(STATUS_OPTIONS)],
started=now() - time_delta, created=now() - time_delta, modified=now() - time_delta, finished=now() - time_delta,
elapsed=0., **jt_defaults)
for i in range(N)
]
ujs = UnifiedJob.objects.bulk_create(jobs)
query = InsertQuery(Job)
query.insert_values(fields, ujs)
with connection.cursor() as cursor:
query, params = query.sql_with_params()[0]
cursor.execute(query, params)
return ujs[-1], jt_pos
i = 1
jt_pos = 0
s = time()
while jobs > 0:
s_loop = time()
print('running batch {}, runtime {}'.format(i, time() - s))
created, jt_pos = make_batch(min(jobs, batch_size), jt_pos)
print('took {}'.format(time() - s_loop))
i += 1
jobs -= batch_size
return created
def generate_events(events, job, time_delta):
conn = psycopg2.connect(dsn)
cursor = conn.cursor()
print('removing indexes and constraints')
created_time = datetime.datetime.today() - time_delta - datetime.timedelta(seconds=5)
modified_time = datetime.datetime.today() - time_delta
created_stamp = created_time.strftime("%Y-%m-%d %H:%M:%S")
modified_stamp = modified_time.strftime("%Y-%m-%d %H:%M:%S")
# get all the indexes for main_jobevent
try:
# disable WAL to drastically increase write speed
# we're not doing replication, and the goal of this script is to just
# insert data as quickly as possible without concern for the risk of
# data loss on crash
# see: https://www.compose.com/articles/faster-performance-with-unlogged-tables-in-postgresql/
cursor.execute('ALTER TABLE main_jobevent SET UNLOGGED')
cursor.execute("SELECT indexname, indexdef FROM pg_indexes WHERE tablename='main_jobevent' AND indexname != 'main_jobevent_pkey1';")
indexes = cursor.fetchall()
cursor.execute(
"SELECT conname, contype, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = 'main_jobevent'::regclass AND conname != 'main_jobevent_pkey1';" # noqa
)
constraints = cursor.fetchall()
# drop all indexes for speed
for indexname, indexdef in indexes:
cursor.execute(f'DROP INDEX IF EXISTS {indexname}')
print(f'DROP INDEX IF EXISTS {indexname}')
for conname, contype, condef in constraints:
cursor.execute(f'ALTER TABLE main_jobevent DROP CONSTRAINT IF EXISTS {conname}')
print(f'ALTER TABLE main_jobevent DROP CONSTRAINT IF EXISTS {conname}')
conn.commit()
print(f'attaching {events} events to job {job}')
cores = multiprocessing.cpu_count()
workers = []
num_procs = min(cores, events)
num_events = events // num_procs
if num_events <= 1:
num_events = events
for i in range(num_procs):
p = multiprocessing.Process(target=firehose, args=(job, num_events, created_stamp, modified_stamp))
p.daemon = True
workers.append(p)
for w in workers:
w.start()
for w in workers:
w.join()
workers = []
print('generating unique start/end line counts')
cursor.execute('CREATE SEQUENCE IF NOT EXISTS firehose_seq;')
cursor.execute('CREATE SEQUENCE IF NOT EXISTS firehose_line_seq MINVALUE 0;')
cursor.execute('ALTER SEQUENCE firehose_seq RESTART WITH 1;')
cursor.execute('ALTER SEQUENCE firehose_line_seq RESTART WITH 0;')
cursor.execute("SELECT nextval('firehose_line_seq')")
conn.commit()
cursor.execute(
"UPDATE main_jobevent SET "
"counter=nextval('firehose_seq')::integer,"
"start_line=nextval('firehose_line_seq')::integer,"
"end_line=currval('firehose_line_seq')::integer + 2 "
f"WHERE job_id={job}"
)
conn.commit()
finally:
# restore all indexes
print(datetime.datetime.utcnow().isoformat())
print('restoring indexes and constraints (this may take awhile)')
workers = []
for indexname, indexdef in indexes:
p = multiprocessing.Process(target=cleanup, args=(indexdef,))
p.daemon = True
workers.append(p)
for w in workers:
w.start()
for w in workers:
w.join()
for conname, contype, condef in constraints:
if contype == 'c':
# if there are any check constraints, don't add them back
# (historically, these are > 0 checks, which are basically
# worthless, because Ansible doesn't emit counters, line
# numbers, verbosity, etc... < 0)
continue
sql = f'ALTER TABLE main_jobevent ADD CONSTRAINT {conname} {condef}'
cleanup(sql)
conn.close()
print(datetime.datetime.utcnow().isoformat())
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--jobs', type=int, help='Number of jobs to create.',
default=1000000) # 1M by default
parser.add_argument(
'--events', type=int, help='Number of events to create.',
default=1000000000) # 1B by default
parser.add_argument(
'--batch-size', type=int, help='Number of jobs to create in a single batch.',
default=1000)
parser.add_argument(
'--days-delta', type=int, help='Number of days old to create the events. Defaults to 0.',
default=0)
parser.add_argument(
'--hours-delta', type=int, help='Number of hours old to create the events. Defaults to 1.',
default=1)
params = parser.parse_args()
jobs = params.jobs
time_delta = params.days_delta, params.hours_delta
time_delta = datetime.timedelta(days=time_delta[0], hours=time_delta[1], seconds=0)
events = params.events
batch_size = params.batch_size
print(datetime.datetime.utcnow().isoformat())
created = generate_jobs(jobs, batch_size=batch_size, time_delta=time_delta)
generate_events(events, str(created.pk), time_delta)
+46
View File
@@ -0,0 +1,46 @@
__all__ = ['pretty_print_model_fields']
def _get_class_full_name(cls_):
return cls_.__module__ + '.' + cls_.__name__
class _ModelFieldRow(object):
def __init__(self, field):
self.field = field
self.name = field.name
self.type_ = _get_class_full_name(type(field))
if self.field.many_to_many\
or self.field.many_to_one\
or self.field.one_to_many\
or self.field.one_to_one:
self.related_model = _get_class_full_name(self.field.remote_field.model)
else:
self.related_model = 'N/A'
def pretty_print(self, max_name_len, max_type_len, max_rel_model_len):
row = []
row.append(self.name)
row.append(' ' * (max_name_len - len(self.name)))
row.append('|')
row.append(self.type_)
row.append(' ' * (max_type_len - len(self.type_)))
row.append('|')
row.append(self.related_model)
row.append(' ' * (max_rel_model_len - len(self.related_model)))
print(''.join(row))
def pretty_print_model_fields(model):
field_info_rows = []
max_lens = [0, 0, 0]
for field in model._meta.get_fields():
field_info_rows.append(_ModelFieldRow(field))
max_lens[0] = max(max_lens[0], len(field_info_rows[-1].name))
max_lens[1] = max(max_lens[1], len(field_info_rows[-1].type_))
max_lens[2] = max(max_lens[2], len(field_info_rows[-1].related_model))
print('=' * (sum(max_lens) + len(max_lens) - 1))
for row in field_info_rows:
row.pretty_print(*max_lens)
print('=' * (sum(max_lens) + len(max_lens) - 1))
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python
import argparse
import urllib.parse
import requests
NAMED_URL_RES_DILIMITER = "--"
NAMED_URL_RES_INNER_DILIMITER = "-"
NAMED_URL_RES_DILIMITER_ENCODE = "%2D"
URL_PATH_RESERVED_CHARSET = {}
for c in ';/?:@=&[]':
URL_PATH_RESERVED_CHARSET[c] = urllib.parse.quote(c, safe='')
def _get_named_url_graph(url, auth):
"""Get the graph data structure Tower used to manage all named URLs.
Args:
url: String representing the URL of tower configuration endpoint where
to fetch graph information.
auth: Tuple of username + password to authenticate connection to Tower.
Return:
A dict of graph nodes that in ensembly represent the graph structure. Each
node is represented as a dict of 'fields' and 'adj_list'.
Raises:
N/A
"""
r = requests.get(url, auth=auth, verify=False)
ret = r.json()['NAMED_URL_GRAPH_NODES']
return ret
def _encode_uri(text):
"""Properly encode input text to make it satisfy named URL convention.
Args:
text: the original string to be encoded.
Return:
The encoded string
Raises:
N/A
"""
for c in URL_PATH_RESERVED_CHARSET:
if c in text:
text = text.replace(c, URL_PATH_RESERVED_CHARSET[c])
text = text.replace(NAMED_URL_RES_INNER_DILIMITER,
'[%s]' % NAMED_URL_RES_INNER_DILIMITER)
return text
def _generate_identifier_component(response, fields):
"""Generate an individual component of named URL identifier.
Args:
response: JSON containing the details of a particular resource object.
fields: name of resource object fields needed to generate a named URL
identifier component.
Return:
A string representing generated identifier component.
Raises:
N/A
"""
ret = []
for field_name in fields:
ret.append(_encode_uri(response[field_name]))
return NAMED_URL_RES_INNER_DILIMITER.join(ret)
def _get_named_url_identifier(url, named_url_graph, resource, tower_host, auth, ret):
"""DFS the named URL graph structure to generate identifier for a resource object.
Args:
url: A string used to access a particular resource object to generate identifier
component from.
named_url_graph: The graph structure used to DFS against.
resource: Key name of the current graph node.
tower_host: String representing the host name of Tower backend.
auth: Tuple of username + password to authenticate connection to Tower.
ret: list of strings storing components that would later be joined into
the final named URL identifier.
Return:
None. Note the actual outcome is stored in argument ret due to the recursive
nature of this function.
Raises:
"""
r = requests.get(url, auth=auth, verify=False).json()
ret.append(_generate_identifier_component(r, named_url_graph[resource]['fields']))
for next_ in named_url_graph[resource]['adj_list']:
next_fk, next_res = tuple(next_)
if next_fk in r['related']:
_get_named_url_identifier(tower_host.strip('/') + r['related'][next_fk],
named_url_graph, next_res, tower_host, auth, ret)
else:
ret.append('')
def main(username=None, password=None, tower_host=None, resource=None, pk=None):
"""Main function for generating and printing named URL of a resource object given its pk.
Args:
username: String representing the username needed to authenticating Tower.
password: String representing the password needed to authenticating Tower.
tower_host: String representing the host name of Tower backend.
resource: REST API name of a specific resource, e.g. name for resource inventory
is 'inventories'.
pk: Primary key of the resource object whose named URL will be derived.
Returns:
None
Raises:
N/A
"""
start_url = '%s/api/v2/%s/%s/' % (tower_host.strip('/'), resource.strip('/'), pk)
conf_url = '%s/api/v2/settings/named-url/' % tower_host.strip('/')
auth = (username, password)
named_url_graph = _get_named_url_graph(conf_url, auth)
named_url_identifier = []
_get_named_url_identifier(start_url, named_url_graph, resource,
tower_host, auth, named_url_identifier)
print('%s/api/v2/%s/%s/' % (tower_host.strip('/'), resource.strip('/'),
NAMED_URL_RES_DILIMITER.join(named_url_identifier)))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--username', type=str, required=True,
help='Name of the Tower user for making requests',
dest='username', metavar='STR')
parser.add_argument('--password', type=str, required=True,
help='Password of the Tower user for making requests',
dest='password', metavar='STR')
parser.add_argument('--tower-host', type=str, required=True,
help='Tower host name, like "http://127.0.0.1"',
dest='tower_host', metavar='STR')
parser.add_argument('--resource', type=str, required=True,
help='Name of the resource in REST endpoints',
dest='resource', metavar='STR')
parser.add_argument('--pk', type=int, required=True,
help='Primary key of resource object whose named URL will be derived',
dest='pk', metavar='INT')
main(**vars(parser.parse_args()))
@@ -0,0 +1,101 @@
# Define parameters
[cmdletbinding()]
Param(
[Alias("k")]
[switch] $insecure = $false,
[Alias("h")]
[switch] $help,
[Alias("s")]
[string] $tower_url,
[Alias("c")]
[string] $host_config_key,
[Alias("t")]
[string] $job_template_id,
[Alias("e")]
[string] $extra_vars
)
# Initialize variables
Set-StrictMode -Version 2
$ErrorActionPreference = "Stop"
$retry_attempts = 10
$attempt = 0
$usage = @"
Request server configuration from Ansible Tower
Usage:
Execution using positional parameters:
$($MyInvocation.MyCommand.Name) https://example.towerhost.net 44d7507f2ead49af5fca80aa18fd24bc 38
Ignore self-signed certificates using named parameters:
$($MyInvocation.MyCommand.Name) -k -s https://example.towerhost.local -c 44d7507f2ead49af5fca80aa18fd24bc -t 38
Execution using optional extra_vars:
$($MyInvocation.MyCommand.Name) https://example.towerhost.net 44d7507f2ead49af5fca80aa18fd24bc 38 '{ key: value, dict: { key: value }}'
Options:
-help, -h Show this message
-tower_url, -s Tower server (e.g. https://<server address>[:server port]) (required)
-insecure, -k Allow insecure SSL connections and transfers
-host_config_key, -c <host config key> Host config key (required)
-job_template_id, -t <job template id> Job template ID (required)
-extra_vars, -e [<extra vars>] Extra variables
"@
# Validate required arguments
If (-not $tower_url -or -not $host_config_key -or -not $job_template_id -or $help) {
Write-Host $usage
Exit 1
}
# Create Invoke-WebRequest JSON data hash tables
If (-not $extra_vars) {
$data = @{
host_config_key=$host_config_key
}
} Else {
$data = @{
host_config_key=$host_config_key
extra_vars=$extra_vars
}
}
# Success on any 2xx status received, failure on only 404 status received, retry any other status every min for up to 10 min
While ($attempt -lt $retry_attempts) {
Try {
If ($insecure) {
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
}
$resp = Invoke-WebRequest -ContentType application/json -Method POST -Body (ConvertTo-Json $data) -Uri $tower_url/api/v2/job_templates/$job_template_id/callback/
If ($resp.StatusCode -match '^2[0-9]+$') {
Exit 0
}
}
Catch [System.Security.Authentication.AuthenticationException] {
Write-Host $_
Exit 1
}
Catch {
$ex = $_
$attempt++
If ($([int]$ex.Exception.Response.StatusCode) -eq 404) {
Write-Host "$([int]$ex.Exception.Response.StatusCode) received... encountered problem, halting"
Exit 1
}
Write-Host "$([int]$ex.Exception.Response.StatusCode) received... retrying in 1 minute (Attempt $attempt)"
}
Finally {
If ($insecure) {
$sp = [System.Net.ServicePointManager]::FindServicePoint($tower_url)
$sp.CloseConnectionGroup("") > $null
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
}
}
Start-Sleep -Seconds 60
}
Exit 1
+96
View File
@@ -0,0 +1,96 @@
#!/bin/bash
fatal() {
if [ -n "${2}" ]; then
echo -e "Error: ${2}"
fi
exit ${1}
}
usage() {
cat << EOF
Usage: $0 <options>
Request server configuration from Ansible Tower.
OPTIONS:
-h Show this message
-s Tower server (e.g. https://tower.example.com) (required)
-k Allow insecure SSL connections and transfers
-c Host config key (required)
-t Job template ID (required)
-e Extra variables
EOF
}
# Initialize variables
INSECURE=""
# Parse arguments
while getopts “hks:c:t:s:e:” OPTION
do
case ${OPTION} in
h)
usage
exit 1
;;
s)
TOWER_SERVER=${OPTARG}
;;
k)
INSECURE="-k"
;;
c)
HOST_CFG_KEY=${OPTARG}
;;
t)
TEMPLATE_ID=${OPTARG}
;;
e)
EXTRA_VARS=${OPTARG}
;;
?)
usage
exit
;;
esac
done
# Validate required arguments
test -z ${TOWER_SERVER} && fatal 1 "Missing required -s argument"
# Make sure TOWER_SERVER starts with http:// or https://
[[ "${TOWER_SERVER}" =~ ^https?:// ]] || fatal 1 "Tower server must begin with http:// or https://"
test -z ${HOST_CFG_KEY} && fatal 1 "Missing required -c argument"
test -z ${TEMPLATE_ID} && fatal 1 "Missing required -t argument"
# Generate curl --data parameter
if [ -n "${EXTRA_VARS}" ]; then
CURL_DATA="{\"host_config_key\": \"${HOST_CFG_KEY}\", \"extra_vars\": \"${EXTRA_VARS}\"}"
else
CURL_DATA="{\"host_config_key\": \"${HOST_CFG_KEY}\"}"
fi
# Success on any 2xx status received, failure on only 404 status received, retry any other status every min for up to 10 min
RETRY_ATTEMPTS=10
ATTEMPT=0
while [[ $ATTEMPT -lt $RETRY_ATTEMPTS ]]
do
set -o pipefail
HTTP_STATUS=$(curl ${INSECURE} -s -i -X POST -H 'Content-Type:application/json' --data "$CURL_DATA" ${TOWER_SERVER}/api/v2/job_templates/${TEMPLATE_ID}/callback/ 2>&1 | head -n1 | awk '{print $2}')
CURL_RC=$?
if [ ${CURL_RC} -ne 0 ]; then
fatal ${CURL_RC} "curl exited with ${CURL_RC}, halting."
fi
# Extract http status code
if [[ ${HTTP_STATUS} =~ ^2[0-9]+$ ]]; then
echo "Success: ${HTTP_STATUS} received."
break
elif [[ ${HTTP_STATUS} =~ ^404$ ]]; then
fatal 1 "Failed: ${HTTP_STATUS} received, encountered problem, halting."
else
ATTEMPT=$((ATTEMPT + 1))
echo "Failed: ${HTTP_STATUS} received, executing retry #${ATTEMPT} in 1 minute."
sleep 60
fi
done
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/expect -f
#
# Helper script to respond to passphrase prompts from the gpg command.
#
# Disable timeout
set timeout -1
# Optionally print usage message
if {[llength $argv] <= 0} {
puts "Usage: sign.exp <command>"
exit 1
}
# Process arguments
set command [join $argv]
if { [info exists env(PASSPHRASE) ] } {
set passphrase $env(PASSPHRASE)
} else {
set passphrase ""
}
# Run the desired command
spawn {*}$command
expect {
-nocase "enter passphrase:" {
send -- "$passphrase\r"
exp_continue
}
-nocase "enter pass phrase:" {
send -- "$passphrase\r"
exp_continue
}
timeout {
puts "expect timeout"
exit 1
}
eof { }
}
lassign [wait] pid spawnid os_error_flag retval
if {$os_error_flag == 0} {
puts "exit status: $retval"
} else {
puts "errno: $retval"
}
exit $retval
+64
View File
@@ -0,0 +1,64 @@
# Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
SOSREPORT_TOWER_COMMANDS = [
"awx-manage --version", # tower version
"awx-manage list_instances", # tower cluster configuration
"awx-manage run_dispatcher --status", # tower dispatch worker status
"awx-manage run_callback_receiver --status", # tower callback worker status
"awx-manage check_license --data", # tower license status
"awx-manage run_wsbroadcast --status", # tower broadcast websocket status
"supervisorctl status", # tower process status
"/var/lib/awx/venv/awx/bin/pip freeze", # pip package list
"/var/lib/awx/venv/awx/bin/pip freeze -l", # pip package list without globally-installed packages
"/var/lib/awx/venv/ansible/bin/pip freeze", # pip package list
"/var/lib/awx/venv/ansible/bin/pip freeze -l", # pip package list without globally-installed packages
"tree -d /var/lib/awx", # show me the dirs
"ls -ll /var/lib/awx", # check permissions
"ls -ll /var/lib/awx/venv", # list all venvs
"ls -ll /etc/tower",
"umask -p" # check current umask
]
SOSREPORT_TOWER_DIRS = [
"/etc/tower/",
"/etc/supervisord.d/",
"/etc/nginx/",
"/var/log/tower",
"/var/log/nginx",
"/var/log/supervisor",
"/var/log/redis",
"/etc/opt/rh/rh-redis5/redis.conf",
"/etc/redis.conf",
"/var/opt/rh/rh-redis5/log/redis/redis.log",
"/var/log/dist-upgrade",
"/var/log/installer",
"/var/log/unattended-upgrades",
"/var/log/apport.log"
]
SOSREPORT_FORBIDDEN_PATHS = [
"/etc/tower/SECRET_KEY",
"/etc/tower/tower.key",
"/etc/tower/awx.key",
"/etc/tower/tower.cert",
"/etc/tower/awx.cert",
"/var/log/tower/profile"
]
class Tower(Plugin, RedHatPlugin, UbuntuPlugin):
'''Collect Ansible Tower related information'''
plugin_name = "tower"
def setup(self):
for path in SOSREPORT_TOWER_DIRS:
self.add_copy_spec(path)
self.add_forbidden_path(SOSREPORT_FORBIDDEN_PATHS)
self.add_cmd_output(SOSREPORT_TOWER_COMMANDS)
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash -x
TS="0.01"
./manage.py ui_test --verbose --time-scale 0.1
./manage.py replay_recording 143 recordings/test_create_two_switches.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_edit_labels2.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_undo_redo.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_undo_redo_control_mouse_wheel.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_deploy_destroy.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_undo_redo_create_destroy.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_multiple_viewers.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_view_hotkeys.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_recording.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_mouse.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_rack.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_link_unconnected.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_touches.replay --time-scale ${TS} --delete-topology-at-start
./manage.py replay_recording 143 recordings/test_export.replay --delete-topology-at-start --time-scale 0.1
./manage.py replay_recording 143 recordings/test_mouse_exit_enter.replay --delete-topology-at-start --time-scale ${TS}
sleep 1
istanbul report --root coverage --dir out text text-summary html