github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/providers/prometheus/provider.go (about)

     1  // Copyright (c) 2021 Terminus, 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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package prometheus
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"net/http"
    21  
    22  	"github.com/prometheus/client_golang/prometheus/promhttp"
    23  
    24  	"github.com/erda-project/erda-infra/base/servicehub"
    25  	"github.com/erda-project/erda-infra/providers/httpserver"
    26  )
    27  
    28  type config struct {
    29  	MetricsPath       string `file:"metrics_path" default:"/metrics"`
    30  	RouterLabelEnable bool   `file:"router_label_enable" default:"true"`
    31  	RouterLabel       string `file:"router_label" default:"admin"`
    32  }
    33  
    34  // provider .
    35  type provider struct {
    36  	server *http.Server
    37  	Cfg    *config
    38  }
    39  
    40  func findRouter(ctx servicehub.Context, service string) (httpserver.Router, error) {
    41  	svc := ctx.Service(service)
    42  	if svc == nil {
    43  		return nil, errors.New("unable to find http router: " + service)
    44  	}
    45  	router, ok := svc.(httpserver.Router)
    46  	if !ok {
    47  		return nil, fmt.Errorf("invalid type %T, which must be httpserver.Router", svc)
    48  	}
    49  	return router, nil
    50  }
    51  
    52  // Init .
    53  func (p *provider) Init(ctx servicehub.Context) error {
    54  	svcName := "http-router"
    55  	if p.Cfg.RouterLabelEnable {
    56  		svcName += "@" + p.Cfg.RouterLabel
    57  	}
    58  
    59  	router, err := findRouter(ctx, svcName)
    60  	if err != nil {
    61  		return fmt.Errorf("find router: %w", err)
    62  	}
    63  
    64  	router.GET(p.Cfg.MetricsPath, promhttp.Handler())
    65  	return nil
    66  }
    67  
    68  func init() {
    69  	servicehub.Register("prometheus", &servicehub.Spec{
    70  		Services:     []string{"prometheus"},
    71  		Description:  "bind prometheus endpoint to http-server",
    72  		Dependencies: []string{"http-server"},
    73  		ConfigFunc:   func() interface{} { return &config{} },
    74  		Creator:      func() servicehub.Provider { return &provider{} },
    75  	})
    76  }