vitess.io/vitess@v0.16.2/go/vt/wrangler/fake_tablet_test.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package wrangler 18 19 import ( 20 "context" 21 "net" 22 "net/http" 23 "testing" 24 "time" 25 26 "github.com/stretchr/testify/require" 27 "google.golang.org/grpc" 28 29 "vitess.io/vitess/go/mysql/fakesqldb" 30 "vitess.io/vitess/go/netutil" 31 "vitess.io/vitess/go/vt/dbconfigs" 32 "vitess.io/vitess/go/vt/mysqlctl/fakemysqldaemon" 33 "vitess.io/vitess/go/vt/topo" 34 "vitess.io/vitess/go/vt/vttablet/grpctmserver" 35 "vitess.io/vitess/go/vt/vttablet/tabletconntest" 36 "vitess.io/vitess/go/vt/vttablet/tabletmanager" 37 "vitess.io/vitess/go/vt/vttablet/tabletservermock" 38 "vitess.io/vitess/go/vt/vttablet/tmclient" 39 "vitess.io/vitess/go/vt/vttablet/tmclienttest" 40 41 querypb "vitess.io/vitess/go/vt/proto/query" 42 topodatapb "vitess.io/vitess/go/vt/proto/topodata" 43 44 // import the gRPC client implementation for tablet manager 45 _ "vitess.io/vitess/go/vt/vttablet/grpctmclient" 46 47 // import the gRPC client implementation for query service 48 _ "vitess.io/vitess/go/vt/vttablet/grpctabletconn" 49 ) 50 51 // This file was copied from testlib. All tests from testlib should be moved 52 // to the current directory. In order to move tests from there, we have to 53 // remove the circular dependency it causes (through vtctl dependence). 54 // The tests in this directory call wrangler functions directly. So, there's 55 // no circular dependency. 56 57 // This file contains utility methods for unit tests. 58 // We allow the creation of fake tablets, and running their event loop based 59 // on a FakeMysqlDaemon. 60 61 // fakeTablet keeps track of a fake tablet in memory. It has: 62 // - a Tablet record (used for creating the tablet, kept for user's information) 63 // - a FakeMysqlDaemon (used by the fake event loop) 64 // - a 'done' channel (used to terminate the fake event loop) 65 type fakeTablet struct { 66 // Tablet and FakeMysqlDaemon are populated at NewFakeTablet time. 67 // We also create the RPCServer, so users can register more services 68 // before calling StartActionLoop(). 69 Tablet *topodatapb.Tablet 70 FakeMysqlDaemon *fakemysqldaemon.FakeMysqlDaemon 71 RPCServer *grpc.Server 72 73 // The following fields are created when we start the event loop for 74 // the tablet, and closed / cleared when we stop it. 75 // The Listener is used by the gRPC server. 76 TM *tabletmanager.TabletManager 77 Listener net.Listener 78 79 // These optional fields are used if the tablet also needs to 80 // listen on the 'vt' port. 81 StartHTTPServer bool 82 HTTPListener net.Listener 83 HTTPServer *http.Server 84 } 85 86 // TabletOption is an interface for changing tablet parameters. 87 // It's a way to pass multiple parameters to NewFakeTablet without 88 // making it too cumbersome. 89 type TabletOption func(tablet *topodatapb.Tablet) 90 91 // TabletKeyspaceShard is the option to set the tablet keyspace and shard 92 func TabletKeyspaceShard(t *testing.T, keyspace, shard string) TabletOption { 93 return func(tablet *topodatapb.Tablet) { 94 tablet.Keyspace = keyspace 95 shard, kr, err := topo.ValidateShardName(shard) 96 if err != nil { 97 t.Fatalf("cannot ValidateShardName value %v", shard) 98 } 99 tablet.Shard = shard 100 tablet.KeyRange = kr 101 } 102 } 103 104 // newFakeTablet creates the test tablet in the topology. 'uid' 105 // has to be between 0 and 99. All the tablet info will be derived 106 // from that. Look at the implementation if you need values. 107 // Use TabletOption implementations if you need to change values at creation. 108 // 'db' can be nil if the test doesn't use a database at all. 109 func newFakeTablet(t *testing.T, wr *Wrangler, cell string, uid uint32, tabletType topodatapb.TabletType, db *fakesqldb.DB, options ...TabletOption) *fakeTablet { 110 if uid > 99 { 111 t.Fatalf("uid has to be between 0 and 99: %v", uid) 112 } 113 mysqlPort := int32(3300 + uid) 114 hostname, err := netutil.FullyQualifiedHostname() 115 require.NoError(t, err) 116 tablet := &topodatapb.Tablet{ 117 Alias: &topodatapb.TabletAlias{Cell: cell, Uid: uid}, 118 Hostname: hostname, 119 MysqlHostname: hostname, 120 PortMap: map[string]int32{ 121 "vt": int32(8100 + uid), 122 "grpc": int32(8200 + uid), 123 }, 124 Keyspace: "test_keyspace", 125 Shard: "0", 126 Type: tabletType, 127 } 128 tablet.MysqlPort = mysqlPort 129 for _, option := range options { 130 option(tablet) 131 } 132 if err := wr.TopoServer().InitTablet(context.Background(), tablet, false /* allowPrimaryOverride */, true /* createShardAndKeyspace */, false /* allowUpdate */); err != nil { 133 t.Fatalf("cannot create tablet %v: %v", uid, err) 134 } 135 136 // create a FakeMysqlDaemon with the right information by default 137 fakeMysqlDaemon := fakemysqldaemon.NewFakeMysqlDaemon(db) 138 fakeMysqlDaemon.MysqlPort.Set(mysqlPort) 139 140 return &fakeTablet{ 141 Tablet: tablet, 142 FakeMysqlDaemon: fakeMysqlDaemon, 143 RPCServer: grpc.NewServer(), 144 } 145 } 146 147 // StartActionLoop will start the action loop for a fake tablet, 148 // using ft.FakeMysqlDaemon as the backing mysqld. 149 func (ft *fakeTablet) StartActionLoop(t *testing.T, wr *Wrangler) { 150 if ft.TM != nil { 151 t.Fatalf("TM for %v is already running", ft.Tablet.Alias) 152 } 153 154 // Listen on a random port for gRPC. 155 var err error 156 ft.Listener, err = net.Listen("tcp", ":0") 157 if err != nil { 158 t.Fatalf("Cannot listen: %v", err) 159 } 160 gRPCPort := int32(ft.Listener.Addr().(*net.TCPAddr).Port) 161 162 // If needed, listen on a random port for HTTP. 163 vtPort := ft.Tablet.PortMap["vt"] 164 if ft.StartHTTPServer { 165 ft.HTTPListener, err = net.Listen("tcp", ":0") 166 if err != nil { 167 t.Fatalf("Cannot listen on http port: %v", err) 168 } 169 handler := http.NewServeMux() 170 ft.HTTPServer = &http.Server{ 171 Handler: handler, 172 } 173 go ft.HTTPServer.Serve(ft.HTTPListener) 174 vtPort = int32(ft.HTTPListener.Addr().(*net.TCPAddr).Port) 175 } 176 ft.Tablet.PortMap["vt"] = vtPort 177 ft.Tablet.PortMap["grpc"] = gRPCPort 178 179 // Create a test tm on that port, and re-read the record 180 // (it has new ports and IP). 181 ft.TM = &tabletmanager.TabletManager{ 182 BatchCtx: context.Background(), 183 TopoServer: wr.TopoServer(), 184 MysqlDaemon: ft.FakeMysqlDaemon, 185 DBConfigs: &dbconfigs.DBConfigs{}, 186 QueryServiceControl: tabletservermock.NewController(), 187 } 188 if err := ft.TM.Start(ft.Tablet, 0); err != nil { 189 t.Fatal(err) 190 } 191 ft.Tablet = ft.TM.Tablet() 192 193 // Register the gRPC server, and starts listening. 194 grpctmserver.RegisterForTest(ft.RPCServer, ft.TM) 195 go ft.RPCServer.Serve(ft.Listener) 196 197 // And wait for it to serve, so we don't start using it before it's 198 // ready. 199 timeout := 5 * time.Second 200 step := 10 * time.Millisecond 201 c := tmclient.NewTabletManagerClient() 202 for timeout >= 0 { 203 ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) 204 err := c.Ping(ctx, ft.TM.Tablet()) 205 cancel() 206 if err == nil { 207 break 208 } 209 time.Sleep(step) 210 timeout -= step 211 } 212 if timeout < 0 { 213 panic("StartActionLoop failed.") 214 } 215 } 216 217 // StopActionLoop will stop the Action Loop for the given FakeTablet 218 func (ft *fakeTablet) StopActionLoop(t *testing.T) { 219 if ft.TM == nil { 220 t.Fatalf("TM for %v is not running", ft.Tablet.Alias) 221 } 222 if ft.StartHTTPServer { 223 ft.HTTPListener.Close() 224 } 225 ft.Listener.Close() 226 ft.TM.Stop() 227 ft.TM = nil 228 ft.Listener = nil 229 ft.HTTPListener = nil 230 } 231 232 // Target returns the keyspace/shard/type info of this tablet as Target. 233 func (ft *fakeTablet) Target() querypb.Target { 234 return querypb.Target{ 235 Keyspace: ft.Tablet.Keyspace, 236 Shard: ft.Tablet.Shard, 237 TabletType: ft.Tablet.Type, 238 } 239 } 240 241 func init() { 242 // enforce we will use the right protocol (gRPC) in all unit tests 243 tabletconntest.SetProtocol("go.vt.wrangler.fake_tablet_test", "grpc") 244 tmclienttest.SetProtocol("go.vt.wrangler.fake_tablet_test", "grpc") 245 }