-
Notifications
You must be signed in to change notification settings - Fork 53
/
remotewrite.go
163 lines (144 loc) · 4.64 KB
/
remotewrite.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
package cortex
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"github.com/rancher/opni/pkg/auth/cluster"
"github.com/rancher/opni/pkg/config/v1beta1"
"github.com/rancher/opni/pkg/util"
"github.com/rancher/opni/plugins/metrics/pkg/apis/remotewrite"
metricsutil "github.com/rancher/opni/plugins/metrics/pkg/util"
"github.com/weaveworks/common/user"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
type RemoteWriteForwarder struct {
remotewrite.UnsafeRemoteWriteServer
RemoteWriteForwarderConfig
util.Initializer
}
var _ remotewrite.RemoteWriteServer = (*RemoteWriteForwarder)(nil)
type RemoteWriteForwarderConfig struct {
CortexClientSet ClientSet `validate:"required"`
Config *v1beta1.GatewayConfigSpec `validate:"required"`
Logger *zap.SugaredLogger `validate:"required"`
}
func (f *RemoteWriteForwarder) Initialize(conf RemoteWriteForwarderConfig) {
f.InitOnce(func() {
if err := metricsutil.Validate.Struct(conf); err != nil {
panic(err)
}
f.RemoteWriteForwarderConfig = conf
})
}
func (f *RemoteWriteForwarder) Push(ctx context.Context, payload *remotewrite.Payload) (_ *emptypb.Empty, pushErr error) {
if !f.Initialized() {
return nil, util.StatusError(codes.Unavailable)
}
clusterId := cluster.StreamAuthorizedID(ctx)
// example: detecting the local cluster via session attributes
//
// attributes := session.StreamAuthorizedAttributes(ctx)
// attrNames := make([]string, 0, len(attributes))
// for _, attr := range attributes {
// attrNames = append(attrNames, attr.Name())
// }
// for _, attr := range attributes {
// if attr.Name() == "local" {
// f.Logger.Debug("detected local cluster")
// }
// }
defer func() {
code := status.Code(pushErr)
mRemoteWriteRequests.WithLabelValues(clusterId, fmt.Sprint(code), code.String()).Inc()
}()
payloadSize := float64(len(payload.Contents))
mIngestBytesTotal.Add(payloadSize)
mIngestBytesByID.WithLabelValues(clusterId).Add(payloadSize)
ctx, span := otel.Tracer("plugin_metrics").Start(ctx, "remoteWriteForwarder.Push",
trace.WithAttributes(attribute.String("clusterId", clusterId)))
defer span.End()
defer func() {
if pushErr != nil {
lg := f.Logger.With(
"err", pushErr,
"clusterId", clusterId,
)
if s, ok := status.FromError(pushErr); ok {
lg = lg.With("code", int32(s.Code()))
}
lg.Error("error pushing metrics to cortex")
}
}()
url := fmt.Sprintf("https://%s/api/v1/push", f.Config.Cortex.Distributor.HTTPAddress)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url,
bytes.NewReader(payload.Contents))
if err != nil {
return nil, err
}
if err := user.InjectOrgIDIntoHTTPRequest(user.InjectOrgID(ctx, clusterId), req); err != nil {
return nil, err
}
for k, v := range payload.Headers {
req.Header.Add(k, v)
}
resp, err := f.CortexClientSet.HTTP().Do(req)
if err != nil {
return nil, status.Errorf(codes.Internal, "error pushing metrics to cortex: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(resp.Body)
return nil, status.New(codes.Code(resp.StatusCode), string(msg)).Err() // match cortex logic
}
return &emptypb.Empty{}, nil
}
func (f *RemoteWriteForwarder) SyncRules(ctx context.Context, payload *remotewrite.Payload) (_ *emptypb.Empty, syncErr error) {
if !f.Initialized() {
return nil, util.StatusError(codes.Unavailable)
}
clusterId := cluster.StreamAuthorizedID(ctx)
ctx, span := otel.Tracer("plugin_metrics").Start(ctx, "remoteWriteForwarder.Push",
trace.WithAttributes(attribute.String("clusterId", clusterId)))
defer span.End()
defer func() {
if syncErr != nil {
f.Logger.With(
"err", syncErr,
"clusterId", clusterId,
).Error("error syncing rules to cortex")
}
}()
url := fmt.Sprintf(
"https://%s/api/v1/rules/%s",
f.Config.Cortex.Ruler.HTTPAddress,
"synced", // set the namespace to synced to differentiate from user rules
)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url,
bytes.NewReader(payload.Contents))
if err != nil {
return nil, err
}
if err := user.InjectOrgIDIntoHTTPRequest(user.InjectOrgID(ctx, clusterId), req); err != nil {
return nil, err
}
for k, v := range payload.Headers {
req.Header.Add(k, v)
}
resp, err := f.CortexClientSet.HTTP().Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return nil, status.Errorf(codes.Internal, "failed to sync rules: %v", resp.Status)
}
return &emptypb.Empty{}, nil
}