-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
134 lines (111 loc) · 4.02 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
metrics2 "github.com/berops/claudie/services/context-box/server/domain/usecases/metrics"
"google.golang.org/grpc/health/grpc_health_v1"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/sync/errgroup"
grpc2 "google.golang.org/grpc"
"github.com/berops/claudie/internal/envs"
"github.com/berops/claudie/internal/utils"
"github.com/berops/claudie/internal/utils/metrics"
"github.com/berops/claudie/internal/worker"
"github.com/berops/claudie/services/context-box/server/adapters/inbound/grpc"
outboundAdapters "github.com/berops/claudie/services/context-box/server/adapters/outbound"
"github.com/berops/claudie/services/context-box/server/domain/usecases"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog/log"
)
const (
defaultPrometheusPort = "9090"
)
func main() {
// initialize logger
utils.InitLog("context-box")
mongoDBConnector := outboundAdapters.NewMongoDBConnector(envs.DatabaseURL)
err := mongoDBConnector.Connect()
if err != nil {
log.Fatal().Msgf("Unable to connect to MongoDB: %v", err)
}
err = mongoDBConnector.Init()
if err != nil {
log.Fatal().Msgf("Unable to perform initialization tasks for MongoDB: %v", err)
}
log.Info().Msgf("Connected to MongoDB")
defer mongoDBConnector.Disconnect()
usecases := &usecases.Usecases{
DB: mongoDBConnector,
}
metricsServer := &http.Server{Addr: fmt.Sprintf(":%s", utils.GetEnvDefault("PROMETHEUS_PORT", defaultPrometheusPort))}
metrics.MustRegisterCounters()
metrics2.MustRegisterCounters()
grpcAdapter := &grpc.GrpcAdapter{}
grpcAdapter.Init(usecases, grpc2.UnaryInterceptor(metrics.MetricsMiddleware))
errGroup, errGroupContext := errgroup.WithContext(context.Background())
errGroup.Go(func() error {
ticker := time.NewTicker(30 * time.Second)
for {
select {
case <-errGroupContext.Done():
ticker.Stop()
return nil
case <-ticker.C:
if err := mongoDBConnector.HealthCheck(); err != nil {
grpcAdapter.HealthCheckServer.SetServingStatus("context-box-readiness", grpc_health_v1.HealthCheckResponse_NOT_SERVING)
log.Debug().Msgf("Failed to verify healthcheck: %v", err)
} else {
grpcAdapter.HealthCheckServer.SetServingStatus("context-box-readiness", grpc_health_v1.HealthCheckResponse_SERVING)
}
}
}
})
// Server goroutine
errGroup.Go(func() error {
return grpcAdapter.Serve()
})
// Go routine to check and enqueue configs periodically
errGroup.Go(func() error {
worker.NewWorker(errGroupContext, 10*time.Second, usecases.EnqueueConfigs, worker.ErrorLogger).Run()
log.Info().Msg("Exited worker loop running EnqueueConfigs")
return nil
})
// Listen for system interruption signals to gracefully shut down
errGroup.Go(func() error {
shutdownSignalChan := make(chan os.Signal, 1)
signal.Notify(shutdownSignalChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(shutdownSignalChan)
var err error
// Wait for either the received signal or
// check if an error occurred in other go-routines.
select {
case <-errGroupContext.Done():
err = errGroupContext.Err()
case shutdownSignal := <-shutdownSignalChan:
log.Info().Msgf("Received program shutdown signal %v", shutdownSignal)
err = errors.New("program interruption signal")
}
if err := metricsServer.Shutdown(errGroupContext); err != nil {
log.Err(err).Msgf("Failed to shutdown metrics server")
}
// Perform graceful shutdown
log.Info().Msg("Gracefully shutting down GrpcAdapter")
grpcAdapter.Stop()
// Sometimes when the container terminates gRPC logs the following message:
// rpc error: code = Unknown desc = Error: No such container: hash of the container...
// It does not affect anything as everything will get terminated gracefully
// this time.Sleep fixes it so that the message won't be logged.
time.Sleep(1 * time.Second)
return err
})
errGroup.Go(func() error {
http.Handle("/metrics", promhttp.Handler())
return metricsServer.ListenAndServe()
})
log.Info().Msgf("Stopping context-box microservice: %v", errGroup.Wait())
}