62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"git.hlsq.asia/mmorpg/service-common/log"
|
|
"git.hlsq.asia/mmorpg/service-common/module"
|
|
"git.hlsq.asia/mmorpg/service-gateway/config"
|
|
"git.hlsq.asia/mmorpg/service-gateway/internal/global"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
"net/http"
|
|
"sync"
|
|
)
|
|
|
|
// ModulePrometheus 普罗米修斯模块
|
|
type ModulePrometheus struct {
|
|
wg *sync.WaitGroup
|
|
server *http.Server
|
|
}
|
|
|
|
func (m *ModulePrometheus) Init() error {
|
|
m.wg = &sync.WaitGroup{}
|
|
|
|
global.OnlineUsersGauge = prometheus.NewGauge(prometheus.GaugeOpts{
|
|
Name: "gateway_online_users_total",
|
|
Help: "Total number of online users in gateway",
|
|
})
|
|
prometheus.MustRegister(global.OnlineUsersGauge)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *ModulePrometheus) Start() error {
|
|
m.wg.Add(1)
|
|
go func() {
|
|
defer m.wg.Done()
|
|
m.server = &http.Server{
|
|
Addr: fmt.Sprintf("%v:%v", config.Get().Metric.Prometheus.Address, config.Get().Metric.Prometheus.Port),
|
|
Handler: promhttp.Handler(),
|
|
}
|
|
if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
log.Errorf("prometheus server failed: %v", err.Error())
|
|
}
|
|
log.Infof("prometheus server stop.")
|
|
}()
|
|
return nil
|
|
}
|
|
|
|
func (m *ModulePrometheus) Stop() error {
|
|
if err := m.server.Shutdown(context.Background()); err != nil {
|
|
log.Errorf("stop prometheus server failed: %v", err)
|
|
}
|
|
m.wg.Wait()
|
|
return nil
|
|
}
|
|
|
|
func (m *ModulePrometheus) Bind(_ ...any) module.Module {
|
|
return m
|
|
}
|