-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
vtctl.go
4166 lines (3796 loc) · 152 KB
/
vtctl.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 2019 The Vitess Authors.
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 vtctl contains the implementation of all the Vitess management
// commands.
package vtctl
// The following comment section contains definitions for command arguments.
/*
COMMAND ARGUMENT DEFINITIONS
- cell, cell name: A cell is a location for a service. Generally, a cell
resides in only one cluster. In Vitess, the terms "cell" and
"data center" are interchangeable. The argument value is a
string that does not contain whitespace.
- tablet alias: A Tablet Alias uniquely identifies a vttablet. The argument
value is in the format
<code><cell name>-<uid></code>.
- keyspace, keyspace name: The name of a sharded database that contains one
or more tables. Vitess distributes keyspace shards into multiple
machines and provides an SQL interface to query the data. The
argument value must be a string that does not contain whitespace.
- port name: A port number. The argument value should be an integer between
<code>0</code> and <code>65535</code>, inclusive.
- shard, shard name: The name of a shard. The argument value is typically in
the format <code><range start>-<range end></code>.
- keyspace/shard: The name of a sharded database that contains one or more
tables as well as the shard associated with the command.
The keyspace must be identified by a string that does not
contain whitepace, while the shard is typically identified
by a string in the format
<code><range start>-<range end></code>.
- duration: The amount of time that the action queue should be blocked.
The value is a string that contains a possibly signed sequence
of decimal numbers, each with optional fraction and a unit
suffix, such as "300ms" or "1h45m". See the definition of the
Go language's <a
href="https://golang.org/pkg/time/#ParseDuration">ParseDuration</a>
function for more details. Note that, in practice, the value
should be a positively signed value.
- db type, tablet type: The vttablet's role. Valid values are:
-- backup: A replica copy of data that is offline to queries other than
for backup purposes
-- batch: A replicated copy of data for OLAP load patterns (typically for
MapReduce jobs)
-- drained: A tablet that is reserved for a background process. For example,
a tablet used by a vtworker process, where the tablet is likely
lagging in replication.
-- experimental: A replica copy of data that is ready but not serving query
traffic. The value indicates a special characteristic of
the tablet that indicates the tablet should not be
considered a potential primary. Vitess also does not
worry about lag for experimental tablets when reparenting.
-- primary: A primary copy of data
-- master: Deprecated, same as primary
-- rdonly: A replica copy of data for OLAP load patterns
-- replica: A replica copy of data ready to be promoted to primary
-- restore: A tablet that is restoring from a snapshot. Typically, this
happens at tablet startup, then it goes to its right state.
-- spare: A replica copy of data that is ready but not serving query traffic.
The data could be a potential primary tablet.
*/
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"vitess.io/vitess/go/textutil"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/cmd/vtctldclient/cli"
"vitess.io/vitess/go/flagutil"
"vitess.io/vitess/go/json2"
"vitess.io/vitess/go/protoutil"
"vitess.io/vitess/go/sqltypes"
hk "vitess.io/vitess/go/vt/hook"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/schema"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/topotools"
"vitess.io/vitess/go/vt/vtctl/workflow"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/wrangler"
tabletmanagerdatapb "vitess.io/vitess/go/vt/proto/tabletmanagerdata"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vschemapb "vitess.io/vitess/go/vt/proto/vschema"
vtctldatapb "vitess.io/vitess/go/vt/proto/vtctldata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/proto/vttime"
)
var (
// ErrUnknownCommand is returned for an unknown command
ErrUnknownCommand = errors.New("unknown command")
)
// Flags are exported for use in go/vt/vtctld.
var (
HealthCheckTopologyRefresh = flag.Duration("vtctl_healthcheck_topology_refresh", 30*time.Second, "refresh interval for re-reading the topology")
HealthcheckRetryDelay = flag.Duration("vtctl_healthcheck_retry_delay", 5*time.Second, "delay before retrying a failed healthcheck")
HealthCheckTimeout = flag.Duration("vtctl_healthcheck_timeout", time.Minute, "the health check timeout period")
)
type command struct {
name string
method func(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error
params string
help string // if help is empty, won't list the command
// if set, PrintAllCommands will not show this command
hidden bool
// deprecation support
deprecated bool
deprecatedBy string
}
type commandGroup struct {
name string
commands []command
}
// commandsMutex protects commands at init time. We use servenv, which calls
// all Run hooks in parallel.
var commandsMutex sync.Mutex
// TODO: Convert these commands to be automatically generated from flag parser.
var commands = []commandGroup{
{
"Tablets", []command{
{
name: "InitTablet",
method: commandInitTablet,
params: "[-allow_update] [-allow_different_shard] [-allow_master_override] [-parent] [-db_name_override=<db name>] [-hostname=<hostname>] [-mysql_port=<port>] [-port=<port>] [-grpc_port=<port>] [-tags=tag1:value1,tag2:value2] -keyspace=<keyspace> -shard=<shard> <tablet alias> <tablet type>",
help: "Initializes a tablet in the topology.",
deprecated: true,
},
{
name: "GetTablet",
method: commandGetTablet,
params: "<tablet alias>",
help: "Outputs a JSON structure that contains information about the Tablet.",
},
{
name: "UpdateTabletAddrs",
method: commandUpdateTabletAddrs,
params: "[-hostname <hostname>] [-ip-addr <ip addr>] [-mysql-port <mysql port>] [-vt-port <vt port>] [-grpc-port <grpc port>] <tablet alias> ",
help: "Updates the IP address and port numbers of a tablet.",
deprecated: true,
},
{
name: "DeleteTablet",
method: commandDeleteTablet,
params: "[-allow_primary] <tablet alias> ...",
help: "Deletes tablet(s) from the topology.",
},
{
name: "SetReadOnly",
method: commandSetReadOnly,
params: "<tablet alias>",
help: "Sets the tablet as read-only.",
},
{
name: "SetReadWrite",
method: commandSetReadWrite,
params: "<tablet alias>",
help: "Sets the tablet as read-write.",
},
{
name: "StartReplication",
method: commandStartReplication,
params: "<table alias>",
help: "Starts replication on the specified tablet.",
},
{
name: "StopReplication",
method: commandStopReplication,
params: "<tablet alias>",
help: "Stops replication on the specified tablet.",
},
{
name: "ChangeTabletType",
method: commandChangeTabletType,
params: "[-dry-run] <tablet alias> <tablet type>",
help: "Changes the db type for the specified tablet, if possible. This command is used primarily to arrange replicas, and it will not convert a primary.\n" +
"NOTE: This command automatically updates the serving graph.\n",
},
{
name: "Ping",
method: commandPing,
params: "<tablet alias>",
help: "Checks that the specified tablet is awake and responding to RPCs. This command can be blocked by other in-flight operations.",
},
{
name: "RefreshState",
method: commandRefreshState,
params: "<tablet alias>",
help: "Reloads the tablet record on the specified tablet.",
},
{
name: "RefreshStateByShard",
method: commandRefreshStateByShard,
params: "[-cells=c1,c2,...] <keyspace/shard>",
help: "Runs 'RefreshState' on all tablets in the given shard.",
},
{
name: "RunHealthCheck",
method: commandRunHealthCheck,
params: "<tablet alias>",
help: "Runs a health check on a remote tablet.",
},
{
name: "IgnoreHealthError",
method: commandIgnoreHealthError,
params: "<tablet alias> <ignore regexp>",
help: "Sets the regexp for health check errors to ignore on the specified tablet. The pattern has implicit ^$ anchors. Set to empty string or restart vttablet to stop ignoring anything.",
deprecated: true,
},
{
name: "Sleep",
method: commandSleep,
params: "<tablet alias> <duration>",
help: "Blocks the action queue on the specified tablet for the specified amount of time. This is typically used for testing.",
},
{
name: "ExecuteHook",
method: commandExecuteHook,
params: "<tablet alias> <hook name> [<param1=value1> <param2=value2> ...]",
help: "Runs the specified hook on the given tablet. A hook is a script that resides in the $VTROOT/vthook directory. You can put any script into that directory and use this command to run that script.\n" +
"For this command, the param=value arguments are parameters that the command passes to the specified hook.",
},
{
name: "ExecuteFetchAsApp",
method: commandExecuteFetchAsApp,
params: "[-max_rows=10000] [-json] [-use_pool] <tablet alias> <sql command>",
help: "Runs the given SQL command as a App on the remote tablet.",
},
{
name: "ExecuteFetchAsDba",
method: commandExecuteFetchAsDba,
params: "[-max_rows=10000] [-disable_binlogs] [-json] <tablet alias> <sql command>",
help: "Runs the given SQL command as a DBA on the remote tablet.",
},
{
name: "VReplicationExec",
method: commandVReplicationExec,
params: "[-json] <tablet alias> <sql command>",
help: "Runs the given VReplication command on the remote tablet.",
},
},
},
{
"Shards", []command{
{
name: "CreateShard",
method: commandCreateShard,
params: "[-force] [-parent] <keyspace/shard>",
help: "Creates the specified shard.",
},
{
name: "GetShard",
method: commandGetShard,
params: "<keyspace/shard>",
help: "Outputs a JSON structure that contains information about the Shard.",
},
{
name: "ValidateShard",
method: commandValidateShard,
params: "[-ping-tablets] <keyspace/shard>",
help: "Validates that all nodes that are reachable from this shard are consistent.",
},
{
name: "ShardReplicationPositions",
method: commandShardReplicationPositions,
params: "<keyspace/shard>",
help: "Shows the replication status of each replica in the shard graph. In this case, the status refers to the replication lag between the primary vttablet and the replica vttablet. In Vitess, data is always written to the primary vttablet first and then replicated to all replica vttablets. Output is sorted by tablet type, then replication position. Use ctrl-C to interrupt command and see partial result if needed.",
},
{
name: "ListShardTablets",
method: commandListShardTablets,
params: "<keyspace/shard>",
help: "Lists all tablets in the specified shard.",
},
{
name: "SetShardIsPrimaryServing",
method: commandSetShardIsPrimaryServing,
params: "<keyspace/shard> <is_serving>",
help: "Add or remove a shard from serving. This is meant as an emergency function. It does not rebuild any serving graph i.e. does not run 'RebuildKeyspaceGraph'.",
},
{
name: "SetShardTabletControl",
method: commandSetShardTabletControl,
params: "[--cells=c1,c2,...] [--denied_tables=t1,t2,...] [--remove] [--disable_query_service] <keyspace/shard> <tablet type>",
help: "Sets the TabletControl record for a shard and type. Only use this for an emergency fix or after a finished vertical split. The *MigrateServedFrom* and *MigrateServedType* commands set this field appropriately already. Always specify the denied_tables flag for vertical splits, but never for horizontal splits.\n" +
"To set the DisableQueryServiceFlag, keep 'denied_tables' empty, and set 'disable_query_service' to true or false. Useful to fix horizontal splits gone wrong.\n" +
"To change the list of denied tables, specify the 'denied_tables' parameter with the new list. Useful to fix tables that are being blocked after a vertical split.\n" +
"To just remove the ShardTabletControl entirely, use the 'remove' flag, useful after a vertical split is finished to remove serving restrictions.",
},
{
name: "UpdateSrvKeyspacePartition",
method: commandUpdateSrvKeyspacePartition,
params: "[--cells=c1,c2,...] [--remove] <keyspace/shard> <tablet type>",
help: "Updates KeyspaceGraph partition for a shard and type. Only use this for an emergency fix during an horizontal shard split. The *MigrateServedType* commands set this field appropriately already. Specify the remove flag, if you want the shard to be removed from the desired partition.",
},
{
name: "SourceShardDelete",
method: commandSourceShardDelete,
params: "<keyspace/shard> <uid>",
help: "Deletes the SourceShard record with the provided index. This is meant as an emergency cleanup function. It does not call RefreshState for the shard primary.",
},
{
name: "SourceShardAdd",
method: commandSourceShardAdd,
params: "[--key_range=<keyrange>] [--tables=<table1,table2,...>] <keyspace/shard> <uid> <source keyspace/shard>",
help: "Adds the SourceShard record with the provided index. This is meant as an emergency function. It does not call RefreshState for the shard primary.",
},
{
name: "ShardReplicationAdd",
method: commandShardReplicationAdd,
params: "<keyspace/shard> <tablet alias> <parent tablet alias>",
help: "Adds an entry to the replication graph in the given cell.",
hidden: true,
},
{
name: "ShardReplicationRemove",
method: commandShardReplicationRemove,
params: "<keyspace/shard> <tablet alias>",
help: "Removes an entry from the replication graph in the given cell.",
hidden: true,
},
{
name: "ShardReplicationFix",
method: commandShardReplicationFix,
params: "<cell> <keyspace/shard>",
help: "Walks through a ShardReplication object and fixes the first error that it encounters.",
},
{
name: "WaitForFilteredReplication",
method: commandWaitForFilteredReplication,
params: "[-max_delay <max_delay, default 30s>] <keyspace/shard>",
help: "Blocks until the specified shard has caught up with the filtered replication of its source shard.",
},
{
name: "RemoveShardCell",
method: commandRemoveShardCell,
params: "[-force] [-recursive] <keyspace/shard> <cell>",
help: "Removes the cell from the shard's Cells list.",
},
{
name: "DeleteShard",
method: commandDeleteShard,
params: "[-recursive] [-even_if_serving] <keyspace/shard> ...",
help: "Deletes the specified shard(s). In recursive mode, it also deletes all tablets belonging to the shard. Otherwise, there must be no tablets left in the shard.",
},
},
},
{
"Keyspaces", []command{
{
name: "CreateKeyspace",
method: commandCreateKeyspace,
params: "[-sharding_column_name=name] [-sharding_column_type=type] [-served_from=tablettype1:ks1,tablettype2:ks2,...] [-force] [-keyspace_type=type] [-base_keyspace=base_keyspace] [-snapshot_time=time] <keyspace name>",
help: "Creates the specified keyspace. keyspace_type can be NORMAL or SNAPSHOT. For a SNAPSHOT keyspace you must specify the name of a base_keyspace, and a snapshot_time in UTC, in RFC3339 time format, e.g. 2006-01-02T15:04:05+00:00",
},
{
name: "DeleteKeyspace",
method: commandDeleteKeyspace,
params: "[-recursive] <keyspace>",
help: "Deletes the specified keyspace. In recursive mode, it also recursively deletes all shards in the keyspace. Otherwise, there must be no shards left in the keyspace.",
},
{
name: "RemoveKeyspaceCell",
method: commandRemoveKeyspaceCell,
params: "[-force] [-recursive] <keyspace> <cell>",
help: "Removes the cell from the Cells list for all shards in the keyspace, and the SrvKeyspace for that keyspace in that cell.",
},
{
name: "GetKeyspace",
method: commandGetKeyspace,
params: "<keyspace>",
help: "Outputs a JSON structure that contains information about the Keyspace.",
},
{
name: "GetKeyspaces",
method: commandGetKeyspaces,
params: "",
help: "Outputs a sorted list of all keyspaces.",
},
{
name: "SetKeyspaceShardingInfo",
method: commandSetKeyspaceShardingInfo,
params: "[-force] <keyspace name> [<column name>] [<column type>]",
help: "Updates the sharding information for a keyspace.",
},
{
name: "SetKeyspaceServedFrom",
method: commandSetKeyspaceServedFrom,
params: "[-source=<source keyspace name>] [-remove] [-cells=c1,c2,...] <keyspace name> <tablet type>",
help: "Changes the ServedFromMap manually. This command is intended for emergency fixes. This field is automatically set when you call the *MigrateServedFrom* command. This command does not rebuild the serving graph.",
},
{
name: "RebuildKeyspaceGraph",
method: commandRebuildKeyspaceGraph,
params: "[-cells=c1,c2,...] [-allow_partial] <keyspace> ...",
help: "Rebuilds the serving data for the keyspace. This command may trigger an update to all connected clients.",
},
{
name: "ValidateKeyspace",
method: commandValidateKeyspace,
params: "[-ping-tablets] <keyspace name>",
help: "Validates that all nodes reachable from the specified keyspace are consistent.",
},
{
name: "Reshard",
method: commandReshard,
params: "[-source_shards=<source_shards>] [-target_shards=<target_shards>] [-cells=<cells>] [-tablet_types=<source_tablet_types>] [-skip_schema_copy] <action> 'action must be one of the following: Create, Complete, Cancel, SwitchTraffic, ReverseTrafffic, Show, or Progress' <keyspace.workflow>",
help: "Start a Resharding process. Example: Reshard -cells='zone1,alias1' -tablet_types='primary,replica,rdonly' ks.workflow001 '0' '-80,80-'",
},
{
name: "MoveTables",
method: commandMoveTables,
params: "[-source=<sourceKs>] [-tables=<tableSpecs>] [-cells=<cells>] [-tablet_types=<source_tablet_types>] [-all] [-exclude=<tables>] [-auto_start] [-stop_after_copy] <action> 'action must be one of the following: Create, Complete, Cancel, SwitchTraffic, ReverseTrafffic, Show, or Progress' <targetKs.workflow>",
help: `Move table(s) to another keyspace, table_specs is a list of tables or the tables section of the vschema for the target keyspace. Example: '{"t1":{"column_vindexes": [{"column": "id1", "name": "hash"}]}, "t2":{"column_vindexes": [{"column": "id2", "name": "hash"}]}}'. In the case of an unsharded target keyspace the vschema for each table may be empty. Example: '{"t1":{}, "t2":{}}'.`,
},
{
name: "Migrate",
method: commandMigrate,
params: "[-cells=<cells>] [-tablet_types=<source_tablet_types>] -workflow=<workflow> <source_keyspace> <target_keyspace> <table_specs>",
help: `Move table(s) to another keyspace, table_specs is a list of tables or the tables section of the vschema for the target keyspace. Example: '{"t1":{"column_vindexes": [{"column": "id1", "name": "hash"}]}, "t2":{"column_vindexes": [{"column": "id2", "name": "hash"}]}}'. In the case of an unsharded target keyspace the vschema for each table may be empty. Example: '{"t1":{}, "t2":{}}'.`,
},
{
name: "DropSources",
method: commandDropSources,
params: "[-dry_run] [-rename_tables] <keyspace.workflow>",
help: "After a MoveTables or Resharding workflow cleanup unused artifacts like source tables, source shards and denylists",
},
{
name: "CreateLookupVindex",
method: commandCreateLookupVindex,
params: "[-cell=<source_cells> DEPRECATED] [-cells=<source_cells>] [-tablet_types=<source_tablet_types>] <keyspace> <json_spec>",
help: `Create and backfill a lookup vindex. the json_spec must contain the vindex and colvindex specs for the new lookup.`,
},
{
name: "ExternalizeVindex",
method: commandExternalizeVindex,
params: "<keyspace>.<vindex>",
help: `Externalize a backfilled vindex.`,
},
{
name: "Materialize",
method: commandMaterialize,
params: `[-cells=<cells>] [-tablet_types=<source_tablet_types>] <json_spec>, example : '{"workflow": "aaa", "source_keyspace": "source", "target_keyspace": "target", "table_settings": [{"target_table": "customer", "source_expression": "select * from customer", "create_ddl": "copy"}]}'`,
help: "Performs materialization based on the json spec. Is used directly to form VReplication rules, with an optional step to copy table structure/DDL.",
},
{
name: "SplitClone",
method: commandSplitClone,
params: "<keyspace> <from_shards> <to_shards>",
help: "Start the SplitClone process to perform horizontal resharding. Example: SplitClone ks '0' '-80,80-'",
deprecated: true,
},
{
name: "VerticalSplitClone",
method: commandVerticalSplitClone,
params: "<from_keyspace> <to_keyspace> <tables>",
help: "Start the VerticalSplitClone process to perform vertical resharding. Example: SplitClone from_ks to_ks 'a,/b.*/'",
deprecated: true,
},
{
name: "VDiff",
method: commandVDiff,
params: "[-source_cell=<cell>] [-target_cell=<cell>] [-tablet_types=primary,replica,rdonly] [-filtered_replication_wait_time=30s] <keyspace.workflow>",
help: "Perform a diff of all tables in the workflow",
},
{
name: "MigrateServedTypes",
method: commandMigrateServedTypes,
params: "[-cells=c1,c2,...] [-reverse] [-skip-refresh-state] [-filtered_replication_wait_time=30s] [-reverse_replication=false] <keyspace/shard> <served tablet type>",
help: "Migrates a serving type from the source shard to the shards that it replicates to. This command also rebuilds the serving graph. The <keyspace/shard> argument can specify any of the shards involved in the migration.",
},
{
name: "MigrateServedFrom",
method: commandMigrateServedFrom,
params: "[-cells=c1,c2,...] [-reverse] [-filtered_replication_wait_time=30s] <destination keyspace/shard> <served tablet type>",
help: "Makes the <destination keyspace/shard> serve the given type. This command also rebuilds the serving graph.",
},
{
name: "SwitchReads",
method: commandSwitchReads,
params: "[-cells=c1,c2,...] [-reverse] -tablet_type={replica|rdonly} [-dry_run] <keyspace.workflow>",
help: "Switch read traffic for the specified workflow.",
},
{
name: "SwitchWrites",
method: commandSwitchWrites,
params: "[-timeout=30s] [-reverse] [-reverse_replication=true] [-dry_run] <keyspace.workflow>",
help: "Switch write traffic for the specified workflow.",
},
{
name: "CancelResharding",
method: commandCancelResharding,
params: "<keyspace/shard>",
help: "Permanently cancels a resharding in progress. All resharding related metadata will be deleted.",
},
{
name: "ShowResharding",
method: commandShowResharding,
params: "<keyspace/shard>",
help: "Displays all metadata about a resharding in progress.",
},
{
name: "FindAllShardsInKeyspace",
method: commandFindAllShardsInKeyspace,
params: "<keyspace>",
help: "Displays all of the shards in the specified keyspace.",
},
{
name: "WaitForDrain",
method: commandWaitForDrain,
params: "[-timeout <duration>] [-retry_delay <duration>] [-initial_wait <duration>] <keyspace/shard> <served tablet type>",
help: "Blocks until no new queries were observed on all tablets with the given tablet type in the specified keyspace. " +
" This can be used as sanity check to ensure that the tablets were drained after running vtctl MigrateServedTypes " +
" and vtgate is no longer using them. If -timeout is set, it fails when the timeout is reached.",
},
{
name: "Mount",
method: commandMount,
params: "[-topo_type=etcd2|consul|zookeeper] [-topo_server=topo_url] [-topo_root=root_topo_node> [-unmount] [-list] [-show] [<cluster_name>]",
help: "Add/Remove/Display/List external cluster(s) to this vitess cluster",
},
},
},
{
"Generic", []command{
{
name: "Validate",
method: commandValidate,
params: "[-ping-tablets]",
help: "Validates that all nodes reachable from the global replication graph and that all tablets in all discoverable cells are consistent.",
},
{
name: "ListAllTablets",
method: commandListAllTablets,
params: "[-keyspace=''] [-tablet_type=<PRIMARY,REPLICA,RDONLY,SPARE>] [<cell_name1>,<cell_name2>,...]",
help: "Lists all tablets in an awk-friendly way.",
},
{
name: "ListTablets",
method: commandListTablets,
params: "<tablet alias> ...",
help: "Lists specified tablets in an awk-friendly way.",
},
{
name: "GenerateShardRanges",
method: commandGenerateShardRanges,
params: "[-num_shards 2]",
help: "Generates shard ranges assuming a keyspace with N shards.",
},
{
name: "Panic",
method: commandPanic,
params: "",
help: "Triggers a panic on the server side, to test the handling.",
hidden: true,
},
},
},
{
"Schema, Version, Permissions", []command{
{
name: "GetSchema",
method: commandGetSchema,
params: "[-tables=<table1>,<table2>,...] [-exclude_tables=<table1>,<table2>,...] [-include-views] <tablet alias>",
help: "Displays the full schema for a tablet, or just the schema for the specified tables in that tablet.",
},
{
name: "ReloadSchema",
method: commandReloadSchema,
params: "<tablet alias>",
help: "Reloads the schema on a remote tablet.",
},
{
name: "ReloadSchemaShard",
method: commandReloadSchemaShard,
params: "[-concurrency=10] [-include_primary=false] <keyspace/shard>",
help: "Reloads the schema on all the tablets in a shard.",
},
{
name: "ReloadSchemaKeyspace",
method: commandReloadSchemaKeyspace,
params: "[-concurrency=10] [-include_primary=false] <keyspace>",
help: "Reloads the schema on all the tablets in a keyspace.",
},
{
name: "ValidateSchemaShard",
method: commandValidateSchemaShard,
params: "[-exclude_tables=''] [-include-views] [-include-vschema] <keyspace/shard>",
help: "Validates that the schema on primary tablet matches all of the replica tablets.",
},
{
name: "ValidateSchemaKeyspace",
method: commandValidateSchemaKeyspace,
params: "[-exclude_tables=''] [-include-views] [-skip-no-primary] [-include-vschema] <keyspace name>",
help: "Validates that the schema on the primary tablet for shard 0 matches the schema on all of the other tablets in the keyspace.",
},
{
name: "ApplySchema",
method: commandApplySchema,
params: "[-allow_long_unavailability] [-wait_replicas_timeout=10s] [-ddl_strategy=<ddl_strategy>] [-uuid_list=<comma_separated_uuids>] [-migration_context=<unique-request-context>] [-skip_preflight] {-sql=<sql> || -sql-file=<filename>} <keyspace>",
help: "Applies the schema change to the specified keyspace on every primary, running in parallel on all shards. The changes are then propagated to replicas via replication. If -allow_long_unavailability is set, schema changes affecting a large number of rows (and possibly incurring a longer period of unavailability) will not be rejected. -ddl_strategy is used to instruct migrations via vreplication, gh-ost or pt-osc with optional parameters. -migration_context allows the user to specify a custom request context for online DDL migrations. If -skip_preflight, SQL goes directly to shards without going through sanity checks.",
},
{
name: "CopySchemaShard",
method: commandCopySchemaShard,
params: "[-tables=<table1>,<table2>,...] [-exclude_tables=<table1>,<table2>,...] [-include-views] [-skip-verify] [-wait_replicas_timeout=10s] {<source keyspace/shard> || <source tablet alias>} <destination keyspace/shard>",
help: "Copies the schema from a source shard's primary (or a specific tablet) to a destination shard. The schema is applied directly on the primary of the destination shard, and it is propagated to the replicas through binlogs.",
},
{
name: "OnlineDDL",
method: commandOnlineDDL,
params: "[-json] <keyspace> <command> [<migration_uuid>]",
help: "Operates on online DDL (migrations). Examples:" +
" \nvtctl OnlineDDL test_keyspace show 82fa54ac_e83e_11ea_96b7_f875a4d24e90" +
" \nvtctl OnlineDDL test_keyspace show all" +
" \nvtctl OnlineDDL test_keyspace show running" +
" \nvtctl OnlineDDL test_keyspace show complete" +
" \nvtctl OnlineDDL test_keyspace show failed" +
" \nvtctl OnlineDDL test_keyspace retry 82fa54ac_e83e_11ea_96b7_f875a4d24e90" +
" \nvtctl OnlineDDL test_keyspace cancel 82fa54ac_e83e_11ea_96b7_f875a4d24e90",
},
{
name: "ValidateVersionShard",
method: commandValidateVersionShard,
params: "<keyspace/shard>",
help: "Validates that the version on primary matches all of the replicas.",
},
{
name: "ValidateVersionKeyspace",
method: commandValidateVersionKeyspace,
params: "<keyspace name>",
help: "Validates that the version on primary of shard 0 matches all of the other tablets in the keyspace.",
},
{
name: "GetPermissions",
method: commandGetPermissions,
params: "<tablet alias>",
help: "Displays the permissions for a tablet.",
},
{
name: "ValidatePermissionsShard",
method: commandValidatePermissionsShard,
params: "<keyspace/shard>",
help: "Validates that the permissions on primary match all the replicas.",
},
{
name: "ValidatePermissionsKeyspace",
method: commandValidatePermissionsKeyspace,
params: "<keyspace name>",
help: "Validates that the permissions on primary of shard 0 match those of all of the other tablets in the keyspace.",
},
{
name: "GetVSchema",
method: commandGetVSchema,
params: "<keyspace>",
help: "Displays the VTGate routing schema.",
},
{
name: "ApplyVSchema",
method: commandApplyVSchema,
params: "{-vschema=<vschema> || -vschema_file=<vschema file> || -sql=<sql> || -sql_file=<sql file>} [-cells=c1,c2,...] [-skip_rebuild] [-dry-run] <keyspace>",
help: "Applies the VTGate routing schema to the provided keyspace. Shows the result after application.",
},
{
name: "GetRoutingRules",
method: commandGetRoutingRules,
params: "",
help: "Displays the VSchema routing rules.",
},
{
name: "ApplyRoutingRules",
method: commandApplyRoutingRules,
params: "{-rules=<rules> || -rules_file=<rules_file>} [-cells=c1,c2,...] [-skip_rebuild] [-dry-run]",
help: "Applies the VSchema routing rules.",
},
{
name: "RebuildVSchemaGraph",
method: commandRebuildVSchemaGraph,
params: "[-cells=c1,c2,...]",
help: "Rebuilds the cell-specific SrvVSchema from the global VSchema objects in the provided cells (or all cells if none provided).",
},
},
},
{
"Serving Graph", []command{
{
name: "GetSrvKeyspaceNames",
method: commandGetSrvKeyspaceNames,
params: "<cell>",
help: "Outputs a list of keyspace names.",
},
{
name: "GetSrvKeyspace",
method: commandGetSrvKeyspace,
params: "<cell> <keyspace>",
help: "Outputs a JSON structure that contains information about the SrvKeyspace.",
},
{
name: "GetSrvVSchema",
method: commandGetSrvVSchema,
params: "<cell>",
help: "Outputs a JSON structure that contains information about the SrvVSchema.",
},
{
name: "DeleteSrvVSchema",
method: commandDeleteSrvVSchema,
params: "<cell>",
help: "Deletes the SrvVSchema object in the given cell.",
},
},
},
{
"Replication Graph", []command{
{
name: "GetShardReplication",
method: commandGetShardReplication,
params: "<cell> <keyspace/shard>",
help: "Outputs a JSON structure that contains information about the ShardReplication.",
},
},
},
{
"Workflow", []command{
{
name: "VExec",
method: commandVExec,
params: "<ks.workflow> <query> --dry-run",
help: "Runs query on all tablets in workflow. Example: VExec merchant.morders \"update _vt.vreplication set Status='Running'\"",
},
},
},
{
"Workflow", []command{
{
name: "Workflow",
method: commandWorkflow,
params: "<ks.workflow> <action> --dry-run",
help: "Start/Stop/Delete/Show/ListAll/Tags Workflow on all target tablets in workflow. Example: Workflow merchant.morders Start",
},
},
},
}
func init() {
// This cannot be in the static `commands` slice, as it causes an init cycle.
// Specifically, we would see:
// `commands` => refers to `commandHelp` => refers to `PrintAllCommands` => refers to `commands`
addCommand("Generic", command{
name: "Help",
method: commandHelp,
params: "[command name]",
help: "Prints the list of available commands, or help on a specific command.",
})
}
func addCommand(groupName string, c command) {
commandsMutex.Lock()
defer commandsMutex.Unlock()
for i, group := range commands {
if group.name == groupName {
commands[i].commands = append(commands[i].commands, c)
return
}
}
panic(fmt.Errorf("trying to add to missing group %v", groupName))
}
func addCommandGroup(groupName string) {
commandsMutex.Lock()
defer commandsMutex.Unlock()
commands = append(commands, commandGroup{
name: groupName,
})
}
func fmtMapAwkable(m map[string]string) string {
pairs := make([]string, len(m))
i := 0
for k, v := range m {
pairs[i] = fmt.Sprintf("%v: %q", k, v)
i++
}
sort.Strings(pairs)
return "[" + strings.Join(pairs, " ") + "]"
}
func fmtTabletAwkable(ti *topo.TabletInfo) string {
keyspace := ti.Keyspace
shard := ti.Shard
if keyspace == "" {
keyspace = "<null>"
}
if shard == "" {
shard = "<null>"
}
mtst := "<null>"
// special case for old primary that hasn't updated topo yet
if ti.PrimaryTermStartTime != nil && ti.PrimaryTermStartTime.Seconds > 0 {
mtst = logutil.ProtoToTime(ti.PrimaryTermStartTime).Format(time.RFC3339)
}
return fmt.Sprintf("%v %v %v %v %v %v %v %v", topoproto.TabletAliasString(ti.Alias), keyspace, shard, topoproto.TabletTypeLString(ti.Type), ti.Addr(), ti.MysqlAddr(), fmtMapAwkable(ti.Tags), mtst)
}
// getFileParam returns a string containing either flag is not "",
// or the content of the file named flagFile
func getFileParam(flag, flagFile, name string) (string, error) {
if flag != "" {
if flagFile != "" {
return "", fmt.Errorf("action requires only one of %v or %v-file", name, name)
}
return flag, nil
}
if flagFile == "" {
return "", fmt.Errorf("action requires one of %v or %v-file", name, name)
}
data, err := os.ReadFile(flagFile)
if err != nil {
return "", fmt.Errorf("cannot read file %v: %v", flagFile, err)
}
return string(data), nil
}
// keyspaceParamsToKeyspaces builds a list of keyspaces.
// It supports topology-based wildcards, and plain wildcards.
// For instance:
// us* // using plain matching
// * // using plain matching
func keyspaceParamsToKeyspaces(ctx context.Context, wr *wrangler.Wrangler, params []string) ([]string, error) {
result := make([]string, 0, len(params))
for _, param := range params {
if len(param) == 0 {
return nil, fmt.Errorf("empty keyspace param in list")
}
if param[0] == '/' {
// this is a topology-specific path
result = append(result, params...)
} else {
// this is not a path, so assume a keyspace name,
// possibly with wildcards
keyspaces, err := wr.TopoServer().ResolveKeyspaceWildcard(ctx, param)
if err != nil {
return nil, fmt.Errorf("failed to resolve keyspace wildcard %v: %v", param, err)
}
result = append(result, keyspaces...)
}
}
return result, nil
}
// shardParamsToKeyspaceShards builds a list of keyspace/shard pairs.
// It supports topology-based wildcards, and plain wildcards.
// For instance:
// user/* // using plain matching
// */0 // using plain matching
func shardParamsToKeyspaceShards(ctx context.Context, wr *wrangler.Wrangler, params []string) ([]topo.KeyspaceShard, error) {
result := make([]topo.KeyspaceShard, 0, len(params))
for _, param := range params {
if param[0] == '/' {
// this is a topology-specific path
for _, path := range params {
keyspace, shard, err := topoproto.ParseKeyspaceShard(path)
if err != nil {
return nil, err
}
result = append(result, topo.KeyspaceShard{Keyspace: keyspace, Shard: shard})
}
} else {
// this is not a path, so assume a keyspace
// name / shard name, each possibly with wildcards
keyspaceShards, err := wr.TopoServer().ResolveShardWildcard(ctx, param)
if err != nil {
return nil, fmt.Errorf("failed to resolve keyspace/shard wildcard %v: %v", param, err)
}
result = append(result, keyspaceShards...)
}
}
return result, nil
}
// tabletParamsToTabletAliases takes multiple params and converts them
// to tablet aliases.
func tabletParamsToTabletAliases(params []string) ([]*topodatapb.TabletAlias, error) {
result := make([]*topodatapb.TabletAlias, len(params))
var err error
for i, param := range params {
result[i], err = topoproto.ParseTabletAlias(param)
if err != nil {
return nil, err
}
}
return result, nil
}
// parseTabletType parses the string tablet type and verifies
// it is an accepted one
func parseTabletType(param string, types []topodatapb.TabletType) (topodatapb.TabletType, error) {
tabletType, err := topoproto.ParseTabletType(param)
if err != nil {
return topodatapb.TabletType_UNKNOWN, fmt.Errorf("invalid tablet type %v: %v", param, err)
}
if !topoproto.IsTypeInList(topodatapb.TabletType(tabletType), types) {
return topodatapb.TabletType_UNKNOWN, fmt.Errorf("type %v is not one of: %v", tabletType, strings.Join(topoproto.MakeStringTypeList(types), " "))
}
return tabletType, nil
}
func commandInitTablet(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
dbNameOverride := subFlags.String("db_name_override", "", "Overrides the name of the database that the vttablet uses")
allowUpdate := subFlags.Bool("allow_update", false, "Use this flag to force initialization if a tablet with the same name already exists. Use with caution.")
allowPrimaryOverride := subFlags.Bool("allow_master_override", false, "Use this flag to force initialization if a tablet is created as primary, and a primary for the keyspace/shard already exists. Use with caution.")
createShardAndKeyspace := subFlags.Bool("parent", false, "Creates the parent shard and keyspace if they don't yet exist")
hostname := subFlags.String("hostname", "", "The server on which the tablet is running")
mysqlHost := subFlags.String("mysql_host", "", "The mysql host for the mysql server")
mysqlPort := subFlags.Int("mysql_port", 0, "The mysql port for the mysql server")
port := subFlags.Int("port", 0, "The main port for the vttablet process")
grpcPort := subFlags.Int("grpc_port", 0, "The gRPC port for the vttablet process")
keyspace := subFlags.String("keyspace", "", "The keyspace to which this tablet belongs")
shard := subFlags.String("shard", "", "The shard to which this tablet belongs")
var tags flagutil.StringMapValue
subFlags.Var(&tags, "tags", "A comma-separated list of key:value pairs that are used to tag the tablet")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 2 {
return fmt.Errorf("the <tablet alias> and <tablet type> arguments are both required for the InitTablet command")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletType, err := parseTabletType(subFlags.Arg(1), topoproto.AllTabletTypes)
if err != nil {
return err
}
// create tablet record
tablet := &topodatapb.Tablet{
Alias: tabletAlias,
Hostname: *hostname,
MysqlHostname: *mysqlHost,
PortMap: make(map[string]int32),
Keyspace: *keyspace,
Shard: *shard,
Type: tabletType,
DbNameOverride: *dbNameOverride,
Tags: tags,
}
if *port != 0 {
tablet.PortMap["vt"] = int32(*port)
}
if *mysqlPort != 0 {