Add env variable for metrics port (#16465)

Signed-off-by: Weida Zhu <weida.zhu@zilliz.com>
pull/16477/head
zwd1208 2022-04-12 20:11:34 +08:00 committed by GitHub
parent 20a4fddf6c
commit a2011c1f25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -17,7 +17,11 @@
package metrics
import (
"fmt"
"net/http"
"os"
"strconv"
// nolint:gosec
_ "net/http/pprof"
@ -28,6 +32,9 @@ import (
)
const (
DefaultListenPort = "9091"
ListenPortEnvKey = "METRICS_PORT"
milvusNamespace = "milvus"
AbandonLabel = "abandon"
@ -78,8 +85,20 @@ func ServeHTTP(r *prometheus.Registry) {
http.Handle("/metrics", promhttp.HandlerFor(r, promhttp.HandlerOpts{}))
http.Handle("/metrics_default", promhttp.Handler())
go func() {
if err := http.ListenAndServe(":9091", nil); err != nil {
bindAddr := getMetricsAddr()
log.Debug("metrics listen", zap.Any("addr", bindAddr))
if err := http.ListenAndServe(bindAddr, nil); err != nil {
log.Error("handle metrics failed", zap.Error(err))
}
}()
}
func getMetricsAddr() string {
port := os.Getenv(ListenPortEnvKey)
_, err := strconv.Atoi(port)
if err != nil {
return fmt.Sprintf(":%s", DefaultListenPort)
}
return fmt.Sprintf(":%s", port)
}

View File

@ -17,9 +17,11 @@
package metrics
import (
"os"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)
func TestRegisterMetrics(t *testing.T) {
@ -33,4 +35,12 @@ func TestRegisterMetrics(t *testing.T) {
RegisterProxy(r)
RegisterQueryNode(r)
RegisterQueryCoord(r)
ServeHTTP(r)
}
func TestGetMetricsAddr(t *testing.T) {
assert.Equal(t, getMetricsAddr(), ":"+DefaultListenPort)
testPort := "9092"
os.Setenv(ListenPortEnvKey, testPort)
assert.Equal(t, getMetricsAddr(), ":"+testPort)
}