-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
203 lines (175 loc) · 4.84 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
// Copyright 2023 StreamNative, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bufio"
"fmt"
"log/slog"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/streamnative/oxia/common"
"github.com/streamnative/oxia/coordinator/impl"
"github.com/streamnative/oxia/coordinator/model"
"github.com/streamnative/oxia/server"
)
var (
logLevelStr string
rootCmd = &cobra.Command{
Use: "oxia-maelstrom",
Short: "Run oxia in Maelstrom mode",
Long: `Run oxia in Maelstrom mode`,
PersistentPreRunE: configureLogLevel,
}
)
type LogLevelError string
func (l LogLevelError) Error() string {
return fmt.Sprintf("unknown log level (%s)", string(l))
}
func init() {
rootCmd.PersistentFlags().StringVarP(&logLevelStr, "log-level", "l", common.DefaultLogLevel.String(), "Set logging level [debug|info|warn|error]")
rootCmd.PersistentFlags().BoolVarP(&common.LogJSON, "log-json", "j", false, "Print logs in JSON format")
}
func configureLogLevel(_ *cobra.Command, _ []string) error {
logLevel, err := common.ParseLogLevel(logLevelStr)
if err != nil {
return LogLevelError(logLevelStr)
}
common.LogLevel = logLevel
common.ConfigureLogger()
return nil
}
var thisNode string
var allNodes []string
func handleInit(scanner *bufio.Scanner) {
for {
if err := receiveInit(scanner); err != nil {
continue
}
return
}
}
func receiveInit(scanner *bufio.Scanner) error {
if !scanner.Scan() {
slog.Error("no init received")
os.Exit(1)
}
line := scanner.Text()
slog.Info(
"Got line",
slog.Any("line", []byte(line)),
)
reqType, req, _ := parseRequest(line)
if reqType != MsgTypeInit {
slog.Error(
"Unexpected request while waiting for init",
slog.Any("req", req),
)
return errors.New("invalid message type")
}
init := req.(*Message[Init])
thisNode = init.Body.NodeId
allNodes = init.Body.NodesIds
slog.Info(
"Received init request",
slog.String("this-node", thisNode),
slog.Any("all-nodes", allNodes),
)
sendResponse(Message[EmptyResponse]{
Src: thisNode,
Dest: init.Src,
Body: EmptyResponse{BaseMessageBody{
Type: "init_ok",
MsgId: msgIdGenerator.Add(1),
InReplyTo: &init.Body.MsgId,
}},
})
return nil
}
func main() {
common.ConfigureLogger()
// NOTE: we must change the default logger to use Stderr for output,
// because stdout is used as communication channel, see `sendErrorWithCode` for
// more details.
slog.SetDefault(slog.New(slog.NewJSONHandler(
os.Stderr,
&slog.HandlerOptions{},
)))
path, _ := os.Getwd()
slog.Info(
"Starting Oxia in Maelstrom mode",
slog.String("PWD", path),
)
scanner := bufio.NewScanner(os.Stdin)
handleInit(scanner)
// Start event loop to handle requests
grpcProvider := newMaelstromGrpcProvider()
replicationGrpcProvider := newMaelstromReplicationRpcProvider()
dispatcher := newDispatcher(grpcProvider, replicationGrpcProvider)
var servers []model.ServerAddress
for _, node := range allNodes {
if node != thisNode {
servers = append(servers, model.ServerAddress{
Public: node,
Internal: node,
})
}
}
dataDir, err := os.MkdirTemp("", "oxia-maelstrom")
if err != nil {
slog.Error(
"failed to create data dir",
slog.Any("error", err),
)
os.Exit(1)
}
if thisNode == "n1" {
// First node is going to be the "coordinator"
clusterConfig := model.ClusterConfig{
Namespaces: []model.NamespaceConfig{{
Name: common.DefaultNamespace,
ReplicationFactor: 3,
InitialShardCount: 1,
}},
Servers: servers,
}
_, err := impl.NewCoordinator(
impl.NewMetadataProviderFile(filepath.Join(dataDir, "cluster-status.json")),
func() (model.ClusterConfig, error) { return clusterConfig, nil }, nil,
newRpcProvider(dispatcher))
if err != nil {
slog.Error(
"failed to create coordinator",
slog.Any("error", err),
)
os.Exit(1)
}
} else {
// Any other node will be a storage node
_, err := server.NewWithGrpcProvider(server.Config{
MetricsServiceAddr: "",
DataDir: filepath.Join(dataDir, thisNode, "db"),
WalDir: filepath.Join(dataDir, thisNode, "wal"),
}, grpcProvider, replicationGrpcProvider)
if err != nil {
return
}
}
for scanner.Scan() {
line := scanner.Text()
rt, req, protoMsg := parseRequest(line)
dispatcher.ReceivedMessage(rt, req, protoMsg)
}
}