/
tikv.go
470 lines (412 loc) · 13.5 KB
/
tikv.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
// Copyright 2020 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package spec
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/luyomo/OhMyTiUP/pkg/aws/api"
"github.com/luyomo/OhMyTiUP/pkg/aws/template/scripts"
"github.com/luyomo/OhMyTiUP/pkg/ctxt"
"github.com/luyomo/OhMyTiUP/pkg/logger/log"
"github.com/luyomo/OhMyTiUP/pkg/meta"
"github.com/luyomo/OhMyTiUP/pkg/utils"
perrs "github.com/pingcap/errors"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
)
const (
metricNameRegionCount = "tikv_raftstore_region_count"
labelNameLeaderCount = "leader"
)
// TiKVSpec represents the TiKV topology specification in topology.yaml
type TiKVSpec struct {
Host string `yaml:"host"`
ListenHost string `yaml:"listen_host,omitempty"`
AdvertiseAddr string `yaml:"advertise_addr,omitempty"`
SSHPort int `yaml:"ssh_port,omitempty" validate:"ssh_port:editable"`
Imported bool `yaml:"imported,omitempty"`
Patched bool `yaml:"patched,omitempty"`
IgnoreExporter bool `yaml:"ignore_exporter,omitempty"`
Port int `yaml:"port" default:"20160"`
StatusPort int `yaml:"status_port" default:"20180"`
AdvertiseStatusAddr string `yaml:"advertise_status_addr,omitempty"`
DeployDir string `yaml:"deploy_dir,omitempty"`
DataDir string `yaml:"data_dir,omitempty"`
LogDir string `yaml:"log_dir,omitempty"`
Offline bool `yaml:"offline,omitempty"`
NumaNode string `yaml:"numa_node,omitempty" validate:"numa_node:editable"`
Config map[string]interface{} `yaml:"config,omitempty" validate:"config:ignore"`
ResourceControl meta.ResourceControl `yaml:"resource_control,omitempty" validate:"resource_control:editable"`
Arch string `yaml:"arch,omitempty"`
OS string `yaml:"os,omitempty"`
}
// checkStoreStatus checks the store status in current cluster
func checkStoreStatus(storeAddr string, tlsCfg *tls.Config, pdList ...string) string {
if len(pdList) < 1 {
return "N/A"
}
pdapi := api.NewPDClient(pdList, statusQueryTimeout, tlsCfg)
store, err := pdapi.GetCurrentStore(storeAddr)
if err != nil {
if errors.Is(err, api.ErrNoStore) {
return "N/A"
}
return "Down"
}
return store.Store.StateName
}
// Status queries current status of the instance
func (s *TiKVSpec) Status(tlsCfg *tls.Config, pdList ...string) string {
storeAddr := addr(s)
state := checkStoreStatus(storeAddr, tlsCfg, pdList...)
if s.Offline && strings.ToLower(state) == "offline" {
state = "Pending Offline" // avoid misleading
}
return state
}
// Role returns the component role of the instance
func (s *TiKVSpec) Role() string {
return ComponentTiKV
}
// SSH returns the host and SSH port of the instance
func (s *TiKVSpec) SSH() (string, int) {
return s.Host, s.SSHPort
}
// GetMainPort returns the main port of the instance
func (s *TiKVSpec) GetMainPort() int {
return s.Port
}
// IsImported returns if the node is imported from TiDB-Ansible
func (s *TiKVSpec) IsImported() bool {
return s.Imported
}
// IgnoreMonitorAgent returns if the node does not have monitor agents available
func (s *TiKVSpec) IgnoreMonitorAgent() bool {
return s.IgnoreExporter
}
// Labels returns the labels of TiKV
func (s *TiKVSpec) Labels() (map[string]string, error) {
lbs := make(map[string]string)
if serverLabels := GetValueFromPath(s.Config, "server.labels"); serverLabels != nil {
m := map[interface{}]interface{}{}
if sm, ok := serverLabels.(map[string]interface{}); ok {
for k, v := range sm {
m[k] = v
}
} else if im, ok := serverLabels.(map[interface{}]interface{}); ok {
m = im
}
for k, v := range m {
key, ok := k.(string)
if !ok {
return nil, perrs.Errorf("TiKV label name %v is not a string, check the instance: %s:%d", k, s.Host, s.GetMainPort())
}
value, ok := v.(string)
if !ok {
return nil, perrs.Errorf("TiKV label value %v is not a string, check the instance: %s:%d", v, s.Host, s.GetMainPort())
}
lbs[key] = value
}
}
return lbs, nil
}
// TiKVComponent represents TiKV component.
type TiKVComponent struct{ Topology *Specification }
// Name implements Component interface.
func (c *TiKVComponent) Name() string {
return ComponentTiKV
}
// Role implements Component interface.
func (c *TiKVComponent) Role() string {
return ComponentTiKV
}
// Instances implements Component interface.
func (c *TiKVComponent) Instances() []Instance {
ins := make([]Instance, 0, len(c.Topology.TiKVServers))
for _, s := range c.Topology.TiKVServers {
s := s
ins = append(ins, &TiKVInstance{BaseInstance{
InstanceSpec: s,
Name: c.Name(),
Host: s.Host,
ListenHost: s.ListenHost,
Port: s.Port,
SSHP: s.SSHPort,
Ports: []int{
s.Port,
s.StatusPort,
},
Dirs: []string{
s.DeployDir,
s.DataDir,
},
StatusFn: s.Status,
UptimeFn: func(tlsCfg *tls.Config) time.Duration {
return UptimeByHost(s.Host, s.StatusPort, tlsCfg)
},
}, c.Topology})
}
return ins
}
// TiKVInstance represent the TiDB instance
type TiKVInstance struct {
BaseInstance
topo Topology
}
// InitConfig implement Instance interface
func (i *TiKVInstance) InitConfig(
ctx context.Context,
e ctxt.Executor,
clusterName,
clusterVersion,
deployUser string,
paths meta.DirPaths,
) error {
topo := i.topo.(*Specification)
if err := i.BaseInstance.InitConfig(ctx, e, topo.GlobalOptions, deployUser, paths); err != nil {
return err
}
enableTLS := topo.GlobalOptions.TLSEnabled
spec := i.InstanceSpec.(*TiKVSpec)
cfg := scripts.
NewTiKVScript(clusterVersion, i.GetHost(), spec.Port, spec.StatusPort, paths.Deploy, paths.Data[0], paths.Log).
WithNumaNode(spec.NumaNode).
AppendEndpoints(topo.Endpoints(deployUser)...).
WithListenHost(i.GetListenHost()).
WithAdvertiseAddr(spec.AdvertiseAddr).
WithAdvertiseStatusAddr(spec.AdvertiseStatusAddr)
fp := filepath.Join(paths.Cache, fmt.Sprintf("run_tikv_%s_%d.sh", i.GetHost(), i.GetPort()))
if err := cfg.ConfigToFile(fp); err != nil {
return err
}
dst := filepath.Join(paths.Deploy, "scripts", "run_tikv.sh")
if err := e.Transfer(ctx, fp, dst, false, 0); err != nil {
return err
}
if _, _, err := e.Execute(ctx, "chmod +x "+dst, false); err != nil {
return err
}
globalConfig := topo.ServerConfigs.TiKV
// merge config files for imported instance
if i.IsImported() {
configPath := ClusterPath(
clusterName,
AnsibleImportedConfigPath,
fmt.Sprintf(
"%s-%s-%d.toml",
i.ComponentName(),
i.GetHost(),
i.GetPort(),
),
)
importConfig, err := os.ReadFile(configPath)
if err != nil {
return err
}
globalConfig, err = mergeImported(importConfig, globalConfig)
if err != nil {
return err
}
}
// set TLS configs
if enableTLS {
if spec.Config == nil {
spec.Config = make(map[string]interface{})
}
spec.Config["security.ca-path"] = fmt.Sprintf(
"%s/tls/%s",
paths.Deploy,
TLSCACert,
)
spec.Config["security.cert-path"] = fmt.Sprintf(
"%s/tls/%s.crt",
paths.Deploy,
i.Role())
spec.Config["security.key-path"] = fmt.Sprintf(
"%s/tls/%s.pem",
paths.Deploy,
i.Role())
}
if err := i.MergeServerConfig(ctx, e, globalConfig, spec.Config, paths); err != nil {
return err
}
return checkConfig(ctx, e, i.ComponentName(), clusterVersion, i.OS(), i.Arch(), i.ComponentName()+".toml", paths, nil)
}
// ScaleConfig deploy temporary config on scaling
func (i *TiKVInstance) ScaleConfig(
ctx context.Context,
e ctxt.Executor,
topo Topology,
clusterName,
clusterVersion,
deployUser string,
paths meta.DirPaths,
) error {
s := i.topo
defer func() {
i.topo = s
}()
i.topo = mustBeClusterTopo(topo)
return i.InitConfig(ctx, e, clusterName, clusterVersion, deployUser, paths)
}
var _ RollingUpdateInstance = &TiKVInstance{}
// PreRestart implements RollingUpdateInstance interface.
func (i *TiKVInstance) PreRestart(topo Topology, apiTimeoutSeconds int, tlsCfg *tls.Config) error {
timeoutOpt := &utils.RetryOption{
Timeout: time.Second * time.Duration(apiTimeoutSeconds),
Delay: time.Second * 2,
}
tidbTopo, ok := topo.(*Specification)
if !ok {
panic("should be type of tidb topology")
}
if len(tidbTopo.TiKVServers) <= 1 {
return nil
}
pdClient := api.NewPDClient(tidbTopo.GetPDList(), 5*time.Second, tlsCfg)
// Make sure there's leader of PD.
// Although we evict pd leader when restart pd,
// But when there's only one PD instance the pd might not serve request right away after restart.
err := pdClient.WaitLeader(timeoutOpt)
if err != nil {
return err
}
if err := pdClient.EvictStoreLeader(addr(i.InstanceSpec.(*TiKVSpec)), timeoutOpt, genLeaderCounter(tidbTopo, tlsCfg)); err != nil {
if utils.IsTimeoutOrMaxRetry(err) {
log.Warnf("Ignore evicting store leader from %s, %v", i.ID(), err)
} else {
return perrs.Annotatef(err, "failed to evict store leader %s", i.GetHost())
}
}
return nil
}
// PostRestart implements RollingUpdateInstance interface.
func (i *TiKVInstance) PostRestart(topo Topology, tlsCfg *tls.Config) error {
tidbTopo, ok := topo.(*Specification)
if !ok {
panic("should be type of tidb topology")
}
if len(tidbTopo.TiKVServers) <= 1 {
return nil
}
pdClient := api.NewPDClient(tidbTopo.GetPDList(), 5*time.Second, tlsCfg)
// remove store leader evict scheduler after restart
if err := pdClient.RemoveStoreEvict(addr(i.InstanceSpec.(*TiKVSpec))); err != nil {
return perrs.Annotatef(err, "failed to remove evict store scheduler for %s", i.GetHost())
}
return nil
}
func addr(spec *TiKVSpec) string {
if spec.AdvertiseAddr != "" {
return spec.AdvertiseAddr
}
if spec.Port == 0 || spec.Port == 80 {
panic(fmt.Sprintf("invalid TiKV port %d", spec.Port))
}
return spec.Host + ":" + strconv.Itoa(spec.Port)
}
func genLeaderCounter(topo *Specification, tlsCfg *tls.Config) func(string) (int, error) {
return func(id string) (int, error) {
statusAddress := ""
foundIds := []string{}
for _, kv := range topo.TiKVServers {
kvid := fmt.Sprintf("%s:%d", kv.Host, kv.Port)
if id == kvid {
statusAddress = fmt.Sprintf("%s:%d", kv.Host, kv.StatusPort)
break
}
foundIds = append(foundIds, kvid)
}
if statusAddress == "" {
return 0, fmt.Errorf("TiKV instance with ID %s not found, found %s", id, strings.Join(foundIds, ","))
}
transport := makeTransport(tlsCfg)
mfChan := make(chan *dto.MetricFamily, 1024)
go func() {
addr := fmt.Sprintf("http://%s/metrics", statusAddress)
// XXX: https://github.com/tikv/tikv/issues/5340
// Some TiKV versions don't handle https correctly
// So we check if it's in that case first
if tlsCfg != nil && checkHTTPS(fmt.Sprintf("https://%s/metrics", statusAddress), tlsCfg) == nil {
addr = fmt.Sprintf("https://%s/metrics", statusAddress)
}
if err := prom2json.FetchMetricFamilies(addr, mfChan, transport); err != nil {
log.Errorf("failed counting leader on %s (status addr %s), %v", id, addr, err)
}
}()
fms := []*prom2json.Family{}
for mf := range mfChan {
fm := prom2json.NewFamily(mf)
fms = append(fms, fm)
}
for _, fm := range fms {
if fm.Name != metricNameRegionCount {
continue
}
for _, m := range fm.Metrics {
if m, ok := m.(prom2json.Metric); ok && m.Labels["type"] == labelNameLeaderCount {
return strconv.Atoi(m.Value)
}
}
}
return 0, perrs.Errorf("metric %s{type=\"%s\"} not found", metricNameRegionCount, labelNameLeaderCount)
}
}
func makeTransport(tlsCfg *tls.Config) *http.Transport {
// Start with the DefaultTransport for sane defaults.
transport := http.DefaultTransport.(*http.Transport).Clone()
// Conservatively disable HTTP keep-alives as this program will only
// ever need a single HTTP request.
transport.DisableKeepAlives = true
// Timeout early if the server doesn't even return the headers.
transport.ResponseHeaderTimeout = time.Minute
// We should clone a tlsCfg because we use it across goroutine
if tlsCfg != nil {
transport.TLSClientConfig = tlsCfg.Clone()
}
// prefer to use the inner http proxy
httpProxy := os.Getenv("TIUP_INNER_HTTP_PROXY")
if len(httpProxy) == 0 {
httpProxy = os.Getenv("HTTP_PROXY")
}
if len(httpProxy) > 0 {
if proxyURL, err := url.Parse(httpProxy); err == nil {
transport.Proxy = http.ProxyURL(proxyURL)
}
}
return transport
}
// Check if the url works with tlsCfg
func checkHTTPS(url string, tlsCfg *tls.Config) error {
transport := makeTransport(tlsCfg)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return perrs.Annotatef(err, "creating GET request for URL %q failed", url)
}
client := http.Client{Transport: transport}
resp, err := client.Do(req)
if err != nil {
return perrs.Annotatef(err, "executing GET request for URL %q failed", url)
}
resp.Body.Close()
return nil
}