forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vtctl.go
2299 lines (2099 loc) · 86.9 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 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// 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="http://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 slaved copy of data that is offline to queries other than
for backup purposes
-- batch: A slaved copy of data for OLAP load patterns (typically for
MapReduce jobs)
-- worker: A tablet that is in use by a vtworker process. The tablet is likely
lagging in replication.
-- experimental: A slaved 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 master. Vitess also does not
worry about lag for experimental tablets when reparenting.
-- master: A primary copy of data
-- rdonly: A slaved copy of data for OLAP load patterns
-- replica: A slaved copy of data ready to be promoted to master
-- restore: A tablet that is restoring from a snapshot. Typically, this
happens at tablet startup, then it goes to its right state.
-- schema_apply: A slaved copy of data that had been serving query traffic
but that is now applying a schema change. Following the
change, the tablet will revert to its serving type.
-- snapshot_source: A slaved copy of data where mysqld is <b>not</b>
running and where Vitess is serving data files to
clone slaves. Use this command to enter this mode:
<pre>vtctl Snapshot -server-mode ...</pre>
Use this command to exit this mode:
<pre>vtctl SnapshotSourceEnd ...</pre>
-- spare: A slaved copy of data that is ready but not serving query traffic.
The data could be a potential master tablet.
*/
package vtctl
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"sort"
"strconv"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/flagutil"
"github.com/youtube/vitess/go/sqltypes"
hk "github.com/youtube/vitess/go/vt/hook"
"github.com/youtube/vitess/go/vt/key"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/mysqlctl/replication"
"github.com/youtube/vitess/go/vt/schemamanager"
"github.com/youtube/vitess/go/vt/tabletserver/tabletconn"
"github.com/youtube/vitess/go/vt/topo"
"github.com/youtube/vitess/go/vt/topo/topoproto"
"github.com/youtube/vitess/go/vt/topotools"
"github.com/youtube/vitess/go/vt/wrangler"
replicationdatapb "github.com/youtube/vitess/go/vt/proto/replicationdata"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
vschemapb "github.com/youtube/vitess/go/vt/proto/vschema"
)
var (
// ErrUnknownCommand is returned for an unknown command
ErrUnknownCommand = errors.New("unknown command")
)
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
}
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
var commands = []commandGroup{
{
"Tablets", []command{
{"InitTablet", commandInitTablet,
"[-allow_update] [-allow_different_shard] [-allow_master_override] [-parent] [-db_name_override=<db name>] [-hostname=<hostname>] [-mysql_port=<port>] [-port=<port>] [-grpc_port=<port>] -keyspace=<keyspace> -shard=<shard> <tablet alias> <tablet type>",
"Initializes a tablet in the topology.\n"},
{"GetTablet", commandGetTablet,
"<tablet alias>",
"Outputs a JSON structure that contains information about the Tablet."},
{"UpdateTabletAddrs", commandUpdateTabletAddrs,
"[-hostname <hostname>] [-ip-addr <ip addr>] [-mysql-port <mysql port>] [-vt-port <vt port>] [-grpc-port <grpc port>] <tablet alias> ",
"Updates the IP address and port numbers of a tablet."},
{"DeleteTablet", commandDeleteTablet,
"[-allow_master] <tablet alias> ...",
"Deletes tablet(s) from the topology."},
{"SetReadOnly", commandSetReadOnly,
"<tablet alias>",
"Sets the tablet as read-only."},
{"SetReadWrite", commandSetReadWrite,
"<tablet alias>",
"Sets the tablet as read-write."},
{"StartSlave", commandStartSlave,
"<tablet alias>",
"Starts replication on the specified slave."},
{"StopSlave", commandStopSlave,
"<tablet alias>",
"Stops replication on the specified slave."},
{"ChangeSlaveType", commandChangeSlaveType,
"[-dry-run] <tablet alias> <tablet type>",
"Changes the db type for the specified tablet, if possible. This command is used primarily to arrange replicas, and it will not convert a master.\n" +
"NOTE: This command automatically updates the serving graph.\n"},
{"Ping", commandPing,
"<tablet alias>",
"Checks that the specified tablet is awake and responding to RPCs. This command can be blocked by other in-flight operations."},
{"RefreshState", commandRefreshState,
"<tablet alias>",
"Reloads the tablet record on the specified tablet."},
{"RunHealthCheck", commandRunHealthCheck,
"<tablet alias>",
"Runs a health check on a remote tablet."},
{"IgnoreHealthError", commandIgnoreHealthError,
"<tablet alias> <ignore regexp>",
"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."},
{"Sleep", commandSleep,
"<tablet alias> <duration>",
"Blocks the action queue on the specified tablet for the specified amount of time. This is typically used for testing."},
{"Backup", commandBackup,
"[-concurrency=4] <tablet alias>",
"Stops mysqld and uses the BackupStorage service to store a new backup. This function also remembers if the tablet was replicating so that it can restore the same state after the backup completes."},
{"ExecuteHook", commandExecuteHook,
"<tablet alias> <hook name> [<param1=value1> <param2=value2> ...]",
"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."},
{"ExecuteFetchAsDba", commandExecuteFetchAsDba,
"[-max_rows=10000] [-disable_binlogs] [-json] <tablet alias> <sql command>",
"Runs the given SQL command as a DBA on the remote tablet."},
},
},
{
"Shards", []command{
{"CreateShard", commandCreateShard,
"[-force] [-parent] <keyspace/shard>",
"Creates the specified shard."},
{"GetShard", commandGetShard,
"<keyspace/shard>",
"Outputs a JSON structure that contains information about the Shard."},
{"TabletExternallyReparented", commandTabletExternallyReparented,
"<tablet alias>",
"Changes metadata in the topology server to acknowledge a shard master change performed by an external tool. See the Reparenting guide for more information:" +
"https://github.com/youtube/vitess/blob/master/doc/Reparenting.md#external-reparents."},
{"ValidateShard", commandValidateShard,
"[-ping-tablets] <keyspace/shard>",
"Validates that all nodes that are reachable from this shard are consistent."},
{"ShardReplicationPositions", commandShardReplicationPositions,
"<keyspace/shard>",
"Shows the replication status of each slave machine in the shard graph. In this case, the status refers to the replication lag between the master vttablet and the slave vttablet. In Vitess, data is always written to the master vttablet first and then replicated to all slave vttablets. Output is sorted by tablet type, then replication position. Use ctrl-C to interrupt command and see partial result if needed."},
{"ListShardTablets", commandListShardTablets,
"<keyspace/shard>",
"Lists all tablets in the specified shard."},
{"SetShardServedTypes", commandSetShardServedTypes,
"<keyspace/shard> [<served tablet type1>,<served tablet type2>,...]",
"Sets a given shard's served tablet types. Does not rebuild any serving graph."},
{"SetShardTabletControl", commandSetShardTabletControl,
"[--cells=c1,c2,...] [--blacklisted_tables=t1,t2,...] [--remove] [--disable_query_service] <keyspace/shard> <tablet type>",
"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 blacklisted_tables flag for vertical splits, but never for horizontal splits."},
{"SourceShardDelete", commandSourceShardDelete,
"<keyspace/shard> <uid>",
"Deletes the SourceShard record with the provided index. This is meant as an emergency cleanup function. It does not call RefreshState for the shard master."},
{"SourceShardAdd", commandSourceShardAdd,
"[--key_range=<keyrange>] [--tables=<table1,table2,...>] <keyspace/shard> <uid> <source keyspace/shard>",
"Adds the SourceShard record with the provided index. This is meant as an emergency function. It does not call RefreshState for the shard master."},
{"ShardReplicationAdd", commandShardReplicationAdd,
"<keyspace/shard> <tablet alias> <parent tablet alias>",
"HIDDEN Adds an entry to the replication graph in the given cell."},
{"ShardReplicationRemove", commandShardReplicationRemove,
"<keyspace/shard> <tablet alias>",
"HIDDEN Removes an entry from the replication graph in the given cell."},
{"ShardReplicationFix", commandShardReplicationFix,
"<cell> <keyspace/shard>",
"Walks through a ShardReplication object and fixes the first error that it encounters."},
{"WaitForFilteredReplication", commandWaitForFilteredReplication,
"[-max_delay <max_delay, default 30s>] <keyspace/shard>",
"Blocks until the specified shard has caught up with the filtered replication of its source shard."},
{"RemoveShardCell", commandRemoveShardCell,
"[-force] [-recursive] <keyspace/shard> <cell>",
"Removes the cell from the shard's Cells list."},
{"DeleteShard", commandDeleteShard,
"[-recursive] <keyspace/shard> ...",
"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{
{"CreateKeyspace", commandCreateKeyspace,
"[-sharding_column_name=name] [-sharding_column_type=type] [-served_from=tablettype1:ks1,tablettype2,ks2,...] [-force] <keyspace name>",
"Creates the specified keyspace."},
{"DeleteKeyspace", commandDeleteKeyspace,
"[-recursive] <keyspace>",
"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."},
{"RemoveKeyspaceCell", commandRemoveKeyspaceCell,
"[-force] [-recursive] <keyspace> <cell>",
"Removes the cell from the Cells list for all shards in the keyspace."},
{"GetKeyspace", commandGetKeyspace,
"<keyspace>",
"Outputs a JSON structure that contains information about the Keyspace."},
{"GetKeyspaces", commandGetKeyspaces,
"",
"Outputs a sorted list of all keyspaces."},
{"SetKeyspaceShardingInfo", commandSetKeyspaceShardingInfo,
"[-force] <keyspace name> [<column name>] [<column type>]",
"Updates the sharding information for a keyspace."},
{"SetKeyspaceServedFrom", commandSetKeyspaceServedFrom,
"[-source=<source keyspace name>] [-remove] [-cells=c1,c2,...] <keyspace name> <tablet type>",
"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."},
{"RebuildKeyspaceGraph", commandRebuildKeyspaceGraph,
"[-cells=c1,c2,...] <keyspace> ...",
"Rebuilds the serving data for the keyspace. This command may trigger an update to all connected clients."},
{"ValidateKeyspace", commandValidateKeyspace,
"[-ping-tablets] <keyspace name>",
"Validates that all nodes reachable from the specified keyspace are consistent."},
{"MigrateServedTypes", commandMigrateServedTypes,
"[-cells=c1,c2,...] [-reverse] [-skip-refresh-state] <keyspace/shard> <served tablet type>",
"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."},
{"MigrateServedFrom", commandMigrateServedFrom,
"[-cells=c1,c2,...] [-reverse] <destination keyspace/shard> <served tablet type>",
"Makes the <destination keyspace/shard> serve the given type. This command also rebuilds the serving graph."},
{"FindAllShardsInKeyspace", commandFindAllShardsInKeyspace,
"<keyspace>",
"Displays all of the shards in the specified keyspace."},
{"WaitForDrain", commandWaitForDrain,
"[-timeout <duration>] <keyspace/shard> <served tablet type>",
"Blocks until no new queries were observed on all tablets with the given tablet type in the specifed 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."},
},
},
{
"Generic", []command{
{"RebuildReplicationGraph", commandRebuildReplicationGraph,
"<cell1>,<cell2>... <keyspace1>,<keyspace2>,...",
"HIDDEN This takes the Thor's hammer approach of recovery and should only be used in emergencies. cell1,cell2,... are the canonical source of data for the system. This function uses that canonical data to recover the replication graph, at which point further auditing with Validate can reveal any remaining issues."},
{"Validate", commandValidate,
"[-ping-tablets]",
"Validates that all nodes reachable from the global replication graph and that all tablets in all discoverable cells are consistent."},
{"ListAllTablets", commandListAllTablets,
"<cell name>",
"Lists all tablets in an awk-friendly way."},
{"ListTablets", commandListTablets,
"<tablet alias> ...",
"Lists specified tablets in an awk-friendly way."},
{"Panic", commandPanic,
"",
"HIDDEN Triggers a panic on the server side, to test the handling."},
},
},
{
"Schema, Version, Permissions", []command{
{"GetSchema", commandGetSchema,
"[-tables=<table1>,<table2>,...] [-exclude_tables=<table1>,<table2>,...] [-include-views] <tablet alias>",
"Displays the full schema for a tablet, or just the schema for the specified tables in that tablet."},
{"ReloadSchema", commandReloadSchema,
"<tablet alias>",
"Reloads the schema on a remote tablet."},
{"ValidateSchemaShard", commandValidateSchemaShard,
"[-exclude_tables=''] [-include-views] <keyspace/shard>",
"Validates that the master schema matches all of the slaves."},
{"ValidateSchemaKeyspace", commandValidateSchemaKeyspace,
"[-exclude_tables=''] [-include-views] <keyspace name>",
"Validates that the master schema from shard 0 matches the schema on all of the other tablets in the keyspace."},
{"ApplySchema", commandApplySchema,
"[-allow_long_unavailability] [-wait_slave_timeout=10s] {-sql=<sql> || -sql-file=<filename>} <keyspace>",
"Applies the schema change to the specified keyspace on every master, running in parallel on all shards. The changes are then propagated to slaves 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."},
{"CopySchemaShard", commandCopySchemaShard,
"[-tables=<table1>,<table2>,...] [-exclude_tables=<table1>,<table2>,...] [-include-views] [-wait_slave_timeout=10s] {<source keyspace/shard> || <source tablet alias>} <destination keyspace/shard>",
"Copies the schema from a source shard's master (or a specific tablet) to a destination shard. The schema is applied directly on the master of the destination shard, and it is propagated to the replicas through binlogs."},
{"ValidateVersionShard", commandValidateVersionShard,
"<keyspace/shard>",
"Validates that the master version matches all of the slaves."},
{"ValidateVersionKeyspace", commandValidateVersionKeyspace,
"<keyspace name>",
"Validates that the master version from shard 0 matches all of the other tablets in the keyspace."},
{"GetPermissions", commandGetPermissions,
"<tablet alias>",
"Displays the permissions for a tablet."},
{"ValidatePermissionsShard", commandValidatePermissionsShard,
"<keyspace/shard>",
"Validates that the master permissions match all the slaves."},
{"ValidatePermissionsKeyspace", commandValidatePermissionsKeyspace,
"<keyspace name>",
"Validates that the master permissions from shard 0 match those of all of the other tablets in the keyspace."},
{"GetVSchema", commandGetVSchema,
"<keyspace>",
"Displays the VTGate routing schema."},
{"ApplyVSchema", commandApplyVSchema,
"{-vschema=<vschema> || -vschema_file=<vschema file>} [-cells=c1,c2,...] [-skip_rebuild] <keyspace>",
"Applies the VTGate routing schema to the provided keyspace. Shows the result after application."},
{"RebuildVSchemaGraph", commandRebuildVSchemaGraph,
"[-cells=c1,c2,...]",
"Rebuilds the cell-specific SrvVSchema from the global VSchema objects in the provided cells (or all cells if none provided)."},
},
},
{
"Serving Graph", []command{
{"GetSrvKeyspaceNames", commandGetSrvKeyspaceNames,
"<cell>",
"Outputs a list of keyspace names."},
{"GetSrvKeyspace", commandGetSrvKeyspace,
"<cell> <keyspace>",
"Outputs a JSON structure that contains information about the SrvKeyspace."},
{"GetSrvVSchema", commandGetSrvVSchema,
"<cell>",
"Outputs a JSON structure that contains information about the SrvVSchema."},
},
},
{
"Replication Graph", []command{
{"GetShardReplication", commandGetShardReplication,
"<cell> <keyspace/shard>",
"Outputs a JSON structure that contains information about the ShardReplication."},
},
},
}
func init() {
// This cannot be in the static 'commands ' array, as commands
// would reference commandHelp that references commands
// (circular reference)
addCommand("Generic", command{"Help", commandHelp,
"[command name]",
"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>"
}
return fmt.Sprintf("%v %v %v %v %v %v %v", topoproto.TabletAliasString(ti.Alias), keyspace, shard, topoproto.TabletTypeLString(ti.Type), ti.Addr(), ti.MysqlAddr(), fmtMapAwkable(ti.Tags))
}
func listTabletsByShard(ctx context.Context, wr *wrangler.Wrangler, keyspace, shard string) error {
tabletAliases, err := wr.TopoServer().FindAllTabletAliasesInShard(ctx, keyspace, shard)
if err != nil {
return err
}
return dumpTablets(ctx, wr, tabletAliases)
}
func dumpAllTablets(ctx context.Context, wr *wrangler.Wrangler, zkVtPath string) error {
tablets, err := topotools.GetAllTablets(ctx, wr.TopoServer(), zkVtPath)
if err != nil {
return err
}
for _, ti := range tablets {
wr.Logger().Printf("%v\n", fmtTabletAwkable(ti))
}
return nil
}
func dumpTablets(ctx context.Context, wr *wrangler.Wrangler, tabletAliases []*topodatapb.TabletAlias) error {
tabletMap, err := wr.TopoServer().GetTabletMap(ctx, tabletAliases)
if err != nil {
return err
}
for _, tabletAlias := range tabletAliases {
ti, ok := tabletMap[*tabletAlias]
if !ok {
log.Warningf("failed to load tablet %v", tabletAlias)
} else {
wr.Logger().Printf("%v\n", fmtTabletAwkable(ti))
}
}
return nil
}
// 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 := ioutil.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 param[0] == '/' {
// this is a topology-specific path
for _, path := range params {
result = append(result, path)
}
} else {
// this is not a path, so assume a keyspace name,
// possibly with wildcards
keyspaces, err := topo.ResolveKeyspaceWildcard(ctx, wr.TopoServer(), 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 := topo.ResolveShardWildcard(ctx, wr.TopoServer(), 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
}
// parseServingTabletType3 parses the tablet type into the enum,
// and makes sure the enum is of serving type (MASTER, REPLICA, RDONLY/BATCH)
func parseServingTabletType3(param string) (topodatapb.TabletType, error) {
servedType, err := topoproto.ParseTabletType(param)
if err != nil {
return topodatapb.TabletType_UNKNOWN, err
}
if !topo.IsInServingGraph(servedType) {
return topodatapb.TabletType_UNKNOWN, fmt.Errorf("served_type has to be in the serving graph, not %v", param)
}
return servedType, 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.")
allowDifferentShard := subFlags.Bool("allow_different_shard", false, "Use this flag to force initialization if a tablet with the same name but a different keyspace/shard already exists. Use with caution.")
allowMasterOverride := subFlags.Bool("allow_master_override", false, "Use this flag to force initialization if a tablet is created as master, and a master 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")
mysqlPort := subFlags.Int("mysql_port", 0, "The mysql port for the mysql daemon")
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,
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 {
tablet.PortMap["mysql"] = int32(*mysqlPort)
}
if *grpcPort != 0 {
tablet.PortMap["grpc"] = int32(*grpcPort)
}
return wr.InitTablet(ctx, tablet, *allowMasterOverride, *allowDifferentShard, *createShardAndKeyspace, *allowUpdate)
}
func commandGetTablet(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the GetTablet command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
return printJSON(wr.Logger(), tabletInfo)
}
func commandUpdateTabletAddrs(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
hostname := subFlags.String("hostname", "", "The fully qualified host name of the server on which the tablet is running.")
ipAddr := subFlags.String("ip-addr", "", "IP address")
mysqlPort := subFlags.Int("mysql-port", 0, "The mysql port for the mysql daemon")
vtPort := subFlags.Int("vt-port", 0, "The main port for the vttablet process")
grpcPort := subFlags.Int("grpc-port", 0, "The gRPC port for the vttablet process")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the UpdateTabletAddrs command.")
}
if *ipAddr != "" && net.ParseIP(*ipAddr) == nil {
return fmt.Errorf("malformed address: %v", *ipAddr)
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
_, err = wr.TopoServer().UpdateTabletFields(ctx, tabletAlias, func(tablet *topodatapb.Tablet) error {
if *hostname != "" {
tablet.Hostname = *hostname
}
if *ipAddr != "" {
tablet.Ip = *ipAddr
}
if *vtPort != 0 || *grpcPort != 0 || *mysqlPort != 0 {
if tablet.PortMap == nil {
tablet.PortMap = make(map[string]int32)
}
if *vtPort != 0 {
tablet.PortMap["vt"] = int32(*vtPort)
}
if *grpcPort != 0 {
tablet.PortMap["grpc"] = int32(*grpcPort)
}
if *mysqlPort != 0 {
tablet.PortMap["mysql"] = int32(*mysqlPort)
}
}
return nil
})
return err
}
func commandDeleteTablet(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
allowMaster := subFlags.Bool("allow_master", false, "Allows for the master tablet of a shard to be deleted. Use with caution.")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() == 0 {
return fmt.Errorf("The <tablet alias> argument must be used to specify at least one tablet when calling the DeleteTablet command.")
}
tabletAliases, err := tabletParamsToTabletAliases(subFlags.Args())
if err != nil {
return err
}
for _, tabletAlias := range tabletAliases {
if err := wr.DeleteTablet(ctx, tabletAlias, *allowMaster); err != nil {
return err
}
}
return nil
}
func commandSetReadOnly(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the SetReadOnly command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("failed reading tablet %v: %v", tabletAlias, err)
}
return wr.TabletManagerClient().SetReadOnly(ctx, ti.Tablet)
}
func commandSetReadWrite(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the SetReadWrite command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("failed reading tablet %v: %v", tabletAlias, err)
}
return wr.TabletManagerClient().SetReadWrite(ctx, ti.Tablet)
}
func commandStartSlave(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("action StartSlave requires <tablet alias>")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("failed reading tablet %v: %v", tabletAlias, err)
}
return wr.TabletManagerClient().StartSlave(ctx, ti.Tablet)
}
func commandStopSlave(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("action StopSlave requires <tablet alias>")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("failed reading tablet %v: %v", tabletAlias, err)
}
return wr.TabletManagerClient().StopSlave(ctx, ti.Tablet)
}
func commandChangeSlaveType(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
dryRun := subFlags.Bool("dry-run", false, "Lists the proposed change without actually executing it")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 2 {
return fmt.Errorf("The <tablet alias> and <db type> arguments are required for the ChangeSlaveType command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
newType, err := parseTabletType(subFlags.Arg(1), topoproto.AllTabletTypes)
if err != nil {
return err
}
if *dryRun {
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return fmt.Errorf("failed reading tablet %v: %v", tabletAlias, err)
}
if !topo.IsTrivialTypeChange(ti.Type, newType) {
return fmt.Errorf("invalid type transition %v: %v -> %v", tabletAlias, ti.Type, newType)
}
wr.Logger().Printf("- %v\n", fmtTabletAwkable(ti))
ti.Type = newType
wr.Logger().Printf("+ %v\n", fmtTabletAwkable(ti))
return nil
}
return wr.ChangeSlaveType(ctx, tabletAlias, newType)
}
func commandPing(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the Ping command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
return wr.TabletManagerClient().Ping(ctx, tabletInfo.Tablet)
}
func commandRefreshState(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the RefreshState command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
return wr.TabletManagerClient().RefreshState(ctx, tabletInfo.Tablet)
}
func commandRunHealthCheck(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The <tablet alias> argument is required for the RunHealthCheck command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
return wr.TabletManagerClient().RunHealthCheck(ctx, tabletInfo.Tablet)
}
func commandIgnoreHealthError(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 2 {
return fmt.Errorf("The <tablet alias> and <ignore regexp> arguments are required for the IgnoreHealthError command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
pattern := subFlags.Arg(1)
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
return wr.TabletManagerClient().IgnoreHealthError(ctx, tabletInfo.Tablet, pattern)
}
func commandWaitForDrain(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
var cells flagutil.StringListValue
subFlags.Var(&cells, "cells", "Specifies a comma-separated list of cells to look for tablets")
timeout := subFlags.Duration("timeout", 0*time.Second, "Timeout after which the command fails")
retryDelay := subFlags.Duration("retry_delay", 1*time.Second, "Time to wait between two checks")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 2 {
return fmt.Errorf("The <keyspace/shard> and <tablet type> arguments are both required for the WaitForDrain command.")
}
if *timeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, *timeout)
defer cancel()
}
keyspace, shard, err := topoproto.ParseKeyspaceShard(subFlags.Arg(0))
if err != nil {
return err
}
servedType, err := parseServingTabletType3(subFlags.Arg(1))
if err != nil {
return err
}
return wr.WaitForDrain(ctx, cells, keyspace, shard, servedType,
*retryDelay, *healthCheckTopologyRefresh, *healthcheckRetryDelay, *healthCheckTimeout)
}
func commandSleep(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 2 {
return fmt.Errorf("The <tablet alias> and <duration> arguments are required for the Sleep command.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
ti, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
duration, err := time.ParseDuration(subFlags.Arg(1))
if err != nil {
return err
}
return wr.TabletManagerClient().Sleep(ctx, ti.Tablet, duration)
}
func commandBackup(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {
concurrency := subFlags.Int("concurrency", 4, "Specifies the number of compression/checksum jobs to run simultaneously")
if err := subFlags.Parse(args); err != nil {
return err
}
if subFlags.NArg() != 1 {
return fmt.Errorf("The Backup command requires the <tablet alias> argument.")
}
tabletAlias, err := topoproto.ParseTabletAlias(subFlags.Arg(0))
if err != nil {
return err
}
tabletInfo, err := wr.TopoServer().GetTablet(ctx, tabletAlias)
if err != nil {
return err
}
stream, err := wr.TabletManagerClient().Backup(ctx, tabletInfo.Tablet, *concurrency)
if err != nil {
return err
}
for {
e, err := stream.Recv()
switch err {
case nil:
logutil.LogEvent(wr.Logger(), e)
case io.EOF:
return nil
default:
return err
}
}
}
func commandExecuteFetchAsDba(ctx context.Context, wr *wrangler.Wrangler, subFlags *flag.FlagSet, args []string) error {