Skip to content

Commit 203a33f

Browse files
committed
playground: wait PD ready before starting TiDB to avoid cluster ID mismatch
1 parent 7d025cb commit 203a33f

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

components/playground/instance/pd.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ package instance
1515

1616
import (
1717
"context"
18+
"encoding/json"
1819
"fmt"
20+
"net/http"
1921
"path/filepath"
2022
"strings"
23+
"time"
2124

2225
"github.com/pingcap/errors"
2326
"github.com/pingcap/tiup/pkg/tidbver"
@@ -236,3 +239,36 @@ func (inst *PDInstance) LogFile() string {
236239
func (inst *PDInstance) Addr() string {
237240
return utils.JoinHostPort(AdvertiseHost(inst.Host), inst.StatusPort)
238241
}
242+
243+
// Ready return nil when PD is ready to serve.
244+
func (inst *PDInstance) Ready(ctx context.Context) error {
245+
url := fmt.Sprintf("http://%s/pd/api/v1/members", inst.Addr())
246+
247+
var r struct {
248+
Header struct {
249+
ClusterID uint64 `json:"cluster_id"`
250+
} `json:"header"`
251+
}
252+
253+
for {
254+
resp, err := http.Get(url)
255+
if err == nil {
256+
if resp.StatusCode == 200 {
257+
err = json.NewDecoder(resp.Body).Decode(&r)
258+
_ = resp.Body.Close()
259+
if err == nil && r.Header.ClusterID != 0 {
260+
return nil
261+
}
262+
} else {
263+
_ = resp.Body.Close()
264+
}
265+
}
266+
267+
select {
268+
case <-ctx.Done():
269+
return ctx.Err()
270+
case <-time.After(time.Second):
271+
// retry
272+
}
273+
}
274+
}

components/playground/playground.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,7 @@ func (p *Playground) bootCluster(ctx context.Context, env *environment.Environme
12851285

12861286
anyPumpReady := false
12871287
allDMMasterReady := false
1288+
allPDReady := false
12881289
// Start all instance except tiflash.
12891290
err := p.WalkInstances(func(cid string, ins instance.Instance) error {
12901291
if cid == spec.ComponentTiFlash {
@@ -1296,6 +1297,19 @@ func (p *Playground) bootCluster(ctx context.Context, env *environment.Environme
12961297
allDMMasterReady = true
12971298
}
12981299

1300+
// wait all PD ready before starting TiDB to avoid cluster ID mismatch
1301+
if cid == spec.ComponentTiDB && !allPDReady {
1302+
for _, pd := range p.pds {
1303+
pdCtx, cancel := context.WithTimeout(ctx, time.Second*120)
1304+
err := pd.Ready(pdCtx)
1305+
cancel()
1306+
if err != nil {
1307+
return errors.Annotatef(err, "failed to wait PD %s to be ready", pd.Addr())
1308+
}
1309+
}
1310+
allPDReady = true
1311+
}
1312+
12991313
err := p.startInstance(ctx, ins)
13001314
if err != nil {
13011315
return err

0 commit comments

Comments
 (0)