forked from bazel-contrib/rules_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprecompiler.py
More file actions
296 lines (254 loc) · 11.3 KB
/
precompiler.py
File metadata and controls
296 lines (254 loc) · 11.3 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
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
# Copyright 2024 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A simple precompiler to generate deterministic pyc files for Bazel."""
# NOTE: Imports specific to the persistent worker should only be imported
# when a persistent worker is used. Avoiding the unnecessary imports
# saves significant startup time for non-worker invocations.
import argparse
import py_compile
import sys
def _create_parser() -> "argparse.Namespace":
parser = argparse.ArgumentParser(fromfile_prefix_chars="@")
parser.add_argument("--invalidation_mode", default="CHECKED_HASH")
parser.add_argument("--optimize", type=int, default=-1)
parser.add_argument("--python_version")
parser.add_argument("--src", action="append", dest="srcs")
parser.add_argument("--src_name", action="append", dest="src_names")
parser.add_argument("--pyc", action="append", dest="pycs")
parser.add_argument("--persistent_worker", action="store_true")
parser.add_argument("--log_level", default="ERROR")
parser.add_argument("--worker_impl", default="async")
return parser
def _compile(options: "argparse.Namespace") -> None:
try:
invalidation_mode = py_compile.PycInvalidationMode[
options.invalidation_mode.upper()
]
except KeyError as e:
raise ValueError(
f"Unknown PycInvalidationMode: {options.invalidation_mode}"
) from e
if not (len(options.srcs) == len(options.src_names) == len(options.pycs)):
raise AssertionError(
"Mismatched number of --src, --src_name, and/or --pyc args"
)
for src, src_name, pyc in zip(options.srcs, options.src_names, options.pycs):
py_compile.compile(
src,
pyc,
doraise=True,
dfile=src_name,
optimize=options.optimize,
invalidation_mode=invalidation_mode,
)
return 0
# A stub type alias for readability.
# See the Bazel WorkRequest object definition:
# https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/worker_protocol.proto
JsonWorkRequest = object
# A stub type alias for readability.
# See the Bazel WorkResponse object definition:
# https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/worker_protocol.proto
JsonWorkResponse = object
class _SerialPersistentWorker:
"""Simple, synchronous, serial persistent worker."""
def __init__(self, instream: "typing.TextIO", outstream: "typing.TextIO"):
self._instream = instream
self._outstream = outstream
self._parser = _create_parser()
def run(self) -> None:
try:
while True:
request = None
try:
request = self._get_next_request()
if request is None:
_logger.info("Empty request: exiting")
break
response = self._process_request(request)
if response: # May be none for cancel request
self._send_response(response)
except Exception:
_logger.exception("Unhandled error: request=%s", request)
output = (
f"Unhandled error:\nRequest: {request}\n"
+ traceback.format_exc()
)
request_id = 0 if not request else request.get("requestId", 0)
self._send_response(
{
"exitCode": 3,
"output": output,
"requestId": request_id,
}
)
finally:
_logger.info("Worker shutting down")
def _get_next_request(self) -> "object | None":
line = self._instream.readline()
if not line:
return None
return json.loads(line)
def _process_request(self, request: "JsonWorkRequest") -> "JsonWorkResponse | None":
if request.get("cancel"):
return None
options = self._options_from_request(request)
_compile(options)
response = {
"requestId": request.get("requestId", 0),
"exitCode": 0,
}
return response
def _options_from_request(
self, request: "JsonWorkResponse"
) -> "argparse.Namespace":
options = self._parser.parse_args(request["arguments"])
if request.get("sandboxDir"):
prefix = request["sandboxDir"]
options.srcs = [os.path.join(prefix, v) for v in options.srcs]
options.pycs = [os.path.join(prefix, v) for v in options.pycs]
return options
def _send_response(self, response: "JsonWorkResponse") -> None:
self._outstream.write(json.dumps(response) + "\n")
self._outstream.flush()
class _AsyncPersistentWorker:
"""Asynchronous, concurrent, persistent worker."""
def __init__(self, reader: "typing.TextIO", writer: "typing.TextIO"):
self._reader = reader
self._writer = writer
self._parser = _create_parser()
self._request_id_to_task = {}
self._task_to_request_id = {}
@classmethod
async def main(cls, instream: "typing.TextIO", outstream: "typing.TextIO") -> None:
reader, writer = await cls._connect_streams(instream, outstream)
await cls(reader, writer).run()
@classmethod
async def _connect_streams(
cls, instream: "typing.TextIO", outstream: "typing.TextIO"
) -> "tuple[asyncio.StreamReader, asyncio.StreamWriter]":
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pipe(lambda: protocol, instream)
w_transport, w_protocol = await loop.connect_write_pipe(
asyncio.streams.FlowControlMixin, outstream
)
writer = asyncio.StreamWriter(w_transport, w_protocol, reader, loop)
return reader, writer
async def run(self) -> None:
while True:
_logger.info("pending requests: %s", len(self._request_id_to_task))
request = await self._get_next_request()
request_id = request.get("requestId", 0)
task = asyncio.create_task(
self._process_request(request), name=f"request_{request_id}"
)
self._request_id_to_task[request_id] = task
self._task_to_request_id[task] = request_id
task.add_done_callback(self._handle_task_done)
async def _get_next_request(self) -> "JsonWorkRequest":
_logger.debug("awaiting line")
line = await self._reader.readline()
_logger.debug("recv line: %s", line)
return json.loads(line)
def _handle_task_done(self, task: "asyncio.Task") -> None:
request_id = self._task_to_request_id[task]
_logger.info("task done: %s %s", request_id, task)
del self._task_to_request_id[task]
del self._request_id_to_task[request_id]
async def _process_request(self, request: "JsonWorkRequest") -> None:
_logger.info("request %s: start: %s", request.get("requestId"), request)
try:
if request.get("cancel", False):
await self._process_cancel_request(request)
else:
await self._process_compile_request(request)
except asyncio.CancelledError:
_logger.info(
"request %s: cancel received, stopping processing",
request.get("requestId"),
)
# We don't send a response because we assume the request that
# triggered cancelling sent the response
raise
except:
_logger.exception("Unhandled error: request=%s", request)
self._send_response(
{
"exitCode": 3,
"output": f"Unhandled error:\nRequest: {request}\n"
+ traceback.format_exc(),
"requestId": 0 if not request else request.get("requestId", 0),
}
)
async def _process_cancel_request(self, request: "JsonWorkRequest") -> None:
request_id = request.get("requestId", 0)
task = self._request_id_to_task.get(request_id)
if not task:
# It must be already completed, so ignore the request, per spec
return
task.cancel()
self._send_response({"requestId": request_id, "wasCancelled": True})
async def _process_compile_request(self, request: "JsonWorkRequest") -> None:
options = self._options_from_request(request)
# _compile performs a varity of blocking IO calls, so run it separately
await asyncio.to_thread(_compile, options)
self._send_response(
{
"requestId": request.get("requestId", 0),
"exitCode": 0,
}
)
def _options_from_request(self, request: "JsonWorkRequest") -> "argparse.Namespace":
options = self._parser.parse_args(request["arguments"])
if request.get("sandboxDir"):
prefix = request["sandboxDir"]
options.srcs = [os.path.join(prefix, v) for v in options.srcs]
options.pycs = [os.path.join(prefix, v) for v in options.pycs]
return options
def _send_response(self, response: "JsonWorkResponse") -> None:
_logger.info("request %s: respond: %s", response.get("requestId"), response)
self._writer.write(json.dumps(response).encode("utf8") + b"\n")
def main(args: "list[str]") -> int:
options = _create_parser().parse_args(args)
# Persistent workers are started with the `--persistent_worker` flag.
# See the following docs for details on persistent workers:
# https://bazel.build/remote/persistent
# https://bazel.build/remote/multiplex
# https://bazel.build/remote/creating
if options.persistent_worker:
global asyncio, itertools, json, logging, os, traceback, _logger
import asyncio
import itertools
import json
import logging
import os.path
import traceback
_logger = logging.getLogger("precompiler")
# Only configure logging for workers. This prevents non-worker
# invocations from spamming stderr with logging info
logging.basicConfig(level=getattr(logging, options.log_level))
_logger.info("persistent worker: impl=%s", options.worker_impl)
if options.worker_impl == "serial":
_SerialPersistentWorker(sys.stdin, sys.stdout).run()
elif options.worker_impl == "async":
asyncio.run(_AsyncPersistentWorker.main(sys.stdin, sys.stdout))
else:
raise ValueError(f"Unknown worker impl: {options.worker_impl}")
else:
_compile(options)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))