forked from cockpit-project/bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3-streamer
executable file
·367 lines (286 loc) · 13.5 KB
/
s3-streamer
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#!/usr/bin/python3
# This file is part of Cockpit.
# Copyright (C) 2022 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import codecs
import json
import locale
import logging
import mimetypes
import os
import platform
import re
import shlex
import subprocess
import tempfile
import textwrap
import time
import urllib.parse
from typing import ClassVar, Collection
from lib import s3
from lib.constants import LIB_DIR
from lib.stores import LOG_STORE
from task import github
logger = logging.getLogger('s3-streamer')
class Destination:
directory: str
def has(self, filename: str) -> bool:
raise NotImplementedError
def write(self, filename: str, data: bytes) -> None:
raise NotImplementedError
def delete(self, filenames: Collection[str]) -> None:
raise NotImplementedError
class LocalDestination(Destination):
def __init__(self, directory: str) -> None:
self.directory = directory
os.makedirs(self.directory)
def path(self, filename: str) -> str:
return os.path.join(self.directory, filename)
def has(self, filename: str) -> bool:
return os.path.exists(self.path(filename))
def write(self, filename: str, data: bytes) -> None:
print(f'Write {self.path(filename)}')
with open(self.path(filename), 'wb+') as file:
file.write(data)
def delete(self, filenames: Collection[str]) -> None:
for filename in filenames:
print(f'Delete {self.path(filename)}')
os.unlink(self.path(filename))
class S3Destination(Destination):
def __init__(self, directory: str) -> None:
self.directory = directory.rstrip('/') + '/'
def url(self, filename: str) -> urllib.parse.ParseResult:
return urllib.parse.urlparse(self.directory + filename)
def has(self, filename: str) -> bool:
raise NotImplementedError('use Index')
def write(self, filename: str, data: bytes) -> None:
content_type, content_encoding = mimetypes.guess_type(filename)
headers = {
'Content-Type': content_type or 'text/plain',
s3.ACL: s3.PUBLIC
}
if content_encoding:
headers['Content-Encoding'] = content_encoding
with s3.urlopen(self.url(filename), data=data, method='PUT', headers=headers) as _:
pass
def delete(self, filenames: Collection[str]) -> None:
# to do: multi-object delete API
for filename in filenames:
with s3.urlopen(self.url(filename), method='DELETE') as _:
pass
class Index(Destination):
files: set[str]
def __init__(self, destination: Destination, filename: str = 'index.html') -> None:
self.destination = destination
self.filename = filename
self.files = set()
self.dirty = True
def has(self, filename: str) -> bool:
return filename in self.files
def write(self, filename: str, data: bytes) -> None:
self.destination.write(filename, data)
self.files.add(filename)
self.dirty = True
def delete(self, filenames: Collection[str]) -> None:
raise NotImplementedError
def sync(self) -> None:
if self.dirty:
self.destination.write(self.filename, textwrap.dedent('''
<html>
<body>
<h1>Directory listing for /</h1>
<hr>
<ul>''' + ''.join(f'''
<li><a href={f}>{f}</a></li> ''' for f in sorted(self.files)) + '''
</ul>
</body>
</html>
''').encode('utf-8'))
self.dirty = False
class AttachmentsDirectory:
def __init__(self, destination: Destination, local_directory: str) -> None:
self.destination = destination
self.path = local_directory
def scan(self) -> None:
for subdir, _dirs, files in os.walk(self.path):
for filename in files:
path = os.path.join(subdir, filename)
name = os.path.relpath(path, start=self.path)
if not self.destination.has(name):
logger.debug('Uploading attachment %s', name)
with open(path, 'rb') as file:
data = file.read()
self.destination.write(name, data)
class ChunkedUploader:
SIZE_LIMIT: ClassVar[int] = 1000000 # 1MB
TIME_LIMIT: ClassVar[int] = 30 # 30s
chunks: list[list[bytes]]
suffixes: set[str]
send_at: float | None
def __init__(self, index: Index, filename: str):
assert locale.getpreferredencoding() == 'UTF-8'
self.input_decoder = codecs.getincrementaldecoder('UTF-8')(errors='replace')
self.suffixes = {'chunks'}
self.chunks = []
self.index = index
self.destination = index.destination
self.filename = filename
self.pending = b''
self.send_at = 0 # Send the first write immediately
def start(self, data: str) -> None:
# Send the initial data immediately, to get the chunks file written out.
self.append_block(data.encode('utf-8'))
AttachmentsDirectory(self.index, f'{LIB_DIR}/s3-html').scan()
def append_block(self, block: bytes) -> None:
self.chunks.append([block])
# 2048 algorithm.
#
# This can be changed to merge more or less often, or to never merge at
# all. The only restriction is that it may only ever update the last
# item in the list.
while len(self.chunks) > 1 and len(self.chunks[-1]) == len(self.chunks[-2]):
last = self.chunks.pop()
second_last = self.chunks.pop()
self.chunks.append(second_last + last)
# Now we figure out how to send that last item.
# Let's keep the client dumb: it doesn't need to know about blocks: only bytes.
chunk_sizes = [sum(len(block) for block in chunk) for chunk in self.chunks]
if chunk_sizes:
last_chunk_start = sum(chunk_sizes[:-1])
last_chunk_end = last_chunk_start + chunk_sizes[-1]
last_chunk_suffix = f'{last_chunk_start}-{last_chunk_end}'
self.destination.write(f'{self.filename}.{last_chunk_suffix}', b''.join(self.chunks[-1]))
self.suffixes.add(last_chunk_suffix)
self.destination.write(f'{self.filename}.chunks', json.dumps(chunk_sizes).encode('ascii'))
def write(self, data: bytes, *, final: bool = False) -> None:
# Transcode the data (if necessary), and ensure that it's complete characters
self.pending += self.input_decoder.decode(data, final=final).encode('utf-8')
if final:
everything = b''.join(b''.join(block for block in chunk) for chunk in self.chunks) + self.pending
self.index.write(self.filename, everything)
# If the client ever sees a 404, it knows that the streaming is over.
self.destination.delete([f'{self.filename}.{suffix}' for suffix in self.suffixes])
if self.pending:
now = time.monotonic()
if self.send_at is None:
self.send_at = now + ChunkedUploader.TIME_LIMIT
if now >= self.send_at or len(self.pending) >= ChunkedUploader.SIZE_LIMIT:
self.append_block(self.pending)
self.send_at = None
self.pending = b''
class Status:
def post(self, state: str, description: str) -> None:
raise NotImplementedError
class GitHubStatus(Status):
def __init__(self, repo: str, revision: str, context: str, link: str) -> None:
logger.debug('GitHub repo %s context %s link %s', repo, context, link)
self.github = github.GitHub(repo=repo)
self.status = {'context': context, 'target_url': link}
self.revision = revision
def post(self, state: str, description: str) -> None:
logger.debug('POST statuses/%s %s %s', self.revision, state, description)
self.github.post(f'statuses/{self.revision}', dict(self.status, state=state, description=description))
class LocalStatus(Status):
def __init__(self, directory: str) -> None:
print(f'Writing logs to {directory}')
def post(self, state: str, description: str) -> None:
print(f'Status [{state}] {description}')
def main() -> None:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--s3', help="Write to the given S3 URL [default: S3_LOGS_URL]")
group.add_argument('--directory', help="Write to the named local directory")
parser.add_argument('--test-name', required=True, help='Test name')
parser.add_argument('--repo', default=None, help="The repository in which the tested PR is opened")
parser.add_argument('--revision', required=True, help="Revision of the PR head")
parser.add_argument('--github-context', required=True, help="The full context as written in github")
parser.add_argument('cmd', nargs='+', help="Command to stream the output of")
args = parser.parse_args()
subdir = f'{args.test_name}-{args.revision[:8]}-{args.github_context}'
subdir = subdir.replace('@', '-').replace('#', '-').replace('/', '-')
destination: Destination
status: Status
if args.directory:
destination = LocalDestination(os.path.join(args.directory, subdir))
status = LocalStatus(destination.directory)
else:
url = args.s3 or os.getenv('S3_LOGS_URL', LOG_STORE)
destination = S3Destination(urllib.parse.urljoin(url, subdir))
status = GitHubStatus(args.repo, args.revision, args.github_context, destination.directory + 'log.html')
# We want the pipe buffer as big as possible, for two reasons:
# - uploading to S3 might take a while and we don't want the output of
# the test to block in the meantime
# - having a large buffer means that we can do a single read and be sure
# to get all the data. This is particularly important at exit: we don't
# wait for EOF on the log before exiting.
#
# This is the default value on Linux, and big enough for our purposes. It
# could theoretically have been lowered via /proc/sys/fs/pipe-max-size, but
# then fcntl() will fail and we'll find out about it.
max_pipe_size = 1048576
with tempfile.TemporaryDirectory() as tmpdir:
index = Index(destination)
attachments_directory = AttachmentsDirectory(index, tmpdir)
log_uploader = ChunkedUploader(index, 'log')
env = {
**os.environ,
'TEST_ATTACHMENTS': tmpdir,
'TEST_ATTACHMENTS_URL': destination.directory,
'COCKPIT_CI_LOG_URL': destination.directory + 'log.html'
}
with subprocess.Popen(args.cmd, env=env,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
# pipesize is new in Python 3.10, LGTM does not know about it yet
stdin=subprocess.DEVNULL, pipesize=max_pipe_size) as process: # lgtm
# We want non-blocking reads so that we can send attachments and
# flush pending chunked data in case the output stalls.
assert process.stdout is not None
os.set_blocking(process.stdout.fileno(), False)
# Send the static files to start
pretty_name = re.sub(r'^pull-(\d+)-\d+-\d+$', r'PR #\1', args.test_name)
log_uploader.start(textwrap.dedent(f"""
{args.repo} {pretty_name}: {args.github_context} on {platform.node()}
Running on: {platform.node()}
Current time: {time.strftime('%c UTC', time.gmtime())}
Test name: {args.test_name}
Command: {shlex.join(args.cmd)}
""").lstrip())
# In progress...
status.post('pending', f'Testing in progress [{platform.node()}]')
process_exited = False
while not process_exited:
# Order is important: poll the process, read the log, upload attachments, send the log.
#
# The idea is that we want to read the log one last time after
# the process has exited, and we also want to make sure that
# any attachment gets uploaded before its mention in the log
# reaches the server.
time.sleep(1)
process_exited = process.poll() is not None
try:
data = os.read(process.stdout.fileno(), max_pipe_size)
except BlockingIOError:
data = b''
attachments_directory.scan()
log_uploader.write(data, final=process_exited)
index.sync()
if process.returncode != 0:
status.post('failure', f'Tests failed with code {process.returncode}')
else:
status.post('success', 'Tests passed')
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
main()