/
remote.go
90 lines (80 loc) · 2.45 KB
/
remote.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
package remote
import (
"fmt"
"net/http"
"time"
"github.com/moira-alert/moira/metric_source"
)
// ErrRemoteStorageDisabled is used to prevent remote.Fetch calls when remote storage is disabled
var ErrRemoteStorageDisabled = fmt.Errorf("remote graphite storage is not enabled")
// ErrRemoteTriggerResponse is a custom error when remote trigger check fails
type ErrRemoteTriggerResponse struct {
InternalError error
Target string
}
// Error is a representation of Error interface method
func (err ErrRemoteTriggerResponse) Error() string {
return fmt.Sprintf("failed to get remote target '%s': %s", err.Target, err.InternalError.Error())
}
// Remote is implementation of MetricSource interface, which implements fetch metrics method from remote graphite installation
type Remote struct {
config *Config
client *http.Client
}
// Create configures remote metric source
func Create(config *Config) metricSource.MetricSource {
return &Remote{
config: config,
client: &http.Client{Timeout: config.Timeout},
}
}
// Fetch fetches remote metrics and converts them to expected format
func (remote *Remote) Fetch(target string, from, until int64, allowRealTimeAlerting bool) (metricSource.FetchResult, error) {
req, err := remote.prepareRequest(from, until, target)
if err != nil {
return nil, ErrRemoteTriggerResponse{
InternalError: err,
Target: target,
}
}
body, err := remote.makeRequest(req)
if err != nil {
return nil, ErrRemoteTriggerResponse{
InternalError: err,
Target: target,
}
}
resp, err := decodeBody(body)
if err != nil {
return nil, ErrRemoteTriggerResponse{
InternalError: err,
Target: target,
}
}
fetchResult := convertResponse(resp, allowRealTimeAlerting)
return &fetchResult, nil
}
// IsConfigured returns false in cases that user does not properly configure remote settings like graphite URL
func (remote *Remote) IsConfigured() (bool, error) {
if remote.config.isEnabled() {
return true, nil
}
return false, ErrRemoteStorageDisabled
}
// IsRemoteAvailable checks if graphite API is available and returns 200 response
func (remote *Remote) IsRemoteAvailable() (bool, error) {
maxRetries := 3
until := time.Now().Unix()
from := until - 600
req, err := remote.prepareRequest(from, until, "NonExistingTarget")
if err != nil {
return false, err
}
for attempt := 0; attempt < maxRetries; attempt++ {
_, err = remote.makeRequest(req)
if err == nil {
return true, nil
}
}
return false, err
}