github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/tests/mq_protocol_tests/framework/mysql/docker_env.go (about)

     1  // Copyright 2020 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package mysql
    15  
    16  import (
    17  	"database/sql"
    18  
    19  	"github.com/integralist/go-findroot/find"
    20  	"github.com/pingcap/errors"
    21  	"github.com/pingcap/log"
    22  	"github.com/pingcap/tiflow/tests/mq_protocol_tests/framework"
    23  	"go.uber.org/zap"
    24  )
    25  
    26  const (
    27  	dockerComposeFilePath = framework.DockerComposeFilePathPrefix + "docker-compose-mysql.yml"
    28  )
    29  
    30  // DockerEnv represents the docker-compose service defined in docker-compose-canal.yml
    31  type DockerEnv struct {
    32  	framework.DockerEnv
    33  }
    34  
    35  // NewDockerEnv creates a new KafkaDockerEnv
    36  func NewDockerEnv(dockerComposeFile string) *DockerEnv {
    37  	healthChecker := func() error {
    38  		if err := checkDbConn(framework.UpstreamDSN); err != nil {
    39  			return err
    40  		}
    41  		if err := checkDbConn(framework.DownstreamDSN); err != nil {
    42  			return err
    43  		}
    44  		// Also check cdc cluster.
    45  		return framework.CdcHealthCheck(framework.ControllerContainerName, framework.UpstreamPD)
    46  	}
    47  	var file string
    48  	if dockerComposeFile == "" {
    49  		st, err := find.Repo()
    50  		if err != nil {
    51  			log.Fatal("Could not find git repo root", zap.Error(err))
    52  		}
    53  		file = st.Path + dockerComposeFilePath
    54  	} else {
    55  		file = dockerComposeFile
    56  	}
    57  
    58  	return &DockerEnv{DockerEnv: framework.DockerEnv{
    59  		DockerComposeOperator: framework.DockerComposeOperator{
    60  			FileName:      file,
    61  			Controller:    framework.ControllerContainerName,
    62  			HealthChecker: healthChecker,
    63  		},
    64  	}}
    65  }
    66  
    67  func checkDbConn(dsn string) error {
    68  	db, err := sql.Open("mysql", dsn)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	if db == nil {
    73  		return errors.New("Can not connect to " + dsn)
    74  	}
    75  	defer db.Close()
    76  	err = db.Ping()
    77  	if err != nil {
    78  		return err
    79  	}
    80  	return nil
    81  }