-
Notifications
You must be signed in to change notification settings - Fork 3
/
ecr_api.py
executable file
·1785 lines (1411 loc) · 56.2 KB
/
ecr_api.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
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# ### mysqlclient ###
# pip install mysqlclient
# https://github.com/PyMySQL/mysqlclient-python
# https://mysqlclient.readthedocs.io/
import os
import sys
import logging
from flask import Flask
from flask_cors import CORS
from flask.views import MethodView
import MySQLdb
from flask import request, abort, jsonify
import re
# import uuid
import json
import time
import werkzeug
from werkzeug.wrappers import Request, Response, ResponseStream
from middleware import middleware
import requests
from error_response import ErrorResponse, ErrorWResponse
import jenkins_server
import xmltodict
import sys
from decorators import *
import config
import yaml
import base64
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.exceptions import HTTPException
from prometheus_client import Counter, make_wsgi_app
import subprocess
import tempfile
import boto3
from botocore.exceptions import ClientError
import authenticators
from token_cache import TokenCache
from pathlib import Path
RAW_GITHUB_URL = "https://raw.githubusercontent.com"
DEFAULT_BRANCH = "main"
app_submission_counter = Counter(
"app_submission_counter",
"This metric counts the total number of successful app submissions.",
)
build_request_counter = Counter(
"build_request_counter", "This metric counts the total number of requested builds."
)
# TODO(sean) make this part of the app config to allow selecting static for testing and sage for deployment.
if config.auth_method == "static":
app_authenticator = authenticators.StaticAuthenticator(config.static_tokens)
elif config.auth_method == "sage":
app_authenticator = authenticators.SageAuthenticator(
url=config.tokenInfoEndpoint, password=config.tokenInfoPassword
)
else:
raise RuntimeError("invalid authenticator")
token_cache = TokenCache(
host=config.redis_host,
port=config.redis_port,
ttl_seconds=config.redis_ttl_seconds,
)
class ECRAuthMiddleware:
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response): # pragma: no cover
app.logger.info("auth middleware: starting request")
request = Request(environ)
try:
authHeader = request.headers["Authorization"]
except KeyError:
app.logger.info("auth middleware: no auth provided")
environ["authenticated"] = False
return self.app(environ, start_response)
authHeaderArray = authHeader.split(maxsplit=2)
if len(authHeaderArray) != 2:
app.logger.info("auth middleware: bad auth header size")
return ErrorWResponse(
f"Authorization failed (could not parse Authorization header)",
status_code=HTTPStatus.UNAUTHORIZED,
)(environ, start_response)
bearer, token = authHeaderArray
bearer = bearer.lower()
if bearer not in ["sage", "static"]:
app.logger.info("auth middleware: bad realm")
return ErrorWResponse(
f"Authorization failed (Authorization bearer not supported)",
status_code=HTTPStatus.UNAUTHORIZED,
)(environ, start_response)
app.logger.info("auth middleware: getting token info")
try:
token_info = self.get_token_info_with_caching(token)
except authenticators.TokenNotFound:
return ErrorWResponse(
"Token not found", status_code=HTTPStatus.UNAUTHORIZED
)(environ, start_response)
app.logger.info("auth middleware: request authenticated as %s", token_info.user)
environ["authenticated"] = True
environ["user"] = token_info.user
environ["scopes"] = token_info.scopes
environ["is_admin"] = token_info.is_admin
environ["is_approved"] = token_info.is_approved
return self.app(environ, start_response)
def get_token_info_with_caching(self, token):
try:
token_info = token_cache.get(token)
app.logger.info(
"auth middleware: using cached token for %s", token_info.user
)
return token_info
except KeyError:
pass
app.logger.info("auth middleware: requesting token")
token_info = app_authenticator.get_token_info(token)
app.logger.info(
"auth middleware: updating cached token for %s", token_info.user
)
token_cache.set(token, token_info)
return token_info
def run_command_communicate(command, input_str=None, cwd=None, timeout=None):
try:
p = subprocess.Popen(
command,
cwd=cwd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
except Exception as e:
raise Exception(f"subprocess.Popen: {str(e)}")
# returns output_stdout,output_stderr
input = None
if input_str:
input = input_str.encode()
try:
stdout, stderr = p.communicate(input=input, timeout=timeout)
except subprocess.TimeoutExpired as e:
p.kill()
raise e
exit_code = p.wait()
return stdout, stderr, exit_code
def preprocess_repository(url, branchOrTag, custom_version, namespace, repository):
version = ""
git_hash_long = ""
temp_dir = Path(config.ecr_temp_dir)
temp_dir.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=temp_dir) as tmpdirname:
app.logger.debug(f"tmpdirname: {tmpdirname}")
subprocess.run(
["git", "clone", "--recursive", "-b", branchOrTag, url, str(tmpdirname)],
env={"GIT_TERMINAL_PROMPT": "0"},
timeout=600,
check=True,
capture_output=True,
)
# best solution, returns "0.0.0-0-g60c72a2" , or "g60c72a2"
command = ["git", "describe", "--always", "--tags", "--long"]
stdout, stderr, exit_code = run_command_communicate(command, cwd=tmpdirname)
stdout_str = ""
if stdout:
stdout_str = stdout.decode("utf-8")
if exit_code != 0:
stderr_str = ""
if stderr:
stderr_str = stderr.decode("utf-8")
raise Exception(
f"Extracting version number failed (stdout={ stdout_str }, stderr={stderr_str}, tmpdirname={tmpdirname})"
)
version = stdout_str.split("\n")[0]
if len(version) == 8 or len(version) == 7:
pass
elif len(version) > 8:
# example format "0.0.0-0-g60c72a2"
version_ar = version.split("-")
if len(version_ar) != 3:
raise Exception(f"Could not parse version string {version}")
version = version_ar[0] + "-" + version_ar[1]
else:
raise Exception(f"Could not parse version string {version}")
# git rev-parse HEAD for long git commit
command = ["git", "rev-parse", "HEAD"]
stdout, stderr, exit_code = run_command_communicate(command, cwd=tmpdirname)
stdout_str = ""
if stdout:
stdout_str = stdout.decode("utf-8")
if exit_code != 0:
stderr_str = ""
if stderr:
stderr_str = stderr.decode("utf-8")
raise Exception(
f"Extracting hash number failed (stdout={ stdout_str }, stderr={stderr_str}, tmpdirname={tmpdirname})"
)
git_hash_long = stdout_str.split("\n")[0]
if len(git_hash_long) != 40:
raise Exception(f"git hash has wrong format ({git_hash_long})")
final_version = ""
if custom_version:
final_version = custom_version
else:
final_version = version
target_gzip = Path(temp_dir, f"{namespace}_{repository}_{final_version}.tgz")
# check that user submission artifact lives directly in temp_dir
if target_gzip.parent != temp_dir:
app.logger.error(
"preprocess_repository: invalid repo gzip artifact path: %s",
target_gzip,
)
raise Exception(
f"Invalid submission! Check that namespace, repository and version are all valid."
)
# tar -czvf file.tar.gz directory
command = ["tar", "-czvf", str(target_gzip), "."]
stdout, stderr, exit_code = run_command_communicate(command, cwd=tmpdirname)
stdout_str = ""
if stdout:
stdout_str = stdout.decode("utf-8")
if exit_code != 0:
stderr_str = ""
if stderr:
stderr_str = stderr.decode("utf-8")
raise Exception(
f"Creating archive failed (stdout={ stdout_str }, stderr={stderr_str}, tmpdirname={tmpdirname})"
)
# TODO upload (and store link (better: no link needed if filename is unique))
if config.S3_ENDPOINT:
s3_client = boto3.client(
"s3",
endpoint_url=config.S3_ENDPOINT,
aws_access_key_id=config.S3_ACCESS_KEY,
aws_secret_access_key=config.S3_SECRET_KEY,
)
object_name = f"{config.S3_FOLDER}/{namespace}/{repository}/{namespace}_{repository}_{final_version}.tgz"
try:
s3_client.upload_file(target_gzip, config.S3_BUCKET, object_name)
except Exception as e:
raise Exception(f"Upload to S3 failed ({str(e)})")
# clean-up
os.remove(target_gzip)
return version, git_hash_long
def submit_app(
requestUser,
isAdmin,
force_overwrite,
postData,
namespace=None,
repository=None,
version=None,
):
ecr_db = ecrdb.EcrDB()
### namespace
# check if namespace exists (create if not) and check permissions
userHasNamespaceWritePermission = False
if not namespace:
namespace = postData.get("namespace", "")
if not namespace:
raise Exception("namespace missing")
_, ok = ecr_db.getNamespace(namespace)
if not ok:
# namespace does not exist. Unless sage assigns usernames, any available namespace can be used
try:
ecr_db.addNamespace(namespace, requestUser)
except Exception as e:
raise Exception(f"Could not create namespace {namespace}: {str(e)}")
userHasNamespaceWritePermission = True
else:
# Namespace exists. Check if User has permission to write.
# If not, user may still have permission to write to existing Repo.
userHasNamespaceWritePermission = ecr_db.hasPermission(
"namespace", namespace, "USER", requestUser, "WRITE"
)
### repository (app name, without version)
if not repository:
repository = postData.get("name", "")
if not repository:
raise Exception("repository name missing")
# check if exists, create if needed
_, ok = ecr_db.getRepository(namespace, repository)
if not ok:
# namespace does not exist. Unless sage assigns usernames, any available namespace can be used
if userHasNamespaceWritePermission:
try:
ecr_db.addRepository(namespace, repository, requestUser)
except Exception as e:
raise Exception(
f"Could not create repository {namespace}/{repository}: {str(e)}"
)
else:
raise ErrorResponse(
f"Not authorized to access namespace {namespace}",
status_code=HTTPStatus.UNAUTHORIZED,
)
else:
# repo exists, check if user has namespace or repo permission
userHasRepoWritePermission = ecr_db.hasPermission(
"repository", f"{namespace}/{repository}", "USER", requestUser, "WRITE"
)
if (not userHasNamespaceWritePermission) and (not userHasRepoWritePermission):
raise ErrorResponse(
f"Not authorized to access repository {namespace}/{repository}",
status_code=HTTPStatus.UNAUTHORIZED,
)
### check if versioned app already exists and if it can be overwritten
if not version:
version = postData.get("version", "")
if version: # if not, version will be extracted from git repo
try:
existing_app, found_app = ecr_db.listApps(
user=requestUser,
namespace=namespace,
repository=repository,
version=version,
)
except Exception as e:
raise Exception(f"ecr_db.listApps failed: {str(e)}")
if found_app:
raise Exception(f"App {namespace}/{repository}:{version} already exists.")
# check if required fields are there
for key in config.required_fields:
if not key in postData:
# return {"error": f'Required field {key} is missing'}
raise Exception(f"Required field {key} is missing")
expected_type = config.required_fields[key]
if not key in postData:
raise Exception(f"key {key} is missing")
value = postData[key]
if type(value).__name__ != expected_type:
raise Exception(
f"Field {key} has to be of type {expected_type}, got {type(value).__name__}"
)
if len(value) == 0:
# return {"error": f'Required field {key} is missing'}
raise Exception(f"Required field {key} is missing")
# check for invalid fields
for key in postData:
if not key in config.valid_fields_set:
# return {"error": f'Field {key} not supported'}
raise Exception(f"Field {key} not supported")
##### source
# source
# [email protected]:<user>/<repo>.git#<tag>
# https://github.com/<user>/<repo>.git#<tag>
# http://sagecontinuum.org/bucket/<bucket_id>
build_source = postData.get("source", None)
# sourcesArray = postData.get("source",[])
# if len(sourcesArray) == 0:
if not build_source:
raise Exception("Field source is missing")
# source_public_git_pattern = re.compile(f'https://github.com/{vc}+/{vc}+.git#{vc}+')
# source_private_git_pattern = re.compile(f'[email protected]/{vc}+/{vc}+.git#{vc}+')
# source_sage_store_pattern = re.compile(f'http://sagecontinuum.org/bucket/[0-9a-z.]+')
# source_matched = False
# for p in [source_public_git_pattern, source_private_git_pattern , source_sage_store_pattern]:
# if p.match(appSource):
# source_matched = True
# break
# if not source_matched:
# raise ErrorResponse('Could not parse source field', status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
##### inputs
# inputs validation
appInputs = postData.get("inputs", [])
for app_input in appInputs:
for field in app_input:
if not field in config.input_fields_valid:
raise Exception(f"Input field {field} not supported")
for expected in config.input_fields_expected:
if not expected in app_input:
raise Exception(f"Expected field {expected} missing")
input_type = app_input["type"]
if not input_type in config.input_valid_types:
raise Exception(f"Input type {input_type} not supported")
appInputs_str = json.dumps(appInputs)
##### resources
# resources_str = None
resourcesArray = postData.get("resources", [])
if not isinstance(resourcesArray, list):
raise Exception(f"Field resources has to be an array")
# resources_str = json.dumps(resourcesArray)
##### metadata
try:
appMetadata = postData.get("metadata", {})
except Exception:
raise Exception(f"Could not retrieve metadata")
if not isinstance(appMetadata, dict):
raise Exception("metadata has to be an object")
url = build_source.get("url") or ""
if url == "":
raise Exception("url missing in source")
tag = build_source.get("tag") or ""
branch = build_source.get("branch") or ""
if branch == "" and tag == "":
raise Exception("Neither tag nor branch specified")
branch_or_tag = ""
if tag != "":
branch_or_tag = tag
else:
branch_or_tag = branch
### git clone, extract info, create archive, upload
extracted_version, git_commit = preprocess_repository(
url, branch_or_tag, version, namespace, repository
)
existing_app_id = None
if not version:
version = extracted_version
try:
existing_app, found_app = ecr_db.listApps(
user=requestUser,
namespace=namespace,
repository=repository,
version=version,
)
except Exception as e:
raise Exception(f"ecr_db.listApps failed: {str(e)}")
if found_app:
if existing_app.get("frozen", False) and (not isAdmin):
raise Exception(
f"App {namespace}/{repository}:{version} already exists and is frozen."
)
if not force_overwrite:
raise Exception(
f"App {namespace}/{repository}:{version} already exists but is not frozen. Use query force=true to overwrite."
)
existing_app_id = existing_app.get("id")
##### create dbObject
dbObject = {}
for key in config.valid_fields_set:
dbObject[key] = ""
dbObject["metadata"] = json.dumps(
appMetadata
) # should at least be an empty dictionary
dbObject["namespace"] = namespace
dbObject["name"] = repository
dbObject["version"] = version
dbObject["inputs"] = appInputs_str
# copy fields
for key in [
"description",
"keywords",
"authors",
"collaborators",
"homepage",
"funding",
"license",
]:
dbObject[key] = postData.get(key, "")
dbObject["frozen"] = postData.get("frozen", False)
dbObject["owner"] = requestUser
id_str = ""
if existing_app_id:
id_str = existing_app_id
else:
# newID = uuid.uuid4()
# id_str = str(newID)
id_str = f"{namespace}/{repository}:{version}"
dbObject["id"] = id_str
# create INSERT statement dynamically
values = []
col_names = []
variables = []
# for key in config.mysql_Apps_fields.keys():
for key in config.valid_fields + ["id", "owner"]:
# print(f"key: {key} value: {dbObject[key]}", file=sys.stderr)
if not key in config.mysql_Apps_fields:
continue
if not key in dbObject:
raise Exception(f"key {key} not in dbObject")
values.append(dbObject[key])
col_names.append(key)
variables.append("%s")
variables_str = ",".join(variables)
col_names_str = ",".join(col_names)
ecr_db = ecrdb.EcrDB()
# for build_source in sourcesArray:
architectures_array = build_source.get("architectures", [])
if len(architectures_array) == 0:
raise Exception("architectures missing in source")
##### architecture
for arch in architectures_array:
if not arch in config.architecture_valid:
valid_arch_str = ",".join(config.architecture_valid)
raise Exception(
f"Architecture {arch} not supported, valid values: {valid_arch_str}"
)
architectures = json.dumps(architectures_array)
directory = build_source.get("directory") or "."
dockerfile = build_source.get("dockerfile") or "Dockerfile"
build_args_dict = build_source.get("build_args", {})
if not isinstance(build_args_dict, dict):
raise Exception(f"build_args needs to be a dictionary")
for key in build_args_dict:
value = build_args_dict[key]
if not isinstance(value, str):
raise Exception(f"build_args values have to be strings")
build_args_str = json.dumps(build_args_dict)
sources_values = [
id_str,
architectures,
url,
branch,
tag,
git_commit,
directory,
dockerfile,
build_args_str,
]
try:
ecr_db.insertApp(
col_names_str, values, variables_str, sources_values, resourcesArray
)
except Exception as e:
raise Exception(f"insertApp returned: {type(e).__name__},{str(e)}")
# dbObject["id"] = newID
# content = {}
# content["data"] = dbObject
returnObj, ok = ecr_db.listApps(
user=requestUser,
namespace=namespace,
repository=repository,
version=version,
isAdmin=isAdmin,
)
# returnObj, ok=ecr_db.getApp(id_str)
if not ok:
raise Exception(f"app not found after inserting, something went wrong")
# save meta files
try:
import_meta_files(
returnObj, namespace=namespace, repository=repository, version=version
)
except Exception as e:
raise Exception(f"import_meta_files failed: {str(e)}")
app_submission_counter.inc(1)
# args = parser.parse_args()
return returnObj
# /apps
class Submit(MethodView):
@login_required
def post(self):
app.logger.info("submit: processing request")
requestUser = request.environ.get("user", "")
isAdmin = request.environ.get("is_admin", False)
force_overwrite = request.args.get("force", "").lower() in ["true", "1"]
app.logger.info("submit: trying to load app spec as json")
postData = request.get_json(force=True, silent=True)
if not postData:
app.logger.info("submit: trying to load app spec as yaml")
# try yaml
yaml_str = request.get_data().decode()
postData = yaml.safe_load(yaml_str)
if not postData:
app.logger.info("submit: could not load app spec")
raise ErrorResponse(
f"Could not parse app spec",
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)
try:
app.logger.info("submit: submitting app")
return_obj = submit_app(requestUser, isAdmin, force_overwrite, postData)
except subprocess.TimeoutExpired as e:
app.logger.error("submit: submitting app timed")
raise ErrorResponse(f"{str(e)}", status_code=HTTPStatus.REQUEST_TIMEOUT)
except ErrorResponse as e:
app.logger.error("submit: submitting app error response")
raise e
except Exception as e:
app.logger.exception("submit: submitting app exception")
raise ErrorResponse(
f"{str(e)}", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
app.logger.info("submit: success")
return jsonify(return_obj)
def import_meta_files(app_obj, namespace=None, repository=None, version=None):
ecr_db = ecrdb.EcrDB()
# use app source.url as source of meta files; todo(nc): support tags
repo_url = app_obj["source"]["url"]
branch = app_obj["source"].get("branch", DEFAULT_BRANCH)
# parse github username/repo_name
if "[email protected]:" in repo_url:
repo_path = repo_url.split(":")[1].replace(".git", "")
else:
repo_path = "/".join(repo_url.split("/")[3:]).replace(".git", "")
meta_path = f"{RAW_GITHUB_URL}/{repo_path}/{branch}/ecr-meta"
# files we'll grab from github and their associated kind
file_dicts = [
{"name": "ecr-icon.jpg", "kind": "thumb"},
{"name": "ecr-science-image.jpg", "kind": "image"},
{"name": "ecr-science-description.md", "kind": "science_description"},
]
for f_dict in file_dicts:
f_name = f_dict["name"]
kind = f_dict["kind"]
url = f"{meta_path}/{f_name}"
res = requests.get(url)
if res.status_code != 200:
continue
blob = res.content
# insert the data
ecr_db.addMetaFile(namespace, repository, version, f_name, blob, kind)
# /apps/<string:namespace>/<string:repository>/<string:version>
class Apps(MethodView):
@login_required
@has_resource_permission("FULL_CONTROL")
def delete(self, namespace, repository, version):
isAdmin = request.environ.get("is_admin", False)
requestUser = request.environ.get("user", "")
ecr_db = ecrdb.EcrDB()
try:
ecr_db.deleteApp(
user=requestUser,
isAdmin=isAdmin,
namespace=namespace,
repository=repository,
version=version,
force=isAdmin,
)
except Exception as e:
app.logger.error(
"failed to delete app %s/%s:%s by %s: %s",
namespace,
repository,
version,
requestUser,
e,
)
# TODO(sean) use different error codes to indicate why request failed: 401 vs 403 vs 404 vs 5xx
raise ErrorResponse(
f"Error deleting app: {e}", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
return jsonify({"deleted": 1})
@has_resource_permission("READ")
def get(self, namespace, repository, version):
requestUser = request.environ.get("user", "")
isAdmin = request.environ.get("is_admin", False)
view = request.args.get("view", "")
ecr_db = ecrdb.EcrDB()
# returnObj, ok=ecr_db.getApp(namespace=namespace, name=repository, version=version)
returnObj, ok = ecr_db.listApps(
user=requestUser,
namespace=namespace,
repository=repository,
version=version,
isAdmin=isAdmin,
view=view,
)
if not ok:
raise ErrorResponse(f"App not found", status_code=HTTPStatus.NOT_FOUND)
return jsonify(returnObj)
@has_resource_permission("WRITE")
def put(self, namespace, repository, version):
ecr_db = ecrdb.EcrDB()
if "frozen" in request.args:
frozen = request.args.get("frozen", "") in ["true", "1"]
if not isinstance(frozen, bool):
raise ErrorResponse(
f"frozen is not bool", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
result = ecr_db.setAppField(
namespace, repository, version, "frozen", frozen
)
result_obj = {"modified": result}
else:
raise ErrorResponse(
f"Not sure what to do", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
return jsonify(result_obj)
# auth disabled because user can create namespace
# @has_resource_permission("WRITE")
def post(self, namespace, repository, version):
app.logger.info("POST apps")
requestUser = request.environ.get("user", "")
isAdmin = request.environ.get("is_admin", False)
force_overwrite = request.args.get("force", "").lower() in ["true", "1"]
postData = request.get_json(force=True, silent=True)
if not postData:
# try yaml
yaml_str = request.get_data().decode("utf-8")
print(f"yaml_str: {yaml_str} ", file=sys.stderr)
postData = yaml.safe_load(yaml_str)
if not postData:
raise ErrorResponse(
f"Could not parse app spec",
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)
# save yaml
try:
app_obj = submit_app(
requestUser,
isAdmin,
force_overwrite,
postData,
namespace=namespace,
repository=repository,
version=version,
)
except ErrorResponse as e:
raise e
except Exception as e:
raise ErrorResponse(
f"{str(e)}", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
return jsonify(app_obj)
# Lists all apps, the user has permission to see
# /apps
class AppsGlobal(MethodView):
# simulate many submissions
# for i in {1..10} ; do cat ./example_app.yaml | sed -e "s/version :.*/version: \"${i}.0\"/" | curl -X POST ${ECR_API}/submit -H "Authorization: sage ${SAGE_USER_TOKEN}" --data-binary @- ; done
def get(self, namespace=None, repository=None, version=None):
requestUser = request.environ.get("user", "")
isAdmin = request.environ.get("is_admin", False)
limit = request.args.get("limit", 1000)
if limit:
limit = int(limit)
if limit > 1000:
limit = 1000
continueT = request.args.get("continue", None)
ecr_db = ecrdb.EcrDB()
filter = {}
filter["public"] = request.args.get("public", "") in ["true", "1"]
filter["shared"] = request.args.get("shared", "") in ["true", "1"]
filter["owner"] = request.args.get("owner", "") in ["true", "1"]
view = request.args.get("view", "")
try:
returnList = ecr_db.listApps(
user=requestUser,
namespace=namespace,
repository=repository,
isAdmin=isAdmin,
limit=limit,
continuationToken=continueT,
filter=filter,
view=view,
)
except Exception as e:
raise ErrorResponse(
f"listApps returned: {str(e)}",
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)
return_obj = {"pagination": {}, "data": returnList}
if len(returnList) > 0:
if len(returnList) == limit:
last = returnList[-1]
last_id = last["id"]
return_obj["pagination"]["continuationToken"] = base64.b64encode(
str.encode(last_id)
).decode() # b64 is just to make it look cooler
else:
return_obj["pagination"]["continuationToken"] = "N/A"
return jsonify(return_obj)
def get_build(requestUser, isAdmin, namespace, repository, version):
try:
js = jenkins_server.JenkinsServer(
host=config.jenkins_server,
username=config.jenkins_user,
password=config.jenkins_token,
)
except Exception as e:
raise ErrorResponse(
f"JenkinsServer({config.jenkins_server}, {config.jenkins_user}) returned: {str(e)}",
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)
# source_name= request.values.get("source", "default")
# source_name = "default"
# strategy to find last build
# 1. check db field "number"
# 2. use global queue id to map to app-specific build number
# 3. take whatever is reported as last build (IS MISLEADING, returns previous build)
ecr_db = ecrdb.EcrDB()
# app_spec, ok = ecr_db.getApp(namespace=namespace, name=repository, version=version)
app_spec, ok = ecr_db.listApps(
user=requestUser,
isAdmin=isAdmin,
namespace=namespace,
repository=repository,
version=version,
)
if not ok:
# return {"error":f"app_spec not found {namespace}/{repository}:{version}"}
return ErrorResponse(
f"app_spec not found {namespace}/{repository}:{version}",
status_code=HTTPStatus.NOT_FOUND,
)
app_id = app_spec.get("id", "")
if not app_id:
return ErrorResponse(
f"app id not found", status_code=HTTPStatus.INTERNAL_SERVER_ERROR
)
# return {"error":"app not found"}
app_human_id = createJenkinsName(app_spec)
# strategy 1: try to find build number in database
number = -1
architectures = ""
try:
number, architectures = ecr_db.getBuildInfo(app_id, "some name")
except Exception as e:
raise ErrorResponse(
f"Could not get build number: {str(e)}",
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
)