-
Notifications
You must be signed in to change notification settings - Fork 41
/
main.go
83 lines (64 loc) · 2.25 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
package main
import (
"context"
"errors"
"fmt"
"github.com/berops/claudie/internal/utils/metrics"
"github.com/prometheus/client_golang/prometheus/promhttp"
grpc2 "google.golang.org/grpc"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
"github.com/berops/claudie/internal/utils"
"github.com/berops/claudie/services/kuber/server/adapters/inbound/grpc"
"github.com/berops/claudie/services/kuber/server/domain/usecases"
)
const (
defaultPrometheusPort = "9090"
)
func main() {
// Initialize logger
utils.InitLog("kuber")
usecases := &usecases.Usecases{}
grpcAdapter := grpc.GrpcAdapter{}
grpcAdapter.Init(usecases, grpc2.UnaryInterceptor(metrics.MetricsMiddleware))
metricsServer := &http.Server{Addr: fmt.Sprintf(":%s", utils.GetEnvDefault("PROMETHEUS_PORT", defaultPrometheusPort))}
metrics.MustRegisterCounters()
errGroup, errGroupContext := errgroup.WithContext(context.Background())
// Start receiving gRPC requests
errGroup.Go(grpcAdapter.Serve)
// Listen for program interruption signals and shut it down gracefully
errGroup.Go(func() error {
shutdownSignalChan := make(chan os.Signal, 1)
signal.Notify(shutdownSignalChan, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(shutdownSignalChan)
var err error
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")
}
// Performing graceful shutdown.
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 Kuber microservice: %s", errGroup.Wait())
}