-
Notifications
You must be signed in to change notification settings - Fork 46
/
metrics.go
165 lines (141 loc) · 4.29 KB
/
metrics.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package metrics
import (
"context"
"net"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opencensus.io/zpages"
"github.com/insolar/insolar/configuration"
"github.com/insolar/insolar/insolar"
"github.com/insolar/insolar/instrumentation/inslogger"
"github.com/insolar/insolar/instrumentation/insmetrics"
"github.com/insolar/insolar/instrumentation/pprof"
"github.com/insolar/insolar/log"
)
const insolarNamespace = "insolar"
const insgorundNamespace = "insgorund"
// Metrics is a component which serve metrics data to Prometheus.
type Metrics struct {
config configuration.Metrics
registry *prometheus.Registry
nodeRole string
handler http.Handler
server *http.Server
listener net.Listener
}
// NewMetrics creates new Metrics instance.
func NewMetrics(
cfg configuration.Metrics,
registry *prometheus.Registry,
nodeRole string,
) *Metrics {
m := &Metrics{
config: cfg,
registry: registry,
nodeRole: nodeRole,
}
return m
}
// Init inits metrics instance. Creates and registers all handlers.
func (m *Metrics) Init(ctx context.Context) error {
mux := http.NewServeMux()
errLogger := &errorLogger{inslogger.FromContext(ctx)}
promHandler := promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{ErrorLog: errLogger})
mux.Handle("/metrics", promHandler)
mux.Handle("/_status", newProcStatus())
mux.Handle("/debug/loglevel", log.NewLoglevelChangeHandler())
pprof.Handle(mux)
if m.config.ZpagesEnabled {
// https://opencensus.io/zpages/
zpages.Handle(mux, "/debug")
}
_, err := insmetrics.RegisterPrometheus(
m.config.Namespace,
m.registry,
m.config.ReportingPeriod,
errLogger,
m.nodeRole,
)
if err != nil {
errLogger.Error(err.Error())
return err
}
m.handler = mux
return nil
}
// Handler returns http handler, created on initialization stage.
func (m *Metrics) Handler() http.Handler {
return m.handler
}
// ErrBind special case for Start method.
// We can use it for easier check in metrics creation code.
var ErrBind = errors.New("Failed to bind")
// Start is implementation of insolar.Component interface.
func (m *Metrics) Start(ctx context.Context) error {
inslog := inslogger.FromContext(ctx)
m.server = &http.Server{
Addr: m.config.ListenAddress,
Handler: m.handler,
}
listener, err := net.Listen("tcp", m.server.Addr)
if err != nil {
if opErr, ok := err.(*net.OpError); ok {
if opErr.Op == "listen" && IsAddrInUse(opErr) {
return errors.Wrapf(ErrBind, "addr=%v", m.server.Addr)
}
}
return errors.Wrap(err, "Failed to listen at address")
}
m.listener = listener
inslog.Info("Started metrics server: ", m.listener.Addr().String())
go func() {
inslog.Debug("Metrics server starting on ", m.server.Addr)
if err := m.server.Serve(listener); err != http.ErrServerClosed {
inslog.Error("Failed to start metrics server ", err)
}
}()
return nil
}
// Stop is implementation of insolar.Component interface.
func (m *Metrics) Stop(ctx context.Context) error {
if m.server == nil {
return nil
}
const timeOut = 3
inslogger.FromContext(ctx).Info("Shutting down metrics server")
ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Duration(timeOut)*time.Second)
defer cancel()
err := m.server.Shutdown(ctxWithTimeout)
return errors.Wrap(err, "Can't gracefully stop metrics server")
}
// errorLogger wrapper for error logs.
type errorLogger struct {
insolar.Logger
}
// Println is wrapper method for Error method.
func (e *errorLogger) Println(v ...interface{}) {
e.Error(v)
}
// IsAddrInUse checks error text for well known phrase.
func IsAddrInUse(err error) bool {
return strings.Contains(err.Error(), "address already in use")
}