forked from googleapis/cloud-bigtable-cbt-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbt.go
executable file
·2356 lines (2100 loc) · 73.1 KB
/
cbt.go
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 main
// Command docs are in cbtdoc.go.
import (
"bytes"
"context"
_ "embed"
"encoding/csv"
"flag"
"fmt"
"go/format"
"io"
"log"
"os"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/tabwriter"
"text/template"
"time"
"cloud.google.com/go/bigtable"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)
var (
oFlag = flag.String("o", "", "if set, redirect stdout to this file")
config *Config
client *bigtable.Client
table tableLike
adminClient *bigtable.AdminClient
instanceAdminClient *bigtable.InstanceAdminClient
version = "<unknown version>"
revision = "<unknown revision>"
revisionDate = "<unknown revision date>"
cliUserAgent = "cbt-cli-go/unknown"
//go:embed THIRD_PARTY_NOTICES.txt
noticesContents []byte
)
type tableLike interface {
ReadRows(ctx context.Context, arg bigtable.RowSet, f func(bigtable.Row) bool, opts ...bigtable.ReadOption) (err error)
ReadRow(context.Context, string, ...bigtable.ReadOption) (bigtable.Row, error)
}
func getCredentialOpts(opts []option.ClientOption) []option.ClientOption {
if ts := config.TokenSource; ts != nil {
opts = append(opts, option.WithTokenSource(ts))
}
if tlsCreds := config.TLSCreds; tlsCreds != nil {
opts = append(opts, option.WithGRPCDialOption(grpc.WithTransportCredentials(tlsCreds)))
}
return opts
}
func getClient(clientConf bigtable.ClientConfig) *bigtable.Client {
if client == nil {
var opts []option.ClientOption
if ep := config.DataEndpoint; ep != "" {
opts = append(opts, option.WithEndpoint(ep))
}
opts = append(opts, option.WithUserAgent(cliUserAgent))
opts = getCredentialOpts(opts)
var err error
client, err = bigtable.NewClientWithConfig(context.Background(), config.Project, config.Instance, clientConf, opts...)
if err != nil {
log.Fatalf("Making bigtable.Client: %v", err)
}
}
return client
}
func getTable(clientConf bigtable.ClientConfig, tableName string) tableLike {
if table != nil {
return table
}
table = getClient(clientConf).Open(tableName)
return table
}
func getAdminClient() *bigtable.AdminClient {
if adminClient == nil {
var opts []option.ClientOption
if ep := config.AdminEndpoint; ep != "" {
opts = append(opts, option.WithEndpoint(ep))
}
opts = append(opts, option.WithUserAgent(cliUserAgent))
opts = getCredentialOpts(opts)
var err error
adminClient, err = bigtable.NewAdminClient(context.Background(), config.Project, config.Instance, opts...)
if err != nil {
log.Fatalf("Making bigtable.AdminClient: %v", err)
}
}
return adminClient
}
func getInstanceAdminClient() *bigtable.InstanceAdminClient {
if instanceAdminClient == nil {
var opts []option.ClientOption
if ep := config.AdminEndpoint; ep != "" {
opts = append(opts, option.WithEndpoint(ep))
}
opts = getCredentialOpts(opts)
var err error
instanceAdminClient, err = bigtable.NewInstanceAdminClient(context.Background(), config.Project, opts...)
if err != nil {
log.Fatalf("Making bigtable.InstanceAdminClient: %v", err)
}
}
return instanceAdminClient
}
func main() {
var err error
config, err = Load()
if err != nil {
log.Fatal(err)
}
config.RegisterFlags()
flag.Usage = func() { usage(os.Stderr) }
flag.Parse()
if flag.NArg() == 0 {
usage(os.Stderr)
os.Exit(1)
}
if *oFlag != "" {
f, err := os.Create(*oFlag)
if err != nil {
log.Fatal(err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatal(err)
}
}()
os.Stdout = f
}
doMain(config, flag.Args())
}
func doMain(config *Config, args []string) {
if config.UserAgent != "" {
cliUserAgent = config.UserAgent
}
var ctx context.Context
if config.Timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), config.Timeout)
defer cancel()
} else {
ctx = context.Background()
}
if config.AuthToken != "" {
ctx = metadata.AppendToOutgoingContext(ctx, "x-goog-iam-authorization-token", config.AuthToken)
}
for _, cmd := range commands {
if cmd.Name == args[0] {
if err := config.CheckFlags(cmd.Required); err != nil {
log.Fatal(err)
}
cmd.do(ctx, args[1:]...)
return
}
}
log.Fatalf("Unknown command %q", args[0])
}
func usage(w io.Writer) {
fmt.Fprintf(w, "Usage: %s [flags] <command> ...\n", os.Args[0])
flag.CommandLine.SetOutput(w)
flag.CommandLine.PrintDefaults()
fmt.Fprintf(w, "\n%s", cmdSummary)
}
var cmdSummary string // generated in init, below
func init() {
var buf bytes.Buffer
tw := tabwriter.NewWriter(&buf, 10, 8, 4, '\t', 0)
for _, cmd := range commands {
fmt.Fprintf(tw, "cbt %s\t%s\n", cmd.Name, cmd.Desc)
}
tw.Flush()
buf.WriteString(configHelp)
buf.WriteString("\ncbt " + version + " " + revision + " " + revisionDate + "\n")
cmdSummary = buf.String()
}
const configHelp = `
Preview features are not currently available to most Cloud Bigtable customers. Alpha
features might be changed in backward-incompatible ways and are not recommended
for production use. They are not subject to any SLA or deprecation policy.
Syntax rules for the Bash shell apply to the ` + "`cbt`" + ` CLI. This means, for example,
that you must put quotes around values that contain spaces or operators. It also means that
if a value is arbitrary bytes, you need to prefix it with a dollar sign and use single quotes.
Example:
cbt -project my-project -instance my-instance lookup my-table $'\224\257\312W\365:\205d\333\2471\315\'
For convenience, you can add values for the -project, -instance, -creds, -admin-endpoint and -data-endpoint
options to your ~/.cbtrc file in the following format:
project = my-project-123
instance = my-instance
creds = path-to-account-key.json
admin-endpoint = hostname:port
data-endpoint = hostname:port
auth-token = AJAvW039NO1nDcijk_J6_rFXG_...
timeout = 30s
All values are optional and can be overridden at the command prompt.
`
// const formatHelp = `
// ## Custom data formatting for the ` + "`" + `lookup` + "`" +
// ` and ` + "`" + `read` + "`" + ` commands.
// You can provide custom formatting information for formatting stored
// data values in the ` + "`" + `lookup` + "`" + ` and ` + "`" + `read` +
// "`" + ` commands.
// The formatting data follows a formatting model consisting of an
// encoding and type for each column.
// The available encodings are:
// - ` + "`" + `Hex` + "`" + ` (alias: ` + "`" + `H` + "`" + `)
// - ` + "`" + `BigEndian` + "`" + ` (aliases: ` + "`" + `BINARY` + "`" + `, ` +
// "`" + `B` + "`" + `)
// - ` + "`" + `LittleEndian` + "`" + ` (alias: ` + "`" + `L` + "`" + `)
// - ` + "`" + `ProtocolBuffer` + "`" + ` (aliases: ` + "`" + `Proto` + "`" + `, ` +
// "`" + `P` + "`" + `)
// Encoding names and aliases are case insensitive.
// The Hex encoding is type agnostic. Data are displayed as a raw
// hexadecimal representation of the stored data.
// The available types for the BigEndian and LittleEndian encodings are ` +
// "`" + `int8` + "`" + `, ` + "`" + `int16` + "`" + `, ` + "`" +
// `int32` + "`" + `, ` + "`" + `int64` + "`" + `, ` + "`" + `uint8` +
// "`" + `, ` + "`" + `uint16` + "`" + `, ` + "`" + `uint32` + "`" + `, ` +
// "`" + `uint64` + "`" + `, ` + "`" + `float32` + "`" + `, and ` + "`" +
// `float64` + "`" + `. Stored data length must be a multiple of the
// type sized, in bytes. Data are displayed as scalars if the stored
// length matches the type size, or as arrays otherwise. Types names are case
// insensitive.
// The types given for the ` + "`" + `ProtocolBuffer` + "`" + ` encoding
// must case-insensitively match message types defined in provided
// protocol-buffer definition files. If no type is specified, it
// defaults to the column name for the column data being displayed.
// Encoding and type are provided at the column level. Default encodings
// and types may be provided overall and at the column-family level. You
// don't need to define column formatting at the family level unless you
// have multiple column families and want to provide family-specific
// defaults or need to specify different formats for columns of the same
// name in different families.
// Protocol-buffer definition files may be given, as well as directories
// used to search for definition files and files imported by them. If
// no paths are specified, then the current working directory is used.
// Locations of standard protocol buffer imports (` + "`" +
// `google/protobuf/*` + "`" + `) need not be specified.
// Format information in YAML format is provided using the ` + "`" +
// `format-file` + "`" + ` option for the ` + "`" + `lookup` + "`" + `
// and ` + "`" + `read` + "`" + ` commands (e.g ` + "`" +
// `format-file=myformat.yml` + "`" + `).
// The YAML file provides an object with optional properties:
// ` + "`" + `default_encoding` + "`" + `
// : The name of the overall default encoding
// ` + "`" + `default_type` + "`" + `
// : The name of the overall default type
// ` + "`" + `protocol_buffer_definitions` + "`" + `
// : A list of protocol-buffer files defining
// : available message types.
// ` + "`" + `protocol_buffer_paths` + "`" + `
// : A list of directories to search for definition
// : files and imports. If not provided, the current
// : working directory will be used. Locations
// : need not be provided for standard
// : protocol-buffer imports.
// ` + "`" + `columns` + "`" + `
// : A mapping from column names to column objects.
// ` + "`" + `families` + "`" + `
// : A mapping from family names to family objects.
// Column objects have two properties:
// ` + "`" + `encoding` + "`" + `
// : The encoding to be used for the column
// : (overriding the default encoding, if any)
// ` + "`" + `type` + "`" + `
// : The data type to be used for the column
// : (overriding the default type, if any)
// Family objects have properties:
// ` + "`" + `default_encoding` + "`" + `
// : The name of the default encoding for columns in
// : the family
// ` + "`" + `default_type` + "`" + `
// : The name of the default type for columns in the
// : family
// ` + "`" + `columns` + "`" + `
// : A mapping from column names to column objects for
// : columns in the family.
// Here's an example of a format file:` + "\n```" + `
// default_encoding: ProtocolBuffer
// protocol_buffer_definitions:
// - MyProto.proto
// columns:
// contact:
// type: person
// size:
// encoding: BigEndian
// type: uint32
// ` + "```" + `
// `
const docIntroTemplate = `The ` + "`cbt`" + ` CLI is a command-line interface that lets you interact with Cloud Bigtable.
See the [cbt CLI overview](https://cloud.google.com/bigtable/docs/cbt-overview) to learn how to install the ` + "`cbt`" + ` CLI.
Before you use the ` + "`cbt`" + ` CLI, you should be familiar with the [Bigtable overview](https://cloud.google.com/bigtable/docs/overview).
The examples on this page use [sample data](https://cloud.google.com/bigtable/docs/using-filters#data) similar to data
that you might store in Bigtable.
Usage:
cbt [-<option> <option-argument>] <command> <required-argument> [optional-argument]
The commands are:
{{range .Commands}}
{{printf "%-25s %s" .Name .Desc}}{{end}}
The options are:
{{range .Flags}}
-{{.Name}} string
{{.Usage}}{{end}}
Example: cbt -instance=my-instance ls
Use "cbt help \<command>" for more information about a command.
{{.ConfigHelp}}
`
var commands = []struct {
Name, Desc string
do func(context.Context, ...string)
Usage string
Required RequiredFlags
}{
{
Name: "count",
Desc: "Count rows in a table",
do: doCount,
Usage: "cbt count <table-id> [prefix=<row-key-prefix>]",
Required: ProjectAndInstanceRequired,
},
{
Name: "createappprofile",
Desc: "Create app profile for an instance",
do: doCreateAppProfile,
Usage: "cbt createappprofile <instance-id> <app-profile-id> <description> " +
"(route-any | [ route-to=<cluster-id> : transactional-writes]) [-force] \n" +
" force: Optional flag to override any warnings causing the command to fail\n\n" +
" Examples:\n" +
" cbt createappprofile my-instance multi-cluster-app-profile-1 \"Routes to nearest available cluster\" route-any\n" +
" cbt createappprofile my-instance single-cluster-app-profile-1 \"Europe routing\" route-to=my-instance-cluster-2",
Required: ProjectAndInstanceRequired,
},
{
Name: "createcluster",
Desc: "Create a cluster in the configured instance ",
do: doCreateCluster,
Usage: "cbt createcluster <cluster-id> <zone> <num-nodes> <storage-type>\n" +
" cluster-id Permanent, unique ID for the cluster in the instance\n" +
" zone The zone in which to create the cluster\n" +
" num-nodes The number of nodes to create\n" +
" storage-type SSD or HDD\n\n" +
" Example: cbt createcluster my-instance-c2 europe-west1-b 3 SSD",
Required: ProjectAndInstanceRequired,
},
{
Name: "createfamily",
Desc: "Create a column family",
do: doCreateFamily,
Usage: "cbt createfamily <table-id> <family>\n\n" +
" Example: cbt createfamily mobile-time-series stats_summary",
Required: ProjectAndInstanceRequired,
},
{
Name: "createinstance",
Desc: "Create an instance with an initial cluster",
do: doCreateInstance,
Usage: "cbt createinstance <instance-id> <display-name> <cluster-id> <zone> <num-nodes> <storage-type>\n" +
" instance-id Permanent, unique ID for the instance\n" +
" display-name Description of the instance\n" +
" cluster-id Permanent, unique ID for the cluster in the instance\n" +
" zone The zone in which to create the cluster\n" +
" num-nodes The number of nodes to create\n" +
" storage-type SSD or HDD\n\n" +
" Example: cbt createinstance my-instance \"My instance\" my-instance-c1 us-central1-b 3 SSD",
Required: ProjectRequired,
},
// {
// Name: "createsnapshot",
// Desc: "Create a backup from a source table (deprecated)",
// do: doSnapshotTable,
// Usage: "cbt createsnapshot <cluster> <backup> <table> [ttl=<d>]\n" +
// ` [ttl=<d>] Lifespan of the backup (e.g. "1h", "4d")`,
// Required: ProjectAndInstanceRequired,
// },
{
Name: "createtable",
Desc: "Create a table",
do: doCreateTable,
Usage: "cbt createtable <table-id> [families=<family>:<gcpolicy-expression>:<type-expression>,...]\n" +
" [splits=<split-row-key-1>,<split-row-key-2>,...]\n" +
" families Column families and their associated garbage collection (gc) policies and types.\n" +
" Put gc policies in quotes when they include shell operators && and ||. For gcpolicy,\n" +
" see \"setgcpolicy\".\n" +
" Currently only the type \"intsum\" is supported.\n" +
" splits Row key(s) where the table should initially be split\n\n" +
" Example: cbt createtable mobile-time-series \"families=stats_summary:maxage=10d||maxversions=1,stats_detail:maxage=10d||maxversions=1\" splits=tablet,phone",
Required: ProjectAndInstanceRequired,
},
// {
// Name: "createtablefromsnapshot",
// Desc: "Create a table from a backup (deprecated)",
// do: doCreateTableFromSnapshot,
// Usage: "cbt createtablefromsnapshot <table> <cluster> <backup>\n" +
// " table The name of the table to create\n" +
// " cluster The cluster where the snapshot is located\n" +
// " backup The snapshot to restore\n",
// Required: ProjectAndInstanceRequired,
// },
{
Name: "deleteallrows",
Desc: "Delete all rows",
do: doDeleteAllRows,
Usage: "cbt deleteallrows <table-id>\n\n" +
" Example: cbt deleteallrows mobile-time-series",
Required: ProjectAndInstanceRequired,
},
{
Name: "deleteappprofile",
Desc: "Delete app profile for an instance",
do: doDeleteAppProfile,
Usage: "cbt deleteappprofile <instance-id> <profile-id>\n\n" +
" Example: cbt deleteappprofile my-instance single-cluster",
Required: ProjectAndInstanceRequired,
},
{
Name: "deletecluster",
Desc: "Delete a cluster from the configured instance ",
do: doDeleteCluster,
Usage: "cbt deletecluster <cluster-id>\n\n" +
" Example: cbt deletecluster my-instance-c2",
Required: ProjectAndInstanceRequired,
},
{
Name: "deletecolumn",
Desc: "Delete all cells in a column",
do: doDeleteColumn,
Usage: "cbt deletecolumn <table-id> <row-key> <family> <column> [app-profile=<app-profile-id>]\n" +
" app-profile=<app-profile-id> The app profile ID to use for the request\n\n" +
" Example: cbt deletecolumn mobile-time-series phone#4c410523#20190501 stats_summary os_name",
Required: ProjectAndInstanceRequired,
},
{
Name: "deletefamily",
Desc: "Delete a column family",
do: doDeleteFamily,
Usage: "cbt deletefamily <table-id> <family>\n\n" +
" Example: cbt deletefamily mobile-time-series stats_summary",
Required: ProjectAndInstanceRequired,
},
{
Name: "deleteinstance",
Desc: "Delete an instance",
do: doDeleteInstance,
Usage: "cbt deleteinstance <instance-id>\n\n" +
" Example: cbt deleteinstance my-instance",
Required: ProjectRequired,
},
{
Name: "deleterow",
Desc: "Delete a row",
do: doDeleteRow,
Usage: "cbt deleterow <table-id> <row-key> [app-profile=<app-profile-id>]\n" +
" app-profile=<app-profile-id> The app profile ID to use for the request\n\n" +
" Example: cbt deleterow mobile-time-series phone#4c410523#20190501",
Required: ProjectAndInstanceRequired,
},
// {
// Name: "deletesnapshot",
// Desc: "Delete snapshot in a cluster (deprecated)",
// do: doDeleteSnapshot,
// Usage: "cbt deletesnapshot <cluster> <backup>",
// Required: ProjectAndInstanceRequired,
// },
{
Name: "deletetable",
Desc: "Delete a table",
do: doDeleteTable,
Usage: "cbt deletetable <table-id>\n\n" +
" Example: cbt deletetable mobile-time-series",
Required: ProjectAndInstanceRequired,
},
{
Name: "doc",
Desc: "Print godoc-suitable documentation for cbt",
do: doDoc,
Usage: "cbt doc",
Required: NoneRequired,
},
{
Name: "getappprofile",
Desc: "Read app profile for an instance",
do: doGetAppProfile,
Usage: "cbt getappprofile <instance-id> <profile-id>",
Required: ProjectAndInstanceRequired,
},
// {
// Name: "getsnapshot",
// Desc: "Get backups info (deprecated)",
// do: doGetSnapshot,
// Usage: "cbt getsnapshot <cluster> <backup>",
// Required: ProjectAndInstanceRequired,
// },
{
Name: "help",
Desc: "Print help text",
do: doHelp,
Usage: "cbt help <command>\n\n" +
" Example: cbt help createtable",
Required: NoneRequired,
},
{
Name: "import",
Desc: "Batch write many rows based on the input file",
do: doImport,
Usage: "cbt import <table-id> <input-file> [app-profile=<app-profile-id>] [column-family=<family-name>] [batch-size=<500>] [workers=<1>] [timestamp=<now|value-encoded>]\n" +
" app-profile=<app-profile-id> The app profile ID to use for the request\n" +
" column-family=<family-name> The column family label to use\n" +
" batch-size=<500> The max number of rows per batch write request\n" +
" workers=<1> The number of worker threads\n" +
" timestamp=<now|value-encoded> Whether to use current time for all cells or interpret the timestamp from cell value. Defaults to 'now'.\n\n" +
" Import data from a CSV file into an existing Cloud Bigtable table that already has the column families your data requires.\n\n" +
" The CSV file can support two rows of headers:\n" +
" - (Optional) column families\n" +
" - Column qualifiers\n" +
" Because the first column is reserved for row keys, leave it empty in the header rows.\n" +
" In the column family header, provide each column family once; it applies to the column it is in and every column to the right until another column family is found.\n" +
" Each row after the header rows should contain a row key in the first column, followed by the data cells for the row.\n" +
" See the example below. If you don't provide a column family header row, the column header is your first row and your import command must include the `column-family` flag to specify an existing column family. \n\n" +
" The timestamp for each cell will default to current time (timestamp=now), to explicitly set the timestamp for cells, set timestamp=value-encoded use <val>[@<timestamp>] as the value for the cell.\n" +
" If no timestamp is delimited for a cell, current time will be used. If the timestamp cannot be parsed, '@<timestamp>' will be interpreted as part of the value.\n" +
" For most uses, a timestamp is the number of microseconds since 1970-01-01 00:00:00 UTC.\n\n" +
" ,column-family-1,,column-family-2, // Optional column family row (1st cell empty)\n" +
" ,column-1,column-2,column-3,column-4 // Column qualifiers row (1st cell empty)\n" +
" a,TRUE,,,FALSE // Rowkey 'a' followed by data\n" +
" b,,,TRUE,FALSE // Rowkey 'b' followed by data\n" +
" c,,TRUE,,TRUE // Rowkey 'c' followed by data\n" +
" d,TRUE@1577862000000000,,,FALSE // Rowkey 'd' followed by data\n\n" +
" Examples:\n" +
" cbt import csv-import-table data.csv\n" +
" cbt import csv-import-table data-no-families.csv app-profile=batch-write-profile column-family=my-family workers=5\n",
Required: ProjectAndInstanceRequired,
},
{
Name: "listappprofile",
Desc: "Lists app profile for an instance",
do: doListAppProfiles,
Usage: "cbt listappprofile <instance-id> ",
Required: ProjectAndInstanceRequired,
},
{
Name: "listclusters",
Desc: "List clusters in an instance",
do: doListClusters,
Usage: "cbt listclusters",
Required: ProjectAndInstanceRequired,
},
{
Name: "listinstances",
Desc: "List instances in a project",
do: doListInstances,
Usage: "cbt listinstances",
Required: ProjectRequired,
},
// {
// Name: "listsnapshots",
// Desc: "List backups in a cluster (deprecated)",
// do: doListSnapshots,
// Usage: "cbt listsnapshots [<cluster>]",
// Required: ProjectAndInstanceRequired,
// },
{
Name: "lookup",
Desc: "Read from a single row",
do: doLookup,
Usage: "cbt lookup <table-id> <row-key> [columns=<family>:<qualifier>,...] [cells-per-column=<n>]" +
" [app-profile=<app profile id>]\n" +
" row-key String or raw bytes. Raw bytes must be enclosed in single quotes and have a dollar-sign prefix\n" +
" columns=<family>:<qualifier>,... Read only these columns, comma-separated\n" +
" cells-per-column=<n> Read only this number of cells per column\n" +
" app-profile=<app-profile-id> The app profile ID to use for the request\n" +
" format-file=<path-to-format-file> The path to a format-configuration file to use for the request\n" +
" keys-only=<true|false> Whether to print only row keys\n" +
" include-stats=full Include a summary of request stats at the end of the request\n" +
"\n" +
" Example: cbt lookup mobile-time-series phone#4c410523#20190501 columns=stats_summary:os_build,os_name cells-per-column=1\n" +
" Example: cbt lookup mobile-time-series $'\\x41\\x42'",
Required: ProjectAndInstanceRequired,
},
{
Name: "ls",
Desc: "List tables and column families",
do: doLS,
Usage: "cbt ls List tables\n" +
"cbt ls <table-id> List a table's column families and garbage collection policies\n\n" +
" Example: cbt ls mobile-time-series",
Required: ProjectAndInstanceRequired,
},
{
Name: "mddoc",
Desc: "Print documentation for cbt in Markdown format",
do: doMDDoc,
Usage: "cbt mddoc",
Required: NoneRequired,
},
{
Name: "notices",
Desc: "Display licence information for any third-party dependencies",
do: doNotices,
Usage: "cbt notices",
Required: NoneRequired,
},
{
Name: "read",
Desc: "Read rows",
do: doRead,
Usage: "cbt read <table-id> [authorized-view=<authorized-view-id>] [start=<row-key>] [end=<row-key>] [prefix=<row-key-prefix>]" +
" [regex=<regex>] [columns=<family>:<qualifier>,...] [count=<n>] [cells-per-column=<n>]" +
" [app-profile=<app-profile-id>]\n" +
" authorized-view=<authorized-view-id> Read from the specified authorized view of the table\n" +
" start=<row-key> Start reading at this row\n" +
" end=<row-key> Stop reading before this row\n" +
" prefix=<row-key-prefix> Read rows with this prefix\n" +
" regex=<regex> Read rows with keys matching this regex\n" +
" reversed=<true|false> Read rows in reverse order\n" +
" columns=<family>:<qualifier>,... Read only these columns, comma-separated\n" +
" count=<n> Read only this many rows\n" +
" cells-per-column=<n> Read only this many cells per column\n" +
" app-profile=<app-profile-id> The app profile ID to use for the request\n" +
" format-file=<path-to-format-file> The path to a format-configuration file to use for the request\n" +
" keys-only=<true|false> Whether to print only row keys\n" +
" include-stats=full Include a summary of request stats at the end of the request\n" +
"\n" +
" Examples: (see 'set' examples to create data to read)\n" +
" cbt read mobile-time-series prefix=phone columns=stats_summary:os_build,os_name count=10\n" +
" cbt read mobile-time-series start=phone#4c410523#20190501 end=phone#4c410523#20190601\n" +
" cbt read mobile-time-series regex=\"phone.*\" cells-per-column=1\n" +
" cbt read mobile-time-series start=phone#4c410523#20190501 end=phone#4c410523#20190601 reversed=true count=10\n\n" +
" Note: Using a regex without also specifying start, end, prefix, or count results in a full\n" +
" table scan, which can be slow.\n",
Required: ProjectAndInstanceRequired,
},
{
Name: "set",
Desc: "Set value of a cell (write)",
do: doSet,
Usage: "cbt set <table-id> <row-key> [authorized-view=<authorized-view-id>] [app-profile=<app-profile-id>] <family>:<column>=<val>[@<timestamp>] ...\n" +
" authorized-view=<authorized-view-id> Write to the specified authorized view of the table\n" +
" app-profile=<app profile id> The app profile ID to use for the request\n" +
" <family>:<column>=<val>[@<timestamp>] may be repeated to set multiple cells.\n\n" +
" timestamp is an optional integer. \n" +
" If the timestamp cannot be parsed, '@<timestamp>' will be interpreted as part of the value.\n" +
" For most uses, a timestamp is the number of microseconds since 1970-01-01 00:00:00 UTC.\n\n" +
" Examples:\n" +
" cbt set mobile-time-series phone#4c410523#20190501 stats_summary:connected_cell=1@12345 stats_summary:connected_cell=0@1570041766\n" +
" cbt set mobile-time-series phone#4c410523#20190501 stats_summary:os_build=PQ2A.190405.003 stats_summary:os_name=android",
Required: ProjectAndInstanceRequired,
},
{
Name: "addtocell",
Desc: "Add a value to an aggregate cell (write)",
do: doAddToCell,
Usage: "cbt addtocell <table-id> <row-key> [app-profile=<app-profile-id>] <family>:<column>=<val>[@<timestamp>] ...\n" +
" app-profile=<app profile id> The app profile ID to use for the request\n" +
" <family>:<column>=<val>[@<timestamp>] may be repeated to set multiple cells.\n\n" +
" If <val> can be parsed as an integer it will be used as one, otherwise the call will fail.\n" +
" timestamp is an optional integer. \n" +
" If the timestamp cannot be parsed, '@<timestamp>' will be interpreted as part of the value.\n" +
" For most uses, a timestamp is the number of microseconds since 1970-01-01 00:00:00 UTC.\n\n" +
" Examples:\n" +
" cbt addtocell table1 user1 sum_cf:col1=1@12345",
Required: ProjectAndInstanceRequired,
},
{
Name: "setgcpolicy",
Desc: "Set the garbage-collection policy (age, versions) for a column family",
do: doSetGCPolicy,
Usage: "cbt setgcpolicy <table> <family> ((maxage=<d> | maxversions=<n>) [(and|or) (maxage=<d> | maxversions=<n>),...] | never) [force]\n" +
" force: Optional flag to override warnings when relaxing the garbage-collection policy on replicated clusters.\n" +
" This may cause your clusters to be temporarily inconsistent, make sure you understand the risks\n" +
" listed at https://cloud.google.com/bigtable/docs/garbage-collection#increasing\n\n" +
" maxage=<d> Maximum timestamp age to preserve. Acceptable units: ms, s, m, h, d\n" +
" maxversions=<n> Maximum number of versions to preserve\n" +
" Put garbage collection policies in quotes when they include shell operators && and ||.\n\n" +
" Examples:\n" +
" cbt setgcpolicy mobile-time-series stats_detail maxage=10d\n" +
" cbt setgcpolicy mobile-time-series stats_summary maxage=10d or maxversions=1 force\n",
Required: ProjectAndInstanceRequired,
},
{
Name: "updateappprofile",
Desc: "Update app profile for an instance",
do: doUpdateAppProfile,
Usage: "cbt updateappprofile <instance-id> <profile-id> <description>" +
"(route-any | [ route-to=<cluster-id> : transactional-writes]) [-force] \n" +
" force: Optional flag to override any warnings causing the command to fail\n\n" +
" Example: cbt updateappprofile my-instance multi-cluster-app-profile-1 \"Use this one.\" route-any",
Required: ProjectAndInstanceRequired,
},
{
Name: "updatecluster",
Desc: "Update a cluster in the configured instance",
do: doUpdateCluster,
Usage: "cbt updatecluster <cluster-id> [num-nodes=<num-nodes>]\n" +
" cluster-id Permanent, unique ID for the cluster in the instance\n" +
" num-nodes The new number of nodes\n\n" +
" Example: cbt updatecluster my-instance-c1 num-nodes=5",
Required: ProjectAndInstanceRequired,
},
{
Name: "version",
Desc: "Print the current cbt version",
do: doVersion,
Usage: "cbt version",
Required: NoneRequired,
},
{
Name: "waitforreplication",
Desc: "Block until all the completed writes have been replicated to all the clusters",
do: doWaitForReplicaiton,
Usage: "cbt waitforreplication <table-id>\n",
Required: ProjectAndInstanceRequired,
},
}
func doNotices(ctx context.Context, args ...string) {
fmt.Println(string(noticesContents))
}
func doCount(ctx context.Context, args ...string) {
if len(args) < 1 {
log.Fatal("usage: cbt count <table> [prefix=<row-key-prefix>]")
}
parsed, err := parseArgs(args[1:], []string{"prefix"})
if err != nil {
log.Fatal(err)
}
rr := bigtable.InfiniteRange("")
if prefix, ok := parsed["prefix"]; ok {
rr = bigtable.PrefixRange(prefix)
}
tbl := getTable(bigtable.ClientConfig{}, args[0])
filter := bigtable.ChainFilters(
bigtable.CellsPerRowLimitFilter(1),
bigtable.StripValueFilter(),
)
n := 0
err = tbl.ReadRows(ctx, rr, func(_ bigtable.Row) bool {
n++
return true
}, bigtable.RowFilter(filter))
if err != nil {
log.Fatalf("Reading rows: %v", err)
}
fmt.Println(n)
}
func parseFamilyType(s string) (bigtable.Type, error) {
if strings.ToLower(s) == "intsum" {
return bigtable.AggregateType{
Input: bigtable.Int64Type{},
Aggregator: bigtable.SumAggregator{}}, nil
}
return nil, fmt.Errorf("unknown type %s", s)
}
func parseFamilyText(family string) (string, bigtable.Family, error) {
famPolicy := strings.Split(family, ":")
var gcPolicy bigtable.GCPolicy
var tpe bigtable.Type
var err error = nil
if len(famPolicy) < 2 {
gcPolicy = bigtable.NoGcPolicy()
} else {
gcPolicy, err = parseGCPolicy(famPolicy[1])
if err != nil {
return "", bigtable.Family{}, err
}
if len(famPolicy) == 3 {
tpe, err = parseFamilyType(famPolicy[2])
}
}
return famPolicy[0], bigtable.Family{GCPolicy: gcPolicy, ValueType: tpe}, nil
}
func doCreateTable(ctx context.Context, args ...string) {
if len(args) < 1 {
log.Fatal("usage: cbt createtable <table> [families=family[:gcpolicy[:type]],...] [splits=split,...]")
}
tblConf := bigtable.TableConf{TableID: args[0]}
parsed, err := parseArgs(args[1:], []string{"families", "splits"})
if err != nil {
log.Fatal(err)
}
for key, val := range parsed {
chunks, err := csv.NewReader(strings.NewReader(val)).Read()
if err != nil {
log.Fatalf("Invalid %s arg format: %v", key, err)
}
switch key {
case "families":
tblConf.ColumnFamilies = make(map[string]bigtable.Family)
for _, family := range chunks {
familyId, familyConfig, err := parseFamilyText(family)
if err != nil {
log.Fatal(err)
}
tblConf.ColumnFamilies[familyId] = familyConfig
}
case "splits":
tblConf.SplitKeys = chunks
}
}
if err := getAdminClient().CreateTableFromConf(ctx, &tblConf); err != nil {
log.Fatalf("Creating table: %v", err)
}
}
func doCreateFamily(ctx context.Context, args ...string) {
if len(args) != 2 {
log.Fatal("usage: cbt createfamily <table> <family>")
}
familyId, config, err := parseFamilyText(args[1])
if err != nil {
log.Fatal(err)
}
err = getAdminClient().CreateColumnFamilyWithConfig(ctx, args[0], familyId, config)
if err != nil {
log.Fatalf("Creating column family: %v", err)
}
}
func doCreateInstance(ctx context.Context, args ...string) {
if len(args) < 6 {
log.Fatal("cbt createinstance <instance-id> <display-name> <cluster-id> <zone> <num-nodes> <storage type>")
}
numNodes, err := strconv.ParseInt(args[4], 0, 32)
if err != nil {
log.Fatalf("Bad num-nodes %q: %v", args[4], err)
}
sType, err := parseStorageType(args[5])
if err != nil {
log.Fatal(err)
}
ic := bigtable.InstanceWithClustersConfig{
InstanceID: args[0],
DisplayName: args[1],
Clusters: []bigtable.ClusterConfig{{
ClusterID: args[2],
Zone: args[3],
NumNodes: int32(numNodes),
StorageType: sType,
}},
}
err = getInstanceAdminClient().CreateInstanceWithClusters(ctx, &ic)
if err != nil {
log.Fatalf("Creating instance: %v", err)
}
}
func doCreateCluster(ctx context.Context, args ...string) {
if len(args) < 4 {
log.Fatal("usage: cbt createcluster <cluster-id> <zone> <num-nodes> <storage type>")
}
numNodes, err := strconv.ParseInt(args[2], 0, 32)
if err != nil {
log.Fatalf("Bad num_nodes %q: %v", args[2], err)
}
sType, err := parseStorageType(args[3])
if err != nil {
log.Fatal(err)
}
cc := bigtable.ClusterConfig{
InstanceID: config.Instance,
ClusterID: args[0],
Zone: args[1],
NumNodes: int32(numNodes),
StorageType: sType,
}
err = getInstanceAdminClient().CreateCluster(ctx, &cc)
if err != nil {
log.Fatalf("Creating cluster: %v", err)
}
}
func doUpdateCluster(ctx context.Context, args ...string) {
if len(args) < 2 {
log.Fatal("cbt updatecluster <cluster-id> [num-nodes=num-nodes]")
}
numNodes := int64(0)
parsed, err := parseArgs(args[1:], []string{"num-nodes"})
if err != nil {
log.Fatal(err)
}
if val, ok := parsed["num-nodes"]; ok {
numNodes, err = strconv.ParseInt(val, 0, 32)
if err != nil {
log.Fatalf("Bad num-nodes %q: %v", val, err)
}