-
Notifications
You must be signed in to change notification settings - Fork 0
/
initdb.py
1391 lines (1161 loc) · 43.4 KB
/
initdb.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
# isort: skip_file
from typing import Dict, Any
import logging
import json
import hashlib
import random
import argparse
import calendar
import hashlib
import json
import logging
import os
import random
import unittest
from datetime import date, datetime, timedelta
from email.utils import formatdate
from itertools import count
from threading import Event
from typing import Any, Dict
from uuid import UUID, uuid4
from freezegun import freeze_time
from peewee import SqliteDatabase
from app import app, docker_v2_signing_key
from app import storage as store
from app import tf
from data import model
from data.database import (
AccessTokenKind,
ApprBlobPlacementLocation,
ApprTagKind,
BuildTriggerService,
DeletedNamespace,
DeletedRepository,
DisableReason,
ExternalNotificationEvent,
ExternalNotificationMethod,
FederatedLogin,
ImageStorageLocation,
ImageStorageSignatureKind,
ImageStorageTransformation,
LabelSourceType,
LogEntryKind,
LoginService,
ManifestChild,
MediaType,
NotificationKind,
OAuthAuthorizationCode,
ProxyCacheConfig,
QuayRegion,
QuayService,
QuotaLimits,
QuotaType,
RepoMirrorConfig,
RepoMirrorRule,
Repository,
RepositoryKind,
RepositoryState,
Role,
ServiceKeyApprovalType,
TagKind,
TeamRole,
User,
UserOrganizationQuota,
UserPromptKind,
UserRegion,
Visibility,
all_models,
appr_classes,
db,
db_encrypter,
get_epoch_timestamp_ms,
)
from data.decorators import is_deprecated_model
from data.encryption import FieldEncrypter
from data.fields import Credential
from data.logs_model import logs_model
from data.queue import WorkQueue
from data.registry_model import registry_model
from data.registry_model.datatypes import RepositoryReference
from digest.digest_tools import sha256_digest
from image.docker.schema1 import (
DOCKER_SCHEMA1_CONTENT_TYPES,
DockerSchema1ManifestBuilder,
)
from image.docker.schema2 import DOCKER_SCHEMA2_CONTENT_TYPES
from image.docker.schema2.config import DockerSchema2Config
from image.docker.schema2.manifest import DockerSchema2ManifestBuilder
from image.oci import OCI_CONTENT_TYPES
from storage.basestorage import StoragePaths
from workers import repositoryactioncounter
logger = logging.getLogger(__name__)
TEST_STRIPE_ID = "cus_2tmnh3PkXQS8NG"
IS_TESTING_REAL_DATABASE = bool(os.environ.get("TEST_DATABASE_URI"))
TEMP_BLOB_EXPIRATION = 120 # seconds
def __generate_service_key(
kid,
name,
user,
timestamp,
approval_type,
expiration=None,
metadata=None,
service="sample_service",
rotation_duration=None,
):
_, key = model.service_keys.generate_service_key(
service,
expiration,
kid=kid,
name=name,
metadata=metadata,
rotation_duration=rotation_duration,
)
if approval_type is not None:
model.service_keys.approve_service_key(
key.kid, approval_type, notes="The **test** approval"
)
key_metadata = {
"kid": kid,
"preshared": True,
"service": service,
"name": name,
"expiration_date": expiration,
"auto_approved": True,
}
logs_model.log_action(
"service_key_approve", None, performer=user, timestamp=timestamp, metadata=key_metadata
)
logs_model.log_action(
"service_key_create", None, performer=user, timestamp=timestamp, metadata=key_metadata
)
def _populate_blob(repo, content):
assert isinstance(repo, Repository)
assert isinstance(content, bytes)
digest = str(sha256_digest(content))
location = ImageStorageLocation.get(name="local_us")
blob = model.blob.store_blob_record_and_temp_link_in_repo(
repo, digest, location, len(content), TEMP_BLOB_EXPIRATION
)
return blob, digest
def __create_manifest_and_tags(
repo, structure, creator_username, tag_map, current_level=0, builder=None, last_leaf_id=None
):
num_layers, subtrees, tag_names = structure
num_layers = num_layers or 1
tag_names = tag_names or []
tag_names = [tag_names] if not isinstance(tag_names, list) else tag_names
repo_ref = RepositoryReference.for_repo_obj(repo)
builder = (
builder
if builder
else DockerSchema1ManifestBuilder(repo.namespace_user.username, repo.name, "")
)
# TODO: Change this to a mixture of Schema1 and Schema2 manifest once we no longer need to
# read from storage for Schema2.
# Populate layers. Note, we do this in reverse order using insert_layer, as it is easier to
# add the leaf last (even though Schema1 has it listed first).
parent_id = last_leaf_id
leaf_id = None
for layer_index in range(0, num_layers):
content = "layer-%s-%s-%s" % (layer_index, current_level, get_epoch_timestamp_ms())
_, digest = _populate_blob(repo, content.encode("ascii"))
current_id = "abcdef%s%s%s" % (layer_index, current_level, get_epoch_timestamp_ms())
if layer_index == num_layers - 1:
leaf_id = current_id
config = {
"id": current_id,
"Size": len(content),
}
if parent_id:
config["parent"] = parent_id
builder.insert_layer(digest, json.dumps(config))
parent_id = current_id
for tag_name in tag_names:
adjusted_tag_name = tag_name
now = datetime.utcnow()
if tag_name[0] == "#":
adjusted_tag_name = tag_name[1:]
now = now - timedelta(seconds=1)
manifest = builder.clone(adjusted_tag_name).build()
with freeze_time(now):
created_tag, _ = registry_model.create_manifest_and_retarget_tag(
repo_ref, manifest, adjusted_tag_name, store, raise_on_error=True
)
assert created_tag
tag_map[adjusted_tag_name] = created_tag
for subtree in subtrees:
__create_manifest_and_tags(
repo,
subtree,
creator_username,
tag_map,
current_level=current_level + 1,
builder=builder,
last_leaf_id=leaf_id,
)
def __generate_repository(user_obj, name, description, is_public, permissions, structure):
repo = model.repository.create_repository(user_obj.username, name, user_obj)
if is_public:
model.repository.set_repository_visibility(repo, "public")
if description:
repo.description = description
repo.save()
for delegate, role in permissions:
model.permission.set_user_repo_permission(delegate.username, user_obj.username, name, role)
tag_map = {}
if isinstance(structure, list):
for leaf in structure:
__create_manifest_and_tags(repo, leaf, user_obj.username, tag_map)
else:
__create_manifest_and_tags(repo, structure, user_obj.username, tag_map)
return repo
db_initialized_for_testing = Event()
testcases: Dict[unittest.TestCase, Dict[str, Any]] = {}
def finished_database_for_testing(testcase):
"""
Called when a testcase has finished using the database, indicating that any changes should be
discarded.
"""
testcases[testcase]["savepoint"].rollback()
testcases[testcase]["savepoint"].__exit__(True, None, None)
testcases[testcase]["transaction"].__exit__(True, None, None)
def setup_database_for_testing(testcase):
"""
Called when a testcase has started using the database, indicating that the database should be
setup (if not already) and a savepoint created.
"""
# Sanity check to make sure we're not killing our prod db
if not IS_TESTING_REAL_DATABASE and not isinstance(db.obj, SqliteDatabase):
raise RuntimeError("Attempted to wipe production database!")
if not db_initialized_for_testing.is_set():
logger.debug("Setting up DB for testing.")
# Setup the database.
if os.environ.get("SKIP_DB_SCHEMA", "") != "true":
wipe_database()
initialize_database()
populate_database()
models_missing_data = find_models_missing_data()
if models_missing_data:
raise RuntimeError(
"%s models are missing data: %s", len(models_missing_data), models_missing_data
)
# Enable foreign key constraints.
if not IS_TESTING_REAL_DATABASE:
db.obj.execute_sql("PRAGMA foreign_keys = ON;")
db_initialized_for_testing.set()
# Initialize caches.
Repository.kind.get_id("image")
# Create a savepoint for the testcase.
testcases[testcase] = {}
testcases[testcase]["transaction"] = db.transaction()
testcases[testcase]["transaction"].__enter__()
testcases[testcase]["savepoint"] = db.savepoint()
testcases[testcase]["savepoint"].__enter__()
def initialize_database():
db_encrypter.initialize(FieldEncrypter("anothercrazykey!"))
db.create_tables(all_models)
Role.create(name="admin")
Role.create(name="write")
Role.create(name="read")
TeamRole.create(name="admin")
TeamRole.create(name="creator")
TeamRole.create(name="member")
Visibility.create(name="public")
Visibility.create(name="private")
LoginService.create(name="google")
LoginService.create(name="github")
LoginService.create(name="quayrobot")
LoginService.create(name="ldap")
LoginService.create(name="jwtauthn")
LoginService.create(name="keystone")
LoginService.create(name="dex")
LoginService.create(name="oidc")
BuildTriggerService.create(name="github")
BuildTriggerService.create(name="custom-git")
BuildTriggerService.create(name="bitbucket")
BuildTriggerService.create(name="gitlab")
AccessTokenKind.create(name="build-worker")
AccessTokenKind.create(name="pushpull-token")
LogEntryKind.create(name="user_create")
LogEntryKind.create(name="user_delete")
LogEntryKind.create(name="user_disable")
LogEntryKind.create(name="user_enable")
LogEntryKind.create(name="user_change_email")
LogEntryKind.create(name="user_change_password")
LogEntryKind.create(name="user_change_name")
LogEntryKind.create(name="user_change_invoicing")
LogEntryKind.create(name="user_change_tag_expiration")
LogEntryKind.create(name="user_change_metadata")
LogEntryKind.create(name="user_generate_client_key")
LogEntryKind.create(name="account_change_plan")
LogEntryKind.create(name="account_change_cc")
LogEntryKind.create(name="account_change_password")
LogEntryKind.create(name="account_convert")
LogEntryKind.create(name="create_robot")
LogEntryKind.create(name="delete_robot")
LogEntryKind.create(name="create_repo")
LogEntryKind.create(name="push_repo")
LogEntryKind.create(name="pull_repo")
LogEntryKind.create(name="delete_repo")
LogEntryKind.create(name="create_tag")
LogEntryKind.create(name="move_tag")
LogEntryKind.create(name="delete_tag")
LogEntryKind.create(name="revert_tag")
LogEntryKind.create(name="add_repo_permission")
LogEntryKind.create(name="change_repo_permission")
LogEntryKind.create(name="delete_repo_permission")
LogEntryKind.create(name="change_repo_visibility")
LogEntryKind.create(name="change_repo_trust")
LogEntryKind.create(name="add_repo_accesstoken")
LogEntryKind.create(name="delete_repo_accesstoken")
LogEntryKind.create(name="set_repo_description")
LogEntryKind.create(name="change_repo_state")
LogEntryKind.create(name="build_dockerfile")
LogEntryKind.create(name="org_create")
LogEntryKind.create(name="org_delete")
LogEntryKind.create(name="org_create_team")
LogEntryKind.create(name="org_delete_team")
LogEntryKind.create(name="org_invite_team_member")
LogEntryKind.create(name="org_delete_team_member_invite")
LogEntryKind.create(name="org_add_team_member")
LogEntryKind.create(name="org_team_member_invite_accepted")
LogEntryKind.create(name="org_team_member_invite_declined")
LogEntryKind.create(name="org_remove_team_member")
LogEntryKind.create(name="org_set_team_description")
LogEntryKind.create(name="org_set_team_role")
LogEntryKind.create(name="org_change_email")
LogEntryKind.create(name="org_change_invoicing")
LogEntryKind.create(name="org_change_tag_expiration")
LogEntryKind.create(name="org_change_name")
LogEntryKind.create(name="create_prototype_permission")
LogEntryKind.create(name="modify_prototype_permission")
LogEntryKind.create(name="delete_prototype_permission")
LogEntryKind.create(name="setup_repo_trigger")
LogEntryKind.create(name="delete_repo_trigger")
LogEntryKind.create(name="create_application")
LogEntryKind.create(name="update_application")
LogEntryKind.create(name="delete_application")
LogEntryKind.create(name="reset_application_client_secret")
# Note: These next two are deprecated.
LogEntryKind.create(name="add_repo_webhook")
LogEntryKind.create(name="delete_repo_webhook")
LogEntryKind.create(name="add_repo_notification")
LogEntryKind.create(name="delete_repo_notification")
LogEntryKind.create(name="reset_repo_notification")
LogEntryKind.create(name="regenerate_robot_token")
LogEntryKind.create(name="repo_verb")
LogEntryKind.create(name="repo_mirror_enabled")
LogEntryKind.create(name="repo_mirror_disabled")
LogEntryKind.create(name="repo_mirror_config_changed")
LogEntryKind.create(name="repo_mirror_sync_started")
LogEntryKind.create(name="repo_mirror_sync_failed")
LogEntryKind.create(name="repo_mirror_sync_success")
LogEntryKind.create(name="repo_mirror_sync_now_requested")
LogEntryKind.create(name="repo_mirror_sync_tag_success")
LogEntryKind.create(name="repo_mirror_sync_tag_failed")
LogEntryKind.create(name="repo_mirror_sync_test_success")
LogEntryKind.create(name="repo_mirror_sync_test_failed")
LogEntryKind.create(name="repo_mirror_sync_test_started")
LogEntryKind.create(name="service_key_create")
LogEntryKind.create(name="service_key_approve")
LogEntryKind.create(name="service_key_delete")
LogEntryKind.create(name="service_key_modify")
LogEntryKind.create(name="service_key_extend")
LogEntryKind.create(name="service_key_rotate")
LogEntryKind.create(name="take_ownership")
LogEntryKind.create(name="manifest_label_add")
LogEntryKind.create(name="manifest_label_delete")
LogEntryKind.create(name="change_tag_expiration")
LogEntryKind.create(name="toggle_repo_trigger")
LogEntryKind.create(name="create_app_specific_token")
LogEntryKind.create(name="revoke_app_specific_token")
LogEntryKind.create(name="create_proxy_cache_config")
LogEntryKind.create(name="delete_proxy_cache_config")
LogEntryKind.create(name="start_build_trigger")
LogEntryKind.create(name="cancel_build")
LogEntryKind.create(name="login_success")
LogEntryKind.create(name="logout_success")
LogEntryKind.create(name="permanently_delete_tag")
ImageStorageLocation.create(name="local_eu")
ImageStorageLocation.create(name="local_us")
ApprBlobPlacementLocation.create(name="local_eu")
ApprBlobPlacementLocation.create(name="local_us")
ImageStorageTransformation.create(name="squash")
ImageStorageTransformation.create(name="aci")
ImageStorageSignatureKind.create(name="gpg2")
# NOTE: These MUST be copied over to NotificationKind, since every external
# notification can also generate a Quay.io notification.
ExternalNotificationEvent.create(name="repo_push")
ExternalNotificationEvent.create(name="build_queued")
ExternalNotificationEvent.create(name="build_start")
ExternalNotificationEvent.create(name="build_success")
ExternalNotificationEvent.create(name="build_cancelled")
ExternalNotificationEvent.create(name="build_failure")
ExternalNotificationEvent.create(name="vulnerability_found")
ExternalNotificationEvent.create(name="repo_mirror_sync_started")
ExternalNotificationEvent.create(name="repo_mirror_sync_success")
ExternalNotificationEvent.create(name="repo_mirror_sync_failed")
ExternalNotificationMethod.create(name="quay_notification")
ExternalNotificationMethod.create(name="email")
ExternalNotificationMethod.create(name="webhook")
ExternalNotificationMethod.create(name="flowdock")
ExternalNotificationMethod.create(name="hipchat")
ExternalNotificationMethod.create(name="slack")
NotificationKind.create(name="repo_push")
NotificationKind.create(name="build_queued")
NotificationKind.create(name="build_start")
NotificationKind.create(name="build_success")
NotificationKind.create(name="build_cancelled")
NotificationKind.create(name="build_failure")
NotificationKind.create(name="vulnerability_found")
NotificationKind.create(name="service_key_submitted")
NotificationKind.create(name="password_required")
NotificationKind.create(name="over_private_usage")
NotificationKind.create(name="expiring_license")
NotificationKind.create(name="maintenance")
NotificationKind.create(name="org_team_invite")
NotificationKind.create(name="repo_mirror_sync_started")
NotificationKind.create(name="repo_mirror_sync_success")
NotificationKind.create(name="repo_mirror_sync_failed")
NotificationKind.create(name="test_notification")
QuayRegion.create(name="us")
QuayService.create(name="quay")
MediaType.create(name="text/plain")
MediaType.create(name="application/json")
MediaType.create(name="text/markdown")
for media_type in DOCKER_SCHEMA1_CONTENT_TYPES:
MediaType.create(name=media_type)
for media_type in DOCKER_SCHEMA2_CONTENT_TYPES:
MediaType.create(name=media_type)
for media_type in OCI_CONTENT_TYPES:
MediaType.create(name=media_type)
LabelSourceType.create(name="manifest")
LabelSourceType.create(name="api", mutable=True)
LabelSourceType.create(name="internal")
UserPromptKind.create(name="confirm_username")
UserPromptKind.create(name="enter_name")
UserPromptKind.create(name="enter_company")
RepositoryKind.create(name="image")
RepositoryKind.create(name="application")
ApprTagKind.create(name="tag")
ApprTagKind.create(name="release")
ApprTagKind.create(name="channel")
DisableReason.create(name="user_toggled")
DisableReason.create(name="successive_build_failures")
DisableReason.create(name="successive_build_internal_errors")
TagKind.create(name="tag")
def wipe_database():
logger.debug("Wiping all data from the DB.")
# Sanity check to make sure we're not killing our prod db
if not IS_TESTING_REAL_DATABASE and not isinstance(db.obj, SqliteDatabase):
raise RuntimeError("Attempted to wipe production database!")
db.drop_tables(all_models)
def populate_database(minimal=False):
logger.debug("Populating the DB with test data.")
# Check if the data already exists. If so, we skip. This can happen between calls from the
# "old style" tests and the new py.test's.
try:
User.get(username="devtable")
logger.debug("DB already populated")
return
except User.DoesNotExist:
pass
# Note: databases set up with "real" schema (via Alembic) will not have these types
# type, so we it here it necessary.
try:
ImageStorageLocation.get(name="local_eu")
ImageStorageLocation.get(name="local_us")
except ImageStorageLocation.DoesNotExist:
ImageStorageLocation.create(name="local_eu")
ImageStorageLocation.create(name="local_us")
try:
NotificationKind.get(name="test_notification")
except NotificationKind.DoesNotExist:
NotificationKind.create(name="test_notification")
new_user_1 = model.user.create_user("devtable", "password", "jschorr@devtable.com")
new_user_1.verified = True
new_user_1.stripe_id = TEST_STRIPE_ID
new_user_1.save()
if minimal:
logger.debug("Skipping most db population because user requested mininal db")
return
UserRegion.create(user=new_user_1, location=ImageStorageLocation.get(name="local_us"))
model.release.set_region_release("quay", "us", "v0.1.2")
model.user.create_confirm_email_code(new_user_1, new_email="typo@devtable.com")
disabled_user = model.user.create_user("disabled", "password", "jschorr+disabled@devtable.com")
disabled_user.verified = True
disabled_user.enabled = False
disabled_user.save()
dtrobot = model.user.create_robot("dtrobot", new_user_1)
dtrobot2 = model.user.create_robot("dtrobot2", new_user_1)
new_user_2 = model.user.create_user("public", "password", "jacob.moshenko@gmail.com")
new_user_2.verified = True
new_user_2.save()
new_user_3 = model.user.create_user("freshuser", "password", "jschorr+test@devtable.com")
new_user_3.verified = True
new_user_3.save()
another_robot = model.user.create_robot("anotherrobot", new_user_3)
new_user_4 = model.user.create_user("randomuser", "password", "no4@thanks.com")
new_user_4.verified = True
new_user_4.save()
new_user_5 = model.user.create_user("unverified", "password", "no5@thanks.com")
new_user_5.save()
reader = model.user.create_user("reader", "password", "no1@thanks.com")
reader.verified = True
reader.save()
creatoruser = model.user.create_user("creator", "password", "noc@thanks.com")
creatoruser.verified = True
creatoruser.save()
memberuser = model.user.create_user("member", "password", "nod@thanks.com")
memberuser.verified = True
memberuser.save()
outside_org = model.user.create_user("outsideorg", "password", "no2@thanks.com")
outside_org.verified = True
outside_org.save()
model.notification.create_notification(
"test_notification",
new_user_1,
metadata={"some": "value", "arr": [1, 2, 3], "obj": {"a": 1, "b": 2}},
)
from_date = datetime.utcnow()
to_date = from_date + timedelta(hours=1)
notification_metadata = {
"from_date": formatdate(calendar.timegm(from_date.utctimetuple())),
"to_date": formatdate(calendar.timegm(to_date.utctimetuple())),
"reason": "database migration",
}
model.notification.create_notification(
"maintenance", new_user_1, metadata=notification_metadata
)
__generate_repository(
new_user_4,
"randomrepo",
"Random repo repository.",
False,
[],
(4, [], ["latest", "prod"]),
)
simple_repo = __generate_repository(
new_user_1,
"simple",
"Simple repository.",
False,
[],
(4, [], ["latest", "prod"]),
)
# Add some labels to the latest tag's manifest.
repo_ref = RepositoryReference.for_repo_obj(simple_repo)
tag = registry_model.get_repo_tag(repo_ref, "latest")
manifest = registry_model.get_manifest_for_tag(tag)
assert manifest
first_label = registry_model.create_manifest_label(manifest, "foo", "bar", "manifest")
registry_model.create_manifest_label(manifest, "foo", "baz", "api")
registry_model.create_manifest_label(manifest, "anotherlabel", "1234", "internal")
registry_model.create_manifest_label(
manifest, "jsonlabel", '{"hey": "there"}', "internal", "application/json"
)
label_metadata = {
"key": "foo",
"value": "bar",
"id": first_label._db_id,
"manifest_digest": manifest.digest,
}
logs_model.log_action(
"manifest_label_add",
new_user_1.username,
performer=new_user_1,
timestamp=datetime.now(),
metadata=label_metadata,
repository=simple_repo,
)
model.blob.initiate_upload(new_user_1.username, simple_repo.name, str(uuid4()), "local_us", {})
model.notification.create_repo_notification(
simple_repo, "repo_push", "quay_notification", {}, {}
)
__generate_repository(
new_user_1,
"sharedtags",
"Shared tags repository",
False,
[(new_user_2, "read"), (dtrobot[0], "read")],
(
2,
[
(3, [], ["v2.0", "v2.1", "v2.2"]),
(
1,
[(1, [(1, [], ["prod", "581a284"])], ["staging", "8423b58"]), (1, [], None)],
None,
),
],
None,
),
)
__generate_repository(
new_user_1,
"history",
"Historical repository.",
False,
[],
(4, [(2, [], "#latest"), (3, [], "latest")], None),
)
__generate_repository(
new_user_1,
"complex",
"Complex repository with many branches and tags.",
False,
[(new_user_2, "read"), (dtrobot[0], "read")],
(
2,
[(3, [], "v2.0"), (1, [(1, [(2, [], ["prod"])], "staging"), (1, [], None)], None)],
None,
),
)
__generate_repository(
new_user_1,
"gargantuan",
None,
False,
[],
(
2,
[
(3, [], "v2.0"),
(1, [(1, [(1, [], ["latest", "prod"])], "staging"), (1, [], None)], None),
(20, [], "v3.0"),
(5, [], "v4.0"),
(1, [(1, [], "v5.0"), (1, [], "v6.0")], None),
],
None,
),
)
trusted_repo = __generate_repository(
new_user_1,
"trusted",
"Trusted repository.",
False,
[],
(4, [], ["latest", "prod"]),
)
trusted_repo.trust_enabled = True
trusted_repo.save()
publicrepo = __generate_repository(
new_user_2,
"publicrepo",
"Public repository pullable by the world.",
True,
[],
(10, [], "latest"),
)
__generate_repository(outside_org, "coolrepo", "Some cool repo.", False, [], (5, [], "latest"))
__generate_repository(
new_user_1,
"shared",
"Shared repository, another user can write.",
False,
[(new_user_2, "write"), (reader, "read")],
(5, [], "latest"),
)
__generate_repository(
new_user_1,
"text-full-repo",
"This is a repository for testing text search",
False,
[(new_user_2, "write"), (reader, "read")],
(5, [], "latest"),
)
building = __generate_repository(
new_user_1,
"building",
"Empty repository which is building.",
False,
[(new_user_2, "write"), (reader, "read")],
(0, [], None),
)
new_token = model.token.create_access_token(building, "write", "build-worker")
trigger = model.build.create_build_trigger(
building, "github", "123authtoken", new_user_1, pull_robot=dtrobot[0]
)
trigger.config = json.dumps(
{
"build_source": "jakedt/testconnect",
"subdir": "",
"dockerfile_path": "Dockerfile",
"context": "/",
}
)
trigger.save()
repo = "ci.devtable.com:5000/%s/%s" % (building.namespace_user.username, building.name)
job_config = {
"repository": repo,
"docker_tags": ["latest"],
"build_subdir": "",
"trigger_metadata": {
"commit": "3482adc5822c498e8f7db2e361e8d57b3d77ddd9",
"ref": "refs/heads/master",
"default_branch": "master",
},
}
model.repository.star_repository(new_user_1, simple_repo)
record = model.repository.create_email_authorization_for_repo(
new_user_1.username, "simple", "jschorr@devtable.com"
)
record.confirmed = True
record.save()
model.repository.create_email_authorization_for_repo(
new_user_1.username, "simple", "jschorr+other@devtable.com"
)
build2 = model.build.create_repository_build(
building,
new_token,
job_config,
"68daeebd-a5b9-457f-80a0-4363b882f8ea",
"build-name",
trigger,
)
build2.uuid = "deadpork-dead-pork-dead-porkdeadpork"
build2.save()
build3 = model.build.create_repository_build(
building,
new_token,
job_config,
"f49d07f9-93da-474d-ad5f-c852107c3892",
"build-name",
trigger,
)
build3.uuid = "deadduck-dead-duck-dead-duckdeadduck"
build3.save()
build1 = model.build.create_repository_build(
building, new_token, job_config, "701dcc3724fb4f2ea6c31400528343cd", "build-name", trigger
)
build1.uuid = "deadbeef-dead-beef-dead-beefdeadbeef"
build1.save()
org = model.organization.create_organization("buynlarge", "quay@devtable.com", new_user_1)
org.stripe_id = TEST_STRIPE_ID
org.save()
QuotaType.create(name="Warning")
QuotaType.create(name="Reject")
quota1 = model.namespacequota.create_namespace_quota(org, 3000)
model.namespacequota.create_namespace_quota_limit(quota1, "warning", 50)
quota2 = model.namespacequota.create_namespace_quota(new_user_4, 6000)
model.namespacequota.create_namespace_quota_limit(quota2, "reject", 90)
liborg = model.organization.create_organization(
"library", "quay+library@devtable.com", new_user_1
)
liborg.save()
titiorg = model.organization.create_organization("titi", "quay+titi@devtable.com", new_user_1)
titiorg.save()
thirdorg = model.organization.create_organization(
"sellnsmall", "quay+sell@devtable.com", new_user_1
)
thirdorg.save()
model.user.create_robot("coolrobot", org)
proxyorg = model.organization.create_organization(
"proxyorg", "quay+proxyorg@devtable.com", new_user_1
)
proxyorg.save()
model.proxy_cache.create_proxy_cache_config(proxyorg.username, "docker.io")
oauth_app_1 = model.oauth.create_application(
org,
"Some Test App",
"http://localhost:8000",
"http://localhost:8000/o2c.html",
client_id="deadbeef",
)
model.oauth.create_application(
org,
"Some Other Test App",
"http://quay.io",
"http://localhost:8000/o2c.html",
client_id="deadpork",
description="This is another test application",
)
model.oauth.create_user_access_token(
new_user_1, "deadbeef", "repo:admin", access_token="%s%s" % ("b" * 40, "c" * 40)
)
oauth_credential = Credential.from_string("dswfhasdf1")
OAuthAuthorizationCode.create(
application=oauth_app_1,
code="Z932odswfhasdf1",
scope="repo:admin",
data='{"somejson": "goeshere"}',
code_name="Z932odswfhasdf1Z932o",
code_credential=oauth_credential,
)
model.user.create_robot("neworgrobot", org)
ownerbot = model.user.create_robot("ownerbot", org)[0]
creatorbot = model.user.create_robot("creatorbot", org)[0]
owners = model.team.get_organization_team("buynlarge", "owners")
owners.description = "Owners have unfetterd access across the entire org."
owners.save()
org_repo = __generate_repository(
org,
"orgrepo",
"Repository owned by an org.",
False,
[(outside_org, "read")],
(4, [], ["latest", "prod"]),
)
__generate_repository(
org,
"anotherorgrepo",
"Another repository owned by an org.",
False,
[],
(4, [], ["latest", "prod"]),
)
creators = model.team.create_team("creators", org, "creator", "Creators of orgrepo.")
proxymembers = model.team.create_team("members", proxyorg, "member", "Members of proxyorg.")
reader_team = model.team.create_team("readers", org, "member", "Readers of orgrepo.")
model.team.add_or_invite_to_team(new_user_1, reader_team, outside_org)
model.permission.set_team_repo_permission(
reader_team.name, org_repo.namespace_user.username, org_repo.name, "read"
)
model.team.add_user_to_team(new_user_2, reader_team)
model.team.add_user_to_team(reader, reader_team)
model.team.add_user_to_team(ownerbot, owners)
model.team.add_user_to_team(creatorbot, creators)
model.team.add_user_to_team(creatoruser, creators)
model.team.add_user_to_team(memberuser, proxymembers)
sell_owners = model.team.get_organization_team("sellnsmall", "owners")