-
Notifications
You must be signed in to change notification settings - Fork 75
/
builtin.py
224 lines (191 loc) · 5.22 KB
/
builtin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import asyncio
import concurrent.futures
import glob
import json
import logging
import os
import shutil
import sys
import tempfile
import uuid
from functools import partial
from pprint import pprint
from typing import Callable, Dict, List, Optional
import ansible_runner
import dpath.util
import durable.lang
import yaml
from .collection import find_playbook, has_playbook, split_collection_name
from .conf import settings
from .exception import ShutdownException
from .util import get_horizontal_rule
async def none(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
):
pass
async def debug(**kwargs):
print(get_horizontal_rule("="))
print("context:")
pprint(durable.lang.c.__dict__)
print(get_horizontal_rule("="))
print("facts:")
pprint(durable.lang.get_facts(kwargs["ruleset"]))
print(get_horizontal_rule("="))
print("kwargs:")
pprint(kwargs)
print(get_horizontal_rule("="))
sys.stdout.flush()
async def print_event(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
var_root: Optional[str] = None,
pretty: Optional[str] = None,
):
print_fn: Callable = print
if pretty:
print_fn = pprint
if var_root:
print_fn(dpath.util.get(variables["event"], var_root, separator="."))
else:
print_fn(variables["event"])
sys.stdout.flush()
async def assert_fact(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
fact: Dict,
):
logger = logging.getLogger()
logger.debug(f"assert_fact {ruleset} {fact}")
durable.lang.assert_fact(ruleset, fact)
async def retract_fact(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
fact: Dict,
):
durable.lang.retract_fact(ruleset, fact)
async def post_event(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
fact: Dict,
):
durable.lang.post(ruleset, fact)
async def run_playbook(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
name: str,
assert_facts: Optional[bool] = None,
post_events: Optional[bool] = None,
verbosity: int = 0,
var_root: Optional[str] = None,
copy_files: Optional[bool] = False,
**kwargs,
):
logger = logging.getLogger()
temp = tempfile.mkdtemp(prefix="run_playbook")
logger.debug(f"temp {temp}")
logger.debug(f"variables {variables}")
logger.debug(f"facts {facts}")
variables["facts"] = facts
if var_root:
o = dpath.util.get(variables["event"], var_root, separator=".")
variables["event"] = o
os.mkdir(os.path.join(temp, "env"))
with open(os.path.join(temp, "env", "extravars"), "w") as f:
f.write(yaml.dump(variables))
os.mkdir(os.path.join(temp, "inventory"))
with open(os.path.join(temp, "inventory", "hosts"), "w") as f:
f.write(yaml.dump(inventory))
os.mkdir(os.path.join(temp, "project"))
if os.path.exists(name):
shutil.copy(name, os.path.join(temp, "project", name))
elif has_playbook(*split_collection_name(name)):
shutil.copy(
find_playbook(*split_collection_name(name)),
os.path.join(temp, "project", name),
)
else:
raise Exception(f"Could not find a playbook for {name}")
if copy_files:
shutil.copytree(
os.path.dirname(os.path.abspath(name)),
os.path.join(temp, "project"),
dirs_exist_ok=True,
)
host_limit = ",".join(hosts)
job_id = str(uuid.uuid4())
await event_log.put(
dict(type="Job", job_id=job_id, ansible_events_id=settings.identifier)
)
def event_callback(event, *args, **kwargs):
event["job_id"] = job_id
event["ansible_events_id"] = settings.identifier
event_log.put_nowait(dict(type="AnsibleEvent", event=event))
loop = asyncio.get_running_loop()
task_pool = concurrent.futures.ThreadPoolExecutor()
await loop.run_in_executor(
task_pool,
partial(
ansible_runner.run,
playbook=name,
private_data_dir=temp,
limit=host_limit,
verbosity=verbosity,
event_handler=event_callback,
),
)
if assert_facts or post_events:
logger.debug("assert_facts")
for host_facts in glob.glob(
os.path.join(temp, "artifacts", "*", "fact_cache", "*")
):
with open(host_facts) as f:
fact = json.loads(f.read())
logger.debug(f"fact {fact}")
if assert_facts:
durable.lang.assert_fact(ruleset, fact)
if post_events:
durable.lang.post(ruleset, fact)
async def shutdown(
event_log,
inventory: Dict,
hosts: List,
variables: Dict,
facts: Dict,
ruleset: str,
):
raise ShutdownException()
actions: Dict[str, Callable] = dict(
none=none,
debug=debug,
print_event=print_event,
assert_fact=assert_fact,
retract_fact=retract_fact,
post_event=post_event,
run_playbook=run_playbook,
shutdown=shutdown,
)