-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
202 lines (185 loc) · 6.32 KB
/
main.go
File metadata and controls
202 lines (185 loc) · 6.32 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// main.go is the entry point for the Hercules distributed system, launching either a MasterServer
// or a ChunkServer based on command-line flags. It sets up signal handling for graceful shutdown
// and initializes the server with configurable parameters for address, root directory, and logging.
//
// Usage:
//
// go run main.go [-isMaster] [-serverAddress <address>] [-masterAddr <address>] [-rootDir <directory>] [-logLevel <level>]
//
// Example:
//
// # Run as MasterServer
// go run main.go -isMaster -serverAddress 127.0.0.1:9090 -rootDir mroot
// # Run as ChunkServer
// go run main.go -serverAddress 127.0.0.1:8085 -masterAddr 127.0.0.1:9090 -rootDir croot
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"slices"
"strconv"
"syscall"
"time"
chunkserver "github.com/caleberi/distributed-system/chunkserver"
"github.com/caleberi/distributed-system/common"
failuredetector "github.com/caleberi/distributed-system/detector"
"github.com/caleberi/distributed-system/gateway"
"github.com/caleberi/distributed-system/hercules"
"github.com/caleberi/distributed-system/master_server"
masterserver "github.com/caleberi/distributed-system/master_server"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
ChunkServer string = "chunk_server"
MasterServer string = "master_server"
GatewayAddress string = "gateway_server"
)
type Config struct {
ServerType string
RootDir string
LogLevel string
ServerAddress common.ServerAddr
MasterAddress common.ServerAddr
RedisAddress common.ServerAddr
GatewayAddress int
}
func parseConfig() (Config, error) {
gatewayAddr, _ := strconv.Atoi(os.Getenv("GATEWAY_ADDR"))
serverType := flag.String("ServerType", "chunk_server", "run as a particular server (default: chunk_server, master_server, gateway_server)")
serverAddress := flag.String("serverAddr", os.Getenv("SERVER_ADDRESS"), "server address to listen on (host:port)")
masterAddress := flag.String("masterAddr", os.Getenv("MASTER_ADDR"), "master server address (host:port)")
redisAddress := flag.String("redisAddr", os.Getenv("REDIS_ADDR"), "redis server address (host:port)")
gatewayAddress := flag.Int("gatewayAddr", gatewayAddr, "gateway http server address (host:port)")
rootDir := flag.String("rootDir", "mroot", "root directory for file system storage")
logLevel := flag.String("logLevel", "debug", "logging level (debug, info, warn, error)")
flag.Parse()
absRootDir, err := filepath.Abs(*rootDir)
if err != nil {
return Config{}, fmt.Errorf("failed to resolve root directory %s: %w", *rootDir, err)
}
switch *logLevel {
case "debug", "info", "warn", "error":
default:
return Config{}, fmt.Errorf("invalid log level: %s; must be debug, info, warn, or error", *logLevel)
}
supportedServerType := []string{GatewayAddress, ChunkServer, MasterServer}
if !slices.Contains(supportedServerType, *serverType) {
return Config{}, fmt.Errorf("server type not supported")
}
return Config{
ServerType: *serverType,
ServerAddress: common.ServerAddr(*serverAddress),
MasterAddress: common.ServerAddr(*masterAddress),
GatewayAddress: *gatewayAddress,
RedisAddress: common.ServerAddr(*redisAddress),
RootDir: absRootDir,
LogLevel: *logLevel,
}, nil
}
func setupLogger(level string) error {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
switch level {
case "debug":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "info":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "warn":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "error":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
default:
return fmt.Errorf("unsupported log level: %s", level)
}
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
return nil
}
func main() {
cfg, err := parseConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse configuration: %v\n", err)
os.Exit(1)
}
if err := setupLogger(cfg.LogLevel); err != nil {
fmt.Fprintf(os.Stderr, "Failed to setup logger: %v\n", err)
os.Exit(1)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
switch cfg.ServerType {
case ChunkServer:
log.Info().Msgf("Starting ChunkServer on %s, connecting to master at %s, using root directory %s",
cfg.ServerAddress, cfg.MasterAddress, cfg.RootDir)
server, err := chunkserver.NewChunkServer(cfg.ServerAddress, cfg.MasterAddress, cfg.RedisAddress, cfg.RootDir)
if err != nil {
log.Error().Err(err).Msg("Failed to create ChunkServer")
os.Exit(1)
}
go func() {
<-quit
log.Info().Msg("Received shutdown signal, stopping ChunkServer...")
if err := server.Shutdown(); err != nil {
log.Err(err).Msg("Error shutting down ChunkServer")
}
cancel()
}()
<-ctx.Done()
case MasterServer:
log.Info().Msgf("Starting MasterServer on %s with root directory %s", cfg.ServerAddress, cfg.RootDir)
server := masterserver.NewMasterServer(ctx, master_server.MasterServerConfig{
ServerAddress: cfg.ServerAddress,
RootDir: cfg.RootDir,
RedisAddr: string(cfg.RedisAddress),
EntryExpiryTime: 10 * time.Millisecond,
WindowSize: 100,
SuspicionLevel: failuredetector.SuspicionLevel{
AccumulationThreshold: 3.0,
UpperBoundThreshold: 8.0,
},
})
go func() {
<-quit
log.Info().Msg("Received shutdown signal, stopping MasterServer...")
server.Shutdown()
cancel()
}()
<-ctx.Done()
default:
log.Info().Msgf("Starting GatewayServer on :%d", cfg.GatewayAddress)
client := hercules.NewHerculesClient(ctx, cfg.MasterAddress, 5*time.Minute)
server, err := gateway.NewHerculesHTTPGateway(
ctx, client,
gateway.GatewayConfig{
ServerName: "Gateway",
Address: cfg.GatewayAddress,
Logger: log.Logger,
TlsDir: "",
EnableTLS: false,
MaxHeaderBytes: 1 << 20,
IdleTimeout: 10 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
})
if err != nil {
log.Err(err).Msg("Error starting server")
os.Exit(1)
}
server.Start()
go func() {
<-quit
log.Info().Msg("Received shutdown signal, stopping Gateway Server...")
if err := server.Shutdown(); err != nil {
log.Err(err).Msg("Error shutting down Gateway Server")
}
cancel()
}()
<-ctx.Done()
}
log.Info().Msg("Server shutdown complete")
}