File: aggregating_querier.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (237 lines) | stat: -rw-r--r-- 5,944 bytes parent folder | download
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
package tracker

import (
	"context"
	"fmt"
	"sync"
	"time"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/retry"
	"go.uber.org/zap"
)

type pollingState byte

const (
	stopped pollingState = iota
	running
)

// PollKasUrlsByAgentIdCallback is called periodically with found kas URLs for a particular agent id.
type PollKasUrlsByAgentIdCallback func(kasUrls []string)

type PollingQuerier interface {
	PollKasUrlsByAgentId(ctx context.Context, agentId int64, cb PollKasUrlsByAgentIdCallback)
	CachedKasUrlsByAgentId(agentId int64) []string
}

type pollConsumer struct {
	ctxDone  <-chan struct{}
	kasUrlsC chan<- []string
}

type pollingContext struct {
	mu        sync.Mutex
	consumers map[*pollConsumer]struct{}
	cancel    context.CancelFunc
	kasUrls   []string
	stoppedAt time.Time
	state     pollingState
}

func newPollingContext() *pollingContext {
	return &pollingContext{
		consumers: map[*pollConsumer]struct{}{},
		state:     stopped,
	}
}

func (c *pollingContext) copyConsumersInto(consumers []pollConsumer) []pollConsumer {
	consumers = consumers[:0]
	c.mu.Lock()
	defer c.mu.Unlock()
	for h := range c.consumers {
		consumers = append(consumers, *h)
	}
	return consumers
}

func (c *pollingContext) setKasUrls(kasUrls []string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.kasUrls = kasUrls
}

func (c *pollingContext) isExpired(before time.Time) bool {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.state == stopped && c.stoppedAt.Before(before)
}

// AggregatingQuerier groups polling requests.
type AggregatingQuerier struct {
	log        *zap.Logger
	delegate   Querier
	api        modshared.Api
	pollConfig retry.PollConfigFactory
	gcPeriod   time.Duration

	mu        sync.Mutex
	listeners map[int64]*pollingContext
}

func NewAggregatingQuerier(log *zap.Logger, delegate Querier, api modshared.Api, pollConfig retry.PollConfigFactory, gcPeriod time.Duration) *AggregatingQuerier {
	return &AggregatingQuerier{
		log:        log,
		delegate:   delegate,
		api:        api,
		pollConfig: pollConfig,
		gcPeriod:   gcPeriod,
		listeners:  make(map[int64]*pollingContext),
	}
}

func (q *AggregatingQuerier) Run(ctx context.Context) error {
	done := ctx.Done()
	t := time.NewTicker(q.gcPeriod)
	defer t.Stop()
	for {
		select {
		case <-done:
			return nil
		case <-t.C:
			q.runGc()
		}
	}
}

func (q *AggregatingQuerier) runGc() {
	before := time.Now().Add(-q.gcPeriod)
	q.mu.Lock()
	defer q.mu.Unlock()
	for agentId, pc := range q.listeners {
		if pc.isExpired(before) {
			delete(q.listeners, agentId)
		}
	}
}

func (q *AggregatingQuerier) PollKasUrlsByAgentId(ctx context.Context, agentId int64, cb PollKasUrlsByAgentIdCallback) {
	kasUrlsC := make(chan []string)
	ctxDone := ctx.Done()
	h := &pollConsumer{
		ctxDone:  ctxDone,
		kasUrlsC: kasUrlsC,
	}
	q.maybeStartPolling(agentId, h) // nolint: contextcheck
	defer q.maybeStopPolling(agentId, h)
	for {
		select {
		case <-ctxDone:
			return
		case kasUrls := <-kasUrlsC:
			cb(kasUrls)
		}
	}
}

func (q *AggregatingQuerier) CachedKasUrlsByAgentId(agentId int64) []string {
	q.mu.Lock()
	defer q.mu.Unlock()
	pc := q.listeners[agentId]
	if pc == nil { // no existing context
		return nil
	}
	pc.mu.Lock()
	defer pc.mu.Unlock()
	return pc.kasUrls
}

func (q *AggregatingQuerier) maybeStartPolling(agentId int64, h *pollConsumer) {
	q.mu.Lock()
	defer q.mu.Unlock()
	pc := q.listeners[agentId]
	if pc == nil { // no existing context
		pc = newPollingContext()
		q.listeners[agentId] = pc
	}
	q.registerConsumerLocked(agentId, pc, h)
}

func (q *AggregatingQuerier) registerConsumerLocked(agentId int64, pc *pollingContext, h *pollConsumer) {
	pc.mu.Lock()
	defer pc.mu.Unlock()
	pc.consumers[h] = struct{}{} // register for notifications
	switch pc.state {
	case stopped:
		pc.state = running
		ctx, cancel := context.WithCancel(context.Background())
		pc.cancel = cancel
		go q.poll(ctx, agentId, pc)
	case running:
		// Already polling, nothing to do.
	default:
		panic(fmt.Sprintf("invalid state value: %d", pc.state))
	}
}

func (q *AggregatingQuerier) maybeStopPolling(agentId int64, h *pollConsumer) {
	q.mu.Lock()
	defer q.mu.Unlock()

	pc := q.listeners[agentId]
	if q.unregisterConsumerLocked(pc, h) {
		// No point in keeping this pollingContext around if it doesn't have any cached URLs.
		delete(q.listeners, agentId)
	}
}

func (q *AggregatingQuerier) unregisterConsumerLocked(pc *pollingContext, h *pollConsumer) bool {
	pc.mu.Lock()
	defer pc.mu.Unlock()

	delete(pc.consumers, h)
	if len(pc.consumers) == 0 {
		pc.cancel()     // stop polling
		pc.cancel = nil // release the kraken! err... GC
		pc.state = stopped
		pc.stoppedAt = time.Now()
		return len(pc.kasUrls) == 0
	}
	return false
}

func (q *AggregatingQuerier) poll(ctx context.Context, agentId int64, pc *pollingContext) {
	var consumers []pollConsumer // reuse slice between polls
	// err can only be retry.ErrWaitTimeout
	_ = retry.PollWithBackoff(ctx, q.pollConfig(), func(ctx context.Context) (error, retry.AttemptResult) {
		var kasUrls []string
		err := q.delegate.KasUrlsByAgentId(ctx, agentId, func(kasUrl string) (bool, error) {
			kasUrls = append(kasUrls, kasUrl)
			return false, nil
		})
		if err != nil {
			q.api.HandleProcessingError(ctx, q.log, agentId, "KasUrlsByAgentId() failed", err)
			// fallthrough
		}
		if len(kasUrls) > 0 {
			consumers = pc.copyConsumersInto(consumers)
			for _, h := range consumers {
				select {
				case <-h.ctxDone:
					// This PollKasUrlsByAgentId() invocation is no longer interested in being called. Ignore it.
				case h.kasUrlsC <- kasUrls:
					// Data sent.
				}
			}
		}
		if err != nil && len(kasUrls) == 0 {
			// if there was an error, and we failed to retrieve any kas URLs from Redis, we don't want to erase the
			// cache. So, no-op here.
		} else {
			pc.setKasUrls(kasUrls)
		}
		return nil, retry.Continue
	})
}