Skip to content

Commit

Permalink
use port to probe db in playground (#2296)
Browse files Browse the repository at this point in the history
  • Loading branch information
KanShiori authored Oct 31, 2023
1 parent bdf6f26 commit b8fbc84
Showing 1 changed file with 5 additions and 13 deletions.
18 changes: 5 additions & 13 deletions components/playground/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ package main

import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net"
"net/http"
_ "net/http/pprof"
"os"
Expand Down Expand Up @@ -419,36 +419,28 @@ func populateDefaultOpt(flagSet *pflag.FlagSet) error {
return nil
}

func tryConnect(dsn string) error {
cli, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer cli.Close()

conn, err := cli.Conn(context.Background())
func tryConnect(addr string, timeoutSec int) error {
conn, err := net.DialTimeout("tcp", addr, time.Duration(timeoutSec)*time.Second)
if err != nil {
return err
}
defer conn.Close()

return nil
}

// checkDB check if the addr is connectable by getting a connection from sql.DB. timeout <=0 means no timeout
func checkDB(dbAddr string, timeout int) bool {
dsn := fmt.Sprintf("root:@tcp(%s)/", dbAddr)
if timeout > 0 {
for i := 0; i < timeout; i++ {
if tryConnect(dsn) == nil {
if tryConnect(dbAddr, timeout) == nil {
return true
}
time.Sleep(time.Second)
}
return false
}
for {
if err := tryConnect(dsn); err == nil {
if err := tryConnect(dbAddr, timeout); err == nil {
return true
}
time.Sleep(time.Second)
Expand Down

0 comments on commit b8fbc84

Please sign in to comment.