-
Notifications
You must be signed in to change notification settings - Fork 482
/
kubernetes.go
251 lines (210 loc) · 6.01 KB
/
kubernetes.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
// Package kubernetes implements the logic for remote.kubernetes.secret and remote.kubernetes.configmap component.
package kubernetes
import (
"context"
"fmt"
"reflect"
"sync"
"time"
"github.com/go-kit/log"
"github.com/grafana/agent/component"
"github.com/grafana/agent/component/common/kubernetes"
"github.com/grafana/river/rivertypes"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
client_go "k8s.io/client-go/kubernetes"
)
type ResourceType string
const (
TypeSecret ResourceType = "secret"
TypeConfigMap ResourceType = "configmap"
)
// Arguments control the component.
type Arguments struct {
Namespace string `river:"namespace,attr"`
Name string `river:"name,attr"`
PollFrequency time.Duration `river:"poll_frequency,attr,optional"`
PollTimeout time.Duration `river:"poll_timeout,attr,optional"`
// Client settings to connect to Kubernetes.
Client kubernetes.ClientArguments `river:"client,block,optional"`
}
// DefaultArguments holds default settings for Arguments.
var DefaultArguments = Arguments{
PollFrequency: 1 * time.Minute,
PollTimeout: 15 * time.Second,
}
// SetToDefault implements river.Defaulter.
func (args *Arguments) SetToDefault() {
*args = DefaultArguments
}
// Validate implements river.Validator.
func (args *Arguments) Validate() error {
if args.PollFrequency <= 0 {
return fmt.Errorf("poll_frequency must be greater than 0")
}
if args.PollTimeout <= 0 {
return fmt.Errorf("poll_timeout must not be greater than 0")
}
return nil
}
// Exports holds settings exported by this component.
type Exports struct {
Data map[string]rivertypes.OptionalSecret `river:"data,attr"`
}
// Component implements the remote.kubernetes.* component.
type Component struct {
log log.Logger
opts component.Options
mut sync.Mutex
args Arguments
client *client_go.Clientset
kind ResourceType
lastPoll time.Time
lastExports Exports // Used for determining whether exports should be updated
healthMut sync.RWMutex
health component.Health
}
var (
_ component.Component = (*Component)(nil)
_ component.HealthComponent = (*Component)(nil)
)
// New returns a new, unstarted remote.kubernetes.* component.
func New(opts component.Options, args Arguments, rType ResourceType) (*Component, error) {
c := &Component{
log: opts.Logger,
opts: opts,
kind: rType,
health: component.Health{
Health: component.HealthTypeUnknown,
Message: "component started",
UpdateTime: time.Now(),
},
}
if err := c.Update(args); err != nil {
return nil, err
}
return c, nil
}
// Run starts the remote.kubernetes.* component.
func (c *Component) Run(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
case <-time.After(c.nextPoll()):
c.poll()
}
}
}
// nextPoll returns how long to wait to poll given the last time a
// poll occurred. nextPoll returns 0 if a poll should occur immediately.
func (c *Component) nextPoll() time.Duration {
c.mut.Lock()
defer c.mut.Unlock()
nextPoll := c.lastPoll.Add(c.args.PollFrequency)
now := time.Now()
if now.After(nextPoll) {
// Poll immediately; next poll period was in the past.
return 0
}
return nextPoll.Sub(now)
}
// poll performs a HTTP GET for the component's configured URL. c.mut must
// not be held when calling. After polling, the component's health is updated
// with the success or failure status.
func (c *Component) poll() {
err := c.pollError()
c.updatePollHealth(err)
}
func (c *Component) updatePollHealth(err error) {
c.healthMut.Lock()
defer c.healthMut.Unlock()
if err == nil {
c.health = component.Health{
Health: component.HealthTypeHealthy,
Message: "got " + string(c.kind),
UpdateTime: time.Now(),
}
} else {
c.health = component.Health{
Health: component.HealthTypeUnhealthy,
Message: fmt.Sprintf("polling failed: %s", err),
UpdateTime: time.Now(),
}
}
}
// pollError is like poll but returns an error if one occurred.
func (c *Component) pollError() error {
c.mut.Lock()
defer c.mut.Unlock()
c.lastPoll = time.Now()
ctx, cancel := context.WithTimeout(context.Background(), c.args.PollTimeout)
defer cancel()
data := map[string]rivertypes.OptionalSecret{}
if c.kind == TypeSecret {
secret, err := c.client.CoreV1().Secrets(c.args.Namespace).Get(ctx, c.args.Name, v1.GetOptions{})
if err != nil {
return err
}
for k, v := range secret.Data {
data[k] = rivertypes.OptionalSecret{
Value: string(v),
IsSecret: true,
}
}
} else if c.kind == TypeConfigMap {
cmap, err := c.client.CoreV1().ConfigMaps(c.args.Namespace).Get(ctx, c.args.Name, v1.GetOptions{})
if err != nil {
return err
}
for k, v := range cmap.Data {
data[k] = rivertypes.OptionalSecret{
Value: v,
IsSecret: false,
}
}
}
newExports := Exports{
Data: data,
}
// Only send a state change event if the exports have changed from the
// previous poll.
if !reflect.DeepEqual(newExports.Data, c.lastExports.Data) {
c.opts.OnStateChange(newExports)
}
c.lastExports = newExports
return nil
}
// Update updates the remote.kubernetes.* component. After the update completes, a
// poll is forced.
func (c *Component) Update(args component.Arguments) (err error) {
// defer initial poll so the lock is released first
defer func() {
if err != nil {
return
}
// Poll after updating and propagate the error if the poll fails. If an error
// occurred during Update, we don't bother to do anything.
// It is important to set err and the health so startup works correctly
err = c.pollError()
c.updatePollHealth(err)
}()
c.mut.Lock()
defer c.mut.Unlock()
newArgs := args.(Arguments)
c.args = newArgs
restConfig, err := c.args.Client.BuildRESTConfig(c.log)
if err != nil {
return err
}
c.client, err = client_go.NewForConfig(restConfig)
if err != nil {
return fmt.Errorf("creating kubernetes client: %w", err)
}
return err
}
// CurrentHealth returns the current health of the component.
func (c *Component) CurrentHealth() component.Health {
c.healthMut.RLock()
defer c.healthMut.RUnlock()
return c.health
}