File: listener.go

package info (click to toggle)
golang-github-containerd-nydus-snapshotter 0.13.4-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,824 kB
  • sloc: sh: 470; makefile: 129
file content (53 lines) | stat: -rw-r--r-- 1,274 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2021. Ant Group. All rights reserved.
 * Copyright (c) 2023. Nydus Developers. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package metrics

import (
	"fmt"
	"net"
	"net/http"

	"github.com/containerd/containerd/log"
	"github.com/containerd/nydus-snapshotter/pkg/metrics/registry"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Endpoint for prometheus metrics
var endpointPromMetrics = "/v1/metrics"

func trapClosedConnErr(err error) error {
	if err == nil || errors.Is(err, net.ErrClosed) {
		return nil
	}
	return err
}

// NewListener creates a new TCP listener bound to the given address.
func NewMetricsHTTPListenerServer(addr string) error {
	if addr == "" {
		return fmt.Errorf("the address for metrics HTTP server is invalid")
	}

	http.Handle(endpointPromMetrics, promhttp.HandlerFor(registry.Registry, promhttp.HandlerOpts{
		ErrorHandling: promhttp.HTTPErrorOnError,
	}))

	l, err := net.Listen("tcp", addr)
	if err != nil {
		return errors.Wrapf(err, "metrics server listener, addr=%s", addr)
	}

	go func() {
		if err := http.Serve(l, nil); trapClosedConnErr(err) != nil {
			log.L.Errorf("Metrics server fails to listen or serve %s: %v", addr, err)
		}
	}()

	return nil
}