forked from DiceDB/dice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
287 lines (244 loc) · 8 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
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
// This file is part of DiceDB.
// Copyright (C) 2024 DiceDB (dicedb.io).
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"runtime"
"runtime/pprof"
"runtime/trace"
"sync"
"syscall"
"time"
"github.com/dicedb/dice/internal/server/httpws"
"github.com/dicedb/dice/internal/cli"
"github.com/dicedb/dice/internal/logger"
"github.com/dicedb/dice/internal/server/abstractserver"
"github.com/dicedb/dice/internal/wal"
"github.com/dicedb/dice/internal/watchmanager"
"github.com/dicedb/dice/config"
diceerrors "github.com/dicedb/dice/internal/errors"
"github.com/dicedb/dice/internal/iothread"
"github.com/dicedb/dice/internal/observability"
"github.com/dicedb/dice/internal/server/resp"
"github.com/dicedb/dice/internal/shard"
dstore "github.com/dicedb/dice/internal/store"
)
const (
WALEngineAOF = "aof"
)
func main() {
iid := observability.GetOrCreateInstanceID()
config.DiceConfig.InstanceID = iid
slog.SetDefault(logger.New())
cli.Execute()
go observability.Ping()
ctx, cancel := context.WithCancel(context.Background())
// Handle SIGTERM and SIGINT
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
var (
cmdWatchChan chan dstore.CmdWatchEvent
serverErrCh = make(chan error, 2)
cmdWatchSubscriptionChan = make(chan watchmanager.WatchSubscription)
wl wal.AbstractWAL
)
wl, _ = wal.NewNullWAL()
if config.DiceConfig.Persistence.Enabled {
if config.DiceConfig.Persistence.WALEngine == WALEngineAOF {
_wl, err := wal.NewAOFWAL(config.DiceConfig.WAL.LogDir)
if err != nil {
slog.Warn("could not create WAL with", slog.String("wal-engine", config.DiceConfig.Persistence.WALEngine), slog.Any("error", err))
sigs <- syscall.SIGKILL
return
}
wl = _wl
} else {
slog.Error("unsupported WAL engine", slog.String("engine", config.DiceConfig.Persistence.WALEngine))
sigs <- syscall.SIGKILL
return
}
if err := wl.Init(time.Now()); err != nil {
slog.Error("could not initialize WAL", slog.Any("error", err))
} else {
go wal.InitBG(wl)
}
slog.Debug("WAL initialization complete")
if config.DiceConfig.Persistence.RestoreFromWAL {
slog.Info("restoring database from WAL")
wal.ReplayWAL(wl)
slog.Info("database restored from WAL")
}
}
if config.DiceConfig.Performance.EnableWatch {
bufSize := config.DiceConfig.Performance.WatchChanBufSize
cmdWatchChan = make(chan dstore.CmdWatchEvent, bufSize)
}
// Get the number of available CPU cores on the machine using runtime.NumCPU().
// This determines the total number of logical processors that can be utilized
// for parallel execution. Setting the maximum number of CPUs to the available
// core count ensures the application can make full use of all available hardware.
var numShards int
numShards = runtime.NumCPU()
if config.DiceConfig.Performance.NumShards > 0 {
numShards = config.DiceConfig.Performance.NumShards
}
// The runtime.GOMAXPROCS(numShards) call limits the number of operating system
// threads that can execute Go code simultaneously to the number of CPU cores.
// This enables Go to run more efficiently, maximizing CPU utilization and
// improving concurrency performance across multiple goroutines.
runtime.GOMAXPROCS(runtime.NumCPU())
// Initialize the ShardManager
shardManager := shard.NewShardManager(uint8(numShards), cmdWatchChan, serverErrCh)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
shardManager.Run(ctx)
}()
var serverWg sync.WaitGroup
if config.DiceConfig.Performance.EnableProfiling {
stopProfiling, err := startProfiling()
if err != nil {
slog.Error("Profiling could not be started", slog.Any("error", err))
sigs <- syscall.SIGKILL
}
defer stopProfiling()
}
ioThreadManager := iothread.NewManager(config.DiceConfig.Performance.MaxClients, shardManager)
respServer := resp.NewServer(shardManager, ioThreadManager, cmdWatchSubscriptionChan, cmdWatchChan, serverErrCh, wl)
serverWg.Add(1)
go runServer(ctx, &serverWg, respServer, serverErrCh)
if config.DiceConfig.HTTP.Enabled {
httpServer := httpws.NewHTTPServer(shardManager, wl)
serverWg.Add(1)
go runServer(ctx, &serverWg, httpServer, serverErrCh)
}
if config.DiceConfig.WebSocket.Enabled {
websocketServer := httpws.NewWebSocketServer(shardManager, config.DiceConfig.WebSocket.Port, wl)
serverWg.Add(1)
go runServer(ctx, &serverWg, websocketServer, serverErrCh)
}
wg.Add(1)
go func() {
defer wg.Done()
<-sigs
cancel()
}()
go func() {
serverWg.Wait()
close(serverErrCh) // Close the channel when both servers are done
}()
for err := range serverErrCh {
if err != nil && errors.Is(err, diceerrors.ErrAborted) {
// if either the AsyncServer/RESPServer or the HTTPServer received an abort command,
// cancel the context, helping gracefully exiting all servers
cancel()
}
}
close(sigs)
if config.DiceConfig.Persistence.Enabled {
wal.ShutdownBG()
}
cancel()
wg.Wait()
}
func runServer(ctx context.Context, wg *sync.WaitGroup, srv abstractserver.AbstractServer, errCh chan<- error) {
defer wg.Done()
if err := srv.Run(ctx); err != nil {
switch {
case errors.Is(err, context.Canceled):
slog.Debug(fmt.Sprintf("%T was canceled", srv))
case errors.Is(err, diceerrors.ErrAborted):
slog.Debug(fmt.Sprintf("%T received abort command", srv))
case errors.Is(err, http.ErrServerClosed):
slog.Debug(fmt.Sprintf("%T received abort command", srv))
default:
slog.Error(fmt.Sprintf("%T error", srv), slog.Any("error", err))
}
errCh <- err
} else {
slog.Debug("bye.")
}
}
func startProfiling() (func(), error) {
// Start CPU profiling
cpuFile, err := os.Create("cpu.prof")
if err != nil {
return nil, fmt.Errorf("could not create cpu.prof: %w", err)
}
if err = pprof.StartCPUProfile(cpuFile); err != nil {
cpuFile.Close()
return nil, fmt.Errorf("could not start CPU profile: %w", err)
}
// Start memory profiling
memFile, err := os.Create("mem.prof")
if err != nil {
pprof.StopCPUProfile()
cpuFile.Close()
return nil, fmt.Errorf("could not create mem.prof: %w", err)
}
// Start block profiling
runtime.SetBlockProfileRate(1)
// Start execution trace
traceFile, err := os.Create("trace.out")
if err != nil {
runtime.SetBlockProfileRate(0)
memFile.Close()
pprof.StopCPUProfile()
cpuFile.Close()
return nil, fmt.Errorf("could not create trace.out: %w", err)
}
if err := trace.Start(traceFile); err != nil {
traceFile.Close()
runtime.SetBlockProfileRate(0)
memFile.Close()
pprof.StopCPUProfile()
cpuFile.Close()
return nil, fmt.Errorf("could not start trace: %w", err)
}
// Return a cleanup function
return func() {
// Stop the CPU profiling and close cpuFile
pprof.StopCPUProfile()
cpuFile.Close()
// Write heap profile
runtime.GC()
if err := pprof.WriteHeapProfile(memFile); err != nil {
slog.Warn("could not write memory profile", slog.Any("error", err))
}
memFile.Close()
// Write block profile
blockFile, err := os.Create("block.prof")
if err != nil {
slog.Warn("could not create block profile", slog.Any("error", err))
} else {
if err := pprof.Lookup("block").WriteTo(blockFile, 0); err != nil {
slog.Warn("could not write block profile", slog.Any("error", err))
}
blockFile.Close()
}
runtime.SetBlockProfileRate(0)
// Stop trace and close traceFile
trace.Stop()
traceFile.Close()
}, nil
}