Debian Codegraph @

scripts/flat-manager-client

raw symbols SCIP
1 #!/usr/bin/python3
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16
17 import asyncio
18 import base64
19 import binascii
20 import errno
21 import fnmatch
22 import gzip
23 import json
24 import logging
25 import os
26 import sys
27 import time
28 import traceback
29 from argparse import ArgumentParser
30 from functools import reduce
31 from urllib.parse import urljoin, urlparse, urlunparse
32 from tenacity import (
33 retry,
34 retry_if_exception_type,
35 stop_after_delay,
36 wait_random_exponential,
37 )
38
39 import aiohttp
40 import aiohttp.client_exceptions
41 import gi
42
43 gi.require_version("OSTree", "1.0")
44 from gi.repository import Gio, GLib, OSTree # noqa: E402
45
46 UPLOAD_CHUNK_LIMIT = 4 * 1024 * 1024
47 DEFAULT_LIMIT = 2**16
48
49
50 def eprint(*args, **kwargs):
51 print(*args, file=sys.stderr, **kwargs)
52
53
54 class UsageException(Exception):
55 def __init__(self, msg):
56 self.msg = msg
57
58 def __str__(self):
59 return self.msg
60
61
62 class ApiError(Exception):
63 def __init__(self, response, body):
64 self.url = str(response.url)
65 self.status = response.status
66
67 try:
68 self.body = json.loads(body)
69 except (json.JSONDecodeError, TypeError):
70 self.body = {
71 "status": self.status,
72 "error-type": "no-error",
73 "message": f"Non-json error from server: {body}",
74 }
75
76 def repr(self):
77 return {
78 "type": "api",
79 "url": self.url,
80 "status_code": self.status,
81 "details": self.body,
82 }
83
84 def __str__(self):
85 return "Api call to %s failed with status %d, details: %s" % (
86 self.url,
87 self.status,
88 self.body,
89 )
90
91
92 class ServerApiError(ApiError):
93 def __init__(self, response, body):
94 super().__init__(response, body)
95
96
97 class FailedJobError(Exception):
98 def __init__(self, job):
99 self.job = job
100
101 def repr(self):
102 return {"type": "job", "job": self.job}
103
104 def __str__(self):
105 return "Job failed: %s" % (self.job)
106
107
108 TENACITY_RETRY_EXCEPTIONS = retry_if_exception_type(
109 (
110 aiohttp.client_exceptions.ServerDisconnectedError,
111 ServerApiError,
112 aiohttp.client_exceptions.ServerConnectionError,
113 aiohttp.client_exceptions.ClientOSError,
114 )
115 )
116 TENACITY_STOP_AFTER = stop_after_delay(300)
117 TENACITY_WAIT_BETWEEN = wait_random_exponential(multiplier=1, max=60)
118
119
120 # This is similar to the regular payload, but opens the file lazily
121 class AsyncNamedFilePart(aiohttp.payload.Payload):
122 def __init__(self, value, disposition="attachment", *args, **kwargs):
123 self._file = None
124 if "filename" not in kwargs:
125 kwargs["filename"] = os.path.basename(value)
126
127 super().__init__(value, *args, **kwargs)
128
129 if self._filename is not None and disposition is not None:
130 self.set_content_disposition(
131 disposition, filename=self._filename, quote_fields=False
132 )
133
134 self._size = os.stat(value).st_size
135
136 def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
137 raise NotImplementedError
138
139 async def write(self, writer):
140 if self._file is None or self._file.closed:
141 self._file = open(self._value, "rb")
142 try:
143 chunk = self._file.read(DEFAULT_LIMIT)
144 while chunk:
145 await writer.write(chunk)
146 chunk = self._file.read(DEFAULT_LIMIT)
147 finally:
148 self._file.close()
149
150 @property
151 def size(self):
152 return self._size
153
154
155 def ostree_object_path(repo, obj):
156 repodir = repo.get_path().get_path()
157 return os.path.join(repodir, "objects", obj[0:2], obj[2:])
158
159
160 def ostree_get_dir_files(repo, objects, dirtree):
161 if dirtree.endswith(".dirtree"):
162 dirtree = dirtree[:-8]
163 dirtreev = repo.load_variant(OSTree.ObjectType.DIR_TREE, dirtree)[1]
164 iter = OSTree.RepoCommitTraverseIter()
165 iter.init_dirtree(repo, dirtreev, 0)
166 while True:
167 type = iter.next()
168 if type == OSTree.RepoCommitIterResult.END:
169 break
170 if type == OSTree.RepoCommitIterResult.ERROR:
171 break
172 if type == OSTree.RepoCommitIterResult.FILE:
173 d = iter.get_file()
174 objects.add(d.out_checksum + ".filez")
175 if type == OSTree.RepoCommitIterResult.DIR:
176 pass
177
178
179 def local_needed_files(repo, metadata_objects):
180 objects = set()
181 for c in metadata_objects:
182 if c.endswith(".dirtree"):
183 ostree_get_dir_files(repo, objects, c)
184 return objects
185
186
187 def local_needed_metadata_dirtree(repo, objects, dirtree_content, dirtree_meta):
188 objects.add(dirtree_meta + ".dirmeta")
189 dirtree_content_name = dirtree_content + ".dirtree"
190 if dirtree_content_name in objects:
191 return
192 objects.add(dirtree_content_name)
193
194 dirtreev = repo.load_variant(OSTree.ObjectType.DIR_TREE, dirtree_content)[1]
195 iter = OSTree.RepoCommitTraverseIter()
196 iter.init_dirtree(repo, dirtreev, 0)
197 while True:
198 type = iter.next()
199 if type == OSTree.RepoCommitIterResult.END:
200 break
201 if type == OSTree.RepoCommitIterResult.ERROR:
202 break
203 if type == OSTree.RepoCommitIterResult.FILE:
204 pass
205 if type == OSTree.RepoCommitIterResult.DIR:
206 d = iter.get_dir()
207 local_needed_metadata_dirtree(
208 repo, objects, d.out_content_checksum, d.out_meta_checksum
209 )
210
211
212 def local_needed_metadata(repo, commits):
213 objects = set()
214 for rev in commits:
215 objects.add(rev + ".commit")
216 commitv = repo.load_variant(OSTree.ObjectType.COMMIT, rev)[1]
217 iter = OSTree.RepoCommitTraverseIter()
218 iter.init_commit(repo, commitv, 0)
219 while True:
220 type = iter.next()
221 if type == OSTree.RepoCommitIterResult.END:
222 break
223 if type == OSTree.RepoCommitIterResult.ERROR:
224 break
225 if type == OSTree.RepoCommitIterResult.FILE:
226 pass
227 if type == OSTree.RepoCommitIterResult.DIR:
228 d = iter.get_dir()
229 local_needed_metadata_dirtree(
230 repo, objects, d.out_content_checksum, d.out_meta_checksum
231 )
232 return objects
233
234
235 def chunks(iterable, n):
236 """Yield successive n-sized chunks from iterable."""
237 for i in range(0, len(iterable), n):
238 yield iterable[i : i + n]
239
240
241 @retry(
242 stop=TENACITY_STOP_AFTER,
243 wait=TENACITY_WAIT_BETWEEN,
244 retry=TENACITY_RETRY_EXCEPTIONS,
245 reraise=True,
246 )
247 async def _missing_chunk(session, build_url, chunk, headers):
248 wanted_json = json.dumps({"wanted": chunk}).encode("utf-8")
249 data = gzip.compress(wanted_json)
250
251 resp = await session.get(build_url + "/missing_objects", data=data, headers=headers)
252 async with resp:
253 if resp.status >= 500:
254 raise ServerApiError(resp, await resp.text())
255 if resp.status != 200:
256 raise ApiError(resp, await resp.text())
257
258 return await resp.json()
259
260
261 async def missing_objects(session, build_url, token, wanted):
262 missing = []
263 for chunk in chunks(wanted, 2000):
264 headers = {
265 "Authorization": "Bearer " + token,
266 "Content-Encoding": "gzip",
267 "Content-Type": "application/json",
268 }
269 data = await _missing_chunk(session, build_url, chunk, headers)
270 missing.extend(data["missing"])
271 return missing
272
273
274 @retry(
275 stop=TENACITY_STOP_AFTER,
276 wait=TENACITY_WAIT_BETWEEN,
277 retry=TENACITY_RETRY_EXCEPTIONS,
278 reraise=True,
279 )
280 async def upload_files(session, build_url, token, files):
281 if len(files) == 0:
282 return
283 print(
284 "Uploading %d files (%d bytes)"
285 % (len(files), reduce(lambda x, y: x + y, map(lambda f: f.size, files)))
286 )
287 with aiohttp.MultipartWriter() as writer:
288 for f in files:
289 writer.append(f)
290 writer.headers["Authorization"] = "Bearer " + token
291 resp = await session.request(
292 "post", build_url + "/upload", data=writer, headers=writer.headers
293 )
294 async with resp:
295 if resp.status >= 500:
296 raise ServerApiError(resp, await resp.text())
297 elif resp.status != 200:
298 raise ApiError(resp, await resp.text())
299
300
301 @retry(
302 stop=TENACITY_STOP_AFTER,
303 wait=TENACITY_WAIT_BETWEEN,
304 retry=TENACITY_RETRY_EXCEPTIONS,
305 reraise=True,
306 )
307 async def upload_deltas(
308 session, repo_path, build_url, token, deltas, refs, ignore_delta
309 ):
310 if not len(deltas):
311 return
312
313 req = []
314 for ref, commit in refs.items():
315 # Skip screenshots here
316 parts = ref.split("/")
317 if (
318 len(parts) == 4
319 and (parts[0] == "app" or parts[0] == "runtime")
320 and not should_skip_delta(parts[1], ignore_delta)
321 ):
322 for delta in deltas:
323 # Only upload from-scratch deltas, as these are the only reused ones
324 if delta == commit:
325 print(" %s: %s" % (ref, delta))
326 delta_name = delta_name_encode(delta)
327 delta_dir = (
328 repo_path + "/deltas/" + delta_name[:2] + "/" + delta_name[2:]
329 )
330 parts = os.listdir(delta_dir)
331 for part in parts:
332 req.append(
333 AsyncNamedFilePart(
334 delta_dir + "/" + part,
335 filename=delta_name + "." + part + ".delta",
336 )
337 )
338
339 if len(req):
340 await upload_files(session, build_url, token, req)
341
342
343 @retry(
344 stop=TENACITY_STOP_AFTER,
345 wait=TENACITY_WAIT_BETWEEN,
346 retry=TENACITY_RETRY_EXCEPTIONS,
347 reraise=True,
348 )
349 async def upload_objects(session, repo_path, build_url, token, objects):
350 req = []
351 total_size = 0
352 for file_obj in objects:
353 named = get_object_multipart(repo_path, file_obj)
354 file_size = named.size
355 if (
356 total_size + file_size > UPLOAD_CHUNK_LIMIT
357 ): # The new object would bring us over the chunk limit
358 if len(req) > 0: # We already have some objects, upload those first
359 next_req = [named]
360 total_size = file_size
361 else:
362 next_req = []
363 req.append(named)
364 total_size = 0
365 await upload_files(session, build_url, token, req)
366 req = next_req
367 else:
368 total_size = total_size + file_size
369 req.append(named)
370
371 # Upload any remainder
372 await upload_files(session, build_url, token, req)
373
374
375 @retry(
376 stop=TENACITY_STOP_AFTER,
377 wait=TENACITY_WAIT_BETWEEN,
378 retry=TENACITY_RETRY_EXCEPTIONS,
379 reraise=True,
380 )
381 async def create_ref(session, build_url, token, ref, commit, build_log_url=None):
382 print("Creating ref %s with commit %s" % (ref, commit))
383 resp = await session.post(
384 build_url + "/build_ref",
385 headers={"Authorization": "Bearer " + token},
386 json={"ref": ref, "commit": commit, "build-log-url": build_log_url},
387 )
388 async with resp:
389 if resp.status >= 500:
390 raise ServerApiError(resp, await resp.text())
391 elif resp.status != 200:
392 raise ApiError(resp, await resp.text())
393
394 data = await resp.json()
395 return data
396
397
398 @retry(
399 stop=TENACITY_STOP_AFTER,
400 wait=TENACITY_WAIT_BETWEEN,
401 retry=TENACITY_RETRY_EXCEPTIONS,
402 reraise=True,
403 )
404 async def add_extra_ids(session, build_url, token, extra_ids):
405 print("Adding extra ids %s" % (extra_ids))
406 resp = await session.post(
407 build_url + "/add_extra_ids",
408 headers={"Authorization": "Bearer " + token},
409 json={"ids": extra_ids},
410 )
411 async with resp:
412 if resp.status >= 500:
413 raise ServerApiError(resp, await resp.text())
414 elif resp.status != 200:
415 raise ApiError(resp, await resp.text())
416
417 data = await resp.json()
418 return data
419
420
421 @retry(
422 stop=TENACITY_STOP_AFTER,
423 wait=TENACITY_WAIT_BETWEEN,
424 retry=TENACITY_RETRY_EXCEPTIONS,
425 reraise=True,
426 )
427 async def get_build(session, build_url, token):
428 resp = await session.get(build_url, headers={"Authorization": "Bearer " + token})
429 if resp.status != 200:
430 if resp.status >= 500:
431 raise ServerApiError(resp, await resp.text())
432 elif resp.status != 200:
433 raise ApiError(resp, await resp.text())
434 data = await resp.json()
435 return data
436
437
438 # For stupid reasons this is a string with json, lets expand it
439 def reparse_job_results(job):
440 job["results"] = json.loads(job.get("results", "{}"))
441 return job
442
443
444 @retry(
445 stop=TENACITY_STOP_AFTER,
446 wait=TENACITY_WAIT_BETWEEN,
447 retry=TENACITY_RETRY_EXCEPTIONS,
448 reraise=True,
449 )
450 async def get_job(session, job_url, token):
451 resp = await session.get(
452 job_url, headers={"Authorization": "Bearer " + token}, json={}
453 )
454 async with resp:
455 if resp.status >= 500:
456 raise ServerApiError(resp, await resp.text())
457 elif resp.status != 200:
458 raise ApiError(resp, await resp.text())
459 data = await resp.json()
460 return data
461
462
463 @retry(
464 stop=TENACITY_STOP_AFTER,
465 wait=TENACITY_WAIT_BETWEEN,
466 retry=TENACITY_RETRY_EXCEPTIONS,
467 reraise=True,
468 )
469 async def wait_for_job(session, job_url, token):
470 reported_delay = False
471 old_job_status = 0
472 printed_len = 0
473 iterations_since_change = 0
474 error_iterations = 0
475 while True:
476 try:
477 resp = await session.get(
478 job_url,
479 headers={"Authorization": "Bearer " + token},
480 json={"log-offset": printed_len},
481 )
482 async with resp:
483 if resp.status == 200:
484 error_iterations = 0
485 job = await resp.json()
486 job_status = job["status"]
487 if job_status == 0 and not reported_delay:
488 reported_delay = True
489 start_after_struct = job.get("start_after", None)
490 if start_after_struct:
491 start_after = start_after_struct.get(
492 "secs_since_epoch", None
493 )
494 now = time.time()
495 if start_after and start_after > now:
496 print(
497 "Waiting %d seconds before starting job"
498 % (int(start_after - now))
499 )
500 if job_status > 0 and old_job_status == 0:
501 print("/ Job was started")
502 old_job_status = job_status
503 log = job["log"]
504 if len(log) > 0:
505 iterations_since_change = 0
506 for line in log.splitlines(True):
507 print("| %s" % line, end="")
508 printed_len = printed_len + len(log)
509 else:
510 iterations_since_change = iterations_since_change + 1
511 if job_status > 1:
512 if job_status == 2:
513 print("\\ Job completed successfully")
514 else:
515 print("\\ Job failed")
516 raise FailedJobError(job)
517 return job
518 else:
519 iterations_since_change = (
520 4 # Start at 4 so we ramp up the delay faster
521 )
522 error_iterations = error_iterations + 1
523 if error_iterations <= 5:
524 print(
525 "Unexpected response %s getting job log, ignoring"
526 % resp.status
527 )
528 else:
529 raise ApiError(resp, await resp.text())
530 except OSError as e:
531 if e.args[0] == errno.ECONNRESET:
532 # Client disconnected, retry
533 # Not sure exactly why, but i got a lot of ConnectionResetErrors here
534 # in tests. I guess the server stops reusing a http2 session after a bit
535 # Should be fine to retry with the backof
536 pass
537 else:
538 raise
539 # Some polling backoff to avoid loading the server
540 if iterations_since_change <= 1:
541 sleep_time = 1
542 elif iterations_since_change < 5:
543 sleep_time = 3
544 elif iterations_since_change < 15:
545 sleep_time = 5
546 elif iterations_since_change < 30:
547 sleep_time = 10
548 else:
549 sleep_time = 60
550 time.sleep(sleep_time)
551
552
553 @retry(
554 stop=TENACITY_STOP_AFTER,
555 wait=TENACITY_WAIT_BETWEEN,
556 retry=TENACITY_RETRY_EXCEPTIONS,
557 reraise=True,
558 )
559 async def wait_for_checks(session, build_url, token):
560 print("Waiting for checks, if any...")
561 while True:
562 resp = await session.get(
563 build_url + "/extended", headers={"Authorization": "Bearer " + token}
564 )
565 async with resp:
566 if resp.status == 404:
567 return
568 if resp.status >= 500:
569 raise ServerApiError(resp, await resp.text())
570 elif resp.status != 200:
571 raise ApiError(resp, await resp.text())
572
573 build = await resp.json()
574
575 # wait for the repo to be validated
576 if build["build"]["repo_state"] == 1:
577 time.sleep(2)
578 else:
579 break
580
581 for check in build["checks"]:
582 print("Waiting for check: %s" % (check["check_name"]))
583 job_url = build_url + "/check/" + check["check_name"] + "/job"
584 await wait_for_job(session, job_url, token)
585
586 resp = await session.get(
587 build_url + "/extended", headers={"Authorization": "Bearer " + token}
588 )
589 async with resp:
590 if resp.status == 404:
591 return
592 if resp.status >= 500:
593 raise ServerApiError(resp, await resp.text())
594 elif resp.status != 200:
595 raise ApiError(resp, await resp.text())
596
597 build = await resp.json()
598 for check in build["checks"]:
599 if check["status"] == 3:
600 print("\\ Check {} has failed".format(check["check_name"]))
601 raise FailedJobError(check)
602
603
604 @retry(
605 stop=TENACITY_STOP_AFTER,
606 wait=TENACITY_WAIT_BETWEEN,
607 retry=TENACITY_RETRY_EXCEPTIONS,
608 reraise=True,
609 )
610 async def commit_build(session, build_url, eol, eol_rebase, token_type, wait, token):
611 print("Committing build %s" % (build_url))
612 json = {"endoflife": eol, "endoflife_rebase": eol_rebase}
613 if token_type is not None:
614 json["token_type"] = token_type
615 resp = await session.post(
616 build_url + "/commit", headers={"Authorization": "Bearer " + token}, json=json
617 )
618 async with resp:
619 if resp.status >= 500:
620 raise ServerApiError(resp, await resp.text())
621 elif resp.status != 200:
622 raise ApiError(resp, await resp.text())
623
624 job = await resp.json()
625 job_url = resp.headers["location"]
626
627 if wait:
628 pass
629
630 print("Waiting for commit job")
631 await wait_for_checks(session, build_url, token)
632 job = await wait_for_job(session, job_url, token)
633
634 reparse_job_results(job)
635 job["location"] = job_url
636 return job
637
638
639 @retry(
640 stop=TENACITY_STOP_AFTER,
641 wait=TENACITY_WAIT_BETWEEN,
642 retry=TENACITY_RETRY_EXCEPTIONS,
643 reraise=True,
644 )
645 async def publish_build(session, build_url, wait, token):
646 print("Publishing build %s" % (build_url))
647 resp = await session.post(
648 build_url + "/publish", headers={"Authorization": "Bearer " + token}, json={}
649 )
650 async with resp:
651 if resp.status == 400:
652 body = await resp.json()
653 try:
654 if isinstance(body, str):
655 body = json.loads(body)
656
657 current_state = body.get("current-state", None)
658
659 if current_state == "published":
660 print("the build has been already published")
661 return {}
662 if current_state == "publishing":
663 print("the build is currently being published")
664 return {}
665 elif current_state == "failed":
666 print("the build has failed")
667 raise ApiError(resp, await resp.text())
668 elif current_state == "validating":
669 print("the build is still being validated or held for review")
670 return {}
671 except json.JSONDecodeError:
672 pass
673
674 if resp.status != 200:
675 raise ApiError(resp, await resp.text())
676
677 job = await resp.json()
678 job_url = resp.headers["location"]
679
680 if wait:
681 print("Waiting for publish job")
682 job = await wait_for_job(session, job_url, token)
683
684 reparse_job_results(job)
685 job["location"] = job_url
686 return job
687
688
689 @retry(
690 stop=TENACITY_STOP_AFTER,
691 wait=TENACITY_WAIT_BETWEEN,
692 retry=TENACITY_RETRY_EXCEPTIONS,
693 reraise=True,
694 )
695 async def purge_build(session, build_url, token):
696 print("Purging build %s" % (build_url))
697 resp = await session.post(
698 build_url + "/purge", headers={"Authorization": "Bearer " + token}, json={}
699 )
700 async with resp:
701 if resp.status >= 500:
702 raise ServerApiError(resp, await resp.text())
703 elif resp.status == 400:
704 response = await resp.json()
705 if response.get("message") == "Can't prune build while in use":
706 return '{"OK"}'
707 else:
708 raise ApiError(resp, await resp.text())
709 elif resp.status != 200:
710 raise ApiError(resp, await resp.text())
711 return await resp.json()
712
713
714 @retry(
715 stop=TENACITY_STOP_AFTER,
716 wait=TENACITY_WAIT_BETWEEN,
717 retry=TENACITY_RETRY_EXCEPTIONS,
718 reraise=True,
719 )
720 async def create_token(session, manager_url, token, name, subject, scope, duration):
721 token_url = urljoin(manager_url, "api/v1/token_subset")
722 resp = await session.post(
723 token_url,
724 headers={"Authorization": "Bearer " + token},
725 json={
726 "name": name,
727 "sub": subject,
728 "scope": scope,
729 "duration": duration,
730 },
731 )
732 async with resp:
733 if resp.status >= 500:
734 raise ServerApiError(resp, await resp.text())
735 elif resp.status != 200:
736 raise ApiError(resp, await resp.text())
737 return await resp.json()
738
739
740 def get_object_multipart(repo_path, object):
741 return AsyncNamedFilePart(
742 repo_path + "/objects/" + object[:2] + "/" + object[2:], filename=object
743 )
744
745
746 @retry(
747 stop=TENACITY_STOP_AFTER,
748 wait=TENACITY_WAIT_BETWEEN,
749 retry=TENACITY_RETRY_EXCEPTIONS,
750 reraise=True,
751 )
752 async def create_command(session, args):
753 build_url = urljoin(args.manager_url, "api/v1/build")
754 json = {"repo": args.repo}
755 if args.app_id is not None:
756 json["app-id"] = args.app_id
757 if args.public_download is not None:
758 json["public-download"] = args.public_download
759 if args.build_log_url is not None:
760 json["build-log-url"] = args.build_log_url
761 resp = await session.post(
762 build_url, headers={"Authorization": "Bearer " + args.token}, json=json
763 )
764 async with resp:
765 if resp.status >= 500:
766 raise ServerApiError(resp, await resp.text())
767 elif resp.status != 200:
768 raise ApiError(resp, await resp.text())
769 data = await resp.json()
770 data["location"] = resp.headers["location"]
771 if not args.print_output:
772 print(resp.headers["location"])
773 return data
774
775
776 def delta_name_part_encode(commit):
777 return base64.b64encode(binascii.unhexlify(commit), b"+_")[:-1].decode("utf-8")
778
779
780 def delta_name_encode(delta):
781 return "-".join(map(delta_name_part_encode, delta.split("-")))
782
783
784 def should_skip_delta(id, globs):
785 if globs:
786 for glob in globs:
787 if fnmatch.fnmatch(id, glob):
788 return True
789 return False
790
791
792 def build_url_to_api(build_url):
793 parts = urlparse(build_url)
794 path = os.path.dirname(os.path.dirname(parts.path))
795 return urlunparse((parts.scheme, parts.netloc, path, None, None, None))
796
797
798 async def push_command(session, args):
799 local_repo = OSTree.Repo.new(Gio.File.new_for_path(args.repo_path))
800 try:
801 local_repo.open(None)
802 except GLib.Error as err:
803 raise UsageException(
804 "Can't open repo %s: %s" % (args.repo_path, err.message)
805 ) from err
806
807 refs = {}
808 if len(args.branches) == 0:
809 _, all_refs = local_repo.list_refs(None, None)
810 for ref in all_refs:
811 if (
812 ref.startswith("app/")
813 or ref.startswith("runtime/")
814 or ref.startswith("screenshots/")
815 ):
816 refs[ref] = all_refs[ref]
817 else:
818 for branch in args.branches:
819 _, rev = local_repo.resolve_rev(branch, False)
820 refs[branch] = rev
821
822 if args.minimal_token:
823 id = os.path.basename(urlparse(args.build_url).path)
824 token = create_token(
825 args.build_url,
826 args.token,
827 "minimal-upload",
828 "build/%s" % (id),
829 ["upload"],
830 60 * 60,
831 )["token"]
832 else:
833 token = args.token
834
835 print("Uploading refs to %s: %s" % (args.build_url, list(refs)))
836
837 metadata_objects = local_needed_metadata(local_repo, refs.values())
838
839 print("Refs contain %d metadata objects" % (len(metadata_objects)))
840
841 missing_metadata_objects = await missing_objects(
842 session, args.build_url, token, list(metadata_objects)
843 )
844
845 print("Remote missing %d of those" % (len(missing_metadata_objects)))
846
847 file_objects = local_needed_files(local_repo, metadata_objects)
848 print("Has %d file objects for those" % (len(file_objects)))
849
850 missing_file_objects = await missing_objects(
851 session, args.build_url, token, list(file_objects)
852 )
853 print("Remote missing %d of those" % (len(missing_file_objects)))
854
855 # First upload all missing file objects
856 print("Uploading file objects")
857 await upload_objects(
858 session, args.repo_path, args.build_url, token, missing_file_objects
859 )
860
861 # Then all the metadata
862 print("Uploading metadata objects")
863 await upload_objects(
864 session, args.repo_path, args.build_url, token, missing_metadata_objects
865 )
866
867 _, deltas = local_repo.list_static_delta_names()
868 print("Uploading deltas")
869 await upload_deltas(
870 session, args.repo_path, args.build_url, token, deltas, refs, args.ignore_delta
871 )
872
873 # Then the refs
874 for ref, commit in refs.items():
875 await create_ref(
876 session,
877 args.build_url,
878 token,
879 ref,
880 commit,
881 build_log_url=args.build_log_url,
882 )
883
884 # Then any extra ids
885 if args.extra_id:
886 await add_extra_ids(session, args.build_url, token, args.extra_id)
887
888 commit_job = None
889 publish_job = None
890 update_job = None
891
892 # Note, this always uses the full token, as the minimal one only has upload permissions
893 if args.commit or args.publish:
894 commit_job = await commit_build(
895 session,
896 args.build_url,
897 args.end_of_life,
898 args.end_of_life_rebase,
899 args.token_type,
900 args.publish or args.wait,
901 args.token,
902 )
903
904 if args.publish:
905 publish_job = await publish_build(
906 session, args.build_url, args.wait or args.wait_update, args.token
907 )
908 update_job_id = publish_job.get("results", {}).get("update-repo-job", None)
909 if update_job_id:
910 print("Queued repo update job %d" % (update_job_id))
911 update_job_url = (
912 build_url_to_api(args.build_url) + "/job/" + str(update_job_id)
913 )
914 if args.wait_update:
915 print("Waiting for repo update job")
916 update_job = await wait_for_job(session, update_job_url, token)
917 else:
918 update_job = await get_job(session, update_job_url, token)
919 reparse_job_results(update_job)
920 update_job["location"] = update_job_url
921
922 data = await get_build(session, args.build_url, args.token)
923 if commit_job:
924 data["commit_job"] = commit_job
925 if publish_job:
926 data["publish_job"] = publish_job
927 if update_job:
928 data["update_job"] = update_job
929 return data
930
931
932 async def commit_command(session, args):
933 job = await commit_build(
934 session,
935 args.build_url,
936 args.end_of_life,
937 args.end_of_life_rebase,
938 args.token_type,
939 args.wait,
940 args.token,
941 )
942 return job
943
944
945 async def publish_command(session, args):
946 job = await publish_build(
947 session, args.build_url, args.wait or args.wait_update, args.token
948 )
949 update_job_id = job.get("results", {}).get("update-repo-job", None)
950 if update_job_id:
951 print("Queued repo update job %d" % (update_job_id))
952 update_job_url = build_url_to_api(args.build_url) + "/job/" + str(update_job_id)
953 if args.wait_update:
954 print("Waiting for repo update job")
955 update_job = await wait_for_job(session, update_job_url, args.token)
956 else:
957 update_job = await get_job(session, update_job_url, args.token)
958 reparse_job_results(update_job)
959 update_job["location"] = update_job_url
960 return job
961
962
963 async def purge_command(session, args):
964 job = await purge_build(session, args.build_url, args.token)
965 return job
966
967
968 async def create_token_command(session, args):
969 data = await create_token(
970 session,
971 args.manager_url,
972 args.token,
973 args.name,
974 args.subject,
975 args.scope,
976 args.duration,
977 )
978 if not args.print_output:
979 print(data["token"])
980 return data
981
982
983 async def follow_job_command(session, args):
984 job = await wait_for_job(session, args.job_url, args.token)
985 return job
986
987
988 async def run_with_session(args):
989 timeout = aiohttp.ClientTimeout(total=90 * 60)
990 async with aiohttp.ClientSession(timeout=timeout) as session:
991 result = await args.func(session, args)
992 return result
993
994
995 if __name__ == "__main__":
996 progname = os.path.basename(sys.argv[0])
997
998 parser = ArgumentParser(prog=progname)
999 parser.add_argument(
1000 "-v", "--verbose", action="store_true", help="enable verbose output"
1001 )
1002 parser.add_argument("--debug", action="store_true", help="enable debugging output")
1003 parser.add_argument("--output", help="Write output json to file")
1004 parser.add_argument("--print-output", action="store_true", help="Print output json")
1005 parser.add_argument("--token", help="use this token")
1006 parser.add_argument("--token-file", help="use token from file")
1007 subparsers = parser.add_subparsers(
1008 title="subcommands",
1009 dest="subparser_name",
1010 description="valid subcommands",
1011 help="additional help",
1012 )
1013
1014 create_parser = subparsers.add_parser("create", help="Create new build")
1015 create_parser.add_argument("manager_url", help="remote repo manager url")
1016 create_parser.add_argument("repo", help="repo name")
1017 create_parser.add_argument("app_id", nargs="?", help="app ID")
1018 create_parser.add_argument(
1019 "--public_download",
1020 action="store_true",
1021 default=None,
1022 help="allow public read access to the build repo",
1023 )
1024 create_parser.add_argument(
1025 "--no_public_download",
1026 action="store_false",
1027 dest="public_download",
1028 default=None,
1029 help="allow public read access to the build repo",
1030 )
1031 create_parser.add_argument(
1032 "--build-log-url", help="Set URL of the build log for the whole build"
1033 )
1034 create_parser.set_defaults(func=create_command)
1035
1036 push_parser = subparsers.add_parser("push", help="Push to repo manager")
1037 push_parser.add_argument("build_url", help="remote build url")
1038 push_parser.add_argument("repo_path", help="local repository")
1039 push_parser.add_argument("branches", nargs="*", help="branches to push")
1040 push_parser.add_argument(
1041 "--commit", action="store_true", help="commit build after pushing"
1042 )
1043 push_parser.add_argument(
1044 "--publish", action="store_true", help="publish build after committing"
1045 )
1046 push_parser.add_argument(
1047 "--extra-id", action="append", help="add extra collection-id"
1048 )
1049 push_parser.add_argument(
1050 "--ignore-delta", action="append", help="don't upload deltas matching this glob"
1051 )
1052 push_parser.add_argument(
1053 "--wait", action="store_true", help="wait for commit/publish to finish"
1054 )
1055 push_parser.add_argument(
1056 "--wait-update", action="store_true", help="wait for update-repo to finish"
1057 )
1058 push_parser.add_argument(
1059 "--minimal-token",
1060 action="store_true",
1061 help="Create minimal token for the upload",
1062 )
1063 push_parser.add_argument("--end-of-life", help="Set end of life")
1064 push_parser.add_argument(
1065 "--end-of-life-rebase", help="Set new ID which will supercede the current one"
1066 )
1067 push_parser.add_argument("--token-type", help="Set token type", type=int)
1068 push_parser.add_argument(
1069 "--build-log-url", help="Set URL of the build log for each uploaded ref"
1070 )
1071 push_parser.set_defaults(func=push_command)
1072
1073 commit_parser = subparsers.add_parser("commit", help="Commit build")
1074 commit_parser.add_argument(
1075 "--wait", action="store_true", help="wait for commit to finish"
1076 )
1077 commit_parser.add_argument("--end-of-life", help="Set end of life")
1078 commit_parser.add_argument(
1079 "--end-of-life-rebase", help="Set new ID which will supercede the current one"
1080 )
1081 commit_parser.add_argument("--token-type", help="Set token type", type=int)
1082 commit_parser.add_argument("build_url", help="remote build url")
1083 commit_parser.set_defaults(func=commit_command)
1084
1085 publish_parser = subparsers.add_parser("publish", help="Publish build")
1086 publish_parser.add_argument(
1087 "--wait", action="store_true", help="wait for publish to finish"
1088 )
1089 publish_parser.add_argument(
1090 "--wait-update", action="store_true", help="wait for update-repo to finish"
1091 )
1092 publish_parser.add_argument("build_url", help="remote build url")
1093 publish_parser.set_defaults(func=publish_command)
1094
1095 purge_parser = subparsers.add_parser("purge", help="Purge build")
1096 purge_parser.add_argument("build_url", help="remote build url")
1097 purge_parser.set_defaults(func=purge_command)
1098
1099 create_token_parser = subparsers.add_parser(
1100 "create-token", help="Create subset token"
1101 )
1102 create_token_parser.add_argument("manager_url", help="remote repo manager url")
1103 create_token_parser.add_argument("name", help="Name")
1104 create_token_parser.add_argument("subject", help="Subject")
1105 create_token_parser.add_argument("scope", nargs="*", help="Scope")
1106 create_token_parser.add_argument(
1107 "--duration",
1108 help="Duration until expires, in seconds",
1109 default=60 * 60 * 24, # Default duration is one day
1110 type=int,
1111 )
1112 create_token_parser.set_defaults(func=create_token_command)
1113
1114 follow_job_parser = subparsers.add_parser(
1115 "follow-job", help="Follow existing job log"
1116 )
1117 follow_job_parser.add_argument("job_url", help="url of job")
1118 follow_job_parser.set_defaults(func=follow_job_command)
1119
1120 args = parser.parse_args()
1121
1122 loglevel = logging.WARNING
1123 if args.verbose:
1124 loglevel = logging.INFO
1125 if args.debug:
1126 loglevel = logging.DEBUG
1127
1128 logging.basicConfig(
1129 format="%(module)s: %(levelname)s: %(message)s",
1130 level=loglevel,
1131 stream=sys.stderr,
1132 )
1133
1134 if not args.subparser_name:
1135 print("No subcommand specified, see --help for usage")
1136 exit(1)
1137
1138 if not args.token:
1139 if args.token_file:
1140 file = open(args.token_file, "rb")
1141 args.token = file.read().splitlines()[0].decode("utf-8").strip()
1142 elif "REPO_TOKEN" in os.environ:
1143 args.token = os.environ["REPO_TOKEN"]
1144 else:
1145 print("No token available, pass with --token, --token-file or $REPO_TOKEN")
1146 exit(1)
1147
1148 res = 1
1149 output = None
1150 try:
1151 result = asyncio.run(run_with_session(args))
1152
1153 output = {
1154 "command": args.subparser_name,
1155 "result": result,
1156 }
1157 res = 0
1158 except (ApiError, FailedJobError) as e:
1159 eprint(str(e))
1160 output = {
1161 "command": args.subparser_name,
1162 "error": e.repr(),
1163 }
1164 except UsageException as e:
1165 eprint(str(e))
1166 output = {
1167 "error": {
1168 "type": "usage",
1169 "details": {
1170 "message": str(e),
1171 },
1172 }
1173 }
1174 except Exception:
1175 ei = sys.exc_info()
1176 eprint(
1177 "Unexpected %s exception in %s: %s"
1178 % (ei[0].__name__, args.subparser_name, ei[1])
1179 )
1180 eprint(traceback.format_exc())
1181 output = {
1182 "command": args.subparser_name,
1183 "error": {
1184 "type": "exception",
1185 "details": {
1186 "error-type": ei[0].__name__,
1187 "message": str(ei[1]),
1188 },
1189 },
1190 }
1191 res = 1
1192
1193 if output:
1194 if args.print_output:
1195 print(json.dumps(output, indent=4))
1196 if args.output:
1197 f = open(args.output, "w+")
1198 f.write(json.dumps(output, indent=4))
1199 f.write("\n")
1200 f.close()
1201 exit(res)