forked from pingcap/tidb
/
plan_replayer.go
380 lines (365 loc) · 10.3 KB
/
plan_replayer.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
// Copyright 2021 PingCAP, Inc.
//
// 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 server
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/gorilla/mux"
"github.com/pingcap/errors"
"github.com/twotigers93/tidb/config"
"github.com/twotigers93/tidb/domain"
"github.com/twotigers93/tidb/domain/infosync"
"github.com/twotigers93/tidb/infoschema"
"github.com/twotigers93/tidb/parser/model"
"github.com/twotigers93/tidb/statistics/handle"
"github.com/twotigers93/tidb/util"
"github.com/twotigers93/tidb/util/logutil"
"github.com/twotigers93/tidb/util/replayer"
"go.uber.org/zap"
)
// PlanReplayerHandler is the handler for dumping plan replayer file.
type PlanReplayerHandler struct {
is infoschema.InfoSchema
statsHandle *handle.Handle
infoGetter *infosync.InfoSyncer
address string
statusPort uint
}
func (s *Server) newPlanReplayerHandler() *PlanReplayerHandler {
cfg := config.GetGlobalConfig()
prh := &PlanReplayerHandler{
address: cfg.AdvertiseAddress,
statusPort: cfg.Status.StatusPort,
}
if s.dom != nil && s.dom.InfoSyncer() != nil {
prh.infoGetter = s.dom.InfoSyncer()
}
if s.dom != nil && s.dom.InfoSchema() != nil {
prh.is = s.dom.InfoSchema()
}
if s.dom != nil && s.dom.StatsHandle() != nil {
prh.statsHandle = s.dom.StatsHandle()
}
return prh
}
func (prh PlanReplayerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
name := params[pFileName]
handler := downloadFileHandler{
filePath: filepath.Join(replayer.GetPlanReplayerDirName(), name),
fileName: name,
infoGetter: prh.infoGetter,
address: prh.address,
statusPort: prh.statusPort,
urlPath: fmt.Sprintf("plan_replayer/dump/%s", name),
downloadedFilename: "plan_replayer",
scheme: util.InternalHTTPSchema(),
statsHandle: prh.statsHandle,
is: prh.is,
}
handleDownloadFile(handler, w, req)
}
func handleDownloadFile(handler downloadFileHandler, w http.ResponseWriter, req *http.Request) {
params := mux.Vars(req)
name := params[pFileName]
path := handler.filePath
isForwarded := len(req.URL.Query().Get("forward")) > 0
localAddr := net.JoinHostPort(handler.address, strconv.Itoa(int(handler.statusPort)))
exist, err := isExists(path)
if err != nil {
writeError(w, err)
return
}
if exist {
//nolint: gosec
file, err := os.Open(path)
if err != nil {
writeError(w, err)
return
}
content, err := io.ReadAll(file)
if err != nil {
writeError(w, err)
return
}
err = file.Close()
if err != nil {
writeError(w, err)
return
}
if handler.downloadedFilename == "plan_replayer" {
content, err = handlePlanReplayerCaptureFile(content, path, handler)
if err != nil {
writeError(w, err)
return
}
}
_, err = w.Write(content)
if err != nil {
writeError(w, err)
return
}
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.zip\"", handler.downloadedFilename))
logutil.BgLogger().Info("return dump file successfully", zap.String("filename", name),
zap.String("address", localAddr), zap.Bool("forwarded", isForwarded))
return
}
// handler.infoGetter will be nil only in unit test
// or we couldn't find file for forward request, return 404
if handler.infoGetter == nil || isForwarded {
logutil.BgLogger().Info("failed to find dump file", zap.String("filename", name),
zap.String("address", localAddr), zap.Bool("forwarded", isForwarded))
w.WriteHeader(http.StatusNotFound)
return
}
// If we didn't find file in origin request, try to broadcast the request to all remote tidb-servers
topos, err := handler.infoGetter.GetAllTiDBTopology(req.Context())
if err != nil {
writeError(w, err)
return
}
client := util.InternalHTTPClient()
// transfer each remote tidb-server and try to find dump file
for _, topo := range topos {
if topo.IP == handler.address && topo.StatusPort == handler.statusPort {
continue
}
remoteAddr := net.JoinHostPort(topo.IP, strconv.Itoa(int(topo.StatusPort)))
url := fmt.Sprintf("%s://%s/%s?forward=true", handler.scheme, remoteAddr, handler.urlPath)
resp, err := client.Get(url)
if err != nil {
logutil.BgLogger().Error("forward request failed",
zap.String("remote-addr", remoteAddr), zap.Error(err))
continue
}
if resp.StatusCode != http.StatusOK {
logutil.BgLogger().Info("can't find file in remote server", zap.String("filename", name),
zap.String("remote-addr", remoteAddr), zap.Int("status-code", resp.StatusCode))
continue
}
content, err := io.ReadAll(resp.Body)
if err != nil {
writeError(w, err)
return
}
err = resp.Body.Close()
if err != nil {
writeError(w, err)
return
}
_, err = w.Write(content)
if err != nil {
writeError(w, err)
return
}
// find dump file in one remote tidb-server, return file directly
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.zip\"", handler.downloadedFilename))
logutil.BgLogger().Info("return dump file successfully in remote server",
zap.String("filename", name), zap.String("remote-addr", remoteAddr))
return
}
// we can't find dump file in any tidb-server, return 404 directly
logutil.BgLogger().Info("can't find dump file in any remote server", zap.String("filename", name))
w.WriteHeader(http.StatusNotFound)
_, err = w.Write([]byte(fmt.Sprintf("can't find dump file %s in any remote server", name)))
writeError(w, err)
}
type downloadFileHandler struct {
scheme string
filePath string
fileName string
infoGetter *infosync.InfoSyncer
address string
statusPort uint
urlPath string
downloadedFilename string
statsHandle *handle.Handle
is infoschema.InfoSchema
}
func isExists(path string) (bool, error) {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
func handlePlanReplayerCaptureFile(content []byte, path string, handler downloadFileHandler) ([]byte, error) {
if !strings.HasPrefix(handler.filePath, "capture_replayer") {
return content, nil
}
b := bytes.NewReader(content)
zr, err := zip.NewReader(b, int64(len(content)))
if err != nil {
return nil, err
}
startTS, err := loadSQLMetaFile(zr)
if err != nil {
return nil, err
}
if startTS == 0 {
return content, nil
}
tbls, err := loadSchemaMeta(zr, handler.is)
if err != nil {
return nil, err
}
for _, tbl := range tbls {
jsonStats, err := handler.statsHandle.DumpHistoricalStatsBySnapshot(tbl.dbName, tbl.info, startTS)
if err != nil {
return nil, err
}
tbl.jsonStats = jsonStats
}
newPath, err := dumpJSONStatsIntoZip(tbls, content, path)
if err != nil {
return nil, err
}
//nolint: gosec
file, err := os.Open(newPath)
if err != nil {
return nil, err
}
content, err = io.ReadAll(file)
if err != nil {
return nil, err
}
err = file.Close()
if err != nil {
return nil, err
}
return content, nil
}
func loadSQLMetaFile(z *zip.Reader) (uint64, error) {
for _, zipFile := range z.File {
if zipFile.Name == domain.PlanReplayerSQLMetaFile {
varMap := make(map[string]string)
v, err := zipFile.Open()
if err != nil {
return 0, errors.AddStack(err)
}
//nolint: errcheck,all_revive
defer v.Close()
_, err = toml.NewDecoder(v).Decode(&varMap)
if err != nil {
return 0, errors.AddStack(err)
}
startTS, err := strconv.ParseUint(varMap[domain.PlanReplayerSQLMetaStartTS], 10, 64)
if err != nil {
return 0, err
}
return startTS, nil
}
}
return 0, nil
}
func loadSchemaMeta(z *zip.Reader, is infoschema.InfoSchema) (map[int64]*tblInfo, error) {
r := make(map[int64]*tblInfo, 0)
for _, zipFile := range z.File {
if zipFile.Name == fmt.Sprintf("schema/%v", domain.PlanReplayerSchemaMetaFile) {
v, err := zipFile.Open()
if err != nil {
return nil, errors.AddStack(err)
}
//nolint: errcheck,all_revive
defer v.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(v)
if err != nil {
return nil, errors.AddStack(err)
}
rows := strings.Split(buf.String(), "\n")
for _, row := range rows {
s := strings.Split(row, ";")
databaseName := s[0]
tableName := s[1]
t, err := is.TableByName(model.NewCIStr(databaseName), model.NewCIStr(tableName))
if err != nil {
return nil, err
}
r[t.Meta().ID] = &tblInfo{
info: t.Meta(),
dbName: databaseName,
tblName: tableName,
}
}
break
}
}
return r, nil
}
func dumpJSONStatsIntoZip(tbls map[int64]*tblInfo, content []byte, path string) (string, error) {
zr, err := zip.NewReader(bytes.NewReader(content), int64(len(content)))
if err != nil {
return "", err
}
newPath := strings.Replace(path, "capture_replayer", "copy_capture_replayer", 1)
zf, err := os.Create(newPath)
if err != nil {
return "", err
}
zw := zip.NewWriter(zf)
for _, f := range zr.File {
err = zw.Copy(f)
if err != nil {
logutil.BgLogger().Error("copy plan replayer zip file failed", zap.Error(err))
return "", err
}
}
for _, tbl := range tbls {
w, err := zw.Create(fmt.Sprintf("stats/%v.%v.json", tbl.dbName, tbl.tblName))
if err != nil {
return "", err
}
data, err := json.Marshal(tbl.jsonStats)
if err != nil {
return "", err
}
_, err = w.Write(data)
if err != nil {
return "", err
}
}
err = zw.Close()
if err != nil {
logutil.BgLogger().Error("Closing file failed", zap.Error(err))
return "", err
}
err = zf.Close()
if err != nil {
logutil.BgLogger().Error("Closing file failed", zap.Error(err))
return "", err
}
return newPath, nil
}
type tblInfo struct {
info *model.TableInfo
jsonStats *handle.JSONTable
dbName string
tblName string
}