-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
export.py
2439 lines (2056 loc) · 81.7 KB
/
export.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
# This is the main code for the `./manage.py export` data export tool.
# User docs: https://zulip.readthedocs.io/en/latest/production/export-and-import.html
#
# Most developers will interact with this primarily when they add a
# new table to the schema, in which case they likely need to (1) add
# it the lists in `ALL_ZULIP_TABLES` and similar data structures and
# (2) if it doesn't belong in EXCLUDED_TABLES, add a Config object for
# it to get_realm_config.
import datetime
import glob
import logging
import os
import shutil
import subprocess
import tempfile
from contextlib import suppress
from functools import lru_cache
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, Tuple, TypedDict
import orjson
from django.apps import apps
from django.conf import settings
from django.db.models import Exists, OuterRef, Q
from django.forms.models import model_to_dict
from django.utils.timezone import is_naive as timezone_is_naive
from mypy_boto3_s3.service_resource import Object
import zerver.lib.upload
from analytics.models import RealmCount, StreamCount, UserCount
from scripts.lib.zulip_tools import overwrite_symlink
from zerver.lib.avatar_hash import user_avatar_path_from_ids
from zerver.lib.pysa import mark_sanitized
from zerver.lib.upload.s3 import get_bucket
from zerver.models import (
AlertWord,
Attachment,
BotConfigData,
BotStorageData,
Client,
CustomProfileField,
CustomProfileFieldValue,
DefaultStream,
GroupGroupMembership,
Huddle,
Message,
MutedUser,
Reaction,
Realm,
RealmAuditLog,
RealmAuthenticationMethod,
RealmDomain,
RealmEmoji,
RealmFilter,
RealmPlayground,
RealmUserDefault,
Recipient,
ScheduledMessage,
Service,
Stream,
Subscription,
UserActivity,
UserActivityInterval,
UserGroup,
UserGroupMembership,
UserHotspot,
UserMessage,
UserPresence,
UserProfile,
UserStatus,
UserTopic,
get_realm,
get_system_bot,
get_user_profile_by_id,
)
# Custom mypy types follow:
Record = Dict[str, Any]
TableName = str
TableData = Dict[TableName, List[Record]]
Field = str
Path = str
Context = Dict[str, Any]
FilterArgs = Dict[str, Any]
IdSource = Tuple[TableName, Field]
SourceFilter = Callable[[Record], bool]
CustomFetch = Callable[[TableData, Context], None]
class MessagePartial(TypedDict):
zerver_message: List[Record]
zerver_userprofile_ids: List[int]
realm_id: int
MESSAGE_BATCH_CHUNK_SIZE = 1000
ALL_ZULIP_TABLES = {
"analytics_fillstate",
"analytics_installationcount",
"analytics_realmcount",
"analytics_streamcount",
"analytics_usercount",
"otp_static_staticdevice",
"otp_static_statictoken",
"otp_totp_totpdevice",
"social_auth_association",
"social_auth_code",
"social_auth_nonce",
"social_auth_partial",
"social_auth_usersocialauth",
"two_factor_phonedevice",
"zerver_alertword",
"zerver_archivedattachment",
"zerver_archivedattachment_messages",
"zerver_archivedmessage",
"zerver_archivedusermessage",
"zerver_attachment",
"zerver_attachment_messages",
"zerver_attachment_scheduled_messages",
"zerver_archivedreaction",
"zerver_archivedsubmessage",
"zerver_archivetransaction",
"zerver_botconfigdata",
"zerver_botstoragedata",
"zerver_client",
"zerver_customprofilefield",
"zerver_customprofilefieldvalue",
"zerver_defaultstream",
"zerver_defaultstreamgroup",
"zerver_defaultstreamgroup_streams",
"zerver_draft",
"zerver_emailchangestatus",
"zerver_groupgroupmembership",
"zerver_huddle",
"zerver_message",
"zerver_missedmessageemailaddress",
"zerver_multiuseinvite",
"zerver_multiuseinvite_streams",
"zerver_preregistrationrealm",
"zerver_preregistrationuser",
"zerver_preregistrationuser_streams",
"zerver_pushdevicetoken",
"zerver_reaction",
"zerver_realm",
"zerver_realmauditlog",
"zerver_realmauthenticationmethod",
"zerver_realmdomain",
"zerver_realmemoji",
"zerver_realmfilter",
"zerver_realmplayground",
"zerver_realmreactivationstatus",
"zerver_realmuserdefault",
"zerver_recipient",
"zerver_scheduledemail",
"zerver_scheduledemail_users",
"zerver_scheduledmessage",
"zerver_scheduledmessagenotificationemail",
"zerver_service",
"zerver_stream",
"zerver_submessage",
"zerver_subscription",
"zerver_useractivity",
"zerver_useractivityinterval",
"zerver_usergroup",
"zerver_usergroupmembership",
"zerver_userhotspot",
"zerver_usermessage",
"zerver_userpresence",
"zerver_userprofile",
"zerver_userprofile_groups",
"zerver_userprofile_user_permissions",
"zerver_userstatus",
"zerver_usertopic",
"zerver_muteduser",
}
# This set contains those database tables that we expect to not be
# included in the export. This tool does validation to ensure that
# every table in the database is either exported or listed here, to
# ensure we never accidentally fail to export a table.
NON_EXPORTED_TABLES = {
# These invitation/confirmation flow tables don't make sense to
# export, since invitations links will be broken by the server URL
# change anyway:
"zerver_emailchangestatus",
"zerver_multiuseinvite",
"zerver_multiuseinvite_streams",
"zerver_preregistrationrealm",
"zerver_preregistrationuser",
"zerver_preregistrationuser_streams",
"zerver_realmreactivationstatus",
# Missed message addresses are low value to export since
# missed-message email addresses include the server's hostname and
# expire after a few days.
"zerver_missedmessageemailaddress",
# Scheduled message notification email data is for internal use by the server.
"zerver_scheduledmessagenotificationemail",
# When switching servers, clients will need to re-log in and
# reregister for push notifications anyway.
"zerver_pushdevicetoken",
# We don't use these generated Django tables
"zerver_userprofile_groups",
"zerver_userprofile_user_permissions",
# These is used for scheduling future activity; it could make
# sense to export, but is relatively low value.
"zerver_scheduledemail",
"zerver_scheduledemail_users",
# These tables are related to a user's 2FA authentication
# configuration, which will need to be set up again on the new
# server.
"two_factor_phonedevice",
"otp_static_staticdevice",
"otp_static_statictoken",
"otp_totp_totpdevice",
# These archive tables should not be exported (they are to support
# restoring content accidentally deleted due to software bugs in
# the retention policy feature)
"zerver_archivedmessage",
"zerver_archivedusermessage",
"zerver_archivedattachment",
"zerver_archivedattachment_messages",
"zerver_archivedreaction",
"zerver_archivedsubmessage",
"zerver_archivetransaction",
# Social auth tables are not needed post-export, since we don't
# use any of this state outside of a direct authentication flow.
"social_auth_association",
"social_auth_code",
"social_auth_nonce",
"social_auth_partial",
"social_auth_usersocialauth",
# We will likely never want to migrate this table, since it's a
# total of all the realmcount values on the server. Might need to
# recompute it after a fillstate import.
"analytics_installationcount",
# Fillstate will require some cleverness to do the right partial export.
"analytics_fillstate",
# These are for unfinished features; we'll want to add them to the
# export before they reach full production status.
"zerver_defaultstreamgroup",
"zerver_defaultstreamgroup_streams",
"zerver_submessage",
# Drafts don't need to be exported as they are supposed to be more ephemeral.
"zerver_draft",
# For any tables listed below here, it's a bug that they are not present in the export.
}
IMPLICIT_TABLES = {
# ManyToMany relationships are exported implicitly when importing
# the parent table.
"zerver_attachment_messages",
"zerver_attachment_scheduled_messages",
}
ATTACHMENT_TABLES = {
"zerver_attachment",
}
MESSAGE_TABLES = {
# message tables get special treatment, because they're by far our
# largest tables and need to be paginated.
"zerver_message",
"zerver_usermessage",
# zerver_reaction belongs here, since it's added late because it
# has a foreign key into the Message table.
"zerver_reaction",
}
# These get their own file as analytics data can be quite large and
# would otherwise make realm.json unpleasant to manually inspect
ANALYTICS_TABLES = {
"analytics_realmcount",
"analytics_streamcount",
"analytics_usercount",
}
# This data structure lists all the Django DateTimeField fields in the
# data model. These are converted to floats during the export process
# via floatify_datetime_fields, and back during the import process.
#
# TODO: This data structure could likely eventually be replaced by
# inspecting the corresponding Django models
DATE_FIELDS: Dict[TableName, List[Field]] = {
"analytics_installationcount": ["end_time"],
"analytics_realmcount": ["end_time"],
"analytics_streamcount": ["end_time"],
"analytics_usercount": ["end_time"],
"zerver_attachment": ["create_time"],
"zerver_message": ["last_edit_time", "date_sent"],
"zerver_muteduser": ["date_muted"],
"zerver_realmauditlog": ["event_time"],
"zerver_realm": ["date_created"],
"zerver_scheduledmessage": ["scheduled_timestamp"],
"zerver_stream": ["date_created"],
"zerver_useractivityinterval": ["start", "end"],
"zerver_useractivity": ["last_visit"],
"zerver_userhotspot": ["timestamp"],
"zerver_userpresence": ["last_active_time", "last_connected_time"],
"zerver_userprofile": ["date_joined", "last_login", "last_reminder"],
"zerver_userprofile_mirrordummy": ["date_joined", "last_login", "last_reminder"],
"zerver_userstatus": ["timestamp"],
"zerver_usertopic": ["last_updated"],
}
def sanity_check_output(data: TableData) -> None:
# First, we verify that the export tool has a declared
# configuration for every table declared in the `models.py` files.
target_models = (
list(apps.get_app_config("analytics").get_models(include_auto_created=True))
+ list(apps.get_app_config("django_otp").get_models(include_auto_created=True))
+ list(apps.get_app_config("otp_static").get_models(include_auto_created=True))
+ list(apps.get_app_config("otp_totp").get_models(include_auto_created=True))
+ list(apps.get_app_config("phonenumber").get_models(include_auto_created=True))
+ list(apps.get_app_config("social_django").get_models(include_auto_created=True))
+ list(apps.get_app_config("two_factor").get_models(include_auto_created=True))
+ list(apps.get_app_config("zerver").get_models(include_auto_created=True))
)
all_tables_db = {model._meta.db_table for model in target_models}
# These assertion statements will fire when we add a new database
# table that is not included in Zulip's data exports. Generally,
# you can add your new table to `ALL_ZULIP_TABLES` and
# `NON_EXPORTED_TABLES` during early work on a new feature so that
# CI passes.
#
# We'll want to make sure we handle it for exports before
# releasing the new feature, but doing so correctly requires some
# expertise on this export system.
error_message = f"""
It appears you've added a new database table, but haven't yet
registered it in ALL_ZULIP_TABLES and the related declarations
in {__file__} for what to include in data exports.
"""
assert all_tables_db == ALL_ZULIP_TABLES, error_message
assert NON_EXPORTED_TABLES.issubset(ALL_ZULIP_TABLES), error_message
assert IMPLICIT_TABLES.issubset(ALL_ZULIP_TABLES), error_message
assert ATTACHMENT_TABLES.issubset(ALL_ZULIP_TABLES), error_message
assert ANALYTICS_TABLES.issubset(ALL_ZULIP_TABLES), error_message
tables = set(ALL_ZULIP_TABLES)
tables -= NON_EXPORTED_TABLES
tables -= IMPLICIT_TABLES
tables -= MESSAGE_TABLES
tables -= ATTACHMENT_TABLES
tables -= ANALYTICS_TABLES
for table in tables:
if table not in data:
logging.warning("??? NO DATA EXPORTED FOR TABLE %s!!!", table)
def write_data_to_file(output_file: Path, data: Any) -> None:
"""
IMPORTANT: You generally don't want to call this directly.
Instead use one of the higher level helpers:
write_table_data
write_records_json_file
The one place we call this directly is for message partials.
"""
with open(output_file, "wb") as f:
# Because we don't pass a default handler, OPT_PASSTHROUGH_DATETIME
# actually causes orjson to raise a TypeError on datetime objects. This
# is what we want, because it helps us check that we correctly
# post-processed them to serialize to UNIX timestamps rather than ISO
# 8601 strings for historical reasons.
f.write(orjson.dumps(data, option=orjson.OPT_INDENT_2 | orjson.OPT_PASSTHROUGH_DATETIME))
logging.info("Finished writing %s", output_file)
def write_table_data(output_file: str, data: Dict[str, Any]) -> None:
# We sort by ids mostly so that humans can quickly do diffs
# on two export jobs to see what changed (either due to new
# data arriving or new code being deployed).
for table in data.values():
table.sort(key=lambda row: row["id"])
assert output_file.endswith(".json")
write_data_to_file(output_file, data)
def write_records_json_file(output_dir: str, records: List[Dict[str, Any]]) -> None:
# We want a somewhat deterministic sorting order here. All of our
# versions of records.json include a "path" field in each element,
# even though there's some variation among avatars/emoji/realm_icons/uploads
# in other fields that get written.
#
# The sorting order of paths isn't entirely sensical to humans,
# because they include ids and even some random numbers,
# but if you export the same realm twice, you should get identical results.
records.sort(key=lambda record: record["path"])
output_file = os.path.join(output_dir, "records.json")
with open(output_file, "wb") as f:
# For legacy reasons we allow datetime objects here, unlike
# write_data_to_file.
f.write(orjson.dumps(records, option=orjson.OPT_INDENT_2))
logging.info("Finished writing %s", output_file)
def make_raw(query: Any, exclude: Optional[List[Field]] = None) -> List[Record]:
"""
Takes a Django query and returns a JSONable list
of dictionaries corresponding to the database rows.
"""
rows = []
for instance in query:
data = model_to_dict(instance, exclude=exclude)
"""
In Django 1.11.5, model_to_dict evaluates the QuerySet of
many-to-many field to give us a list of instances. We require
a list of primary keys, so we get the primary keys from the
instances below.
"""
for field in instance._meta.many_to_many:
if exclude is not None and field.name in exclude:
continue
value = data[field.name]
data[field.name] = [row.id for row in value]
rows.append(data)
return rows
def floatify_datetime_fields(data: TableData, table: TableName) -> None:
for item in data[table]:
for field in DATE_FIELDS[table]:
dt = item[field]
if dt is None:
continue
assert isinstance(dt, datetime.datetime)
assert not timezone_is_naive(dt)
item[field] = dt.timestamp()
class Config:
"""A Config object configures a single table for exporting (and, maybe
some day importing as well. This configuration defines what
process needs to be followed to correctly extract the set of
objects to export.
You should never mutate Config objects as part of the export;
instead use the data to determine how you populate other
data structures.
There are parent/children relationships between Config objects.
The parent should be instantiated first. The child will
append itself to the parent's list of children.
"""
def __init__(
self,
table: Optional[str] = None,
model: Optional[Any] = None,
normal_parent: Optional["Config"] = None,
virtual_parent: Optional["Config"] = None,
filter_args: Optional[FilterArgs] = None,
custom_fetch: Optional[CustomFetch] = None,
custom_tables: Optional[List[TableName]] = None,
concat_and_destroy: Optional[List[TableName]] = None,
id_source: Optional[IdSource] = None,
source_filter: Optional[SourceFilter] = None,
include_rows: Optional[Field] = None,
use_all: bool = False,
is_seeded: bool = False,
exclude: Optional[List[Field]] = None,
) -> None:
assert table or custom_tables
self.table = table
self.model = model
self.normal_parent = normal_parent
self.virtual_parent = virtual_parent
self.filter_args = filter_args
self.include_rows = include_rows
self.use_all = use_all
self.is_seeded = is_seeded
self.exclude = exclude
self.custom_fetch = custom_fetch
self.custom_tables = custom_tables
self.concat_and_destroy = concat_and_destroy
self.id_source = id_source
self.source_filter = source_filter
self.children: List[Config] = []
if self.include_rows:
assert self.include_rows.endswith("_id__in")
if self.custom_fetch:
# enforce a naming convention
assert self.custom_fetch.__name__.startswith("custom_fetch_")
if self.normal_parent is not None:
raise AssertionError(
"""
If you have a custom fetcher, then specify
your parent as a virtual_parent.
"""
)
if normal_parent is not None:
self.parent: Optional[Config] = normal_parent
else:
self.parent = None
if virtual_parent is not None and normal_parent is not None:
raise AssertionError(
"""
If you specify a normal_parent, please
do not create a virtual_parent.
"""
)
if normal_parent is not None:
normal_parent.children.append(self)
elif virtual_parent is not None:
virtual_parent.children.append(self)
elif is_seeded is None:
raise AssertionError(
"""
You must specify a parent if you are
not using is_seeded.
"""
)
if self.id_source is not None:
if self.virtual_parent is None:
raise AssertionError(
"""
You must specify a virtual_parent if you are
using id_source."""
)
if self.id_source[0] != self.virtual_parent.table:
raise AssertionError(
f"""
Configuration error. To populate {self.table}, you
want data from {self.id_source[0]}, but that differs from
the table name of your virtual parent ({self.virtual_parent.table}),
which suggests you many not have set up
the ordering correctly. You may simply
need to assign a virtual_parent, or there
may be deeper issues going on."""
)
def export_from_config(
response: TableData,
config: Config,
seed_object: Optional[Any] = None,
context: Optional[Context] = None,
) -> None:
table = config.table
parent = config.parent
model = config.model
if context is None:
context = {}
if config.custom_tables:
exported_tables = config.custom_tables
else:
assert (
table is not None
), """
You must specify config.custom_tables if you
are not specifying config.table"""
exported_tables = [table]
for t in exported_tables:
logging.info("Exporting via export_from_config: %s", t)
rows = None
if config.is_seeded:
rows = [seed_object]
elif config.custom_fetch:
config.custom_fetch(
response,
context,
)
if config.custom_tables:
for t in config.custom_tables:
if t not in response:
raise AssertionError(f"Custom fetch failed to populate {t}")
elif config.concat_and_destroy:
# When we concat_and_destroy, we are working with
# temporary "tables" that are lists of records that
# should already be ready to export.
data: List[Record] = []
for t in config.concat_and_destroy:
data += response[t]
del response[t]
logging.info("Deleted temporary %s", t)
assert table is not None
response[table] = data
elif config.use_all:
assert model is not None
query = model.objects.all()
rows = list(query)
elif config.normal_parent:
# In this mode, our current model is figuratively Article,
# and normal_parent is figuratively Blog, and
# now we just need to get all the articles
# contained by the blogs.
model = config.model
assert parent is not None
assert parent.table is not None
assert config.include_rows is not None
parent_ids = [r["id"] for r in response[parent.table]]
filter_params: Dict[str, Any] = {config.include_rows: parent_ids}
if config.filter_args is not None:
filter_params.update(config.filter_args)
assert model is not None
try:
query = model.objects.filter(**filter_params)
except Exception:
print(
f"""
Something about your Config seems to make it difficult
to construct a query.
table: {table}
parent: {parent.table}
filter_params: {filter_params}
"""
)
raise
rows = list(query)
elif config.id_source:
# In this mode, we are the figurative Blog, and we now
# need to look at the current response to get all the
# blog ids from the Article rows we fetched previously.
model = config.model
assert model is not None
# This will be a tuple of the form ('zerver_article', 'blog').
(child_table, field) = config.id_source
child_rows = response[child_table]
if config.source_filter:
child_rows = [r for r in child_rows if config.source_filter(r)]
lookup_ids = [r[field] for r in child_rows]
filter_params = dict(id__in=lookup_ids)
if config.filter_args:
filter_params.update(config.filter_args)
query = model.objects.filter(**filter_params)
rows = list(query)
if rows is not None:
assert table is not None # Hint for mypy
response[table] = make_raw(rows, exclude=config.exclude)
# Post-process rows
for t in exported_tables:
if t in DATE_FIELDS:
floatify_datetime_fields(response, t)
# Now walk our children. It's extremely important to respect
# the order of children here.
for child_config in config.children:
export_from_config(
response=response,
config=child_config,
context=context,
)
def get_realm_config() -> Config:
# This function generates the main Config object that defines how
# to do a full-realm export of a single realm from a Zulip server.
realm_config = Config(
table="zerver_realm",
is_seeded=True,
)
Config(
table="zerver_realmauthenticationmethod",
model=RealmAuthenticationMethod,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
custom_tables=["zerver_scheduledmessage"],
virtual_parent=realm_config,
custom_fetch=custom_fetch_scheduled_messages,
)
Config(
table="zerver_defaultstream",
model=DefaultStream,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_customprofilefield",
model=CustomProfileField,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_realmauditlog",
virtual_parent=realm_config,
custom_fetch=custom_fetch_realm_audit_logs_for_realm,
)
Config(
table="zerver_realmemoji",
model=RealmEmoji,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_realmdomain",
model=RealmDomain,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_realmfilter",
model=RealmFilter,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_realmplayground",
model=RealmPlayground,
normal_parent=realm_config,
include_rows="realm_id__in",
)
Config(
table="zerver_client",
model=Client,
virtual_parent=realm_config,
use_all=True,
)
Config(
table="zerver_realmuserdefault",
model=RealmUserDefault,
normal_parent=realm_config,
include_rows="realm_id__in",
)
user_profile_config = Config(
custom_tables=[
"zerver_userprofile",
"zerver_userprofile_mirrordummy",
],
# set table for children who treat us as normal parent
table="zerver_userprofile",
virtual_parent=realm_config,
custom_fetch=custom_fetch_user_profile,
)
user_groups_config = Config(
table="zerver_usergroup",
model=UserGroup,
normal_parent=realm_config,
include_rows="realm_id__in",
exclude=["direct_members", "direct_subgroups"],
)
Config(
table="zerver_usergroupmembership",
model=UserGroupMembership,
normal_parent=user_groups_config,
include_rows="user_group_id__in",
)
Config(
table="zerver_groupgroupmembership",
model=GroupGroupMembership,
normal_parent=user_groups_config,
include_rows="supergroup_id__in",
)
Config(
custom_tables=[
"zerver_userprofile_crossrealm",
],
virtual_parent=user_profile_config,
custom_fetch=custom_fetch_user_profile_cross_realm,
)
Config(
table="zerver_service",
model=Service,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_botstoragedata",
model=BotStorageData,
normal_parent=user_profile_config,
include_rows="bot_profile_id__in",
)
Config(
table="zerver_botconfigdata",
model=BotConfigData,
normal_parent=user_profile_config,
include_rows="bot_profile_id__in",
)
# Some of these tables are intermediate "tables" that we
# create only for the export. Think of them as similar to views.
user_subscription_config = Config(
table="_user_subscription",
model=Subscription,
normal_parent=user_profile_config,
filter_args={"recipient__type": Recipient.PERSONAL},
include_rows="user_profile_id__in",
)
Config(
table="_user_recipient",
model=Recipient,
virtual_parent=user_subscription_config,
id_source=("_user_subscription", "recipient"),
)
#
stream_config = Config(
table="zerver_stream",
model=Stream,
exclude=["email_token"],
normal_parent=realm_config,
include_rows="realm_id__in",
)
stream_recipient_config = Config(
table="_stream_recipient",
model=Recipient,
normal_parent=stream_config,
include_rows="type_id__in",
filter_args={"type": Recipient.STREAM},
)
Config(
table="_stream_subscription",
model=Subscription,
normal_parent=stream_recipient_config,
include_rows="recipient_id__in",
)
#
Config(
custom_tables=[
"_huddle_recipient",
"_huddle_subscription",
"zerver_huddle",
],
virtual_parent=user_profile_config,
custom_fetch=custom_fetch_huddle_objects,
)
# Now build permanent tables from our temp tables.
Config(
table="zerver_recipient",
virtual_parent=realm_config,
concat_and_destroy=[
"_user_recipient",
"_stream_recipient",
"_huddle_recipient",
],
)
Config(
table="zerver_subscription",
virtual_parent=realm_config,
concat_and_destroy=[
"_user_subscription",
"_stream_subscription",
"_huddle_subscription",
],
)
add_user_profile_child_configs(user_profile_config)
return realm_config
def add_user_profile_child_configs(user_profile_config: Config) -> None:
"""
We add tables here that are keyed by user, and for which
we fetch rows using the same scheme whether we are
exporting a realm or a single user.
For any table where there is nuance between how you
fetch for realms vs. single users, it's best to just
keep things simple and have each caller maintain its
own slightly different 4/5 line Config (while still
possibly calling common code deeper in the stack).
As of now, we do NOT include bot tables like Service.
"""
Config(
table="zerver_alertword",
model=AlertWord,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_customprofilefieldvalue",
model=CustomProfileFieldValue,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_muteduser",
model=MutedUser,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_useractivity",
model=UserActivity,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_useractivityinterval",
model=UserActivityInterval,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_userhotspot",
model=UserHotspot,
normal_parent=user_profile_config,
include_rows="user_id__in",
)
Config(
table="zerver_userpresence",
model=UserPresence,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_userstatus",
model=UserStatus,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
Config(
table="zerver_usertopic",
model=UserTopic,
normal_parent=user_profile_config,
include_rows="user_profile_id__in",
)
# We exclude these fields for the following reasons:
# * api_key is a secret.
# * password is a secret.
# * uuid is unlikely to be useful if the domain changes.
EXCLUDED_USER_PROFILE_FIELDS = ["api_key", "password", "uuid"]
def custom_fetch_user_profile(response: TableData, context: Context) -> None:
realm = context["realm"]
exportable_user_ids = context["exportable_user_ids"]
query = UserProfile.objects.filter(realm_id=realm.id).exclude(
# These were, in some early versions of Zulip, inserted into
# the first realm that was created. In those cases, rather
# than include them here, we will include them in the
# crossrealm user list, below.
email__in=settings.CROSS_REALM_BOT_EMAILS,