uptrace / opentelemetry-go-extra

OpenTelemetry instrumentations for Go
https://uptrace.dev/get/instrument/
BSD 2-Clause "Simplified" License
314 stars 72 forks source link

fix(otelsql): the connection to db must be closed after receiving the driver #110

Closed paniclong closed 1 year ago

paniclong commented 1 year ago

This pull request adds closing the database connection after receiving the driver. If this is not done, goroutines will leak.

Code for reproduce:

package main

import (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/uptrace/opentelemetry-go-extra/otelsql"
    "net/http"
    "net/http/pprof"
    "time"
)

func okHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("ok"))
}

func main() {
    r := http.NewServeMux()
    r.HandleFunc("/", okHandler)

    r.HandleFunc("/debug/pprof/", pprof.Index)
    r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
    r.HandleFunc("/debug/pprof/profile", pprof.Profile)
    r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
    r.HandleFunc("/debug/pprof/trace", pprof.Trace)

    go func() {
        for {
            time.Sleep(time.Second)
            mysql, err := otelsql.Open("mysql", "user:12345@tcp(localhost:3306)/service")
            if err != nil {
                fmt.Println(err)
            }
            mysql.Close()
        }
    }()

    http.ListenAndServe(":8080", r)
}

Go to http://localhost:8080/debug/pprof/ and watch the goroutines grow.

vmihailenco commented 1 year ago

Thanks!