-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcatalog_manager_ent.cc
4806 lines (4157 loc) · 191 KB
/
catalog_manager_ent.cc
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
// Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
#include <memory>
#include <regex>
#include <set>
#include <unordered_set>
#include <google/protobuf/util/message_differencer.h>
#include "yb/common/common_fwd.h"
#include "yb/master/catalog_entity_info.h"
#include "yb/master/catalog_manager-internal.h"
#include "yb/master/cdc_consumer_registry_service.h"
#include "yb/master/cdc_rpc_tasks.h"
#include "yb/master/cluster_balance.h"
#include "yb/master/master.h"
#include "yb/master/master_backup.pb.h"
#include "yb/master/master_error.h"
#include "yb/cdc/cdc_consumer.pb.h"
#include "yb/cdc/cdc_service.h"
#include "yb/client/client-internal.h"
#include "yb/client/schema.h"
#include "yb/client/session.h"
#include "yb/client/table.h"
#include "yb/client/table_alterer.h"
#include "yb/client/table_handle.h"
#include "yb/client/table_info.h"
#include "yb/client/yb_op.h"
#include "yb/client/yb_table_name.h"
#include "yb/common/common.pb.h"
#include "yb/common/entity_ids.h"
#include "yb/common/ql_name.h"
#include "yb/common/ql_type.h"
#include "yb/common/schema.h"
#include "yb/common/wire_protocol.h"
#include "yb/consensus/consensus.h"
#include "yb/docdb/consensus_frontier.h"
#include "yb/docdb/doc_write_batch.h"
#include "yb/gutil/bind.h"
#include "yb/gutil/casts.h"
#include "yb/gutil/strings/join.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/master/master_client.pb.h"
#include "yb/master/master_ddl.pb.h"
#include "yb/master/master_defaults.h"
#include "yb/master/master_heartbeat.pb.h"
#include "yb/master/master_replication.pb.h"
#include "yb/master/master_util.h"
#include "yb/master/sys_catalog.h"
#include "yb/master/sys_catalog-internal.h"
#include "yb/master/async_snapshot_tasks.h"
#include "yb/master/async_rpc_tasks.h"
#include "yb/master/encryption_manager.h"
#include "yb/master/restore_sys_catalog_state.h"
#include "yb/master/scoped_leader_shared_lock.h"
#include "yb/master/scoped_leader_shared_lock-internal.h"
#include "yb/rpc/messenger.h"
#include "yb/tablet/operations/snapshot_operation.h"
#include "yb/tablet/tablet_metadata.h"
#include "yb/tablet/tablet_snapshots.h"
#include "yb/tserver/backup.proxy.h"
#include "yb/tserver/service_util.h"
#include "yb/util/cast.h"
#include "yb/util/date_time.h"
#include "yb/util/flag_tags.h"
#include "yb/util/format.h"
#include "yb/util/logging.h"
#include "yb/util/random_util.h"
#include "yb/util/scope_exit.h"
#include "yb/util/service_util.h"
#include "yb/util/status.h"
#include "yb/util/status_format.h"
#include "yb/util/status_log.h"
#include "yb/util/tostring.h"
#include "yb/util/string_util.h"
#include "yb/util/trace.h"
#include "yb/yql/cql/ql/util/statement_result.h"
using namespace std::literals;
using namespace std::placeholders;
using std::string;
using std::unique_ptr;
using std::vector;
using google::protobuf::RepeatedPtrField;
using google::protobuf::util::MessageDifferencer;
using strings::Substitute;
DEFINE_int32(cdc_state_table_num_tablets, 0,
"Number of tablets to use when creating the CDC state table. "
"0 to use the same default num tablets as for regular tables.");
DEFINE_int32(cdc_wal_retention_time_secs, 4 * 3600,
"WAL retention time in seconds to be used for tables for which a CDC stream was "
"created.");
DECLARE_int32(master_rpc_timeout_ms);
DEFINE_bool(enable_transaction_snapshots, true,
"The flag enables usage of transaction aware snapshots.");
TAG_FLAG(enable_transaction_snapshots, hidden);
TAG_FLAG(enable_transaction_snapshots, advanced);
TAG_FLAG(enable_transaction_snapshots, runtime);
DEFINE_test_flag(bool, disable_cdc_state_insert_on_setup, false,
"Disable inserting new entries into cdc state as part of the setup flow.");
DEFINE_bool(allow_consecutive_restore, true,
"Is it allowed to restore to a time before the last restoration was done.");
TAG_FLAG(allow_consecutive_restore, runtime);
namespace yb {
using rpc::RpcContext;
using pb_util::ParseFromSlice;
namespace master {
namespace enterprise {
namespace {
CHECKED_STATUS CheckStatus(const Status& status, const char* action) {
if (status.ok()) {
return status;
}
const Status s = status.CloneAndPrepend(std::string("An error occurred while ") + action);
LOG(WARNING) << s;
return s;
}
CHECKED_STATUS CheckLeaderStatus(const Status& status, const char* action) {
return CheckIfNoLongerLeader(CheckStatus(status, action));
}
template<class RespClass>
CHECKED_STATUS CheckLeaderStatusAndSetupError(
const Status& status, const char* action, RespClass* resp) {
return CheckIfNoLongerLeaderAndSetupError(CheckStatus(status, action), resp);
}
} // namespace
////////////////////////////////////////////////////////////
// Snapshot Loader
////////////////////////////////////////////////////////////
class SnapshotLoader : public Visitor<PersistentSnapshotInfo> {
public:
explicit SnapshotLoader(CatalogManager* catalog_manager) : catalog_manager_(catalog_manager) {}
CHECKED_STATUS Visit(const SnapshotId& snapshot_id, const SysSnapshotEntryPB& metadata) override {
if (TryFullyDecodeTxnSnapshotId(snapshot_id)) {
// Transaction aware snapshots should be already loaded.
return Status::OK();
}
return VisitNonTransactionAwareSnapshot(snapshot_id, metadata);
}
CHECKED_STATUS VisitNonTransactionAwareSnapshot(
const SnapshotId& snapshot_id, const SysSnapshotEntryPB& metadata) {
// Setup the snapshot info.
auto snapshot_info = make_scoped_refptr<SnapshotInfo>(snapshot_id);
auto l = snapshot_info->LockForWrite();
l.mutable_data()->pb.CopyFrom(metadata);
// Add the snapshot to the IDs map (if the snapshot is not deleted).
auto emplace_result = catalog_manager_->non_txn_snapshot_ids_map_.emplace(
snapshot_id, std::move(snapshot_info));
CHECK(emplace_result.second) << "Snapshot already exists: " << snapshot_id;
LOG(INFO) << "Loaded metadata for snapshot (id=" << snapshot_id << "): "
<< emplace_result.first->second->ToString() << ": " << metadata.ShortDebugString();
l.Commit();
return Status::OK();
}
private:
CatalogManager *catalog_manager_;
DISALLOW_COPY_AND_ASSIGN(SnapshotLoader);
};
////////////////////////////////////////////////////////////
// CDC Stream Loader
////////////////////////////////////////////////////////////
class CDCStreamLoader : public Visitor<PersistentCDCStreamInfo> {
public:
explicit CDCStreamLoader(CatalogManager* catalog_manager) : catalog_manager_(catalog_manager) {}
Status Visit(const CDCStreamId& stream_id, const SysCDCStreamEntryPB& metadata)
REQUIRES(catalog_manager_->mutex_) {
DCHECK(!ContainsKey(catalog_manager_->cdc_stream_map_, stream_id))
<< "CDC stream already exists: " << stream_id;
scoped_refptr<NamespaceInfo> ns;
scoped_refptr<TableInfo> table;
if (metadata.has_namespace_id()) {
ns = FindPtrOrNull(catalog_manager_->namespace_ids_map_, metadata.namespace_id());
if (!ns) {
LOG(DFATAL) << "Invalid namespace ID " << metadata.namespace_id() << " for stream "
<< stream_id;
// TODO (#2059): Potentially signals a race condition that namesapce got deleted
// while stream was being created.
// Log error and continue without loading the stream.
return Status::OK();
}
} else {
table = FindPtrOrNull(*catalog_manager_->table_ids_map_, metadata.table_id(0));
if (!table) {
LOG(ERROR) << "Invalid table ID " << metadata.table_id(0) << " for stream " << stream_id;
// TODO (#2059): Potentially signals a race condition that table got deleted while stream
// was being created.
// Log error and continue without loading the stream.
return Status::OK();
}
}
// Setup the CDC stream info.
auto stream = make_scoped_refptr<CDCStreamInfo>(stream_id);
auto l = stream->LockForWrite();
l.mutable_data()->pb.CopyFrom(metadata);
// If the table has been deleted, then mark this stream as DELETING so it can be deleted by the
// catalog manager background thread. Otherwise if this stream is missing an entry
// for state, then mark its state as Active.
if (((table && table->LockForRead()->is_deleting()) ||
(ns && ns->state() == SysNamespaceEntryPB::DELETING)) &&
!l.data().is_deleting()) {
l.mutable_data()->pb.set_state(SysCDCStreamEntryPB::DELETING);
} else if (!l.mutable_data()->pb.has_state()) {
l.mutable_data()->pb.set_state(SysCDCStreamEntryPB::ACTIVE);
}
// Add the CDC stream to the CDC stream map.
catalog_manager_->cdc_stream_map_[stream->id()] = stream;
if (table) {
catalog_manager_->cdc_stream_tables_count_map_[metadata.table_id(0)]++;
}
l.Commit();
LOG(INFO) << "Loaded metadata for CDC stream " << stream->ToString() << ": "
<< metadata.ShortDebugString();
return Status::OK();
}
private:
CatalogManager *catalog_manager_;
DISALLOW_COPY_AND_ASSIGN(CDCStreamLoader);
};
////////////////////////////////////////////////////////////
// Universe Replication Loader
////////////////////////////////////////////////////////////
class UniverseReplicationLoader : public Visitor<PersistentUniverseReplicationInfo> {
public:
explicit UniverseReplicationLoader(CatalogManager* catalog_manager)
: catalog_manager_(catalog_manager) {}
Status Visit(const std::string& producer_id, const SysUniverseReplicationEntryPB& metadata)
REQUIRES(catalog_manager_->mutex_) {
DCHECK(!ContainsKey(catalog_manager_->universe_replication_map_, producer_id))
<< "Producer universe already exists: " << producer_id;
// Setup the universe replication info.
UniverseReplicationInfo* const ri = new UniverseReplicationInfo(producer_id);
{
auto l = ri->LockForWrite();
l.mutable_data()->pb.CopyFrom(metadata);
if (!l->is_active() && !l->is_deleted_or_failed()) {
// Replication was not fully setup.
LOG(WARNING) << "Universe replication in transient state: " << producer_id;
// TODO: Should we delete all failed universe replication items?
}
// Add universe replication info to the universe replication map.
catalog_manager_->universe_replication_map_[ri->id()] = ri;
l.Commit();
}
// Also keep track of consumer tables.
for (const auto& table : metadata.validated_tables()) {
CDCStreamId stream_id = FindWithDefault(metadata.table_streams(), table.first, "");
if (stream_id.empty()) {
LOG(WARNING) << "Unable to find stream id for table: " << table.first;
continue;
}
catalog_manager_->xcluster_consumer_tables_to_stream_map_[table.second].emplace(
metadata.producer_id(), stream_id);
}
LOG(INFO) << "Loaded metadata for universe replication " << ri->ToString();
VLOG(1) << "Metadata for universe replication " << ri->ToString() << ": "
<< metadata.ShortDebugString();
return Status::OK();
}
private:
CatalogManager *catalog_manager_;
DISALLOW_COPY_AND_ASSIGN(UniverseReplicationLoader);
};
////////////////////////////////////////////////////////////
// CatalogManager
////////////////////////////////////////////////////////////
CatalogManager::~CatalogManager() {
if (StartShutdown()) {
CompleteShutdown();
}
}
void CatalogManager::CompleteShutdown() {
snapshot_coordinator_.Shutdown();
// Call shutdown on base class before exiting derived class destructor
// because BgTasks is part of base & uses this derived class on Shutdown.
super::CompleteShutdown();
}
Status CatalogManager::RunLoaders(int64_t term) {
RETURN_NOT_OK(super::RunLoaders(term));
// Clear the snapshots.
non_txn_snapshot_ids_map_.clear();
// Clear CDC stream map.
cdc_stream_map_.clear();
cdc_stream_tables_count_map_.clear();
// Clear universe replication map.
universe_replication_map_.clear();
xcluster_consumer_tables_to_stream_map_.clear();
LOG_WITH_FUNC(INFO) << "Loading snapshots into memory.";
unique_ptr<SnapshotLoader> snapshot_loader(new SnapshotLoader(this));
RETURN_NOT_OK_PREPEND(
sys_catalog_->Visit(snapshot_loader.get()),
"Failed while visiting snapshots in sys catalog");
LOG_WITH_FUNC(INFO) << "Loading CDC streams into memory.";
auto cdc_stream_loader = std::make_unique<CDCStreamLoader>(this);
RETURN_NOT_OK_PREPEND(
sys_catalog_->Visit(cdc_stream_loader.get()),
"Failed while visiting CDC streams in sys catalog");
LOG_WITH_FUNC(INFO) << "Loading universe replication info into memory.";
auto universe_replication_loader = std::make_unique<UniverseReplicationLoader>(this);
RETURN_NOT_OK_PREPEND(
sys_catalog_->Visit(universe_replication_loader.get()),
"Failed while visiting universe replication info in sys catalog");
return Status::OK();
}
Status CatalogManager::CreateSnapshot(const CreateSnapshotRequestPB* req,
CreateSnapshotResponsePB* resp,
RpcContext* rpc) {
LOG(INFO) << "Servicing CreateSnapshot request: " << req->ShortDebugString();
if (FLAGS_enable_transaction_snapshots && req->transaction_aware()) {
return CreateTransactionAwareSnapshot(*req, resp, rpc);
}
if (req->has_schedule_id()) {
auto schedule_id = VERIFY_RESULT(FullyDecodeSnapshotScheduleId(req->schedule_id()));
auto snapshot_id = snapshot_coordinator_.CreateForSchedule(
schedule_id, leader_ready_term(), rpc->GetClientDeadline());
if (!snapshot_id.ok()) {
LOG(INFO) << "Create snapshot failed: " << snapshot_id.status();
return snapshot_id.status();
}
resp->set_snapshot_id(snapshot_id->data(), snapshot_id->size());
return Status::OK();
}
return CreateNonTransactionAwareSnapshot(req, resp, rpc);
}
Status CatalogManager::CreateNonTransactionAwareSnapshot(
const CreateSnapshotRequestPB* req,
CreateSnapshotResponsePB* resp,
RpcContext* rpc) {
SnapshotId snapshot_id;
{
LockGuard lock(mutex_);
TRACE("Acquired catalog manager lock");
// Verify that the system is not in snapshot creating/restoring state.
if (!current_snapshot_id_.empty()) {
return STATUS(IllegalState,
Format(
"Current snapshot id: $0. Parallel snapshot operations are not supported"
": $1", current_snapshot_id_, req),
MasterError(MasterErrorPB::PARALLEL_SNAPSHOT_OPERATION));
}
// Create a new snapshot UUID.
snapshot_id = GenerateIdUnlocked(SysRowEntryType::SNAPSHOT);
}
vector<scoped_refptr<TabletInfo>> all_tablets;
// Create in memory snapshot data descriptor.
scoped_refptr<SnapshotInfo> snapshot(new SnapshotInfo(snapshot_id));
snapshot->mutable_metadata()->StartMutation();
snapshot->mutable_metadata()->mutable_dirty()->pb.set_state(SysSnapshotEntryPB::CREATING);
auto tables = VERIFY_RESULT(CollectTables(req->tables(),
req->add_indexes(),
true /* include_parent_colocated_table */));
std::unordered_set<NamespaceId> added_namespaces;
for (const auto& table : tables) {
snapshot->AddEntries(table, &added_namespaces);
all_tablets.insert(all_tablets.end(), table.tablet_infos.begin(), table.tablet_infos.end());
}
VLOG(1) << "Snapshot " << snapshot->ToString()
<< ": PB=" << snapshot->mutable_metadata()->mutable_dirty()->pb.DebugString();
// Write the snapshot data descriptor to the system catalog (in "creating" state).
RETURN_NOT_OK(CheckLeaderStatus(
sys_catalog_->Upsert(leader_ready_term(), snapshot),
"inserting snapshot into sys-catalog"));
TRACE("Wrote snapshot to system catalog");
// Commit in memory snapshot data descriptor.
snapshot->mutable_metadata()->CommitMutation();
// Put the snapshot data descriptor to the catalog manager.
{
LockGuard lock(mutex_);
TRACE("Acquired catalog manager lock");
// Verify that the snapshot does not exist.
auto inserted = non_txn_snapshot_ids_map_.emplace(snapshot_id, snapshot).second;
RSTATUS_DCHECK(inserted, IllegalState, Format("Snapshot already exists: $0", snapshot_id));
current_snapshot_id_ = snapshot_id;
}
// Send CreateSnapshot requests to all TServers (one tablet - one request).
for (const scoped_refptr<TabletInfo>& tablet : all_tablets) {
TRACE("Locking tablet");
auto l = tablet->LockForRead();
LOG(INFO) << "Sending CreateTabletSnapshot to tablet: " << tablet->ToString();
// Send Create Tablet Snapshot request to each tablet leader.
auto call = CreateAsyncTabletSnapshotOp(
tablet, snapshot_id, tserver::TabletSnapshotOpRequestPB::CREATE_ON_TABLET,
TabletSnapshotOperationCallback());
ScheduleTabletSnapshotOp(call);
}
resp->set_snapshot_id(snapshot_id);
LOG(INFO) << "Successfully started snapshot " << snapshot_id << " creation";
return Status::OK();
}
void CatalogManager::Submit(std::unique_ptr<tablet::Operation> operation, int64_t leader_term) {
operation->SetTablet(tablet_peer()->tablet());
tablet_peer()->Submit(std::move(operation), leader_term);
}
Result<SysRowEntries> CatalogManager::CollectEntries(
const google::protobuf::RepeatedPtrField<TableIdentifierPB>& table_identifiers,
CollectFlags flags) {
RETURN_NOT_OK(CheckIsLeaderAndReady());
SysRowEntries entries;
std::unordered_set<NamespaceId> namespaces;
auto tables = VERIFY_RESULT(CollectTables(table_identifiers, flags, &namespaces));
if (!namespaces.empty()) {
SharedLock lock(mutex_);
for (const auto& ns_id : namespaces) {
auto ns_info = VERIFY_RESULT(FindNamespaceByIdUnlocked(ns_id));
AddInfoEntry(ns_info.get(), entries.mutable_entries());
}
}
for (const auto& table : tables) {
// TODO(txn_snapshot) use single lock to resolve all tables to tablets
SnapshotInfo::AddEntries(table, entries.mutable_entries(), /* tablet_infos= */ nullptr,
&namespaces);
}
return entries;
}
Result<SysRowEntries> CatalogManager::CollectEntriesForSnapshot(
const google::protobuf::RepeatedPtrField<TableIdentifierPB>& tables) {
return CollectEntries(
tables,
CollectFlags{CollectFlag::kAddIndexes, CollectFlag::kIncludeParentColocatedTable,
CollectFlag::kSucceedIfCreateInProgress});
}
server::Clock* CatalogManager::Clock() {
return master_->clock();
}
Status CatalogManager::CreateTransactionAwareSnapshot(
const CreateSnapshotRequestPB& req, CreateSnapshotResponsePB* resp, rpc::RpcContext* rpc) {
CollectFlags flags{CollectFlag::kIncludeParentColocatedTable};
flags.SetIf(CollectFlag::kAddIndexes, req.add_indexes());
SysRowEntries entries = VERIFY_RESULT(CollectEntries(req.tables(), flags));
auto snapshot_id = VERIFY_RESULT(snapshot_coordinator_.Create(
entries, req.imported(), leader_ready_term(), rpc->GetClientDeadline()));
resp->set_snapshot_id(snapshot_id.data(), snapshot_id.size());
return Status::OK();
}
Status CatalogManager::ListSnapshots(const ListSnapshotsRequestPB* req,
ListSnapshotsResponsePB* resp) {
auto txn_snapshot_id = TryFullyDecodeTxnSnapshotId(req->snapshot_id());
{
SharedLock lock(mutex_);
TRACE("Acquired catalog manager lock");
if (!current_snapshot_id_.empty()) {
resp->set_current_snapshot_id(current_snapshot_id_);
}
auto setup_snapshot_pb_lambda = [resp](scoped_refptr<SnapshotInfo> snapshot_info) {
auto snapshot_lock = snapshot_info->LockForRead();
SnapshotInfoPB* const snapshot = resp->add_snapshots();
snapshot->set_id(snapshot_info->id());
*snapshot->mutable_entry() = snapshot_info->metadata().state().pb;
};
if (req->has_snapshot_id()) {
if (!txn_snapshot_id) {
TRACE("Looking up snapshot");
scoped_refptr<SnapshotInfo> snapshot_info =
FindPtrOrNull(non_txn_snapshot_ids_map_, req->snapshot_id());
if (snapshot_info == nullptr) {
return STATUS(InvalidArgument, "Could not find snapshot", req->snapshot_id(),
MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND));
}
setup_snapshot_pb_lambda(snapshot_info);
}
} else {
for (const SnapshotInfoMap::value_type& entry : non_txn_snapshot_ids_map_) {
setup_snapshot_pb_lambda(entry.second);
}
}
}
if (req->prepare_for_backup() && (!req->has_snapshot_id() || !txn_snapshot_id)) {
return STATUS(
InvalidArgument, "Request must have correct snapshot_id", (req->has_snapshot_id() ?
req->snapshot_id() : "None"), MasterError(MasterErrorPB::SNAPSHOT_FAILED));
}
RETURN_NOT_OK(snapshot_coordinator_.ListSnapshots(
txn_snapshot_id, req->list_deleted_snapshots(), resp));
if (req->prepare_for_backup()) {
SharedLock lock(mutex_);
TRACE("Acquired catalog manager lock");
// Repack & extend the backup row entries.
for (SnapshotInfoPB& snapshot : *resp->mutable_snapshots()) {
snapshot.set_format_version(2);
SysSnapshotEntryPB& sys_entry = *snapshot.mutable_entry();
snapshot.mutable_backup_entries()->Reserve(sys_entry.entries_size());
for (SysRowEntry& entry : *sys_entry.mutable_entries()) {
BackupRowEntryPB* const backup_entry = snapshot.add_backup_entries();
// Setup BackupRowEntryPB fields.
// Set BackupRowEntryPB::pg_schema_name for YSQL table to disambiguate in case tables
// in different schema have same name.
if (entry.type() == SysRowEntryType::TABLE) {
TRACE("Looking up table");
scoped_refptr<TableInfo> table_info = FindPtrOrNull(*table_ids_map_, entry.id());
if (table_info == nullptr) {
return STATUS(
InvalidArgument, "Table not found by ID", entry.id(),
MasterError(MasterErrorPB::OBJECT_NOT_FOUND));
}
TRACE("Locking table");
auto l = table_info->LockForRead();
// PG schema name is available for YSQL table only.
// Except '<uuid>.colocated.parent.uuid' table ID.
if (l->table_type() == PGSQL_TABLE_TYPE && !IsColocatedParentTableId(entry.id())) {
const string pg_schema_name = VERIFY_RESULT(GetPgSchemaName(table_info));
VLOG(1) << "PG Schema: " << pg_schema_name << " for table " << table_info->ToString();
backup_entry->set_pg_schema_name(pg_schema_name);
}
}
// Init BackupRowEntryPB::entry.
backup_entry->mutable_entry()->Swap(&entry);
}
sys_entry.clear_entries();
}
}
return Status::OK();
}
Status CatalogManager::ListSnapshotRestorations(const ListSnapshotRestorationsRequestPB* req,
ListSnapshotRestorationsResponsePB* resp) {
TxnSnapshotRestorationId restoration_id = TxnSnapshotRestorationId::Nil();
if (!req->restoration_id().empty()) {
restoration_id = VERIFY_RESULT(FullyDecodeTxnSnapshotRestorationId(req->restoration_id()));
}
TxnSnapshotId snapshot_id = TxnSnapshotId::Nil();
if (!req->snapshot_id().empty()) {
snapshot_id = VERIFY_RESULT(FullyDecodeTxnSnapshotId(req->snapshot_id()));
}
return snapshot_coordinator_.ListRestorations(restoration_id, snapshot_id, resp);
}
Status CatalogManager::RestoreSnapshot(const RestoreSnapshotRequestPB* req,
RestoreSnapshotResponsePB* resp) {
LOG(INFO) << "Servicing RestoreSnapshot request: " << req->ShortDebugString();
auto txn_snapshot_id = TryFullyDecodeTxnSnapshotId(req->snapshot_id());
if (txn_snapshot_id) {
HybridTime ht;
if (req->has_restore_ht()) {
ht = HybridTime(req->restore_ht());
}
TxnSnapshotRestorationId id = VERIFY_RESULT(snapshot_coordinator_.Restore(
txn_snapshot_id, ht, leader_ready_term()));
resp->set_restoration_id(id.data(), id.size());
return Status::OK();
}
return RestoreNonTransactionAwareSnapshot(req->snapshot_id());
}
Status CatalogManager::RestoreNonTransactionAwareSnapshot(const string& snapshot_id) {
LockGuard lock(mutex_);
TRACE("Acquired catalog manager lock");
if (!current_snapshot_id_.empty()) {
return STATUS(
IllegalState,
Format(
"Current snapshot id: $0. Parallel snapshot operations are not supported: $1",
current_snapshot_id_, snapshot_id),
MasterError(MasterErrorPB::PARALLEL_SNAPSHOT_OPERATION));
}
TRACE("Looking up snapshot");
scoped_refptr<SnapshotInfo> snapshot = FindPtrOrNull(non_txn_snapshot_ids_map_, snapshot_id);
if (snapshot == nullptr) {
return STATUS(InvalidArgument, "Could not find snapshot", snapshot_id,
MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND));
}
auto snapshot_lock = snapshot->LockForWrite();
if (snapshot_lock->started_deleting()) {
return STATUS(NotFound, "The snapshot was deleted", snapshot_id,
MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND));
}
if (!snapshot_lock->is_complete()) {
return STATUS(IllegalState, "The snapshot state is not complete", snapshot_id,
MasterError(MasterErrorPB::SNAPSHOT_IS_NOT_READY));
}
TRACE("Updating snapshot metadata on disk");
SysSnapshotEntryPB& snapshot_pb = snapshot_lock.mutable_data()->pb;
snapshot_pb.set_state(SysSnapshotEntryPB::RESTORING);
// Update tablet states.
SetTabletSnapshotsState(SysSnapshotEntryPB::RESTORING, &snapshot_pb);
// Update sys-catalog with the updated snapshot state.
// The mutation will be aborted when 'l' exits the scope on early return.
RETURN_NOT_OK(CheckLeaderStatus(
sys_catalog_->Upsert(leader_ready_term(), snapshot),
"updating snapshot in sys-catalog"));
// CataloManager lock 'lock_' is still locked here.
current_snapshot_id_ = snapshot_id;
// Restore all entries.
for (const SysRowEntry& entry : snapshot_pb.entries()) {
RETURN_NOT_OK(RestoreEntry(entry, snapshot_id));
}
// Commit in memory snapshot data descriptor.
TRACE("Committing in-memory snapshot state");
snapshot_lock.Commit();
LOG(INFO) << "Successfully started snapshot " << snapshot->ToString() << " restoring";
return Status::OK();
}
Status CatalogManager::RestoreEntry(const SysRowEntry& entry, const SnapshotId& snapshot_id) {
switch (entry.type()) {
case SysRowEntryType::NAMESPACE: { // Restore NAMESPACES.
TRACE("Looking up namespace");
scoped_refptr<NamespaceInfo> ns = FindPtrOrNull(namespace_ids_map_, entry.id());
if (ns == nullptr) {
// Restore Namespace.
// TODO: implement
LOG(INFO) << "Restoring: NAMESPACE id = " << entry.id();
return STATUS(NotSupported, Substitute(
"Not implemented: restoring namespace: id=$0", entry.type()));
}
break;
}
case SysRowEntryType::TABLE: { // Restore TABLES.
TRACE("Looking up table");
scoped_refptr<TableInfo> table = FindPtrOrNull(*table_ids_map_, entry.id());
if (table == nullptr) {
// Restore Table.
// TODO: implement
LOG(INFO) << "Restoring: TABLE id = " << entry.id();
return STATUS(NotSupported, Substitute(
"Not implemented: restoring table: id=$0", entry.type()));
}
break;
}
case SysRowEntryType::TABLET: { // Restore TABLETS.
TRACE("Looking up tablet");
scoped_refptr<TabletInfo> tablet = FindPtrOrNull(*tablet_map_, entry.id());
if (tablet == nullptr) {
// Restore Tablet.
// TODO: implement
LOG(INFO) << "Restoring: TABLET id = " << entry.id();
return STATUS(NotSupported, Substitute(
"Not implemented: restoring tablet: id=$0", entry.type()));
} else {
TRACE("Locking tablet");
auto l = tablet->LockForRead();
LOG(INFO) << "Sending RestoreTabletSnapshot to tablet: " << tablet->ToString();
// Send RestoreSnapshot requests to all TServers (one tablet - one request).
auto task = CreateAsyncTabletSnapshotOp(
tablet, snapshot_id, tserver::TabletSnapshotOpRequestPB::RESTORE_ON_TABLET,
TabletSnapshotOperationCallback());
ScheduleTabletSnapshotOp(task);
}
break;
}
default:
return STATUS_FORMAT(
InternalError, "Unexpected entry type in the snapshot: $0", entry.type());
}
return Status::OK();
}
Status CatalogManager::DeleteSnapshot(const DeleteSnapshotRequestPB* req,
DeleteSnapshotResponsePB* resp,
RpcContext* rpc) {
LOG(INFO) << "Servicing DeleteSnapshot request: " << req->ShortDebugString();
auto txn_snapshot_id = TryFullyDecodeTxnSnapshotId(req->snapshot_id());
if (txn_snapshot_id) {
return snapshot_coordinator_.Delete(
txn_snapshot_id, leader_ready_term(), rpc->GetClientDeadline());
}
return DeleteNonTransactionAwareSnapshot(req->snapshot_id());
}
Status CatalogManager::DeleteNonTransactionAwareSnapshot(const SnapshotId& snapshot_id) {
LockGuard lock(mutex_);
TRACE("Acquired catalog manager lock");
TRACE("Looking up snapshot");
scoped_refptr<SnapshotInfo> snapshot = FindPtrOrNull(
non_txn_snapshot_ids_map_, snapshot_id);
if (snapshot == nullptr) {
return STATUS(InvalidArgument, "Could not find snapshot", snapshot_id,
MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND));
}
auto snapshot_lock = snapshot->LockForWrite();
if (snapshot_lock->started_deleting()) {
return STATUS(NotFound, "The snapshot was deleted", snapshot_id,
MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND));
}
if (snapshot_lock->is_restoring()) {
return STATUS(InvalidArgument, "The snapshot is being restored now", snapshot_id,
MasterError(MasterErrorPB::PARALLEL_SNAPSHOT_OPERATION));
}
TRACE("Updating snapshot metadata on disk");
SysSnapshotEntryPB& snapshot_pb = snapshot_lock.mutable_data()->pb;
snapshot_pb.set_state(SysSnapshotEntryPB::DELETING);
// Update tablet states.
SetTabletSnapshotsState(SysSnapshotEntryPB::DELETING, &snapshot_pb);
// Update sys-catalog with the updated snapshot state.
// The mutation will be aborted when 'l' exits the scope on early return.
RETURN_NOT_OK(CheckStatus(
sys_catalog_->Upsert(leader_ready_term(), snapshot),
"updating snapshot in sys-catalog"));
// Send DeleteSnapshot requests to all TServers (one tablet - one request).
for (const SysRowEntry& entry : snapshot_pb.entries()) {
if (entry.type() == SysRowEntryType::TABLET) {
TRACE("Looking up tablet");
scoped_refptr<TabletInfo> tablet = FindPtrOrNull(*tablet_map_, entry.id());
if (tablet == nullptr) {
LOG(WARNING) << "Deleting tablet not found " << entry.id();
} else {
TRACE("Locking tablet");
auto l = tablet->LockForRead();
LOG(INFO) << "Sending DeleteTabletSnapshot to tablet: " << tablet->ToString();
// Send DeleteSnapshot requests to all TServers (one tablet - one request).
auto task = CreateAsyncTabletSnapshotOp(
tablet, snapshot_id, tserver::TabletSnapshotOpRequestPB::DELETE_ON_TABLET,
TabletSnapshotOperationCallback());
ScheduleTabletSnapshotOp(task);
}
}
}
// Commit in memory snapshot data descriptor.
TRACE("Committing in-memory snapshot state");
snapshot_lock.Commit();
LOG(INFO) << "Successfully started snapshot " << snapshot->ToString() << " deletion";
return Status::OK();
}
Status CatalogManager::ImportSnapshotPreprocess(const SnapshotInfoPB& snapshot_pb,
ImportSnapshotMetaResponsePB* resp,
NamespaceMap* namespace_map,
ExternalTableSnapshotDataMap* tables_data) {
for (const BackupRowEntryPB& backup_entry : snapshot_pb.backup_entries()) {
const SysRowEntry& entry = backup_entry.entry();
switch (entry.type()) {
case SysRowEntryType::NAMESPACE: // Recreate NAMESPACE.
RETURN_NOT_OK(ImportNamespaceEntry(entry, namespace_map));
break;
case SysRowEntryType::TABLE: { // Create TABLE metadata.
LOG_IF(DFATAL, entry.id().empty()) << "Empty entry id";
ExternalTableSnapshotData& data = (*tables_data)[entry.id()];
if (data.old_table_id.empty()) {
data.old_table_id = entry.id();
data.table_meta = resp->mutable_tables_meta()->Add();
data.tablet_id_map = data.table_meta->mutable_tablets_ids();
data.table_entry_pb = VERIFY_RESULT(ParseFromSlice<SysTablesEntryPB>(entry.data()));
if (backup_entry.has_pg_schema_name()) {
data.pg_schema_name = backup_entry.pg_schema_name();
}
} else {
LOG_WITH_FUNC(WARNING) << "Ignoring duplicate table with id " << entry.id();
}
LOG_IF(DFATAL, data.old_table_id.empty()) << "Not initialized table id";
}
break;
case SysRowEntryType::TABLET: // Preprocess original tablets.
RETURN_NOT_OK(PreprocessTabletEntry(entry, tables_data));
break;
case SysRowEntryType::CLUSTER_CONFIG: FALLTHROUGH_INTENDED;
case SysRowEntryType::REDIS_CONFIG: FALLTHROUGH_INTENDED;
case SysRowEntryType::UDTYPE: FALLTHROUGH_INTENDED;
case SysRowEntryType::ROLE: FALLTHROUGH_INTENDED;
case SysRowEntryType::SYS_CONFIG: FALLTHROUGH_INTENDED;
case SysRowEntryType::CDC_STREAM: FALLTHROUGH_INTENDED;
case SysRowEntryType::UNIVERSE_REPLICATION: FALLTHROUGH_INTENDED;
case SysRowEntryType::SNAPSHOT: FALLTHROUGH_INTENDED;
case SysRowEntryType::SNAPSHOT_SCHEDULE: FALLTHROUGH_INTENDED;
case SysRowEntryType::DDL_LOG_ENTRY: FALLTHROUGH_INTENDED;
case SysRowEntryType::UNKNOWN:
FATAL_INVALID_ENUM_VALUE(SysRowEntryType, entry.type());
}
}
return Status::OK();
}
Status CatalogManager::ImportSnapshotCreateObject(const SnapshotInfoPB& snapshot_pb,
ImportSnapshotMetaResponsePB* resp,
NamespaceMap* namespace_map,
ExternalTableSnapshotDataMap* tables_data,
CreateObjects create_objects) {
// Create ONLY TABLES or ONLY INDEXES in accordance to the argument.
for (const BackupRowEntryPB& backup_entry : snapshot_pb.backup_entries()) {
const SysRowEntry& entry = backup_entry.entry();
if (entry.type() == SysRowEntryType::TABLE) {
ExternalTableSnapshotData& data = (*tables_data)[entry.id()];
if ((create_objects == CreateObjects::kOnlyIndexes) == data.is_index()) {
RETURN_NOT_OK(ImportTableEntry(*namespace_map, *tables_data, &data));
}
}
}
return Status::OK();
}
Status CatalogManager::ImportSnapshotWaitForTables(const SnapshotInfoPB& snapshot_pb,
ImportSnapshotMetaResponsePB* resp,
ExternalTableSnapshotDataMap* tables_data) {
for (const BackupRowEntryPB& backup_entry : snapshot_pb.backup_entries()) {
const SysRowEntry& entry = backup_entry.entry();
if (entry.type() == SysRowEntryType::TABLE) {
ExternalTableSnapshotData& data = (*tables_data)[entry.id()];
if (!data.is_index()) {
RETURN_NOT_OK(WaitForCreateTableToFinish(data.new_table_id));
}
}
}
return Status::OK();
}
Status CatalogManager::ImportSnapshotProcessTablets(const SnapshotInfoPB& snapshot_pb,
ImportSnapshotMetaResponsePB* resp,
ExternalTableSnapshotDataMap* tables_data) {
for (const BackupRowEntryPB& backup_entry : snapshot_pb.backup_entries()) {
const SysRowEntry& entry = backup_entry.entry();
if (entry.type() == SysRowEntryType::TABLET) {
// Create tablets IDs map.
RETURN_NOT_OK(ImportTabletEntry(entry, tables_data));
}
}
return Status::OK();
}
template <class RespClass>
void ProcessDeleteObjectStatus(const string& obj_name,
const string& id,
const RespClass& resp,
const Status& s) {
Status result = s;
if (result.ok() && resp.has_error()) {
result = StatusFromPB(resp.error().status());
LOG_IF(DFATAL, result.ok()) << "Expecting error status";
}
if (!result.ok()) {
LOG_WITH_FUNC(WARNING) << "Failed to delete new " << obj_name << " with id=" << id
<< ": " << result;
}
}
void CatalogManager::DeleteNewSnapshotObjects(const NamespaceMap& namespace_map,
const ExternalTableSnapshotDataMap& tables_data) {
for (const ExternalTableSnapshotDataMap::value_type& entry : tables_data) {
const TableId& old_id = entry.first;
const TableId& new_id = entry.second.new_table_id;
const TableType type = entry.second.table_entry_pb.table_type();
// Do not delete YSQL objects - it must be deleted via PG API.
if (new_id.empty() || new_id == old_id || type == TableType::PGSQL_TABLE_TYPE) {
continue;
}
LOG_WITH_FUNC(INFO) << "Deleting new table with id=" << new_id << " old id=" << old_id;