-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshutdown.go
More file actions
65 lines (50 loc) · 1.67 KB
/
shutdown.go
File metadata and controls
65 lines (50 loc) · 1.67 KB
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
package service
import (
"context"
)
// gracefulShutdown performs graceful shutdown of the service
func (s *Service) gracefulShutdown() error {
s.Logger.Info("starting graceful shutdown")
// Create a context with timeout for shutdown
ctx, cancel := context.WithTimeout(context.Background(), s.Config.ShutdownTimeout)
defer cancel()
// Execute shutdown hooks
for i, hook := range s.Config.ShutdownHooks {
s.Logger.Info("executing shutdown hook", "index", i)
if err := hook(); err != nil {
s.Logger.Error("shutdown hook failed", "index", i, "error", err)
}
}
// Shutdown servers
var shutdownErrors []error
// Shutdown main HTTP server
if s.server != nil {
s.Logger.Info("shutting down HTTP server")
if err := s.server.Shutdown(ctx); err != nil {
s.Logger.Error("HTTP server shutdown error", "error", err)
shutdownErrors = append(shutdownErrors, err)
}
}
// Shutdown metrics server
if s.metricsServer != nil {
s.Logger.Info("shutting down metrics server")
if err := s.metricsServer.Shutdown(ctx); err != nil {
s.Logger.Error("metrics server shutdown error", "error", err)
shutdownErrors = append(shutdownErrors, err)
}
}
if len(shutdownErrors) > 0 {
s.Logger.Error("shutdown completed with errors", "error_count", len(shutdownErrors))
return shutdownErrors[0] // Return first error
}
s.Logger.Info("graceful shutdown completed")
return nil
}
// AddShutdownHook adds a function to be called during graceful shutdown
func (s *Service) AddShutdownHook(hook func() error) {
s.Config.ShutdownHooks = append(s.Config.ShutdownHooks, hook)
}
// Stop stops the service gracefully
func (s *Service) Stop() error {
return s.gracefulShutdown()
}