forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathyandex_cloud_monitoring.go
259 lines (222 loc) · 7.04 KB
/
yandex_cloud_monitoring.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package yandex_cloud_monitoring
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/outputs"
"github.com/influxdata/telegraf/selfstat"
)
// YandexCloudMonitoring allows publishing of metrics to the Yandex Cloud Monitoring custom metrics
// service
type YandexCloudMonitoring struct {
Timeout config.Duration `toml:"timeout"`
EndpointURL string `toml:"endpoint_url"`
Service string `toml:"service"`
Log telegraf.Logger
MetadataTokenURL string
MetadataFolderURL string
FolderID string
IAMToken string
IamTokenExpirationTime time.Time
client *http.Client
timeFunc func() time.Time
MetricOutsideWindow selfstat.Stat
}
type yandexCloudMonitoringMessage struct {
TS string `json:"ts,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Metrics []yandexCloudMonitoringMetric `json:"metrics"`
}
type yandexCloudMonitoringMetric struct {
Name string `json:"name"`
Labels map[string]string `json:"labels"`
MetricType string `json:"type,omitempty"` // DGAUGE|IGAUGE|COUNTER|RATE. Default: DGAUGE
TS string `json:"ts,omitempty"`
Value float64 `json:"value"`
}
type MetadataIamToken struct {
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
TokenType string `json:"token_type"`
}
const (
defaultRequestTimeout = time.Second * 20
defaultEndpointURL = "https://monitoring.api.cloud.yandex.net/monitoring/v2/data/write"
defaultMetadataTokenURL = "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token"
defaultMetadataFolderURL = "http://169.254.169.254/computeMetadata/v1/yandex/folder-id"
)
var sampleConfig = `
## Timeout for HTTP writes.
# timeout = "20s"
## Yandex.Cloud monitoring API endpoint. Normally should not be changed
# endpoint_url = "https://monitoring.api.cloud.yandex.net/monitoring/v2/data/write"
## All user metrics should be sent with "custom" service specified. Normally should not be changed
# service = "custom"
`
// Description provides a description of the plugin
func (a *YandexCloudMonitoring) Description() string {
return "Send aggregated metrics to Yandex.Cloud Monitoring"
}
// SampleConfig provides a sample configuration for the plugin
func (a *YandexCloudMonitoring) SampleConfig() string {
return sampleConfig
}
// Connect initializes the plugin and validates connectivity
func (a *YandexCloudMonitoring) Connect() error {
if a.Timeout <= 0 {
a.Timeout = config.Duration(defaultRequestTimeout)
}
if a.EndpointURL == "" {
a.EndpointURL = defaultEndpointURL
}
if a.Service == "" {
a.Service = "custom"
}
if a.MetadataTokenURL == "" {
a.MetadataTokenURL = defaultMetadataTokenURL
}
if a.MetadataFolderURL == "" {
a.MetadataFolderURL = defaultMetadataFolderURL
}
a.client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
Timeout: time.Duration(a.Timeout),
}
var err error
a.FolderID, err = a.getFolderIDFromMetadata()
if err != nil {
return err
}
a.Log.Infof("Writing to Yandex.Cloud Monitoring URL: %s", a.EndpointURL)
tags := map[string]string{}
a.MetricOutsideWindow = selfstat.Register("yandex_cloud_monitoring", "metric_outside_window", tags)
return nil
}
// Close shuts down an any active connections
func (a *YandexCloudMonitoring) Close() error {
a.client = nil
return nil
}
// Write writes metrics to the remote endpoint
func (a *YandexCloudMonitoring) Write(metrics []telegraf.Metric) error {
var yandexCloudMonitoringMetrics []yandexCloudMonitoringMetric
for _, m := range metrics {
for _, field := range m.FieldList() {
yandexCloudMonitoringMetrics = append(
yandexCloudMonitoringMetrics,
yandexCloudMonitoringMetric{
Name: field.Key,
Labels: m.Tags(),
TS: fmt.Sprint(m.Time().Format(time.RFC3339)),
Value: field.Value.(float64),
},
)
}
}
var body []byte
jsonBytes, err := json.Marshal(
yandexCloudMonitoringMessage{
Metrics: yandexCloudMonitoringMetrics,
},
)
if err != nil {
return err
}
body = append(jsonBytes, '\n')
return a.send(body)
}
func getResponseFromMetadata(c *http.Client, metadataURL string) ([]byte, error) {
req, err := http.NewRequest("GET", metadataURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
req.Header.Set("Metadata-Flavor", "Google")
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
return nil, fmt.Errorf("unable to fetch instance metadata: [%s] %d",
metadataURL, resp.StatusCode)
}
return body, nil
}
func (a *YandexCloudMonitoring) getFolderIDFromMetadata() (string, error) {
a.Log.Infof("getting folder ID in %s", a.MetadataFolderURL)
body, err := getResponseFromMetadata(a.client, a.MetadataFolderURL)
if err != nil {
return "", err
}
folderID := string(body)
if folderID == "" {
return "", fmt.Errorf("unable to fetch folder id from URL %s: %v", a.MetadataFolderURL, err)
}
return folderID, nil
}
func (a *YandexCloudMonitoring) getIAMTokenFromMetadata() (string, int, error) {
a.Log.Debugf("getting new IAM token in %s", a.MetadataTokenURL)
body, err := getResponseFromMetadata(a.client, a.MetadataTokenURL)
if err != nil {
return "", 0, err
}
var metadata MetadataIamToken
if err := json.Unmarshal(body, &metadata); err != nil {
return "", 0, err
}
if metadata.AccessToken == "" || metadata.ExpiresIn == 0 {
return "", 0, fmt.Errorf("unable to fetch authentication credentials %s: %v", a.MetadataTokenURL, err)
}
return metadata.AccessToken, int(metadata.ExpiresIn), nil
}
func (a *YandexCloudMonitoring) send(body []byte) error {
req, err := http.NewRequest("POST", a.EndpointURL, bytes.NewBuffer(body))
if err != nil {
return err
}
q := req.URL.Query()
q.Add("folderId", a.FolderID)
q.Add("service", a.Service)
req.URL.RawQuery = q.Encode()
req.Header.Set("Content-Type", "application/json")
isTokenExpired := !a.IamTokenExpirationTime.After(time.Now())
if a.IAMToken == "" || isTokenExpired {
token, expiresIn, err := a.getIAMTokenFromMetadata()
if err != nil {
return err
}
a.IamTokenExpirationTime = time.Now().Add(time.Duration(expiresIn) * time.Second)
a.IAMToken = token
}
req.Header.Set("Authorization", "Bearer "+a.IAMToken)
a.Log.Debugf("sending metrics to %s", req.URL.String())
a.Log.Debugf("body: %s", body)
resp, err := a.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil || resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("failed to write batch: [%v] %s", resp.StatusCode, resp.Status)
}
return nil
}
func init() {
outputs.Add("yandex_cloud_monitoring", func() telegraf.Output {
return &YandexCloudMonitoring{
timeFunc: time.Now,
}
})
}