/
playground.go
1476 lines (1303 loc) · 39.3 KB
/
playground.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/AstroProfundis/tabby"
"github.com/fatih/color"
"github.com/juju/ansiterm"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/components/playground/instance"
"github.com/pingcap/tiup/pkg/cluster/api"
"github.com/pingcap/tiup/pkg/cluster/spec"
"github.com/pingcap/tiup/pkg/environment"
logprinter "github.com/pingcap/tiup/pkg/logger/printer"
"github.com/pingcap/tiup/pkg/tidbver"
"github.com/pingcap/tiup/pkg/tui/progress"
"github.com/pingcap/tiup/pkg/utils"
"golang.org/x/mod/semver"
"golang.org/x/sync/errgroup"
)
// The duration process need to quit gracefully, or we kill the process.
const forceKillAfterDuration = time.Second * 10
// Playground represent the playground of a cluster.
type Playground struct {
dataDir string
booted bool
// the latest receive signal
curSig int32
bootOptions *BootOptions
port int
pds []*instance.PDInstance
tsos []*instance.PDInstance
schedulings []*instance.PDInstance
tikvs []*instance.TiKVInstance
tidbs []*instance.TiDBInstance
tiflashs []*instance.TiFlashInstance
tiproxys []*instance.TiProxy
ticdcs []*instance.TiCDC
tikvCdcs []*instance.TiKVCDC
pumps []*instance.Pump
drainers []*instance.Drainer
startedInstances []instance.Instance
idAlloc map[string]int
instanceWaiter errgroup.Group
// not nil iff we start the exec.Cmd successfully.
// we should and can safely call wait() to make sure the process quit
// before playground quit.
monitor *monitor
ngmonitoring *ngMonitoring
grafana *grafana
}
// MonitorInfo represent the monitor
type MonitorInfo struct {
IP string `json:"ip"`
Port int `json:"port"`
BinaryPath string `json:"binary_path"`
}
// NewPlayground create a Playground instance.
func NewPlayground(dataDir string, port int) *Playground {
return &Playground{
dataDir: dataDir,
port: port,
idAlloc: make(map[string]int),
}
}
func (p *Playground) allocID(componentID string) int {
id := p.idAlloc[componentID]
p.idAlloc[componentID] = id + 1
return id
}
func (p *Playground) handleDisplay(r io.Writer) (err error) {
w := ansiterm.NewTabWriter(r, 0, 0, 2, ' ', 0)
t := tabby.NewCustom(w)
// TODO add more info.
header := []any{"Pid", "Role", "Uptime"}
t.AddHeader(header...)
err = p.WalkInstances(func(componentID string, ins instance.Instance) error {
row := make([]any, len(header))
row[0] = strconv.Itoa(ins.Pid())
row[1] = componentID
row[2] = ins.Uptime()
t.AddLine(row...)
return nil
})
if err != nil {
return err
}
t.Print()
return nil
}
var timeoutOpt = &utils.RetryOption{
Timeout: time.Second * 15,
Delay: time.Second * 5,
}
func (p *Playground) binlogClient() (*api.BinlogClient, error) {
var addrs []string
for _, inst := range p.pds {
addrs = append(addrs, inst.Addr())
}
return api.NewBinlogClient(addrs, 5*time.Second, nil)
}
func (p *Playground) pdClient() *api.PDClient {
var addrs []string
for _, inst := range p.pds {
addrs = append(addrs, inst.Addr())
}
return api.NewPDClient(
context.WithValue(context.TODO(), logprinter.ContextKeyLogger, log),
addrs, 10*time.Second, nil,
)
}
func (p *Playground) killKVIfTombstone(inst *instance.TiKVInstance) {
defer logIfErr(p.renderSDFile())
for {
tombstone, err := p.pdClient().IsTombStone(inst.Addr())
if err != nil {
fmt.Println(err)
}
if tombstone {
for i, e := range p.tikvs {
if e == inst {
fmt.Printf("stop tombstone tikv %s\n", inst.Addr())
err = syscall.Kill(inst.Pid(), syscall.SIGQUIT)
if err != nil {
fmt.Println(err)
}
p.tikvs = append(p.tikvs[:i], p.tikvs[i+1:]...)
return
}
}
}
time.Sleep(time.Second * 5)
}
}
func (p *Playground) removePumpWhenTombstone(c *api.BinlogClient, inst *instance.Pump) {
defer logIfErr(p.renderSDFile())
for {
tombstone, err := c.IsPumpTombstone(context.TODO(), inst.Addr())
if err != nil {
fmt.Println(err)
}
if tombstone {
for i, e := range p.pumps {
if e == inst {
fmt.Printf("pump already offline %s\n", inst.Addr())
p.pumps = append(p.pumps[:i], p.pumps[i+1:]...)
return
}
}
}
time.Sleep(time.Second * 5)
}
}
func (p *Playground) removeDrainerWhenTombstone(c *api.BinlogClient, inst *instance.Drainer) {
defer logIfErr(p.renderSDFile())
for {
tombstone, err := c.IsDrainerTombstone(context.TODO(), inst.Addr())
if err != nil {
fmt.Println(err)
}
if tombstone {
for i, e := range p.drainers {
if e == inst {
fmt.Printf("drainer already offline %s\n", inst.Addr())
p.drainers = append(p.drainers[:i], p.drainers[i+1:]...)
return
}
}
}
time.Sleep(time.Second * 5)
}
}
func (p *Playground) killTiFlashIfTombstone(inst *instance.TiFlashInstance) {
defer logIfErr(p.renderSDFile())
for {
tombstone, err := p.pdClient().IsTombStone(inst.Addr())
if err != nil {
fmt.Println(err)
}
if tombstone {
for i, e := range p.tiflashs {
if e == inst {
fmt.Printf("stop tombstone tiflash %s\n", inst.Addr())
err = syscall.Kill(inst.Pid(), syscall.SIGQUIT)
if err != nil {
fmt.Println(err)
}
p.tiflashs = append(p.tiflashs[:i], p.tiflashs[i+1:]...)
return
}
}
}
time.Sleep(time.Second * 5)
}
}
func (p *Playground) handleScaleIn(w io.Writer, pid int) error {
var cid string
var inst instance.Instance
err := p.WalkInstances(func(wcid string, winst instance.Instance) error {
if winst.Pid() == pid {
cid = wcid
inst = winst
}
return nil
})
if err != nil {
return err
}
if inst == nil {
fmt.Fprintf(w, "no instance with id: %d\n", pid)
return nil
}
switch cid {
case spec.ComponentPD:
// microservice not support scale in temporarily
for i := 0; i < len(p.pds); i++ {
if p.pds[i].Pid() == pid {
inst := p.pds[i]
err := p.pdClient().DelPD(inst.Name(), timeoutOpt)
if err != nil {
return err
}
p.pds = append(p.pds[:i], p.pds[i+1:]...)
}
}
case spec.ComponentTiKV:
for i := 0; i < len(p.tikvs); i++ {
if p.tikvs[i].Pid() == pid {
inst := p.tikvs[i]
err := p.pdClient().DelStore(inst.Addr(), timeoutOpt)
if err != nil {
return err
}
go p.killKVIfTombstone(inst)
fmt.Fprintf(w, "tikv will be stop when tombstone\n")
return nil
}
}
case spec.ComponentTiDB:
for i := 0; i < len(p.tidbs); i++ {
if p.tidbs[i].Pid() == pid {
p.tidbs = append(p.tidbs[:i], p.tidbs[i+1:]...)
}
}
case spec.ComponentCDC:
for i := 0; i < len(p.ticdcs); i++ {
if p.ticdcs[i].Pid() == pid {
p.ticdcs = append(p.ticdcs[:i], p.ticdcs[i+1:]...)
}
}
case spec.ComponentTiProxy:
for i := 0; i < len(p.tiproxys); i++ {
if p.tiproxys[i].Pid() == pid {
p.tiproxys = append(p.tiproxys[:i], p.tiproxys[i+1:]...)
}
}
case spec.ComponentTiKVCDC:
for i := 0; i < len(p.tikvCdcs); i++ {
if p.tikvCdcs[i].Pid() == pid {
p.tikvCdcs = append(p.tikvCdcs[:i], p.tikvCdcs[i+1:]...)
}
}
case spec.ComponentTiFlash:
for i := 0; i < len(p.tiflashs); i++ {
if p.tiflashs[i].Pid() == pid {
inst := p.tiflashs[i]
err := p.pdClient().DelStore(inst.Addr(), timeoutOpt)
if err != nil {
return err
}
go p.killTiFlashIfTombstone(inst)
fmt.Fprintf(w, "TiFlash will be stop when tombstone\n")
return nil
}
}
case spec.ComponentPump:
for i := 0; i < len(p.pumps); i++ {
if p.pumps[i].Pid() == pid {
inst := p.pumps[i]
c, err := p.binlogClient()
if err != nil {
return err
}
err = c.OfflinePump(context.TODO(), inst.Addr())
if err != nil {
return err
}
go p.removePumpWhenTombstone(c, inst)
fmt.Fprintf(w, "pump will be stop when offline\n")
return nil
}
}
case spec.ComponentDrainer:
for i := 0; i < len(p.drainers); i++ {
if p.drainers[i].Pid() == pid {
inst := p.drainers[i]
c, err := p.binlogClient()
if err != nil {
return err
}
err = c.OfflineDrainer(context.TODO(), inst.Addr())
if err != nil {
return err
}
go p.removeDrainerWhenTombstone(c, inst)
fmt.Fprintf(w, "drainer will be stop when offline\n")
return nil
}
}
default:
fmt.Fprintf(w, "unknown component in scale in: %s", cid)
return nil
}
err = syscall.Kill(pid, syscall.SIGQUIT)
if err != nil {
return errors.AddStack(err)
}
logIfErr(p.renderSDFile())
fmt.Fprintf(w, "scale in %s success\n", cid)
return nil
}
func (p *Playground) sanitizeConfig(boot instance.Config, cfg *instance.Config) error {
if cfg.BinPath == "" {
cfg.BinPath = boot.BinPath
}
if cfg.ConfigPath == "" {
cfg.ConfigPath = boot.ConfigPath
}
if cfg.Host == "" {
cfg.Host = boot.Host
}
path, err := getAbsolutePath(cfg.ConfigPath)
if err != nil {
return err
}
cfg.ConfigPath = path
return nil
}
func (p *Playground) sanitizeComponentConfig(cid string, cfg *instance.Config) error {
switch cid {
case spec.ComponentPD:
return p.sanitizeConfig(p.bootOptions.PD, cfg)
case spec.ComponentTiKV:
return p.sanitizeConfig(p.bootOptions.TiKV, cfg)
case spec.ComponentTiDB:
return p.sanitizeConfig(p.bootOptions.TiDB, cfg)
case spec.ComponentTiFlash:
return p.sanitizeConfig(p.bootOptions.TiFlash, cfg)
case spec.ComponentCDC:
return p.sanitizeConfig(p.bootOptions.TiCDC, cfg)
case spec.ComponentTiKVCDC:
return p.sanitizeConfig(p.bootOptions.TiKVCDC, cfg)
case spec.ComponentPump:
return p.sanitizeConfig(p.bootOptions.Pump, cfg)
case spec.ComponentDrainer:
return p.sanitizeConfig(p.bootOptions.Drainer, cfg)
case spec.ComponentTiProxy:
return p.sanitizeConfig(p.bootOptions.TiProxy, cfg)
default:
return fmt.Errorf("unknown %s in sanitizeConfig", cid)
}
}
func (p *Playground) startInstance(ctx context.Context, inst instance.Instance) error {
var version utils.Version
var err error
boundVersion := p.bindVersion(inst.Component(), p.bootOptions.Version)
component := inst.Component()
if component == "tso" || component == "scheduling" {
component = string(instance.PDRoleNormal)
}
version, err = environment.GlobalEnv().V1Repository().ResolveComponentVersion(component, boundVersion)
if err != nil {
return err
}
fmt.Printf("Start %s instance:%s\n", inst.Component(), version)
err = inst.Start(ctx, version)
if err != nil {
return err
}
p.addWaitInstance(inst)
return nil
}
func (p *Playground) addWaitInstance(inst instance.Instance) {
p.startedInstances = append(p.startedInstances, inst)
p.instanceWaiter.Go(func() error {
err := inst.Wait()
if err != nil && atomic.LoadInt32(&p.curSig) == 0 {
fmt.Print(color.RedString("%s quit: %s\n", inst.Component(), err.Error()))
if lines, _ := utils.TailN(inst.LogFile(), 10); len(lines) > 0 {
for _, line := range lines {
fmt.Println(line)
}
fmt.Print(color.YellowString("...\ncheck detail log from: %s\n", inst.LogFile()))
}
} else {
fmt.Printf("%s quit\n", inst.Component())
}
return err
})
}
func (p *Playground) handleScaleOut(w io.Writer, cmd *Command) error {
// Ignore Config.Num, always one command as scale out one instance.
err := p.sanitizeComponentConfig(cmd.ComponentID, &cmd.Config)
if err != nil {
return err
}
// TODO: Support scale-out in CSE mode
inst, err := p.addInstance(cmd.ComponentID, instance.PDRoleNormal, instance.TiFlashRoleNormal, cmd.Config)
if err != nil {
return err
}
err = p.startInstance(
context.WithValue(context.TODO(), logprinter.ContextKeyLogger, log),
inst,
)
if err != nil {
return err
}
if cmd.ComponentID == "tidb" {
addr := p.tidbs[len(p.tidbs)-1].Addr()
if checkDB(addr, cmd.UpTimeout) {
ss := strings.Split(addr, ":")
connectMsg := "To connect new added TiDB: mysql --comments --host %s --port %s -u root -p (no password)"
fmt.Println(color.GreenString(connectMsg, ss[0], ss[1]))
fmt.Fprintln(w, color.GreenString(connectMsg, ss[0], ss[1]))
}
}
if cmd.ComponentID == "tiproxy" {
addr := p.tiproxys[len(p.tidbs)-1].Addr()
if checkDB(addr, cmd.UpTimeout) {
ss := strings.Split(addr, ":")
connectMsg := "To connect to the newly added TiProxy: mysql --comments --host %s --port %s -u root -p (no password)"
fmt.Println(color.GreenString(connectMsg, ss[0], ss[1]))
fmt.Fprintln(w, color.GreenString(connectMsg, ss[0], ss[1]))
}
}
logIfErr(p.renderSDFile())
return nil
}
func (p *Playground) handleCommand(cmd *Command, w io.Writer) error {
fmt.Printf("receive command: %s\n", cmd.CommandType)
switch cmd.CommandType {
case DisplayCommandType:
return p.handleDisplay(w)
case ScaleInCommandType:
return p.handleScaleIn(w, cmd.PID)
case ScaleOutCommandType:
return p.handleScaleOut(w, cmd)
}
return nil
}
func (p *Playground) listenAndServeHTTP() error {
http.HandleFunc("/command", p.commandHandler)
return http.ListenAndServe(":"+strconv.Itoa(p.port), nil)
}
func (p *Playground) commandHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
data, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(403)
fmt.Fprintln(w, err)
return
}
cmd := new(Command)
err = json.Unmarshal(data, cmd)
if err != nil {
w.WriteHeader(403)
fmt.Fprintln(w, err)
return
}
// Mapping command line component id to internal spec component id.
if cmd.ComponentID == "ticdc" {
cmd.ComponentID = spec.ComponentCDC
}
err = p.handleCommand(cmd, w)
if err != nil {
w.WriteHeader(403)
fmt.Fprintln(w, err)
}
}
// RWalkInstances work like WalkInstances, but in the reverse order.
func (p *Playground) RWalkInstances(fn func(componentID string, ins instance.Instance) error) error {
var ids []string
var instances []instance.Instance
_ = p.WalkInstances(func(id string, ins instance.Instance) error {
ids = append(ids, id)
instances = append(instances, ins)
return nil
})
for i := len(ids); i > 0; i-- {
err := fn(ids[i-1], instances[i-1])
if err != nil {
return err
}
}
return nil
}
// WalkInstances call fn for every instance and stop if return not nil.
func (p *Playground) WalkInstances(fn func(componentID string, ins instance.Instance) error) error {
for _, ins := range p.pds {
err := fn(spec.ComponentPD, ins)
if err != nil {
return err
}
}
for _, ins := range p.tsos {
err := fn(spec.ComponentPD, ins)
if err != nil {
return err
}
}
for _, ins := range p.schedulings {
err := fn(spec.ComponentPD, ins)
if err != nil {
return err
}
}
for _, ins := range p.tikvs {
err := fn(spec.ComponentTiKV, ins)
if err != nil {
return err
}
}
for _, ins := range p.pumps {
err := fn(spec.ComponentPump, ins)
if err != nil {
return err
}
}
for _, ins := range p.tidbs {
err := fn(spec.ComponentTiDB, ins)
if err != nil {
return err
}
}
for _, ins := range p.tiproxys {
err := fn(spec.ComponentTiProxy, ins)
if err != nil {
return err
}
}
for _, ins := range p.ticdcs {
err := fn(spec.ComponentCDC, ins)
if err != nil {
return err
}
}
for _, ins := range p.tikvCdcs {
err := fn(spec.ComponentTiKVCDC, ins)
if err != nil {
return err
}
}
for _, ins := range p.drainers {
err := fn(spec.ComponentDrainer, ins)
if err != nil {
return err
}
}
for _, ins := range p.tiflashs {
err := fn(spec.ComponentTiFlash, ins)
if err != nil {
return err
}
}
return nil
}
func (p *Playground) enableBinlog() bool {
return p.bootOptions.Pump.Num > 0
}
func (p *Playground) addInstance(componentID string, pdRole instance.PDRole, tiflashRole instance.TiFlashRole, cfg instance.Config) (ins instance.Instance, err error) {
if cfg.BinPath != "" {
cfg.BinPath, err = getAbsolutePath(cfg.BinPath)
if err != nil {
return nil, err
}
}
if cfg.ConfigPath != "" {
cfg.ConfigPath, err = getAbsolutePath(cfg.ConfigPath)
if err != nil {
return nil, err
}
}
dataDir := p.dataDir
id := p.allocID(componentID)
dir := filepath.Join(dataDir, fmt.Sprintf("%s-%d", componentID, id))
if componentID == string(instance.PDRoleNormal) && (pdRole != instance.PDRoleNormal && pdRole != instance.PDRoleAPI) {
id = p.allocID(string(pdRole))
dir = filepath.Join(dataDir, fmt.Sprintf("%s-%d", pdRole, id))
}
if err = utils.MkdirAll(dir, 0755); err != nil {
return nil, err
}
// look more like listen ip?
host := p.bootOptions.Host
if cfg.Host != "" {
host = cfg.Host
}
switch componentID {
case spec.ComponentPD:
inst := instance.NewPDInstance(pdRole, cfg.BinPath, dir, host, cfg.ConfigPath, id, p.pds, cfg.Port, p.bootOptions.Mode == "tidb-cse")
ins = inst
if pdRole == instance.PDRoleNormal || pdRole == instance.PDRoleAPI {
if p.booted {
inst.Join(p.pds)
p.pds = append(p.pds, inst)
} else {
p.pds = append(p.pds, inst)
for _, pd := range p.pds {
pd.InitCluster(p.pds)
}
}
} else if pdRole == instance.PDRoleTSO {
p.tsos = append(p.tsos, inst)
} else if pdRole == instance.PDRoleScheduling {
p.schedulings = append(p.schedulings, inst)
}
case spec.ComponentTiDB:
inst := instance.NewTiDBInstance(cfg.BinPath, dir, host, cfg.ConfigPath, id, cfg.Port, p.pds, dataDir, p.enableBinlog(), p.bootOptions.Mode == "tidb-cse")
ins = inst
p.tidbs = append(p.tidbs, inst)
case spec.ComponentTiKV:
inst := instance.NewTiKVInstance(cfg.BinPath, dir, host, cfg.ConfigPath, id, cfg.Port, p.pds, p.tsos, p.bootOptions.Mode == "tidb-cse", p.bootOptions.CSEOpts, p.bootOptions.PDMode == "ms")
ins = inst
p.tikvs = append(p.tikvs, inst)
case spec.ComponentTiFlash:
inst := instance.NewTiFlashInstance(tiflashRole, p.bootOptions.CSEOpts, cfg.BinPath, dir, host, cfg.ConfigPath, id, p.pds, p.tidbs, cfg.Version)
ins = inst
p.tiflashs = append(p.tiflashs, inst)
case spec.ComponentTiProxy:
if err := instance.GenTiProxySessionCerts(dataDir); err != nil {
return nil, err
}
inst := instance.NewTiProxy(cfg.BinPath, dir, host, cfg.ConfigPath, id, cfg.Port, p.pds)
ins = inst
p.tiproxys = append(p.tiproxys, inst)
case spec.ComponentCDC:
inst := instance.NewTiCDC(cfg.BinPath, dir, host, cfg.ConfigPath, id, cfg.Port, p.pds)
ins = inst
p.ticdcs = append(p.ticdcs, inst)
case spec.ComponentTiKVCDC:
inst := instance.NewTiKVCDC(cfg.BinPath, dir, host, cfg.ConfigPath, id, p.pds)
ins = inst
p.tikvCdcs = append(p.tikvCdcs, inst)
case spec.ComponentPump:
inst := instance.NewPump(cfg.BinPath, dir, host, cfg.ConfigPath, id, p.pds)
ins = inst
p.pumps = append(p.pumps, inst)
case spec.ComponentDrainer:
inst := instance.NewDrainer(cfg.BinPath, dir, host, cfg.ConfigPath, id, p.pds)
ins = inst
p.drainers = append(p.drainers, inst)
default:
return nil, errors.Errorf("unknown component: %s", componentID)
}
return
}
func (p *Playground) waitAllDBUp() ([]string, []string) {
var tidbSucc []string
var tiproxySucc []string
if len(p.tidbs) > 0 {
var wg sync.WaitGroup
var tidbMu, tiproxyMu sync.Mutex
var bars *progress.MultiBar
if len(p.tiproxys) > 0 {
bars = progress.NewMultiBar(color.YellowString("Waiting for tidb and tiproxy instances ready"))
} else {
bars = progress.NewMultiBar(color.YellowString("Waiting for tidb instances ready"))
}
for _, db := range p.tidbs {
wg.Add(1)
prefix := color.YellowString(db.Addr())
bar := bars.AddBar(prefix)
go func(dbInst *instance.TiDBInstance) {
defer wg.Done()
if s := checkDB(dbInst.Addr(), options.TiDB.UpTimeout); s {
{
tidbMu.Lock()
tidbSucc = append(tidbSucc, dbInst.Addr())
tidbMu.Unlock()
}
bar.UpdateDisplay(&progress.DisplayProps{
Prefix: prefix,
Mode: progress.ModeDone,
})
} else {
bar.UpdateDisplay(&progress.DisplayProps{
Prefix: prefix,
Mode: progress.ModeError,
})
}
}(db)
}
for _, db := range p.tiproxys {
wg.Add(1)
prefix := color.YellowString(db.Addr())
bar := bars.AddBar(prefix)
go func(dbInst *instance.TiProxy) {
defer wg.Done()
if s := checkDB(dbInst.Addr(), options.TiProxy.UpTimeout); s {
{
tiproxyMu.Lock()
tiproxySucc = append(tiproxySucc, dbInst.Addr())
tiproxyMu.Unlock()
}
bar.UpdateDisplay(&progress.DisplayProps{
Prefix: prefix,
Mode: progress.ModeDone,
})
} else {
bar.UpdateDisplay(&progress.DisplayProps{
Prefix: prefix,
Mode: progress.ModeError,
})
}
}(db)
}
bars.StartRenderLoop()
wg.Wait()
bars.StopRenderLoop()
}
return tidbSucc, tiproxySucc
}
func (p *Playground) waitAllTiFlashUp() {
if len(p.tiflashs) > 0 {
var endpoints []string
for _, pd := range p.pds {
endpoints = append(endpoints, pd.Addr())
}
pdClient := api.NewPDClient(
context.WithValue(context.TODO(), logprinter.ContextKeyLogger, log),
endpoints, 10*time.Second, nil,
)
var wg sync.WaitGroup
bars := progress.NewMultiBar(color.YellowString("Waiting for tiflash instances ready"))
for _, flash := range p.tiflashs {
wg.Add(1)
prefix := color.YellowString(flash.Addr())
bar := bars.AddBar(prefix)
go func(flashInst *instance.TiFlashInstance) {
defer wg.Done()
displayResult := &progress.DisplayProps{
Prefix: prefix,
}
if cmd := flashInst.Cmd(); cmd == nil {
displayResult.Mode = progress.ModeError
displayResult.Suffix = "initialize command failed"
} else if state := cmd.ProcessState; state != nil && state.Exited() {
displayResult.Mode = progress.ModeError
displayResult.Suffix = fmt.Sprintf("process exited with code: %d", state.ExitCode())
} else if s := checkStoreStatus(pdClient, flashInst.Addr(), options.TiFlash.UpTimeout); !s {
displayResult.Mode = progress.ModeError
displayResult.Suffix = "failed to up after timeout"
} else {
displayResult.Mode = progress.ModeDone
}
bar.UpdateDisplay(displayResult)
}(flash)
}
bars.StartRenderLoop()
wg.Wait()
bars.StopRenderLoop()
}
}
func (p *Playground) bindVersion(comp string, version string) (bindVersion string) {
bindVersion = version
switch comp {
case spec.ComponentTiKVCDC:
bindVersion = p.bootOptions.TiKVCDC.Version
case spec.ComponentTiProxy:
bindVersion = p.bootOptions.TiProxy.Version
default:
}
return
}
//revive:disable:cognitive-complexity
//revive:disable:error-strings
func (p *Playground) bootCluster(ctx context.Context, env *environment.Environment, options *BootOptions) error {
for _, cfg := range []*instance.Config{
&options.PD,
&options.TSO,
&options.Scheduling,
&options.TiProxy,
&options.TiDB,
&options.TiKV,
&options.TiFlash,
&options.TiFlashCompute,
&options.TiFlashWrite,
&options.Pump,
&options.Drainer,
&options.TiKVCDC,
} {
path, err := getAbsolutePath(cfg.ConfigPath)
if err != nil {
return errors.Annotatef(err, "cannot eval absolute directory: %s", cfg.ConfigPath)
}
cfg.ConfigPath = path
}
p.bootOptions = options
// All others components depend on the pd, we just ensure the pd count must be great than 0
if options.PDMode != "ms" && options.PD.Num < 1 {
return fmt.Errorf("all components count must be great than 0 (pd=%v)", options.PD.Num)
}
if !utils.Version(options.Version).IsNightly() {
if semver.Compare(options.Version, "v3.1.0") < 0 && options.TiFlash.Num != 0 {
fmt.Println(color.YellowString("Warning: current version %s doesn't support TiFlash", options.Version))
options.TiFlash.Num = 0
} else if runtime.GOOS == "darwin" && semver.Compare(options.Version, "v4.0.0") < 0 {
// only runs tiflash on version later than v4.0.0 when executing on darwin
fmt.Println(color.YellowString("Warning: current version %s doesn't support TiFlash on darwin", options.Version))
options.TiFlash.Num = 0
}
}
type InstancePair struct {
comp string
pdRole instance.PDRole
tiflashRole instance.TiFlashRole
instance.Config
}
instances := []InstancePair{
{spec.ComponentTiProxy, "", "", options.TiProxy},
{spec.ComponentTiKV, "", "", options.TiKV},
{spec.ComponentPump, "", "", options.Pump},
{spec.ComponentTiDB, "", "", options.TiDB},
{spec.ComponentCDC, "", "", options.TiCDC},
{spec.ComponentTiKVCDC, "", "", options.TiKVCDC},
{spec.ComponentDrainer, "", "", options.Drainer},
}
if options.Mode == "tidb" {
instances = append(instances,
InstancePair{spec.ComponentTiFlash, instance.PDRoleNormal, instance.TiFlashRoleNormal, options.TiFlash},
)
} else if options.Mode == "tidb-cse" {
if !tidbver.TiFlashPlaygroundNewStartMode(options.Version) {
// For simplicity, currently we only implemented disagg mode when TiFlash can run without config.
return fmt.Errorf("TiUP playground only supports CSE mode for TiDB cluster >= v7.1.0 (or nightly)")
}
if !strings.HasPrefix(options.CSEOpts.S3Endpoint, "https://") && !strings.HasPrefix(options.CSEOpts.S3Endpoint, "http://") {
return fmt.Errorf("CSE mode requires S3 endpoint to start with http:// or https://")
}
isSecure := strings.HasPrefix(options.CSEOpts.S3Endpoint, "https://")
rawEndpoint := strings.TrimPrefix(options.CSEOpts.S3Endpoint, "https://")
rawEndpoint = strings.TrimPrefix(rawEndpoint, "http://")
// Currently we always assign region=local. Other regions are not supported.
if strings.Contains(rawEndpoint, "amazonaws.com") {
return fmt.Errorf("Currently TiUP playground CSE mode only supports local S3 (like minio). S3 on AWS Regions are not supported. Contributions are welcome!")
}
// Preflight check whether specified object storage is available.
s3Client, err := minio.New(rawEndpoint, &minio.Options{
Creds: credentials.NewStaticV4(options.CSEOpts.AccessKey, options.CSEOpts.SecretKey, ""),
Secure: isSecure,
})
if err != nil {
return errors.Annotate(err, "CSE mode preflight check failed")
}
ctxCheck, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
bucketExists, err := s3Client.BucketExists(ctxCheck, options.CSEOpts.Bucket)
if err != nil {
return errors.Annotate(err, "CSE mode preflight check failed")
}
if !bucketExists {
// Try to create bucket.
err := s3Client.MakeBucket(ctxCheck, options.CSEOpts.Bucket, minio.MakeBucketOptions{})
if err != nil {
return fmt.Errorf("CSE mode preflight check failed: Bucket %s doesn't exist", options.CSEOpts.Bucket)