-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathadmin.go
More file actions
3821 lines (3379 loc) · 133 KB
/
Copy pathadmin.go
File metadata and controls
3821 lines (3379 loc) · 133 KB
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 2015 Google LLC
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.
*/
package bigtable
import (
"container/list"
"context"
"errors"
"fmt"
"math"
"regexp"
"strings"
"time"
admin "cloud.google.com/go/bigtable/admin/apiv2"
btapb "cloud.google.com/go/bigtable/admin/apiv2/adminpb"
btopt "cloud.google.com/go/bigtable/internal/option"
"cloud.google.com/go/iam"
"cloud.google.com/go/internal/optional"
"cloud.google.com/go/longrunning"
lroauto "cloud.google.com/go/longrunning/autogen"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/cloudresourcemanager/v1"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
gtransport "google.golang.org/api/transport/grpc"
"google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
grpcstatus "google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
field_mask "google.golang.org/protobuf/types/known/fieldmaskpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
// UNIVERSE_DOMAIN placeholder is replaced by the UniverseDomain from DialSettings while creating GRPC connection/dial pool.
const adminAddr = "bigtableadmin.UNIVERSE_DOMAIN:443"
const mtlsAdminAddr = "bigtableadmin.mtls.googleapis.com:443"
var (
errExpiryMissing = errors.New("WithExpiry is a required option")
adminRetryOptions = []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return &bigtableAdminRetryer{
Backoff: defaultBackoff,
}
}),
}
)
// bigtableAdminRetryer extends the generic gax Retryer, but also checks
// error messages to check if operation can be retried
//
// Retry is made if :
// - error code is one of the `idempotentRetryCodes` OR
// - error code is internal and error message is one of the `retryableInternalErrMsgs`
type bigtableAdminRetryer struct {
gax.Backoff
}
func (r *bigtableAdminRetryer) Retry(err error) (time.Duration, bool) {
// Similar to gax.OnCodes but shares the backoff with INTERNAL retry messages check
st, ok := grpcstatus.FromError(err)
if !ok {
return 0, false
}
c := st.Code()
_, isIdempotent := isIdempotentRetryCode[c]
if isIdempotent ||
(grpcstatus.Code(err) == codes.Internal && containsAny(err.Error(), retryableInternalErrMsgs)) {
pause := r.Backoff.Pause()
return pause, true
}
return 0, false
}
// ErrPartiallyUnavailable is returned when some locations (clusters) are
// unavailable. Both partial results (retrieved from available locations)
// and the error are returned when this exception occurred.
type ErrPartiallyUnavailable struct {
Locations []string // unavailable locations
}
func (e ErrPartiallyUnavailable) Error() string {
return fmt.Sprintf("Unavailable locations: %v", e.Locations)
}
// AdminClient is a client type for performing admin operations within a specific instance.
type AdminClient struct {
connPool gtransport.ConnPool
tClient btapb.BigtableTableAdminClient
lroClient *lroauto.OperationsClient
tableAdminClient *admin.BigtableTableAdminClient
project, instance string
// Metadata to be sent with each request.
md metadata.MD
}
// NewAdminClient creates a new AdminClient for a given project and instance.
func NewAdminClient(ctx context.Context, project, instance string, opts ...option.ClientOption) (*AdminClient, error) {
o, err := btopt.DefaultClientOptions(adminAddr, mtlsAdminAddr, AdminScope, clientUserAgent)
if err != nil {
return nil, err
}
// Add gRPC client interceptors to supply Google client information. No external interceptors are passed.
o = append(o, btopt.ClientInterceptorOptions(nil, nil)...)
// Need to add scopes for long running operations (for create table & snapshots)
o = append(o, option.WithScopes(cloudresourcemanager.CloudPlatformScope))
o = append(o, internaloption.EnableNewAuthLibrary())
o = append(o, internaloption.EnableJwtWithScope())
o = append(o, opts...)
connPool, err := gtransport.DialPool(ctx, o...)
if err != nil {
return nil, fmt.Errorf("dialing: %w", err)
}
lroClient, err := lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
if err != nil {
// This error "should not happen", since we are just reusing old connection
// and never actually need to dial.
// If this does happen, we could leak conn. However, we cannot close conn:
// If the user invoked the function with option.WithGRPCConn,
// we would close a connection that's still in use.
// TODO(pongad): investigate error conditions.
return nil, err
}
tableAdminClient, err := admin.NewBigtableTableAdminClient(ctx, gtransport.WithConnPool(connPool))
if err != nil {
return nil, err
}
return &AdminClient{
connPool: connPool,
tClient: btapb.NewBigtableTableAdminClient(connPool),
lroClient: lroClient,
tableAdminClient: tableAdminClient,
project: project,
instance: instance,
md: metadata.Pairs(resourcePrefixHeader, fmt.Sprintf("projects/%s/instances/%s", project, instance)),
}, nil
}
// Close closes the AdminClient.
func (ac *AdminClient) Close() error {
return ac.connPool.Close()
}
// TableAdminClientV2 returns the GAPIC generated BigtableTableAdminClient.
//
// The returned client shares the underlying connection pool with AdminClient.
// Since the connection pool is shared, calling Close on either the returned client
// or the parent AdminClient will close the connection pool, making both clients
// unusable.
func (ac *AdminClient) TableAdminClientV2() *admin.BigtableTableAdminClient {
return ac.tableAdminClient
}
func (ac *AdminClient) instancePrefix() string {
return instancePrefix(ac.project, ac.instance)
}
func instancePrefix(project, instance string) string {
return fmt.Sprintf("projects/%s/instances/%s", project, instance)
}
func (ac *AdminClient) backupPath(cluster, instance, backup string) string {
return fmt.Sprintf("projects/%s/instances/%s/clusters/%s/backups/%s", ac.project, instance, cluster, backup)
}
func (ac *AdminClient) authorizedViewPath(table, authorizedView string) string {
return fmt.Sprintf("%s/tables/%s/authorizedViews/%s", ac.instancePrefix(), table, authorizedView)
}
func (ac *AdminClient) schemaBundlePath(table, schemaBundle string) string {
return fmt.Sprintf("%s/tables/%s/schemaBundles/%s", ac.instancePrefix(), table, schemaBundle)
}
func logicalViewPath(project, instance, logicalView string) string {
return fmt.Sprintf("%s/logicalViews/%s", instancePrefix(project, instance), logicalView)
}
func materializedlViewPath(project, instance, materializedView string) string {
return fmt.Sprintf("%s/materializedViews/%s", instancePrefix(project, instance), materializedView)
}
func appProfilePath(project, instance, appProfile string) string {
return fmt.Sprintf("%s/appProfiles/%s", instancePrefix(project, instance), appProfile)
}
// EncryptionInfo represents the encryption info of a table.
type EncryptionInfo struct {
Status *Status
Type EncryptionType
KMSKeyVersion string
}
func newEncryptionInfo(pbInfo *btapb.EncryptionInfo) *EncryptionInfo {
return &EncryptionInfo{
Status: pbInfo.EncryptionStatus,
Type: EncryptionType(pbInfo.EncryptionType.Number()),
KMSKeyVersion: pbInfo.KmsKeyVersion,
}
}
// Status references google.golang.org/grpc/status.
// It represents an RPC status code, message, and details of EncryptionInfo.
// https://pkg.go.dev/google.golang.org/grpc/internal/status
type Status = status.Status
// EncryptionType is the type of encryption for an instance.
type EncryptionType int32
const (
// EncryptionTypeUnspecified is the type was not specified, though data at rest remains encrypted.
EncryptionTypeUnspecified EncryptionType = iota
// GoogleDefaultEncryption represents that data backing this resource is
// encrypted at rest with a key that is fully managed by Google. No key
// version or status will be populated. This is the default state.
GoogleDefaultEncryption
// CustomerManagedEncryption represents that data backing this resource is
// encrypted at rest with a key that is managed by the customer.
// The in-use version of the key and its status are populated for
// CMEK-protected tables.
// CMEK-protected backups are pinned to the key version that was in use at
// the time the backup was taken. This key version is populated but its
// status is not tracked and is reported as `UNKNOWN`.
CustomerManagedEncryption
)
// EncryptionInfoByCluster is a map of cluster name to EncryptionInfo
type EncryptionInfoByCluster map[string][]*EncryptionInfo
// EncryptionInfo gets the current encryption info for the table across all of the clusters.
// The returned map will be keyed by cluster id and contain a status for all of the keys in use.
func (ac *AdminClient) EncryptionInfo(ctx context.Context, table string) (EncryptionInfoByCluster, error) {
ctx = mergeOutgoingMetadata(ctx, ac.md)
res, err := ac.getTable(ctx, table, btapb.Table_ENCRYPTION_VIEW)
if err != nil {
return nil, err
}
encryptionInfo := EncryptionInfoByCluster{}
for key, cs := range res.ClusterStates {
for _, pbInfo := range cs.EncryptionInfo {
info := EncryptionInfo{}
info.Status = pbInfo.EncryptionStatus
info.Type = EncryptionType(pbInfo.EncryptionType.Number())
info.KMSKeyVersion = pbInfo.KmsKeyVersion
encryptionInfo[key] = append(encryptionInfo[key], &info)
}
}
return encryptionInfo, nil
}
// Tables returns a list of the tables in the instance.
func (ac *AdminClient) Tables(ctx context.Context) ([]string, error) {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
req := &btapb.ListTablesRequest{
Parent: prefix,
}
var res *btapb.ListTablesResponse
err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
var err error
res, err = ac.tClient.ListTables(ctx, req)
return err
}, adminRetryOptions...)
if err != nil {
return nil, err
}
names := make([]string, 0, len(res.Tables))
for _, tbl := range res.Tables {
names = append(names, strings.TrimPrefix(tbl.Name, prefix+"/tables/"))
}
return names, nil
}
// ChangeStreamRetention indicates how long bigtable should retain change data.
// Minimum is 1 day. Maximum is 7. nil to not change the retention period. 0 to
// disable change stream retention.
type ChangeStreamRetention optional.Duration
// DeletionProtection indicates whether the table, authorized view, logical view or
// materialized view is protected against data loss i.e. when set to protected,
// deleting the view, the table, the column families in the table,
// and the instance containing the table or view would be prohibited.
type DeletionProtection int
// None indicates that deletion protection is unset
// Protected indicates that deletion protection is enabled
// Unprotected indicates that deletion protection is disabled
const (
None DeletionProtection = iota
Protected
Unprotected
)
// TableAutomatedBackupConfig generalizes automated backup configurations.
// Currently, the only supported type of automated backup configuration
// is TableAutomatedBackupPolicy.
type TableAutomatedBackupConfig interface {
isTableAutomatedBackupConfig()
}
// TableAutomatedBackupPolicy defines an automated backup policy for a table.
// Use nil TableAutomatedBackupPolicy to disable Automated Backups on a table.
// Use nil for a specific field to ignore that field when updating the policy on a table.
type TableAutomatedBackupPolicy struct {
// How long the automated backups should be retained. The only
// supported value at this time is 3 days.
RetentionPeriod optional.Duration
// How frequently automated backups should occur. The only
// supported value at this time is 24 hours.
Frequency optional.Duration
// Optional. A list of Cloud Bigtable zones where automated backups are
// allowed to be created. If empty, automated backups will be created in all
// zones of the instance. Locations are in the format
// `projects/{project}/locations/{zone}`.
// This field can only set for tables in Enterprise Plus instances.
Locations []string
// Optional. The amount of time that the automated backups remain hot.
// If specified, the backups created by this policy are `HOT` backups.
// If not specified, the backups are `STANDARD` backups.
// The value must be at least 24 hours and at most 10 days, and can't
// exceed the policy's `RetentionPeriod`.
// Only SSD instances support `HOT` automated backups.
KeepHotDuration optional.Duration
// Optional. If `true`, automated backups are explicitly disabled on this
// table. This allows users to opt out of default enablement.
Disabled bool
}
func (*TableAutomatedBackupPolicy) isTableAutomatedBackupConfig() {}
// TieredStorageConfig defines a tiered storage configuration for a table.
type TieredStorageConfig struct {
// Rule to specify what data is stored in the infrequent access(IA) tier.
// The IA tier allows storing more data per node with reduced performance.
InfrequentAccess TieredStorageRule
}
// TieredStorageRule defines a tiered storage rule for a table.
type TieredStorageRule interface {
isTieredStorageRule()
}
// TieredStorageIncludeIfOlderThan defines a tiered storage rule that includes
// cells older than the given age.
type TieredStorageIncludeIfOlderThan struct {
Duration optional.Duration
}
func (*TieredStorageIncludeIfOlderThan) isTieredStorageRule() {}
func toAutomatedBackupConfigProto(automatedBackupConfig TableAutomatedBackupConfig) (*btapb.Table_AutomatedBackupPolicy_, error) {
if automatedBackupConfig == nil {
return nil, nil
}
switch backupConfig := automatedBackupConfig.(type) {
case *TableAutomatedBackupPolicy:
return backupConfig.toProto()
default:
return nil, fmt.Errorf("error: Unknown type of automated backup configuration")
}
}
func (abp *TableAutomatedBackupPolicy) toProto() (*btapb.Table_AutomatedBackupPolicy_, error) {
if abp.Disabled {
if abp.RetentionPeriod != nil || abp.Frequency != nil || len(abp.Locations) > 0 || abp.KeepHotDuration != nil {
return nil, errors.New("cannot specify other automated backup policy fields when Disabled is true")
}
return &btapb.Table_AutomatedBackupPolicy_{
AutomatedBackupPolicy: &btapb.Table_AutomatedBackupPolicy{
Disabled: true,
},
}, nil
}
pbAutomatedBackupPolicy := &btapb.Table_AutomatedBackupPolicy{
RetentionPeriod: durationpb.New(0),
Frequency: durationpb.New(0),
Locations: abp.Locations,
}
if abp.RetentionPeriod == nil && abp.Frequency == nil && abp.KeepHotDuration == nil {
return nil, errors.New("at least one of RetentionPeriod, Frequency, or KeepHotDuration must be set")
}
if abp.RetentionPeriod != nil {
pbAutomatedBackupPolicy.RetentionPeriod = durationpb.New(optional.ToDuration(abp.RetentionPeriod))
}
if abp.Frequency != nil {
pbAutomatedBackupPolicy.Frequency = durationpb.New(optional.ToDuration(abp.Frequency))
}
if abp.KeepHotDuration != nil {
pbAutomatedBackupPolicy.KeepHotDuration = durationpb.New(optional.ToDuration(abp.KeepHotDuration))
}
return &btapb.Table_AutomatedBackupPolicy_{
AutomatedBackupPolicy: pbAutomatedBackupPolicy,
}, nil
}
func (tsc *TieredStorageConfig) toProto() (*btapb.TieredStorageConfig, error) {
if tsc == nil {
return nil, nil
}
pb := &btapb.TieredStorageConfig{}
if tsc.InfrequentAccess != nil {
switch rule := tsc.InfrequentAccess.(type) {
case *TieredStorageIncludeIfOlderThan:
pb.InfrequentAccess = &btapb.TieredStorageRule{
Rule: &btapb.TieredStorageRule_IncludeIfOlderThan{
IncludeIfOlderThan: durationpb.New(optional.ToDuration(rule.Duration)),
},
}
default:
return nil, fmt.Errorf("bigtable: unknown tiered storage rule type: %T", rule)
}
}
return pb, nil
}
// Family represents a column family with its optional GC policy and value type.
type Family struct {
GCPolicy GCPolicy
ValueType Type
}
// UpdateTableConf is unused
type UpdateTableConf struct{}
// TableConf contains all the information necessary to create a table with column families.
type TableConf struct {
TableID string
SplitKeys []string
// DEPRECATED: Use ColumnFamilies instead.
// Families is a map from family name to GCPolicy.
// Only one of Families or ColumnFamilies may be set.
Families map[string]GCPolicy
// ColumnFamilies is a map from family name to family configuration.
// Only one of Families or ColumnFamilies may be set.
ColumnFamilies map[string]Family
// DeletionProtection can be none, protected or unprotected
// set to protected to make the table protected against data loss
DeletionProtection DeletionProtection
ChangeStreamRetention ChangeStreamRetention
// AutomatedBackupConfig defines the automated backup policy for the table.
AutomatedBackupConfig TableAutomatedBackupConfig
// RowKeySchema describes the structure of the row keys in the table.
RowKeySchema *StructType
// TieredStorageConfig represents rules for the table to specify what data is stored in each storage tier.
TieredStorageConfig *TieredStorageConfig
}
// CreateTable creates a new table in the instance.
// This method may return before the table's creation is complete.
func (ac *AdminClient) CreateTable(ctx context.Context, table string) error {
return ac.CreateTableFromConf(ctx, &TableConf{TableID: table, ChangeStreamRetention: nil, DeletionProtection: None})
}
// CreatePresplitTable creates a new table in the instance.
// The list of row keys will be used to initially split the table into multiple tablets.
// Given two split keys, "s1" and "s2", three tablets will be created,
// spanning the key ranges: [, s1), [s1, s2), [s2, ).
// This method may return before the table's creation is complete.
func (ac *AdminClient) CreatePresplitTable(ctx context.Context, table string, splitKeys []string) error {
return ac.CreateTableFromConf(ctx, &TableConf{TableID: table, SplitKeys: splitKeys, ChangeStreamRetention: nil, DeletionProtection: None})
}
// CreateTableFromConf creates a new table in the instance from the given configuration.
func (ac *AdminClient) CreateTableFromConf(ctx context.Context, conf *TableConf) error {
if conf.TableID == "" {
return errors.New("TableID is required")
}
ctx = mergeOutgoingMetadata(ctx, ac.md)
var reqSplits []*btapb.CreateTableRequest_Split
for _, split := range conf.SplitKeys {
reqSplits = append(reqSplits, &btapb.CreateTableRequest_Split{Key: []byte(split)})
}
var tbl btapb.Table
// we'd rather not set anything explicitly if users don't specify a value and let the server set the default value.
// if DeletionProtection is not set, currently the API will default it to false.
if conf.DeletionProtection == Protected {
tbl.DeletionProtection = true
} else if conf.DeletionProtection == Unprotected {
tbl.DeletionProtection = false
}
if conf.ChangeStreamRetention != nil && conf.ChangeStreamRetention.(time.Duration) != 0 {
tbl.ChangeStreamConfig = &btapb.ChangeStreamConfig{}
tbl.ChangeStreamConfig.RetentionPeriod = durationpb.New(conf.ChangeStreamRetention.(time.Duration))
}
if conf.AutomatedBackupConfig != nil {
proto, err := toAutomatedBackupConfigProto(conf.AutomatedBackupConfig)
if err != nil {
return err
}
tbl.AutomatedBackupConfig = proto
}
if conf.RowKeySchema != nil {
tbl.RowKeySchema = conf.RowKeySchema.proto().GetStructType()
}
if conf.TieredStorageConfig != nil {
proto, err := conf.TieredStorageConfig.toProto()
if err != nil {
return err
}
tbl.TieredStorageConfig = proto
}
if conf.Families != nil && conf.ColumnFamilies != nil {
return errors.New("only one of Families or ColumnFamilies may be set, not both")
}
if conf.ColumnFamilies != nil {
tbl.ColumnFamilies = make(map[string]*btapb.ColumnFamily)
for fam, config := range conf.ColumnFamilies {
var gcPolicy *btapb.GcRule
if config.GCPolicy != nil {
gcPolicy = config.GCPolicy.proto()
} else {
gcPolicy = &btapb.GcRule{}
}
var typeProto *btapb.Type = nil
if config.ValueType != nil {
typeProto = config.ValueType.proto()
}
tbl.ColumnFamilies[fam] = &btapb.ColumnFamily{GcRule: gcPolicy, ValueType: typeProto}
}
} else if conf.Families != nil {
tbl.ColumnFamilies = make(map[string]*btapb.ColumnFamily)
for fam, policy := range conf.Families {
tbl.ColumnFamilies[fam] = &btapb.ColumnFamily{GcRule: policy.proto()}
}
}
prefix := ac.instancePrefix()
req := &btapb.CreateTableRequest{
Parent: prefix,
TableId: conf.TableID,
Table: &tbl,
InitialSplits: reqSplits,
}
_, err := ac.tClient.CreateTable(ctx, req)
return err
}
// CreateColumnFamily creates a new column family in a table.
func (ac *AdminClient) CreateColumnFamily(ctx context.Context, table, family string) error {
// TODO(dsymonds): Permit specifying gcexpr and any other family settings.
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
req := &btapb.ModifyColumnFamiliesRequest{
Name: prefix + "/tables/" + table,
Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
Id: family,
Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Create{Create: &btapb.ColumnFamily{}},
}},
}
_, err := ac.tClient.ModifyColumnFamilies(ctx, req)
return err
}
// CreateColumnFamilyWithConfig creates a new column family in a table with an optional GC policy and value type.
func (ac *AdminClient) CreateColumnFamilyWithConfig(ctx context.Context, table, family string, config Family) error {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
cf := &btapb.ColumnFamily{}
if config.GCPolicy != nil {
cf.GcRule = config.GCPolicy.proto()
}
if config.ValueType != nil {
cf.ValueType = config.ValueType.proto()
}
req := &btapb.ModifyColumnFamiliesRequest{
Name: prefix + "/tables/" + table,
Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
Id: family,
Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Create{Create: cf},
}},
}
_, err := ac.tClient.ModifyColumnFamilies(ctx, req)
return err
}
const (
deletionProtectionFieldMask = "deletion_protection"
changeStreamConfigFieldMask = "change_stream_config"
automatedBackupPolicyFieldMask = "automated_backup_policy"
retentionPeriodFieldMaskPath = "retention_period"
frequencyFieldMaskPath = "frequency"
locationsFieldMaskPath = "locations"
keepHotDurationFieldMaskPath = "keep_hot_duration"
disabledFieldMaskPath = "disabled"
rowKeySchemaMaskPath = "row_key_schema"
tieredStorageConfigFieldMask = "tiered_storage_config"
)
func (ac *AdminClient) newUpdateTableRequestProto(tableID string) (*btapb.UpdateTableRequest, error) {
if tableID == "" {
return nil, errors.New("TableID is required")
}
updateMask := &field_mask.FieldMask{
Paths: []string{},
}
req := &btapb.UpdateTableRequest{
Table: &btapb.Table{
Name: ac.instancePrefix() + "/tables/" + tableID,
},
UpdateMask: updateMask,
}
return req, nil
}
func (ac *AdminClient) updateTableAndWait(ctx context.Context, updateTableRequest *btapb.UpdateTableRequest) error {
ctx = mergeOutgoingMetadata(ctx, ac.md)
lro, err := ac.tClient.UpdateTable(ctx, updateTableRequest)
if err != nil {
return fmt.Errorf("error from update: %w", err)
}
var tbl btapb.Table
op := longrunning.InternalNewOperation(ac.lroClient, lro)
err = op.Wait(ctx, &tbl)
if err != nil {
return fmt.Errorf("error from operation: %v", err)
}
return nil
}
// UpdateTableDisableChangeStream updates a table to disable change stream for table ID.
func (ac *AdminClient) UpdateTableDisableChangeStream(ctx context.Context, tableID string) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = []string{changeStreamConfigFieldMask}
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableWithChangeStream updates a table to with the given table ID and change stream config.
func (ac *AdminClient) UpdateTableWithChangeStream(ctx context.Context, tableID string, changeStreamRetention ChangeStreamRetention) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = []string{changeStreamConfigFieldMask + "." + retentionPeriodFieldMaskPath}
req.Table.ChangeStreamConfig = &btapb.ChangeStreamConfig{}
req.Table.ChangeStreamConfig.RetentionPeriod = durationpb.New(changeStreamRetention.(time.Duration))
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableWithDeletionProtection updates a table with the given table ID and deletion protection parameter.
func (ac *AdminClient) UpdateTableWithDeletionProtection(ctx context.Context, tableID string, deletionProtection DeletionProtection) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = []string{deletionProtectionFieldMask}
req.Table.DeletionProtection = deletionProtection != Unprotected
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableDisableAutomatedBackupPolicy updates a table to disable automated backups for table ID.
func (ac *AdminClient) UpdateTableDisableAutomatedBackupPolicy(ctx context.Context, tableID string) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = []string{automatedBackupPolicyFieldMask}
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableWithAutomatedBackupPolicy updates a table to with the given table ID and automated backup policy config.
func (ac *AdminClient) UpdateTableWithAutomatedBackupPolicy(ctx context.Context, tableID string, automatedBackupPolicy TableAutomatedBackupPolicy) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
abc, err := toAutomatedBackupConfigProto(&automatedBackupPolicy)
if err != nil {
return err
}
if automatedBackupPolicy.Disabled {
req.UpdateMask.Paths = append(req.UpdateMask.Paths, automatedBackupPolicyFieldMask+"."+disabledFieldMaskPath)
req.Table.AutomatedBackupConfig = abc
return ac.updateTableAndWait(ctx, req)
}
// If the AutomatedBackupPolicy is not at least partially specified, or if all duration fields are 0, then this is an
// incorrect configuration for updating the table, and should be rejected.
if abc.AutomatedBackupPolicy.RetentionPeriod.Seconds == 0 && abc.AutomatedBackupPolicy.Frequency.Seconds == 0 && abc.AutomatedBackupPolicy.GetKeepHotDuration().GetSeconds() == 0 {
return errors.New("Invalid automated backup policy. If you're intending to disable automated backups, please use the UpdateTableDisableAutomatedBackupPolicy method instead")
}
if abc.AutomatedBackupPolicy.RetentionPeriod.Seconds != 0 {
// Update Retention Period
req.UpdateMask.Paths = append(req.UpdateMask.Paths, automatedBackupPolicyFieldMask+"."+retentionPeriodFieldMaskPath)
}
if abc.AutomatedBackupPolicy.Frequency.Seconds != 0 {
// Update Frequency
req.UpdateMask.Paths = append(req.UpdateMask.Paths, automatedBackupPolicyFieldMask+"."+frequencyFieldMaskPath)
}
if automatedBackupPolicy.Locations != nil {
// Update Locations
req.UpdateMask.Paths = append(req.UpdateMask.Paths, automatedBackupPolicyFieldMask+"."+locationsFieldMaskPath)
}
if automatedBackupPolicy.KeepHotDuration != nil {
// Update KeepHotDuration
req.UpdateMask.Paths = append(req.UpdateMask.Paths, automatedBackupPolicyFieldMask+"."+keepHotDurationFieldMaskPath)
}
req.Table.AutomatedBackupConfig = abc
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableWithRowKeySchema updates a table with RowKeySchema.
func (ac *AdminClient) UpdateTableWithRowKeySchema(ctx context.Context, tableID string, rowKeySchema StructType) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = append(req.UpdateMask.Paths, rowKeySchemaMaskPath)
req.Table.RowKeySchema = rowKeySchema.proto().GetStructType()
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableRemoveRowKeySchema removes a RowKeySchema from a table.
func (ac *AdminClient) UpdateTableRemoveRowKeySchema(ctx context.Context, tableID string) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = append(req.UpdateMask.Paths, rowKeySchemaMaskPath)
req.IgnoreWarnings = true
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableWithTieredStorageConfig updates a table with TieredStorageConfig.
func (ac *AdminClient) UpdateTableWithTieredStorageConfig(ctx context.Context, tableID string, tieredStorageConfig *TieredStorageConfig) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
proto, err := tieredStorageConfig.toProto()
if err != nil {
return err
}
req.UpdateMask.Paths = append(req.UpdateMask.Paths, tieredStorageConfigFieldMask)
req.Table.TieredStorageConfig = proto
return ac.updateTableAndWait(ctx, req)
}
// UpdateTableRemoveTieredStorageConfig removes a TieredStorageConfig from a table.
func (ac *AdminClient) UpdateTableRemoveTieredStorageConfig(ctx context.Context, tableID string) error {
req, err := ac.newUpdateTableRequestProto(tableID)
if err != nil {
return err
}
req.UpdateMask.Paths = append(req.UpdateMask.Paths, tieredStorageConfigFieldMask)
return ac.updateTableAndWait(ctx, req)
}
// DeleteTable deletes a table and all of its data.
func (ac *AdminClient) DeleteTable(ctx context.Context, table string) error {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
req := &btapb.DeleteTableRequest{
Name: prefix + "/tables/" + table,
}
_, err := ac.tClient.DeleteTable(ctx, req)
return err
}
// DeleteColumnFamily deletes a column family in a table and all of its data.
func (ac *AdminClient) DeleteColumnFamily(ctx context.Context, table, family string) error {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
req := &btapb.ModifyColumnFamiliesRequest{
Name: prefix + "/tables/" + table,
Modifications: []*btapb.ModifyColumnFamiliesRequest_Modification{{
Id: family,
Mod: &btapb.ModifyColumnFamiliesRequest_Modification_Drop{Drop: true},
}},
}
_, err := ac.tClient.ModifyColumnFamilies(ctx, req)
return err
}
// TableInfo represents information about a table.
type TableInfo struct {
// DEPRECATED - This field is deprecated. Please use FamilyInfos instead.
Families []string
FamilyInfos []FamilyInfo
// DeletionProtection indicates whether the table is protected against data loss
// DeletionProtection could be None depending on the table view
// for example when using NAME_ONLY, the response does not contain DeletionProtection and the value should be None
DeletionProtection DeletionProtection
ChangeStreamRetention ChangeStreamRetention
AutomatedBackupConfig TableAutomatedBackupConfig
EffectiveAutomatedBackupPolicy *TableAutomatedBackupPolicy
RowKeySchema *StructType
TieredStorageConfig *TieredStorageConfig
}
func protoToTableAutomatedBackupPolicy(pb *btapb.Table_AutomatedBackupPolicy) *TableAutomatedBackupPolicy {
if pb == nil {
return nil
}
abp := &TableAutomatedBackupPolicy{
Locations: pb.GetLocations(),
Disabled: pb.GetDisabled(),
}
if pb.GetRetentionPeriod() != nil {
abp.RetentionPeriod = pb.GetRetentionPeriod().AsDuration()
}
if pb.GetFrequency() != nil {
abp.Frequency = pb.GetFrequency().AsDuration()
}
if pb.GetKeepHotDuration() != nil {
abp.KeepHotDuration = pb.GetKeepHotDuration().AsDuration()
}
return abp
}
// FamilyInfo represents information about a column family.
type FamilyInfo struct {
Name string
GCPolicy string
FullGCPolicy GCPolicy
ValueType Type
}
func (ac *AdminClient) getTable(ctx context.Context, table string, view btapb.Table_View) (*btapb.Table, error) {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
req := &btapb.GetTableRequest{
Name: prefix + "/tables/" + table,
View: view,
}
var res *btapb.Table
err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error {
var err error
res, err = ac.tClient.GetTable(ctx, req)
return err
}, adminRetryOptions...)
if err != nil {
return nil, err
}
return res, nil
}
// TableInfo retrieves information about a table.
func (ac *AdminClient) TableInfo(ctx context.Context, table string) (*TableInfo, error) {
ctx = mergeOutgoingMetadata(ctx, ac.md)
res, err := ac.getTable(ctx, table, btapb.Table_SCHEMA_VIEW)
if err != nil {
return nil, err
}
ti := &TableInfo{}
for name, fam := range res.ColumnFamilies {
ti.Families = append(ti.Families, name)
ti.FamilyInfos = append(ti.FamilyInfos, FamilyInfo{
Name: name,
GCPolicy: GCRuleToString(fam.GcRule),
FullGCPolicy: gcRuleToPolicy(fam.GcRule),
ValueType: ProtoToType(fam.ValueType),
})
}
// we expect DeletionProtection to be in the response because Table_SCHEMA_VIEW is being used in this function
// but when using NAME_ONLY, the response does not contain DeletionProtection and it could be nil
if res.DeletionProtection == true {
ti.DeletionProtection = Protected
} else {
ti.DeletionProtection = Unprotected
}
if res.ChangeStreamConfig != nil && res.ChangeStreamConfig.RetentionPeriod != nil {
ti.ChangeStreamRetention = res.ChangeStreamConfig.RetentionPeriod.AsDuration()
}
if res.AutomatedBackupConfig != nil {
switch res.AutomatedBackupConfig.(type) {
case *btapb.Table_AutomatedBackupPolicy_:
ti.AutomatedBackupConfig = protoToTableAutomatedBackupPolicy(res.GetAutomatedBackupPolicy())
default:
return nil, fmt.Errorf("error: Unknown type of automated backup configuration")
}
}
if res.GetEffectiveAutomatedBackupPolicy() != nil {
ti.EffectiveAutomatedBackupPolicy = protoToTableAutomatedBackupPolicy(res.GetEffectiveAutomatedBackupPolicy())
}
if res.RowKeySchema != nil {
structType := structProtoToType(res.RowKeySchema).(StructType)
ti.RowKeySchema = &structType
}
if res.TieredStorageConfig != nil {
ti.TieredStorageConfig = &TieredStorageConfig{}
if res.TieredStorageConfig.InfrequentAccess != nil {
switch rule := res.TieredStorageConfig.InfrequentAccess.Rule.(type) {
case *btapb.TieredStorageRule_IncludeIfOlderThan:
ti.TieredStorageConfig.InfrequentAccess = &TieredStorageIncludeIfOlderThan{
Duration: rule.IncludeIfOlderThan.AsDuration(),
}
}
}
}
return ti, nil
}
type updateFamilyOption struct {
ignoreWarnings bool
}
// GCPolicyOption is deprecated, kept for backwards compatibility, use UpdateFamilyOption in new code
type GCPolicyOption interface {
apply(s *updateFamilyOption)
}
// UpdateFamilyOption is the interface to update family settings
type UpdateFamilyOption GCPolicyOption
type ignoreWarnings bool
func (w ignoreWarnings) apply(s *updateFamilyOption) {
s.ignoreWarnings = bool(w)
}
// IgnoreWarnings returns a updateFamilyOption that ignores safety checks when modifying the column families
func IgnoreWarnings() GCPolicyOption {
return ignoreWarnings(true)
}
// SetGCPolicy specifies which cells in a column family should be garbage collected.
// GC executes opportunistically in the background; table reads may return data
// matching the GC policy.
func (ac *AdminClient) SetGCPolicy(ctx context.Context, table, family string, policy GCPolicy) error {
return ac.UpdateFamily(ctx, table, family, Family{GCPolicy: policy})
}
// SetGCPolicyWithOptions is similar to SetGCPolicy but allows passing options
func (ac *AdminClient) SetGCPolicyWithOptions(ctx context.Context, table, family string, policy GCPolicy, opts ...GCPolicyOption) error {
familyOpts := []UpdateFamilyOption{}
for _, opt := range opts {
if opt != nil {
familyOpts = append(familyOpts, opt.(UpdateFamilyOption))
}
}
return ac.UpdateFamily(ctx, table, family, Family{GCPolicy: policy}, familyOpts...)
}
// UpdateFamily updates column families' garbage collection policies and value type.
func (ac *AdminClient) UpdateFamily(ctx context.Context, table, familyName string, family Family, opts ...UpdateFamilyOption) error {
ctx = mergeOutgoingMetadata(ctx, ac.md)
prefix := ac.instancePrefix()
s := updateFamilyOption{}
for _, opt := range opts {
if opt != nil {
opt.apply(&s)
}
}
cf := &btapb.ColumnFamily{}
mask := &field_mask.FieldMask{}
if family.GCPolicy != nil {
cf.GcRule = family.GCPolicy.proto()
mask.Paths = append(mask.Paths, "gc_rule")
}
if family.ValueType != nil {
cf.ValueType = family.ValueType.proto()
mask.Paths = append(mask.Paths, "value_type")
}