-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkernel.go
More file actions
187 lines (155 loc) · 5.07 KB
/
kernel.go
File metadata and controls
187 lines (155 loc) · 5.07 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
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
package cosy
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"os/signal"
"sync/atomic"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/go-gormigrate/gormigrate/v2"
"github.com/uozi-tech/cosy/cron"
"github.com/uozi-tech/cosy/kernel"
"github.com/uozi-tech/cosy/logger"
"github.com/uozi-tech/cosy/model"
"github.com/uozi-tech/cosy/redis"
"github.com/uozi-tech/cosy/router"
"github.com/uozi-tech/cosy/settings"
"github.com/uozi-tech/cosy/sonyflake"
)
var (
TCPAddr *net.TCPAddr
listener net.Listener
tlsCertCache atomic.Value // Stores tls.Certificate
)
// loadAndCacheCertificate loads TLS certificate from disk and stores it in cache
func loadAndCacheCertificate(certFile, keyFile string) error {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
tlsCertCache.Store(&cert)
logger.Info("SSL certificate loaded and cached successfully")
return nil
}
// ReloadTLSCertificate reloads the TLS certificate from disk
func ReloadTLSCertificate() error {
return loadAndCacheCertificate(settings.ServerSettings.SSLCert, settings.ServerSettings.SSLKey)
}
// SetListener Set the listener
func SetListener(l net.Listener) {
listener = l
}
// Boot the server
func Boot(confPath string) {
// Create a context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Initialize settings package
settings.Init(confPath)
// Set gin mode
gin.SetMode(settings.ServerSettings.RunMode)
// Initialize logger package
logger.Init(settings.ServerSettings.RunMode)
defer logger.Sync()
// Initialize audit SLS producer
if err := logger.InitAuditSLSProducer(ctx); err != nil {
logger.Warnf("Failed to initialize audit SLS producer: %v", err)
}
// If redis settings addr is not empty, init redis
if settings.RedisSettings.Addr != "" {
redis.Init()
}
// Initialize sonyflake
sonyflake.Init()
// Start cron
cron.Start()
defer cron.Stop()
// Gin router initialization
router.Init()
// Kernel boot
kernel.Boot(ctx)
addr := fmt.Sprintf("%s:%d", settings.ServerSettings.Host, settings.ServerSettings.Port)
// If the listener is nil, create a new listener, otherwise use the preset listener.
if listener == nil {
var err error
listener, err = net.Listen("tcp", addr)
if err != nil {
logger.Fatalf("listen: %s\n", err)
}
}
// Preload certificate to cache if HTTPS is enabled
var tlsConfig *tls.Config
if settings.ServerSettings.EnableHTTPS {
if err := loadAndCacheCertificate(settings.ServerSettings.SSLCert, settings.ServerSettings.SSLKey); err != nil {
logger.Fatalf("Failed to load initial SSL certificate: %s\n", err)
}
// Create TLS config with GetCertificate function for certificate hot-reloading
tlsConfig = &tls.Config{
GetCertificate: func(info *tls.ClientHelloInfo) (*tls.Certificate, error) {
certVal, ok := tlsCertCache.Load().(*tls.Certificate)
if !ok {
logger.Error("No valid certificate found in cache")
return nil, errors.New("no valid certificate available")
}
return certVal, nil
},
}
}
// Create and initialize server factory with protocol support
serverFactory := kernel.NewServerFactory(router.GetEngine(), tlsConfig)
if err := serverFactory.Initialize(); err != nil {
logger.Fatalf("Failed to initialize server factory: %v", err)
}
TCPAddr = listener.Addr().(*net.TCPAddr)
// Start all protocol servers in a goroutine with proper error handling
serverStarted := make(chan error, 1)
go func() {
if err := serverFactory.Start(ctx, listener); err != nil {
serverStarted <- err
return
}
serverStarted <- nil
}()
// Wait for server to start or fail
select {
case err := <-serverStarted:
if err != nil {
logger.Fatalf("Failed to start servers: %v", err)
}
case <-ctx.Done():
// If we receive shutdown signal before server starts, just exit
logger.Info("Received shutdown signal before server started")
return
}
// Listen for the interrupt signal.
<-ctx.Done()
// Restore default behavior on the interrupt signal and notify user of shutdown.
logger.Info("shutting down gracefully, press Ctrl+C again to force")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := serverFactory.Shutdown(shutdownCtx); err != nil {
logger.Fatal("Server forced to shutdown: ", err)
}
logger.Info("Server exited")
}
// RegisterInitFunc Register init functions, this function should be called before kernel boot.
func RegisterInitFunc(f ...func()) {
kernel.RegisterInitFunc(f...)
}
// RegisterGoroutine Register syncs functions, this function should be called before kernel boot.
func RegisterGoroutine(f ...func(context.Context)) {
kernel.RegisterGoroutine(f...)
}
func RegisterMigrationsBeforeAutoMigrate(m []*gormigrate.Migration) {
model.RegisterMigrationsBeforeAutoMigrate(m)
}
// RegisterMigration Register a migration
func RegisterMigration(m []*gormigrate.Migration) {
model.RegisterMigration(m)
}