forked from python/docsbuild-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_docs_server.py
More file actions
169 lines (141 loc) · 4.26 KB
/
build_docs_server.py
File metadata and controls
169 lines (141 loc) · 4.26 KB
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
"""Github hook server.
This is a simple HTTP server handling Github Webhooks requests to
build the doc when needed.
It needs a GH_SECRET environment variable to be able to receive hooks
on `/hook/github`.
Its logging can be configured by giving a yaml file path to the
`--logging-config` argument.
By default the loglevel is `DEBUG` on `stderr`, the default config can
be found in the code so one can bootstrap a different config from it.
"""
from pathlib import Path
import argparse
import asyncio
import logging.config
import os
from aiohttp import web
from gidgethub import sansio
import yaml
from build_docs import VERSIONS
__version__ = "0.0.1"
DEFAULT_LOGGING_CONFIG = """
---
version: 1
disable_existing_loggers: false
formatters:
normal:
format: '%(asctime)s - %(levelname)s - %(message)s'
handlers:
stderr:
class: logging.StreamHandler
stream: ext://sys.stderr
level: DEBUG
formatter: normal
loggers:
build_docs_server:
level: DEBUG
handlers: [stderr]
aiohttp.access:
level: DEBUG
handlers: [stderr]
aiohttp.client:
level: DEBUG
handlers: [stderr]
aiohttp.internal:
level: DEBUG
handlers: [stderr]
aiohttp.server:
level: DEBUG
handlers: [stderr]
aiohttp.web:
level: DEBUG
handlers: [stderr]
aiohttp.websocket:
level: DEBUG
handlers: [stderr]
"""
logger = logging.getLogger("build_docs_server")
async def version(request):
return web.json_response(
{
"name": "docs.python.org Github handler",
"version": __version__,
"source": "https://github.com/python/docsbuild-scripts",
}
)
async def child_waiter(app):
while True:
try:
status = os.waitid(os.P_ALL, 0, os.WNOHANG | os.WEXITED)
logger.debug("Child completed with status %s", str(status))
except ChildProcessError:
await asyncio.sleep(600)
async def start_child_waiter(app):
app["child_waiter"] = asyncio.ensure_future(child_waiter(app))
async def stop_child_waiter(app):
app["child_waiter"].cancel()
async def hook(request):
body = await request.read()
event = sansio.Event.from_http(
request.headers, body, secret=os.environ.get("GH_SECRET")
)
if event.event != "push":
logger.debug("Received a %s event, nothing to do.", event.event)
return web.Response()
touched_files = (
set(event.data["head_commit"]["added"])
| set(event.data["head_commit"]["modified"])
| set(event.data["head_commit"]["removed"])
)
if not any("Doc" in touched_file for touched_file in touched_files):
logger.debug("No documentation file modified, ignoring.")
return web.Response() # Nothing to do
branch = event.data["ref"].split("/")[-1]
known_branches = {version.branch for version in VERSION}
if branch not in known_branches:
logger.warning("Ignoring a change in branch %s (unknown branch)", branch)
return web.Response() # Nothing to do
logger.debug("Forking a build for branch %s", branch)
pid = os.fork()
if pid == 0:
os.execl(
"/usr/bin/env",
"/usr/bin/env",
"python",
"build_docs.py",
"--branch",
branch,
)
else:
return web.Response()
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--path", help="Unix socket to listen for connections.")
parser.add_argument("--port", help="Local port to listen for connections.")
parser.add_argument(
"--logging-config",
help="yml file containing a Python logging dictconfig, see README.md",
)
return parser.parse_args()
def main():
args = parse_args()
logging.config.dictConfig(
yaml.load(
Path(args.logging_config).read_text()
if args.logging_config
else DEFAULT_LOGGING_CONFIG,
Loader=yaml.SafeLoader,
)
)
app = web.Application()
app.on_startup.append(start_child_waiter)
app.on_cleanup.append(stop_child_waiter)
app.add_routes(
[
web.get("/", version),
web.post("/hooks/github", hook),
]
)
web.run_app(app, path=args.path, port=args.port)
if __name__ == "__main__":
main()