|
| 1 | +/* |
| 2 | +Copyright 2024 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 transaction |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + _ "embed" |
| 22 | + "encoding/json" |
| 23 | + "flag" |
| 24 | + "fmt" |
| 25 | + "io" |
| 26 | + "os" |
| 27 | + "sync" |
| 28 | + "testing" |
| 29 | + "time" |
| 30 | + |
| 31 | + "github.com/stretchr/testify/require" |
| 32 | + |
| 33 | + "vitess.io/vitess/go/mysql" |
| 34 | + "vitess.io/vitess/go/sqltypes" |
| 35 | + "vitess.io/vitess/go/test/endtoend/cluster" |
| 36 | + "vitess.io/vitess/go/test/endtoend/utils" |
| 37 | + binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata" |
| 38 | + querypb "vitess.io/vitess/go/vt/proto/query" |
| 39 | + topodatapb "vitess.io/vitess/go/vt/proto/topodata" |
| 40 | + "vitess.io/vitess/go/vt/vtgate/vtgateconn" |
| 41 | +) |
| 42 | + |
| 43 | +var ( |
| 44 | + clusterInstance *cluster.LocalProcessCluster |
| 45 | + vtParams mysql.ConnParams |
| 46 | + vtgateGrpcAddress string |
| 47 | + keyspaceName = "ks" |
| 48 | + cell = "zone1" |
| 49 | + hostname = "localhost" |
| 50 | + sidecarDBName = "vt_ks" |
| 51 | + |
| 52 | + //go:embed schema.sql |
| 53 | + SchemaSQL string |
| 54 | + |
| 55 | + //go:embed vschema.json |
| 56 | + VSchema string |
| 57 | +) |
| 58 | + |
| 59 | +func TestMain(m *testing.M) { |
| 60 | + defer cluster.PanicHandler(nil) |
| 61 | + flag.Parse() |
| 62 | + |
| 63 | + exitcode := func() int { |
| 64 | + clusterInstance = cluster.NewCluster(cell, hostname) |
| 65 | + defer clusterInstance.Teardown() |
| 66 | + |
| 67 | + // Start topo server |
| 68 | + if err := clusterInstance.StartTopo(); err != nil { |
| 69 | + return 1 |
| 70 | + } |
| 71 | + |
| 72 | + // Reserve vtGate port in order to pass it to vtTablet |
| 73 | + clusterInstance.VtgateGrpcPort = clusterInstance.GetAndReservePort() |
| 74 | + |
| 75 | + // Set extra args for twopc |
| 76 | + clusterInstance.VtGateExtraArgs = append(clusterInstance.VtGateExtraArgs, |
| 77 | + "--transaction_mode", "TWOPC", |
| 78 | + ) |
| 79 | + clusterInstance.VtTabletExtraArgs = append(clusterInstance.VtTabletExtraArgs, |
| 80 | + "--twopc_enable", |
| 81 | + "--twopc_coordinator_address", fmt.Sprintf("localhost:%d", clusterInstance.VtgateGrpcPort), |
| 82 | + "--twopc_abandon_age", "3600", |
| 83 | + "--queryserver-config-transaction-cap", "3", |
| 84 | + ) |
| 85 | + |
| 86 | + // Start keyspace |
| 87 | + keyspace := &cluster.Keyspace{ |
| 88 | + Name: keyspaceName, |
| 89 | + SchemaSQL: SchemaSQL, |
| 90 | + VSchema: VSchema, |
| 91 | + SidecarDBName: sidecarDBName, |
| 92 | + } |
| 93 | + if err := clusterInstance.StartKeyspace(*keyspace, []string{"-80", "80-"}, 1, false); err != nil { |
| 94 | + return 1 |
| 95 | + } |
| 96 | + |
| 97 | + // Start Vtgate |
| 98 | + if err := clusterInstance.StartVtgate(); err != nil { |
| 99 | + return 1 |
| 100 | + } |
| 101 | + vtParams = clusterInstance.GetVTParams(keyspaceName) |
| 102 | + vtgateGrpcAddress = fmt.Sprintf("%s:%d", clusterInstance.Hostname, clusterInstance.VtgateGrpcPort) |
| 103 | + |
| 104 | + return m.Run() |
| 105 | + }() |
| 106 | + os.Exit(exitcode) |
| 107 | +} |
| 108 | + |
| 109 | +func start(t *testing.T) (*mysql.Conn, func()) { |
| 110 | + ctx := context.Background() |
| 111 | + conn, err := mysql.Connect(ctx, &vtParams) |
| 112 | + require.NoError(t, err) |
| 113 | + |
| 114 | + deleteAll := func() { |
| 115 | + tables := []string{"twopc_user"} |
| 116 | + for _, table := range tables { |
| 117 | + _, _ = utils.ExecAllowError(t, conn, "delete from "+table) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + deleteAll() |
| 122 | + |
| 123 | + return conn, func() { |
| 124 | + deleteAll() |
| 125 | + conn.Close() |
| 126 | + cluster.PanicHandler(t) |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +type extractInterestingValues func(dtidMap map[string]string, vals []sqltypes.Value) []sqltypes.Value |
| 131 | + |
| 132 | +var tables = map[string]extractInterestingValues{ |
| 133 | + "ks.dt_state": func(dtidMap map[string]string, vals []sqltypes.Value) (out []sqltypes.Value) { |
| 134 | + dtid := getDTID(dtidMap, vals[0].ToString()) |
| 135 | + dtState := getDTState(vals[1]) |
| 136 | + out = append(out, sqltypes.NewVarChar(dtid), sqltypes.NewVarChar(dtState.String())) |
| 137 | + return |
| 138 | + }, |
| 139 | + "ks.dt_participant": func(dtidMap map[string]string, vals []sqltypes.Value) (out []sqltypes.Value) { |
| 140 | + dtid := getDTID(dtidMap, vals[0].ToString()) |
| 141 | + out = append([]sqltypes.Value{sqltypes.NewVarChar(dtid)}, vals[1:]...) |
| 142 | + return |
| 143 | + }, |
| 144 | + "ks.redo_state": func(dtidMap map[string]string, vals []sqltypes.Value) (out []sqltypes.Value) { |
| 145 | + dtid := getDTID(dtidMap, vals[0].ToString()) |
| 146 | + dtState := getDTState(vals[1]) |
| 147 | + out = append(out, sqltypes.NewVarChar(dtid), sqltypes.NewVarChar(dtState.String())) |
| 148 | + return |
| 149 | + }, |
| 150 | + "ks.redo_statement": func(dtidMap map[string]string, vals []sqltypes.Value) (out []sqltypes.Value) { |
| 151 | + dtid := getDTID(dtidMap, vals[0].ToString()) |
| 152 | + out = append([]sqltypes.Value{sqltypes.NewVarChar(dtid)}, vals[1:]...) |
| 153 | + return |
| 154 | + }, |
| 155 | + "ks.twopc_user": func(_ map[string]string, vals []sqltypes.Value) []sqltypes.Value { return vals }, |
| 156 | +} |
| 157 | + |
| 158 | +func getDTState(val sqltypes.Value) querypb.TransactionState { |
| 159 | + s, _ := val.ToInt() |
| 160 | + return querypb.TransactionState(s) |
| 161 | +} |
| 162 | + |
| 163 | +func getDTID(dtidMap map[string]string, dtKey string) string { |
| 164 | + dtid, exists := dtidMap[dtKey] |
| 165 | + if !exists { |
| 166 | + dtid = fmt.Sprintf("dtid-%d", len(dtidMap)+1) |
| 167 | + dtidMap[dtKey] = dtid |
| 168 | + } |
| 169 | + return dtid |
| 170 | +} |
| 171 | + |
| 172 | +func runVStream(t *testing.T, ctx context.Context, ch chan *binlogdatapb.VEvent, vtgateConn *vtgateconn.VTGateConn) { |
| 173 | + vgtid := &binlogdatapb.VGtid{ |
| 174 | + ShardGtids: []*binlogdatapb.ShardGtid{ |
| 175 | + {Keyspace: keyspaceName, Shard: "-80", Gtid: "current"}, |
| 176 | + {Keyspace: keyspaceName, Shard: "80-", Gtid: "current"}, |
| 177 | + }} |
| 178 | + filter := &binlogdatapb.Filter{ |
| 179 | + Rules: []*binlogdatapb.Rule{{ |
| 180 | + Match: "/.*/", |
| 181 | + }}, |
| 182 | + } |
| 183 | + vReader, err := vtgateConn.VStream(ctx, topodatapb.TabletType_PRIMARY, vgtid, filter, nil) |
| 184 | + require.NoError(t, err) |
| 185 | + |
| 186 | + // Use a channel to signal that the first VGTID event has been processed |
| 187 | + firstEventProcessed := make(chan struct{}) |
| 188 | + var once sync.Once |
| 189 | + |
| 190 | + go func() { |
| 191 | + for { |
| 192 | + evs, err := vReader.Recv() |
| 193 | + if err == io.EOF || ctx.Err() != nil { |
| 194 | + return |
| 195 | + } |
| 196 | + require.NoError(t, err) |
| 197 | + |
| 198 | + for _, ev := range evs { |
| 199 | + // Signal the first event has been processed using sync.Once |
| 200 | + if ev.Type == binlogdatapb.VEventType_VGTID { |
| 201 | + once.Do(func() { close(firstEventProcessed) }) |
| 202 | + } |
| 203 | + if ev.Type == binlogdatapb.VEventType_ROW || ev.Type == binlogdatapb.VEventType_FIELD { |
| 204 | + ch <- ev |
| 205 | + } |
| 206 | + } |
| 207 | + } |
| 208 | + }() |
| 209 | + |
| 210 | + // Wait for the first event to be processed |
| 211 | + <-firstEventProcessed |
| 212 | +} |
| 213 | + |
| 214 | +func retrieveTransitions(t *testing.T, ch chan *binlogdatapb.VEvent, tableMap map[string][]*querypb.Field, dtMap map[string]string) map[string][]string { |
| 215 | + logTable := make(map[string][]string) |
| 216 | + |
| 217 | + keepWaiting := true |
| 218 | + for keepWaiting { |
| 219 | + select { |
| 220 | + case re := <-ch: |
| 221 | + if re.RowEvent != nil { |
| 222 | + shard := re.RowEvent.Shard |
| 223 | + tableName := re.RowEvent.TableName |
| 224 | + fields, ok := tableMap[tableName] |
| 225 | + require.Truef(t, ok, "table %s not found in fields map", tableName) |
| 226 | + for _, rc := range re.RowEvent.RowChanges { |
| 227 | + logEvent(logTable, dtMap, shard, tableName, fields, rc) |
| 228 | + } |
| 229 | + } |
| 230 | + if re.FieldEvent != nil { |
| 231 | + tableMap[re.FieldEvent.TableName] = re.FieldEvent.Fields |
| 232 | + } |
| 233 | + case <-time.After(1 * time.Second): |
| 234 | + keepWaiting = false |
| 235 | + } |
| 236 | + } |
| 237 | + return logTable |
| 238 | +} |
| 239 | + |
| 240 | +func logEvent(logTable map[string][]string, dtMap map[string]string, shard string, tbl string, fields []*querypb.Field, rc *binlogdatapb.RowChange) { |
| 241 | + key := fmt.Sprintf("%s:%s", tbl, shard) |
| 242 | + |
| 243 | + var eventType string |
| 244 | + var vals []sqltypes.Value |
| 245 | + switch { |
| 246 | + case rc.Before == nil && rc.After == nil: |
| 247 | + panic("do not expect row event with both before and after nil") |
| 248 | + case rc.Before == nil: |
| 249 | + eventType = "insert" |
| 250 | + vals = sqltypes.MakeRowTrusted(fields, rc.After) |
| 251 | + case rc.After == nil: |
| 252 | + eventType = "delete" |
| 253 | + vals = sqltypes.MakeRowTrusted(fields, rc.Before) |
| 254 | + default: |
| 255 | + eventType = "update" |
| 256 | + vals = sqltypes.MakeRowTrusted(fields, rc.After) |
| 257 | + } |
| 258 | + execFunc, exists := tables[tbl] |
| 259 | + if exists { |
| 260 | + vals = execFunc(dtMap, vals) |
| 261 | + } |
| 262 | + logTable[key] = append(logTable[key], fmt.Sprintf("%s:%v", eventType, vals)) |
| 263 | +} |
| 264 | + |
| 265 | +func prettyPrint(v interface{}) string { |
| 266 | + b, err := json.MarshalIndent(v, "", " ") |
| 267 | + if err != nil { |
| 268 | + return fmt.Sprintf("got error marshalling: %v", err) |
| 269 | + } |
| 270 | + return string(b) |
| 271 | +} |
0 commit comments