forked from rqlite/rqlite
/
main.go
307 lines (267 loc) · 8.32 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
rqlite -- a replicated SQLite database.
rqlite is a distributed system that provides a replicated SQLite database.
rqlite is written in Go and uses Raft to achieve consensus across all the
instances of the SQLite databases. rqlite ensures that every change made to
the database is made to a majority of underlying SQLite files, or none-at-all.
*/
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"runtime/pprof"
"time"
"github.com/rqlite/rqlite/auth"
"github.com/rqlite/rqlite/cluster"
httpd "github.com/rqlite/rqlite/http"
"github.com/rqlite/rqlite/store"
"github.com/rqlite/rqlite/tcp"
)
const sqliteDSN = "db.sqlite"
const logo = `
_ _ _ _
| (_) | | |
_ __ __ _| |_| |_ ___ __| |
| '__/ _ | | | __/ _ \/ _ |
| | | (_| | | | || __/ (_| |
|_| \__, |_|_|\__\___|\__,_|
| |
|_|
`
// These variables are populated via the Go linker.
var (
version = "3"
commit string
branch string
buildtime string
)
const (
muxRaftHeader = 1 // Raft consensus communications
muxMetaHeader = 2 // Cluster meta communications
)
const (
publishPeerDelay = 1 * time.Second
publishPeerTimeout = 30 * time.Second
)
var httpAddr string
var httpAdv string
var authFile string
var x509Cert string
var x509Key string
var raftAddr string
var raftAdv string
var joinAddr string
var noVerify bool
var expvar bool
var dsn string
var onDisk bool
var showVersion bool
var cpuprofile string
const desc = `rqlite is a distributed system that provides a replicated SQLite database.`
func init() {
flag.StringVar(&httpAddr, "http", "localhost:4001", "HTTP query server address. Set X.509 cert and key for HTTPS.")
flag.StringVar(&httpAdv, "httpadv", "", "HTTP redirection advertise address. If not set, same as query server.")
flag.StringVar(&x509Cert, "x509cert", "", "Path to X.509 certificate")
flag.StringVar(&x509Key, "x509key", "", "Path to X.509 private key for certificate")
flag.StringVar(&authFile, "auth", "", "Path to authentication and authorization file. If not set, not enabled.")
flag.StringVar(&raftAddr, "raft", "localhost:4002", "Raft communication bind address")
flag.StringVar(&raftAdv, "raftadv", "", "Raft advertise address. If not set, same as bind")
flag.StringVar(&joinAddr, "join", "", "protocol://host:port of leader to join")
flag.BoolVar(&noVerify, "noverify", false, "Skip verification of any HTTPS cert when joining")
flag.BoolVar(&expvar, "expvar", true, "Serve expvar data on HTTP server")
flag.StringVar(&dsn, "dsn", "", `SQLite DSN parameters. E.g. "cache=shared&mode=memory"`)
flag.BoolVar(&onDisk, "ondisk", false, "Use an on-disk SQLite database")
flag.BoolVar(&showVersion, "version", false, "Show version information and exit")
flag.StringVar(&cpuprofile, "cpuprofile", "", "Write CPU profile to file")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "\n%s\n\n", desc)
fmt.Fprintf(os.Stderr, "Usage: %s [arguments] <data directory>\n", os.Args[0])
flag.PrintDefaults()
}
// If commit, branch, or build time are not set, make that clear.
if commit == "" {
commit = "unknown"
}
if branch == "" {
branch = "unknown"
}
if buildtime == "" {
buildtime = "unknown"
}
}
func main() {
flag.Parse()
if showVersion {
fmt.Printf("rqlited version %s (commit %s)\n", version, commit)
os.Exit(0)
}
// Ensure the data path is set.
if flag.NArg() == 0 {
flag.Usage()
os.Exit(1)
}
dataPath := flag.Arg(0)
// Display logo.
fmt.Println(logo)
// Configure logging and pump out initial message.
log.SetFlags(log.LstdFlags)
log.SetPrefix("[rqlited] ")
log.Printf("rqlited starting, version %s, commit %s, branch %s", version, commit, branch)
// Set up profiling, if requested.
if cpuprofile != "" {
log.Println("profiling enabled")
f, err := os.Create(cpuprofile)
if err != nil {
log.Printf("unable to create path: %s", err.Error())
}
defer f.Close()
err = pprof.StartCPUProfile(f)
if err != nil {
log.Fatalf("unable to start CPU Profile: %s", err.Error())
}
defer pprof.StopCPUProfile()
}
// Set up TCP communication between nodes.
ln, err := net.Listen("tcp", raftAddr)
if err != nil {
log.Fatalf("failed to listen on %s: %s", raftAddr, err.Error())
}
var adv net.Addr
if raftAdv != "" {
adv, err = net.ResolveTCPAddr("tcp", raftAdv)
if err != nil {
log.Fatalf("failed to resolve advertise address %s: %s", raftAdv, err.Error())
}
}
mux := tcp.NewMux(ln, adv)
go mux.Serve()
// Start up mux and get transports for cluster.
raftTn := mux.Listen(muxRaftHeader)
// Create and open the store.
dataPath, err = filepath.Abs(dataPath)
if err != nil {
log.Fatalf("failed to determine absolute data path: %s", err.Error())
}
dbConf := store.NewDBConfig(dsn, !onDisk)
store := store.New(dbConf, dataPath, raftTn)
if err := store.Open(joinAddr == ""); err != nil {
log.Fatalf("failed to open store: %s", err.Error())
}
// Create and configure cluster service.
tn := mux.Listen(muxMetaHeader)
cs := cluster.NewService(tn, store)
if err := cs.Open(); err != nil {
log.Fatalf("failed to open cluster service: %s", err.Error())
}
// If join was specified, make the join request.
if joinAddr != "" {
if !store.JoinRequired() {
log.Println("node is already member of cluster, ignoring join request")
} else {
if err := join(joinAddr, noVerify, raftAddr, raftAdv); err != nil {
log.Fatalf("failed to join node at %s: %s", joinAddr, err.Error())
}
log.Println("successfully joined node at", joinAddr)
}
}
// Publish to the cluster the mapping between this Raft address and API address.
// The Raft layer broadcasts the resolved address, so use that as the key. But
// only set different HTTP advertise address if set.
apiAdv := httpAddr
if httpAdv != "" {
apiAdv = httpAdv
}
if err := publishAPIAddr(cs, raftTn.Addr().String(), apiAdv, publishPeerTimeout); err != nil {
log.Fatalf("failed to set peer for %s to %s: %s", raftAddr, httpAddr, err.Error())
}
log.Printf("set peer for %s to %s", raftTn.Addr().String(), apiAdv)
// Create HTTP server and load authentication information, if supplied.
var s *httpd.Service
if authFile != "" {
f, err := os.Open(authFile)
if err != nil {
log.Fatalf("failed to open authentication file %s: %s", authFile, err.Error())
}
credentialStore := auth.NewCredentialsStore()
if err := credentialStore.Load(f); err != nil {
log.Fatalf("failed to load authentication file: %s", err.Error())
}
s = httpd.New(httpAddr, store, credentialStore)
} else {
s = httpd.New(httpAddr, store, nil)
}
s.CertFile = x509Cert
s.KeyFile = x509Key
s.Expvar = expvar
s.BuildInfo = map[string]interface{}{
"commit": commit,
"branch": branch,
"version": version,
"build_time": buildtime,
}
if err := s.Start(); err != nil {
log.Fatalf("failed to start HTTP server: %s", err.Error())
}
terminate := make(chan os.Signal, 1)
signal.Notify(terminate, os.Interrupt)
<-terminate
if err := store.Close(true); err != nil {
log.Printf("failed to close store: %s", err.Error())
}
log.Println("rqlite server stopped")
}
func join(joinAddr string, skipVerify bool, raftAddr, raftAdv string) error {
addr := raftAddr
if raftAdv != "" {
addr = raftAdv
}
b, err := json.Marshal(map[string]string{"addr": addr})
if err != nil {
return err
}
// Check for protocol scheme, and insert default if necessary.
fullAddr := httpd.NormalizeAddr(fmt.Sprintf("%s/join", joinAddr))
// Enable skipVerify as requested.
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: skipVerify},
}
client := &http.Client{Transport: tr}
// Attempt to join.
resp, err := client.Post(fullAddr, "application-type/json", bytes.NewReader(b))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("failed to join, node returned: %s", resp.Status)
}
return nil
}
func publishAPIAddr(c *cluster.Service, raftAddr, apiAddr string, t time.Duration) error {
tck := time.NewTicker(publishPeerDelay)
defer tck.Stop()
tmr := time.NewTimer(t)
defer tmr.Stop()
for {
select {
case <-tck.C:
if err := c.SetPeer(raftAddr, apiAddr); err != nil {
log.Printf("failed to set peer for %s to %s: %s (retrying)",
raftAddr, apiAddr, err.Error())
continue
}
return nil
case <-tmr.C:
return fmt.Errorf("set peer timeout expired")
}
}
}