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
+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