prometheus

Форк
0
128 строк · 3.7 Кб
1
// Copyright 2022 The Prometheus Authors
2
// Licensed under the Apache License, Version 2.0 (the "License");
3
// you may not use this file except in compliance with the License.
4
// You may obtain a copy of the License at
5
//
6
// http://www.apache.org/licenses/LICENSE-2.0
7
//
8
// Unless required by applicable law or agreed to in writing, software
9
// distributed under the License is distributed on an "AS IS" BASIS,
10
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
// See the License for the specific language governing permissions and
12
// limitations under the License.
13

14
package ionos
15

16
import (
17
	"errors"
18
	"fmt"
19
	"time"
20

21
	"github.com/go-kit/log"
22
	"github.com/prometheus/client_golang/prometheus"
23
	"github.com/prometheus/common/config"
24
	"github.com/prometheus/common/model"
25

26
	"github.com/prometheus/prometheus/discovery"
27
	"github.com/prometheus/prometheus/discovery/refresh"
28
)
29

30
const (
31
	// metaLabelPrefix is the meta prefix used for all meta labels in this
32
	// discovery.
33
	metaLabelPrefix    = model.MetaLabelPrefix + "ionos_"
34
	metaLabelSeparator = ","
35
)
36

37
func init() {
38
	discovery.RegisterConfig(&SDConfig{})
39
}
40

41
// Discovery periodically performs IONOS Cloud target discovery. It implements
42
// the Discoverer interface.
43
type Discovery struct{}
44

45
// NewDiscovery returns a new refresh.Discovery for IONOS Cloud.
46
func NewDiscovery(conf *SDConfig, logger log.Logger, metrics discovery.DiscovererMetrics) (*refresh.Discovery, error) {
47
	m, ok := metrics.(*ionosMetrics)
48
	if !ok {
49
		return nil, fmt.Errorf("invalid discovery metrics type")
50
	}
51

52
	if conf.ionosEndpoint == "" {
53
		conf.ionosEndpoint = "https://api.ionos.com"
54
	}
55

56
	d, err := newServerDiscovery(conf, logger)
57
	if err != nil {
58
		return nil, err
59
	}
60

61
	return refresh.NewDiscovery(
62
		refresh.Options{
63
			Logger:              logger,
64
			Mech:                "ionos",
65
			Interval:            time.Duration(conf.RefreshInterval),
66
			RefreshF:            d.refresh,
67
			MetricsInstantiator: m.refreshMetrics,
68
		},
69
	), nil
70
}
71

72
// DefaultSDConfig is the default IONOS Cloud service discovery configuration.
73
var DefaultSDConfig = SDConfig{
74
	HTTPClientConfig: config.DefaultHTTPClientConfig,
75
	RefreshInterval:  model.Duration(60 * time.Second),
76
	Port:             80,
77
}
78

79
// SDConfig configuration to use for IONOS Cloud Discovery.
80
type SDConfig struct {
81
	// DatacenterID: IONOS Cloud data center ID used to discover targets.
82
	DatacenterID string `yaml:"datacenter_id"`
83

84
	HTTPClientConfig config.HTTPClientConfig `yaml:",inline"`
85

86
	RefreshInterval model.Duration `yaml:"refresh_interval"`
87
	Port            int            `yaml:"port"`
88

89
	ionosEndpoint string // For tests only.
90
}
91

92
// NewDiscovererMetrics implements discovery.Config.
93
func (*SDConfig) NewDiscovererMetrics(reg prometheus.Registerer, rmi discovery.RefreshMetricsInstantiator) discovery.DiscovererMetrics {
94
	return &ionosMetrics{
95
		refreshMetrics: rmi,
96
	}
97
}
98

99
// Name returns the name of the IONOS Cloud service discovery.
100
func (c SDConfig) Name() string {
101
	return "ionos"
102
}
103

104
// NewDiscoverer returns a new discovery.Discoverer for IONOS Cloud.
105
func (c SDConfig) NewDiscoverer(options discovery.DiscovererOptions) (discovery.Discoverer, error) {
106
	return NewDiscovery(&c, options.Logger, options.Metrics)
107
}
108

109
// UnmarshalYAML implements the yaml.Unmarshaler interface.
110
func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
111
	*c = DefaultSDConfig
112
	type plain SDConfig
113
	err := unmarshal((*plain)(c))
114
	if err != nil {
115
		return err
116
	}
117

118
	if c.DatacenterID == "" {
119
		return errors.New("datacenter id can't be empty")
120
	}
121

122
	return c.HTTPClientConfig.Validate()
123
}
124

125
// SetDirectory joins any relative file paths with dir.
126
func (c *SDConfig) SetDirectory(dir string) {
127
	c.HTTPClientConfig.SetDirectory(dir)
128
}
129

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.