本文整理汇总了Golang中github.com/youtube/vitess/go/vt/tabletmanager/tmclient.NewTabletManagerClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTabletManagerClient函数的具体用法?Golang NewTabletManagerClient怎么用?Golang NewTabletManagerClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewTabletManagerClient函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestTabletExternallyReparentedFailedOldMaster
func TestTabletExternallyReparentedFailedOldMaster(t *testing.T) {
tabletmanager.SetReparentFlags(time.Minute /* finalizeTimeout */)
ctx := context.Background()
ts := zktopo.NewTestServer(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create an old master, a new master, and a good slave.
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topo.TYPE_MASTER)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topo.TYPE_REPLICA)
goodSlave := NewFakeTablet(t, wr, "cell1", 2, topo.TYPE_REPLICA)
// Reparent to a replica, and pretend the old master is not responding.
// On the elected master, we will respond to
// TabletActionSlaveWasPromoted
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// On the old master, we will only get a
// TabletActionSlaveWasRestarted call, let's just not
// respond to it at all
// On the good slave, we will respond to
// TabletActionSlaveWasRestarted.
goodSlave.StartActionLoop(t, wr)
defer goodSlave.StopActionLoop(t)
// The reparent should work as expected here
t.Logf("TabletExternallyReparented(new master) expecting success")
tmc := tmclient.NewTabletManagerClient()
ti, err := ts.GetTablet(ctx, newMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
waitID := makeWaitID()
if err := tmc.TabletExternallyReparented(context.Background(), ti, waitID); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
waitForExternalReparent(t, waitID)
// Now double-check the serving graph is good.
// Should only have one good replica left.
addrs, _, err := ts.GetEndPoints(ctx, "cell1", "test_keyspace", "0", topo.TYPE_REPLICA)
if err != nil {
t.Fatalf("GetEndPoints failed at the end: %v", err)
}
if len(addrs.Entries) != 1 {
t.Fatalf("GetEndPoints has too many entries: %v", addrs)
}
// check the old master was converted to spare
tablet, err := ts.GetTablet(ctx, oldMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet(%v) failed: %v", oldMaster.Tablet.Alias, err)
}
if tablet.Type != topo.TYPE_SPARE {
t.Fatalf("old master should be spare but is: %v", tablet.Type)
}
}
示例2: TestTabletExternallyReparentedFailedOldMaster
func TestTabletExternallyReparentedFailedOldMaster(t *testing.T) {
tabletmanager.SetReparentFlags(time.Minute /* finalizeTimeout */)
ctx := context.Background()
db := fakesqldb.Register()
ts := zktestserver.New(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
// Create an old master, a new master, and a good slave.
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topodatapb.TabletType_MASTER, db)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topodatapb.TabletType_REPLICA, db)
goodSlave := NewFakeTablet(t, wr, "cell1", 2, topodatapb.TabletType_REPLICA, db)
// Reparent to a replica, and pretend the old master is not responding.
// On the elected master, we will respond to
// TabletActionSlaveWasPromoted
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// On the old master, we will only get a
// TabletActionSlaveWasRestarted call, let's just not
// respond to it at all
// On the good slave, we will respond to
// TabletActionSlaveWasRestarted.
goodSlave.StartActionLoop(t, wr)
defer goodSlave.StopActionLoop(t)
// The reparent should work as expected here
t.Logf("TabletExternallyReparented(new master) expecting success")
tmc := tmclient.NewTabletManagerClient()
ti, err := ts.GetTablet(ctx, newMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
waitID := makeWaitID()
if err := tmc.TabletExternallyReparented(context.Background(), ti.Tablet, waitID); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
waitForExternalReparent(t, waitID)
// check the old master was converted to replica
tablet, err := ts.GetTablet(ctx, oldMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet(%v) failed: %v", oldMaster.Tablet.Alias, err)
}
if tablet.Type != topodatapb.TabletType_REPLICA {
t.Fatalf("old master should be spare but is: %v", tablet.Type)
}
}
示例3: ExecuteVtctlCommand
// ExecuteVtctlCommand is part of the pb.VtctlServer interface
func (s *VtctlServer) ExecuteVtctlCommand(args *pb.ExecuteVtctlCommandRequest, stream pbs.Vtctl_ExecuteVtctlCommandServer) (err error) {
defer servenv.HandlePanic("vtctl", &err)
// create a logger, send the result back to the caller
logstream := logutil.NewChannelLogger(10)
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// send logs to the caller
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for e := range logstream {
// Note we don't interrupt the loop here, as
// we still need to flush and finish the
// command, even if the channel to the client
// has been broken. We'll just keep trying.
stream.Send(&pb.ExecuteVtctlCommandResponse{
Event: logutil.LoggerEventToProto(&e),
})
}
wg.Done()
}()
// create the wrangler
wr := wrangler.New(logger, s.ts, tmclient.NewTabletManagerClient(), time.Duration(args.LockTimeout))
// execute the command
err = vtctl.RunCommand(stream.Context(), wr, args.Args)
// close the log channel, and wait for them all to be sent
close(logstream)
wg.Wait()
return err
}
示例4: TestInitMasterShardChecks
// TestInitMasterShardChecks makes sure the safety checks work
func TestInitMasterShardChecks(t *testing.T) {
ctx := context.Background()
db := fakesqldb.Register()
ts := zktestserver.New(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
master := NewFakeTablet(t, wr, "cell1", 0, topodatapb.TabletType_MASTER, db)
// InitShardMaster with an unknown tablet
if err := wr.InitShardMaster(ctx, master.Tablet.Keyspace, master.Tablet.Shard, &topodatapb.TabletAlias{
Cell: master.Tablet.Alias.Cell,
Uid: master.Tablet.Alias.Uid + 1,
}, false /*force*/, 10*time.Second); err == nil || !strings.Contains(err.Error(), "is not in the shard") {
t.Errorf("InitShardMaster with unknown alias returned wrong error: %v", err)
}
// InitShardMaster with two masters in the shard, no force flag
// (master2 needs to run InitTablet with -force, as it is the second
// master in the same shard)
master2 := NewFakeTablet(t, wr, "cell1", 1, topodatapb.TabletType_MASTER, db, ForceInitTablet())
if err := wr.InitShardMaster(ctx, master2.Tablet.Keyspace, master2.Tablet.Shard, master2.Tablet.Alias, false /*force*/, 10*time.Second); err == nil || !strings.Contains(err.Error(), "is not the only master in the shard") {
t.Errorf("InitShardMaster with two masters returned wrong error: %v", err)
}
// InitShardMaster where the new master fails (use force flag
// as we have 2 masters). We force the failure by making the
// SQL commands executed on the master unexpected by the test fixture
master.StartActionLoop(t, wr)
defer master.StopActionLoop(t)
master2.StartActionLoop(t, wr)
defer master2.StopActionLoop(t)
if err := wr.InitShardMaster(ctx, master.Tablet.Keyspace, master.Tablet.Shard, master.Tablet.Alias, true /*force*/, 10*time.Second); err == nil || !strings.Contains(err.Error(), "unexpected extra query") {
t.Errorf("InitShardMaster with new master failing in new master InitMaster returned wrong error: %v", err)
}
}
示例5: ApplyTabletAction
// ApplyTabletAction applies the provided action to the tablet.
func (ar *ActionRepository) ApplyTabletAction(ctx context.Context, actionName string, tabletAlias *topodatapb.TabletAlias, r *http.Request) *ActionResult {
result := &ActionResult{
Name: actionName,
Parameters: topoproto.TabletAliasString(tabletAlias),
}
action, ok := ar.tabletActions[actionName]
if !ok {
result.error("Unknown tablet action")
return result
}
// check the role
if action.role != "" {
if err := acl.CheckAccessHTTP(r, action.role); err != nil {
result.error("Access denied")
return result
}
}
// run the action
ctx, cancel := context.WithTimeout(ctx, *actionTimeout)
wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, tmclient.NewTabletManagerClient())
output, err := action.method(ctx, wr, tabletAlias, r)
cancel()
if err != nil {
result.error(err.Error())
return result
}
result.Output = output
return result
}
示例6: ApplyShardAction
// ApplyShardAction applies the provided action to the shard.
func (ar *ActionRepository) ApplyShardAction(ctx context.Context, actionName, keyspace, shard string, r *http.Request) *ActionResult {
// if the shard name contains a '-', we assume it's the
// name for a ranged based shard, so we lower case it.
if strings.Contains(shard, "-") {
shard = strings.ToLower(shard)
}
result := &ActionResult{Name: actionName, Parameters: keyspace + "/" + shard}
action, ok := ar.shardActions[actionName]
if !ok {
result.error("Unknown shard action")
return result
}
ctx, cancel := context.WithTimeout(ctx, *actionTimeout)
wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, tmclient.NewTabletManagerClient())
output, err := action(ctx, wr, keyspace, shard, r)
cancel()
if err != nil {
result.error(err.Error())
return result
}
result.Output = output
return result
}
示例7: TestNewRestartableResultReader
// TestNewRestartableResultReader tests the correct error handling e.g.
// if the connection to a tablet fails due to a canceled context.
func TestNewRestartableResultReader(t *testing.T) {
wantErr := errors.New("restartable_result_reader_test.go: context canceled")
tabletconn.RegisterDialer("fake_dialer", func(tablet *topodatapb.Tablet, timeout time.Duration) (tabletconn.TabletConn, error) {
return nil, wantErr
})
protocol := flag.CommandLine.Lookup("tablet_protocol").Value.String()
flag.Set("tablet_protocol", "fake_dialer")
// Restore the previous flag value after the test.
defer flag.Set("tablet_protocol", protocol)
// Create dependencies e.g. a "singleTabletProvider" instance.
ts := zktestserver.New(t, []string{"cell1"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
alias := &topodatapb.TabletAlias{
Cell: "cell1",
Uid: 1,
}
tablet := &topodatapb.Tablet{
Keyspace: "ks1",
Shard: "-80",
Alias: alias,
}
ctx := context.Background()
if err := ts.CreateTablet(ctx, tablet); err != nil {
t.Fatalf("CreateTablet failed: %v", err)
}
tp := newSingleTabletProvider(ctx, ts, alias)
_, err := NewRestartableResultReader(ctx, wr.Logger(), tp, nil /* td */, chunk{}, false)
if err == nil || !strings.Contains(err.Error(), wantErr.Error()) {
t.Fatalf("NewRestartableResultReader() should have failed because the context is canceled: %v", err)
}
}
示例8: TestEmergencyReparentShardMasterElectNotBest
// TestEmergencyReparentShardMasterElectNotBest tries to emergency reparent
// to a host that is not the latest in replication position.
func TestEmergencyReparentShardMasterElectNotBest(t *testing.T) {
ctx := context.Background()
ts := zktopo.NewTestServer(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create a master, a couple good slaves
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topo.TYPE_MASTER)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topo.TYPE_REPLICA)
moreAdvancedSlave := NewFakeTablet(t, wr, "cell1", 2, topo.TYPE_REPLICA)
// new master
newMaster.FakeMysqlDaemon.Replicating = true
newMaster.FakeMysqlDaemon.CurrentMasterPosition = myproto.ReplicationPosition{
GTIDSet: myproto.MariadbGTID{
Domain: 2,
Server: 123,
Sequence: 456,
},
}
newMaster.FakeMysqlDaemon.ExpectedExecuteSuperQueryList = []string{
"STOP SLAVE",
}
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// old master, will be scrapped
oldMaster.StartActionLoop(t, wr)
defer oldMaster.StopActionLoop(t)
// more advanced slave
moreAdvancedSlave.FakeMysqlDaemon.Replicating = true
moreAdvancedSlave.FakeMysqlDaemon.CurrentMasterPosition = myproto.ReplicationPosition{
GTIDSet: myproto.MariadbGTID{
Domain: 2,
Server: 123,
Sequence: 457,
},
}
moreAdvancedSlave.FakeMysqlDaemon.ExpectedExecuteSuperQueryList = []string{
"STOP SLAVE",
}
moreAdvancedSlave.StartActionLoop(t, wr)
defer moreAdvancedSlave.StopActionLoop(t)
// run EmergencyReparentShard
if err := wr.EmergencyReparentShard(ctx, newMaster.Tablet.Keyspace, newMaster.Tablet.Shard, newMaster.Tablet.Alias, 10*time.Second); err == nil || !strings.Contains(err.Error(), "is more advanced than master elect tablet") {
t.Fatalf("EmergencyReparentShard returned the wrong error: %v", err)
}
// check what was run
if err := newMaster.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("newMaster.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
if err := oldMaster.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("oldMaster.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
if err := moreAdvancedSlave.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("moreAdvancedSlave.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
}
示例9: TestTabletExternallyReparentedWithDifferentMysqlPort
// TestTabletExternallyReparentedWithDifferentMysqlPort makes sure
// that if mysql is restarted on the master-elect tablet and has a different
// port, we pick it up correctly.
func TestTabletExternallyReparentedWithDifferentMysqlPort(t *testing.T) {
tabletmanager.SetReparentFlags(time.Minute /* finalizeTimeout */)
ctx := context.Background()
db := fakesqldb.Register()
ts := zktopo.NewTestServer(t, []string{"cell1"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create an old master, a new master, two good slaves, one bad slave
oldMaster := NewFakeTablet(t, wr, "cell1", 0, pb.TabletType_MASTER, db)
newMaster := NewFakeTablet(t, wr, "cell1", 1, pb.TabletType_REPLICA, db)
goodSlave := NewFakeTablet(t, wr, "cell1", 2, pb.TabletType_REPLICA, db)
// Now we're restarting mysql on a different port, 3301->3303
// but without updating the Tablet record in topology.
// On the elected master, we will respond to
// TabletActionSlaveWasPromoted, so we need a MysqlDaemon
// that returns no master, and the new port (as returned by mysql)
newMaster.FakeMysqlDaemon.MysqlPort = 3303
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// On the old master, we will only respond to
// TabletActionSlaveWasRestarted and point to the new mysql port
oldMaster.StartActionLoop(t, wr)
defer oldMaster.StopActionLoop(t)
// On the good slaves, we will respond to
// TabletActionSlaveWasRestarted and point to the new mysql port
goodSlave.StartActionLoop(t, wr)
defer goodSlave.StopActionLoop(t)
// This tests the good case, where everything works as planned
t.Logf("TabletExternallyReparented(new master) expecting success")
tmc := tmclient.NewTabletManagerClient()
ti, err := ts.GetTablet(ctx, newMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
waitID := makeWaitID()
if err := tmc.TabletExternallyReparented(context.Background(), ti, waitID); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
waitForExternalReparent(t, waitID)
}
示例10: TestSplitCloneV2_RetryDueToReparent
// TestSplitCloneV2_RetryDueToReparent tests that vtworker correctly failovers
// during a reparent.
// NOTE: worker.py is an end-to-end test which tests this as well.
func TestSplitCloneV2_RetryDueToReparent(t *testing.T) {
tc := &splitCloneTestCase{t: t}
tc.setUp(false /* v3 */)
defer tc.tearDown()
// Provoke a reparent just before the copy finishes.
// leftReplica will take over for the last, 30th, insert and the BLP checkpoint.
tc.leftReplicaFakeDb.addExpectedQuery("INSERT INTO `vt_ks`.`table1` (`id`, `msg`, `keyspace_id`) VALUES (*", nil)
expectBlpCheckpointCreationQueries(tc.leftReplicaFakeDb)
// Do not let leftMaster succeed the 30th write.
tc.leftMasterFakeDb.deleteAllEntriesAfterIndex(28)
tc.leftMasterFakeDb.addExpectedQuery("INSERT INTO `vt_ks`.`table1` (`id`, `msg`, `keyspace_id`) VALUES (*", errReadOnly)
tc.leftMasterFakeDb.enableInfinite()
// When vtworker encounters the readonly error on leftMaster, do the reparent.
tc.leftMasterFakeDb.getEntry(29).AfterFunc = func() {
// Reparent from leftMaster to leftReplica.
// NOTE: This step is actually not necessary due to our fakes which bypass
// a lot of logic. Let's keep it for correctness though.
ti, err := tc.ts.GetTablet(context.Background(), tc.leftReplica.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
tmc := tmclient.NewTabletManagerClient()
if err := tmc.TabletExternallyReparented(context.Background(), ti.Tablet, "wait id 1"); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
// Update targets in fake query service and send out a new health response.
tc.leftMasterQs.UpdateType(topodatapb.TabletType_REPLICA)
tc.leftMasterQs.AddDefaultHealthResponse()
tc.leftReplicaQs.UpdateType(topodatapb.TabletType_MASTER)
tc.leftReplicaQs.AddDefaultHealthResponse()
// After this, vtworker will retry. The following situations can occur:
// 1. HealthCheck picked up leftReplica as new MASTER
// => retry will succeed.
// 2. HealthCheck picked up no changes (leftMaster remains MASTER)
// => retry will hit leftMaster which keeps responding with readonly err.
// 3. HealthCheck picked up leftMaster as REPLICA, but leftReplica is still
// a REPLICA.
// => vtworker has no MASTER to go to and will keep retrying.
}
// Only wait 1 ms between retries, so that the test passes faster.
*executeFetchRetryTime = 1 * time.Millisecond
// Run the vtworker command.
if err := runCommand(t, tc.wi, tc.wi.wr, tc.defaultWorkerArgs); err != nil {
t.Fatal(err)
}
wantRetryCountMin := int64(1)
if got := statsRetryCount.Get(); got < wantRetryCountMin {
t.Errorf("Wrong statsRetryCounter: got %v, wanted >= %v", got, wantRetryCountMin)
}
}
示例11: StartActionLoop
// StartActionLoop will start the action loop for a fake tablet,
// using ft.FakeMysqlDaemon as the backing mysqld.
func (ft *FakeTablet) StartActionLoop(t *testing.T, wr *wrangler.Wrangler) {
if ft.Agent != nil {
t.Fatalf("Agent for %v is already running", ft.Tablet.Alias)
}
// Listen on a random port for gRPC
var err error
ft.Listener, err = net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("Cannot listen: %v", err)
}
gRPCPort := int32(ft.Listener.Addr().(*net.TCPAddr).Port)
// if needed, listen on a random port for HTTP
vtPort := ft.Tablet.PortMap["vt"]
if ft.StartHTTPServer {
ft.HTTPListener, err = net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("Cannot listen on http port: %v", err)
}
handler := http.NewServeMux()
ft.HTTPServer = http.Server{
Handler: handler,
}
go ft.HTTPServer.Serve(ft.HTTPListener)
vtPort = int32(ft.HTTPListener.Addr().(*net.TCPAddr).Port)
}
// create a test agent on that port, and re-read the record
// (it has new ports and IP)
ft.Agent = tabletmanager.NewTestActionAgent(context.Background(), wr.TopoServer(), ft.Tablet.Alias, vtPort, gRPCPort, ft.FakeMysqlDaemon)
ft.Tablet = ft.Agent.Tablet()
// create the gRPC server
ft.RPCServer = grpc.NewServer()
grpctmserver.RegisterForTest(ft.RPCServer, ft.Agent)
go ft.RPCServer.Serve(ft.Listener)
// and wait for it to serve, so we don't start using it before it's
// ready.
timeout := 5 * time.Second
step := 10 * time.Millisecond
c := tmclient.NewTabletManagerClient()
for timeout >= 0 {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
err := c.Ping(ctx, topo.NewTabletInfo(ft.Agent.Tablet(), -1))
cancel()
if err == nil {
break
}
time.Sleep(step)
timeout -= step
}
if timeout < 0 {
panic("StartActionLoop failed.")
}
}
示例12: TestTabletData
func TestTabletData(t *testing.T) {
db := fakesqldb.Register()
ts := zktestserver.New(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
if err := ts.CreateKeyspace(context.Background(), "ks", &topodatapb.Keyspace{
ShardingColumnName: "keyspace_id",
ShardingColumnType: topodatapb.KeyspaceIdType_UINT64,
}); err != nil {
t.Fatalf("CreateKeyspace failed: %v", err)
}
tablet1 := testlib.NewFakeTablet(t, wr, "cell1", 0, topodatapb.TabletType_MASTER, db, testlib.TabletKeyspaceShard(t, "ks", "-80"))
tablet1.StartActionLoop(t, wr)
defer tablet1.StopActionLoop(t)
shsq := newStreamHealthTabletServer(t)
grpcqueryservice.Register(tablet1.RPCServer, shsq)
thc := newTabletHealthCache(ts)
stats := &querypb.RealtimeStats{
HealthError: "testHealthError",
SecondsBehindMaster: 72,
CpuUsage: 1.1,
}
// Keep broadcasting until the first result goes through.
stop := make(chan struct{})
go func() {
for {
select {
case <-stop:
return
default:
shsq.BroadcastHealth(42, stats)
}
}
}()
// Start streaming and wait for the first result.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
result, err := thc.Get(ctx, tablet1.Tablet.Alias)
cancel()
close(stop)
if err != nil {
t.Fatalf("thc.Get failed: %v", err)
}
if got, want := result.RealtimeStats, stats; !proto.Equal(got, want) {
t.Errorf("RealtimeStats = %#v, want %#v", got, want)
}
}
示例13: TestTabletExternallyReparentedContinueOnUnexpectedMaster
// TestTabletExternallyReparentedContinueOnUnexpectedMaster makes sure
// that we ignore mysql's master if the flag is set
func TestTabletExternallyReparentedContinueOnUnexpectedMaster(t *testing.T) {
tabletmanager.SetReparentFlags(time.Minute /* finalizeTimeout */)
ctx := context.Background()
ts := zktopo.NewTestServer(t, []string{"cell1"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create an old master, a new master, two good slaves, one bad slave
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topo.TYPE_MASTER)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topo.TYPE_REPLICA)
goodSlave := NewFakeTablet(t, wr, "cell1", 2, topo.TYPE_REPLICA)
// On the elected master, we will respond to
// TabletActionSlaveWasPromoted, so we need a MysqlDaemon
// that returns no master, and the new port (as returned by mysql)
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// On the old master, we will only respond to
// TabletActionSlaveWasRestarted and point to a bad host
oldMaster.StartActionLoop(t, wr)
defer oldMaster.StopActionLoop(t)
// On the good slave, we will respond to
// TabletActionSlaveWasRestarted and point to a bad host
goodSlave.StartActionLoop(t, wr)
defer goodSlave.StopActionLoop(t)
// This tests the good case, where everything works as planned
t.Logf("TabletExternallyReparented(new master) expecting success")
tmc := tmclient.NewTabletManagerClient()
ti, err := ts.GetTablet(ctx, newMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
if err := tmc.TabletExternallyReparented(context.Background(), ti, ""); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
}
示例14: TestReparentTablet
func TestReparentTablet(t *testing.T) {
ctx := context.Background()
db := fakesqldb.Register()
ts := zktestserver.New(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
// create shard and tablets
if err := ts.CreateShard(ctx, "test_keyspace", "0"); err != nil {
t.Fatalf("CreateShard failed: %v", err)
}
master := NewFakeTablet(t, wr, "cell1", 1, topodatapb.TabletType_MASTER, db)
slave := NewFakeTablet(t, wr, "cell1", 2, topodatapb.TabletType_REPLICA, db)
// mark the master inside the shard
si, err := ts.GetShard(ctx, "test_keyspace", "0")
if err != nil {
t.Fatalf("GetShard failed: %v", err)
}
si.MasterAlias = master.Tablet.Alias
if err := ts.UpdateShard(ctx, si); err != nil {
t.Fatalf("UpdateShard failed: %v", err)
}
// master action loop (to initialize host and port)
master.StartActionLoop(t, wr)
defer master.StopActionLoop(t)
// slave loop
slave.FakeMysqlDaemon.SetMasterCommandsInput = fmt.Sprintf("%v:%v", master.Tablet.Hostname, master.Tablet.PortMap["mysql"])
slave.FakeMysqlDaemon.SetMasterCommandsResult = []string{"set master cmd 1"}
slave.FakeMysqlDaemon.ExpectedExecuteSuperQueryList = []string{
"set master cmd 1",
}
slave.StartActionLoop(t, wr)
defer slave.StopActionLoop(t)
// run ReparentTablet
if err := wr.ReparentTablet(ctx, slave.Tablet.Alias); err != nil {
t.Fatalf("ReparentTablet failed: %v", err)
}
// check what was run
if err := slave.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("slave.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
checkSemiSyncEnabled(t, false, true, slave)
}
示例15: main
func main() {
defer exit.RecoverAll()
defer logutil.Flush()
flag.Parse()
args := flag.Args()
if len(args) == 0 {
flag.Usage()
exit.Return(1)
}
action := args[0]
startMsg := fmt.Sprintf("USER=%v SUDO_USER=%v %v", os.Getenv("USER"), os.Getenv("SUDO_USER"), strings.Join(os.Args, " "))
if syslogger, err := syslog.New(syslog.LOG_INFO, "vtctl "); err == nil {
syslogger.Info(startMsg)
} else {
log.Warningf("cannot connect to syslog: %v", err)
}
topoServer := topo.GetServer()
defer topo.CloseServers()
ctx, cancel := context.WithTimeout(context.Background(), *waitTime)
wr := wrangler.New(logutil.NewConsoleLogger(), topoServer, tmclient.NewTabletManagerClient(), *lockWaitTimeout)
installSignalHandlers(cancel)
for _, f := range initFuncs {
f()
}
err := vtctl.RunCommand(ctx, wr, args)
cancel()
switch err {
case vtctl.ErrUnknownCommand:
flag.Usage()
exit.Return(1)
case nil:
// keep going
default:
log.Errorf("action failed: %v %v", action, err)
exit.Return(255)
}
}