/
statuser.go
456 lines (394 loc) · 13.7 KB
/
statuser.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/RHEnVision/provisioning-backend/internal/clients"
"github.com/RHEnVision/provisioning-backend/internal/db"
"github.com/RHEnVision/provisioning-backend/internal/models"
"github.com/RHEnVision/provisioning-backend/internal/notifications"
"github.com/RHEnVision/provisioning-backend/internal/ptr"
"github.com/RHEnVision/provisioning-backend/internal/random"
// Clients
_ "github.com/RHEnVision/provisioning-backend/internal/clients/http/azure"
_ "github.com/RHEnVision/provisioning-backend/internal/clients/http/ec2"
_ "github.com/RHEnVision/provisioning-backend/internal/clients/http/gcp"
_ "github.com/RHEnVision/provisioning-backend/internal/clients/http/image_builder"
_ "github.com/RHEnVision/provisioning-backend/internal/clients/http/sources"
"github.com/RHEnVision/provisioning-backend/internal/config"
"github.com/RHEnVision/provisioning-backend/internal/kafka"
"github.com/RHEnVision/provisioning-backend/internal/metrics"
"github.com/RHEnVision/provisioning-backend/internal/logging"
"github.com/RHEnVision/provisioning-backend/internal/telemetry"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const ChannelBuffer = 32
type SourceInfo struct {
MessageContext context.Context // Carries logger and identity
Authentication clients.Authentication
SourceApplicationID string
}
var (
chAws = make(chan SourceInfo, ChannelBuffer)
chAzure = make(chan SourceInfo, ChannelBuffer)
chGcp = make(chan SourceInfo, ChannelBuffer)
chSend = make(chan kafka.SourceResult, ChannelBuffer)
receiverWG = sync.WaitGroup{}
processingWG = sync.WaitGroup{}
senderWG = sync.WaitGroup{}
)
func init() {
random.SeedGlobal()
}
func processMessage(msgCtx context.Context, message *kafka.GenericMessage) {
logger := zerolog.Ctx(msgCtx)
// Get source id
asm, err := kafka.NewAvailabilityStatusMessage(message)
if err != nil {
logger.Warn().Err(err).Msg("Could not get availability status message")
return
}
// Set source id as logging field
sourceId := asm.SourceID
logger = ptr.To(logger.With().Str("source_id", sourceId).Logger())
ctx := logger.WithContext(msgCtx)
logger.Trace().Msgf("Sources availability check for %s", sourceId)
// Get sources client
sourcesClient, err := clients.GetSourcesClient(ctx)
if err != nil {
logger.Warn().Err(err).Msg("Could not get sources client")
return
}
// Fetch authentication from Sources
authentication, err := sourcesClient.GetAuthentication(ctx, sourceId)
if err != nil {
metrics.IncTotalInvalidAvailabilityCheckReqs()
if errors.Is(err, clients.ErrNotFound) {
logger.Warn().Err(err).Msg("Not found error from sources")
return
}
if errors.Is(err, clients.ErrBadRequest) {
logger.Warn().Err(err).Msg("Bad request error from sources")
return
}
logger.Warn().Err(err).Msg("Could not get authentication")
return
}
s := SourceInfo{
MessageContext: ctx,
Authentication: *authentication,
SourceApplicationID: authentication.SourceApplictionID,
}
switch authentication.ProviderType {
case models.ProviderTypeAWS:
chAws <- s
case models.ProviderTypeAzure:
chAzure <- s
case models.ProviderTypeGCP:
chGcp <- s
case models.ProviderTypeNoop:
case models.ProviderTypeUnknown:
logger.Warn().Err(err).Msg("Authentication provider type is unknown")
}
}
func checkSourceAvailabilityAzure(cancelCtx context.Context) {
defer processingWG.Done()
for s := range chAzure {
ctx := s.MessageContext
logger := zerolog.Ctx(ctx)
if random.Float32() > config.Azure.AvailabilityRate {
logger.Trace().Msgf("Skipping Azure source availability status %s", s.SourceApplicationID)
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeAzure.String(), "skipped", nil)
continue
}
logger.Trace().Msgf("Checking Azure source availability status %s", s.SourceApplicationID)
metrics.ObserveAvailabilityCheckReqsDuration(models.ProviderTypeAzure.String(), func() error {
var err error
sr := kafka.SourceResult{
MessageContext: ctx,
ResourceID: s.SourceApplicationID,
ResourceType: "Application",
}
azureClient, err := clients.GetAzureClient(ctx, &s.Authentication)
if err != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = "We could not log into this Azure account"
logger.Warn().Err(err).Msg("Failed to create Azure client")
} else {
_, verifyErr := azureClient.TenantId(ctx)
if verifyErr != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = "Red Hat HCC provisioning service account can not connect to your subscription"
logger.Info().Err(err).Str("source_id", sr.ResourceID).Msg("Failed to fetch subscription's tenant from Azure")
} else {
sr.Status = kafka.StatusAvailable
}
}
chSend <- sr
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeAzure.String(), sr.Status.String(), nil)
return fmt.Errorf("error during check: %w", err)
})
if cancelCtx.Err() != nil {
break
}
time.Sleep(config.Azure.AvailabilityDelay)
}
}
func checkSourceAvailabilityAWS(cancelCtx context.Context) {
defer processingWG.Done()
for s := range chAws {
ctx := s.MessageContext
logger := zerolog.Ctx(ctx)
if random.Float32() > config.AWS.AvailabilityRate {
logger.Trace().Msgf("Skipping AWS source availability status %s", s.SourceApplicationID)
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeAWS.String(), "skipped", nil)
continue
}
logger.Trace().Msgf("Checking AWS source availability status %s", s.SourceApplicationID)
metrics.ObserveAvailabilityCheckReqsDuration(models.ProviderTypeAWS.String(), func() error {
var err error
var permissions []string
sr := kafka.SourceResult{
MessageContext: ctx,
ResourceID: s.SourceApplicationID,
ResourceType: "Application",
}
ec2Client, err := clients.GetEC2Client(ctx, &s.Authentication, "")
if err != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = "Could not log into AWS account"
logger.Warn().Err(err).Msg("Could not get aws assumed client")
} else {
sr.Status = kafka.StatusAvailable
permissions, err = ec2Client.CheckPermission(ctx, &s.Authentication)
if err != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = fmt.Sprintf("Missing AWS permissions %s", strings.Join(permissions, ", "))
sr.MissingPermissions = permissions
if logger.Info().Enabled() {
arr := zerolog.Arr()
for _, p := range permissions {
arr.Str(p)
}
logger.Info().Err(err).
Array("missing_aws_permissions", arr).
Str("source_id", sr.ResourceID).Msg("Missing AWS permissions")
}
}
}
chSend <- sr
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeAWS.String(), sr.Status.String(), err)
return fmt.Errorf("error during check: %w", err)
})
if cancelCtx.Err() != nil {
break
}
time.Sleep(config.AWS.AvailabilityDelay)
}
}
func checkSourceAvailabilityGCP(cancelCtx context.Context) {
defer processingWG.Done()
for s := range chGcp {
ctx := s.MessageContext
logger := zerolog.Ctx(ctx)
if random.Float32() > config.GCP.AvailabilityRate {
logger.Trace().Msgf("Skipping GCP source availability status %s", s.SourceApplicationID)
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeGCP.String(), "skipped", nil)
continue
}
logger.Trace().Msgf("Checking GCP source availability status %s", s.SourceApplicationID)
metrics.ObserveAvailabilityCheckReqsDuration(models.ProviderTypeGCP.String(), func() error {
var err error
sr := kafka.SourceResult{
MessageContext: s.MessageContext,
ResourceID: s.SourceApplicationID,
ResourceType: "Application",
}
gcpClient, err := clients.GetGCPClient(ctx, &s.Authentication)
if err != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = "Could not list log into GCP account"
logger.Warn().Err(err).Msg("Could not get gcp client")
chSend <- sr
}
_, err = gcpClient.ListAllRegions(ctx)
if err != nil {
sr.Status = kafka.StatusUnavailable
sr.Err = err
sr.UserError = "Could not list gcp regions using the provided source"
logger.Warn().Err(err).Msg("Could not list gcp regions")
chSend <- sr
} else {
sr.Status = kafka.StatusAvailable
chSend <- sr
}
metrics.IncTotalSentAvailabilityCheckReqs(models.ProviderTypeGCP.String(), sr.Status.String(), err)
return fmt.Errorf("error during check: %w", err)
})
if cancelCtx.Err() != nil {
break
}
time.Sleep(config.GCP.AvailabilityDelay)
}
}
func sendResults(cancelCtx context.Context, batchSize int, tickDuration time.Duration) {
messages := make([]*kafka.GenericMessage, 0, batchSize)
ticker := time.NewTicker(tickDuration)
defer senderWG.Done()
for {
select {
case sr := <-chSend:
ctx := sr.MessageContext
logger := zerolog.Ctx(ctx)
msg, err := sr.GenericMessage(ctx)
if err != nil {
logger.Warn().Err(err).Msg("Could not generate generic message")
continue
}
messages = append(messages, &msg)
length := len(messages)
if length >= batchSize {
logger.Trace().Int("messages", length).Msgf("Sending %d source availability status messages (full buffer)", length)
err := kafka.Send(ctx, messages...)
if err != nil {
logger.Warn().Err(err).Msg("Could not send source availability status messages (full buffer)")
}
messages = messages[:0]
}
case <-ticker.C:
logger := zerolog.Ctx(cancelCtx)
length := len(messages)
if length > 0 {
logger.Trace().Int("messages", length).Msgf("Sending %d source availability status messages (tick)", length)
err := kafka.Send(cancelCtx, messages...)
if err != nil {
logger.Warn().Err(err).Msg("Could not send source availability status messages (tick)")
}
messages = messages[:0]
}
case <-cancelCtx.Done():
logger := zerolog.Ctx(cancelCtx)
ticker.Stop()
length := len(messages)
if length > 0 {
logger.Trace().Int("messages", length).Msgf("Sending %d source availability status messages (cancel)", length)
err := kafka.Send(cancelCtx, messages...)
if err != nil {
logger.Warn().Err(err).Msg("Could not send source availability status messages (cancel)")
}
}
return
}
}
}
func statuser() {
ctx := context.Background()
config.Initialize("config/api.env", "config/statuser.env")
// initialize cloudwatch using the AWS clients
logger, closeFunc := logging.InitializeLogger()
defer closeFunc()
logging.DumpConfigForDevelopment()
// initialize telemetry
tel := telemetry.Initialize(ctx, &log.Logger)
defer tel.Close(ctx)
// initialize platform kafka and notifications
if config.Kafka.Enabled {
err := kafka.InitializeKafkaBroker(ctx)
if err != nil {
logger.Fatal().Err(err).Msg("Unable to initialize the platform kafka")
}
if config.Application.Notifications.Enabled {
notifications.Initialize(ctx)
}
}
// metrics
logger.Info().Msgf("Starting new instance on port %d with prometheus on %d", config.Application.Port, config.Prometheus.Port)
metricsRouter := chi.NewRouter()
metricsRouter.Handle(config.Prometheus.Path, promhttp.Handler())
metricsServer := http.Server{
Addr: fmt.Sprintf(":%d", config.Prometheus.Port),
Handler: metricsRouter,
}
signalNotify := make(chan struct{})
go func() {
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT, syscall.SIGTERM)
<-sigint
if shutdownErr := metricsServer.Shutdown(context.Background()); shutdownErr != nil {
logger.Warn().Err(shutdownErr).Msg("Metrics service shutdown error")
}
close(signalNotify)
}()
go func() {
if listenErr := metricsServer.ListenAndServe(); listenErr != nil {
var errInUse syscall.Errno
if errors.As(listenErr, &errInUse) && errInUse == syscall.EADDRINUSE {
logger.Warn().Err(listenErr).Msg("Not starting metrics service, port already in use")
} else if !errors.Is(listenErr, http.ErrServerClosed) {
logger.Warn().Err(listenErr).Msg("Metrics service listen error")
}
}
}()
// start the consumer
receiverWG.Add(1)
cancelCtx, consumerCancelFunc := context.WithCancel(ctx)
consumerNotify := make(chan struct{})
go func() {
defer receiverWG.Done()
kafka.Consume(cancelCtx, kafka.AvailabilityStatusRequestTopic, time.Now(), processMessage)
close(consumerNotify)
}()
metrics.RegisterStatuserMetrics()
// initialize the database
logger.Debug().Msg("Initializing database connection")
err := db.Initialize(ctx, "public")
if err != nil {
log.Fatal().Err(err).Msg("Error initializing database")
}
defer db.Close()
// start processing goroutines
processingWG.Add(3)
go checkSourceAvailabilityAWS(cancelCtx)
go checkSourceAvailabilityGCP(cancelCtx)
go checkSourceAvailabilityAzure(cancelCtx)
senderWG.Add(1)
// processing can be slowed down by configuration: send messages in maximum
// batch size of 8 messages or 4 seconds (what comes first)
go sendResults(cancelCtx, 8, 4*time.Second)
logger.Info().Msg("Statuser process started")
select {
case <-signalNotify:
logger.Info().Msg("Exiting due to signal")
case <-consumerNotify:
logger.Warn().Msg("Exiting due to closed consumer")
}
// stop kafka receiver (can take up to 10 seconds) and wait until it returns
consumerCancelFunc()
receiverWG.Wait()
// close all processors and wait until it exits the range loop
close(chAws)
close(chAzure)
close(chGcp)
processingWG.Wait()
// close the sending channel and wait until it exits the range loop
close(chSend)
senderWG.Wait()
logger.Info().Msg("Consumer shutdown initiated")
consumerCancelFunc()
logger.Info().Msg("Shutdown finished, exiting")
}