This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
/
daemon.go
342 lines (314 loc) · 9.52 KB
/
daemon.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package main
import (
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/NebulousLabs/Sia/api"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/modules/consensus"
"github.com/NebulousLabs/Sia/modules/explorer"
"github.com/NebulousLabs/Sia/modules/gateway"
"github.com/NebulousLabs/Sia/modules/host"
"github.com/NebulousLabs/Sia/modules/miner"
"github.com/NebulousLabs/Sia/modules/renter"
"github.com/NebulousLabs/Sia/modules/transactionpool"
"github.com/NebulousLabs/Sia/modules/wallet"
"github.com/NebulousLabs/Sia/profile"
"github.com/bgentry/speakeasy"
"github.com/spf13/cobra"
)
// verifyAPISecurity checks that the security values are consistent with a
// sane, secure system.
func verifyAPISecurity(config Config) error {
// Make sure that only the loopback address is allowed unless the
// --disable-api-security flag has been used.
if !config.Siad.AllowAPIBind {
addr := modules.NetAddress(config.Siad.APIaddr)
if !addr.IsLoopback() {
if addr.Host() == "" {
return fmt.Errorf("a blank host will listen on all interfaces, did you mean localhost:%v?\nyou must pass --disable-api-security to bind Siad to a non-localhost address", addr.Port())
}
return errors.New("you must pass --disable-api-security to bind Siad to a non-localhost address")
}
return nil
}
// If the --disable-api-security flag is used, enforce that
// --authenticate-api must also be used.
if config.Siad.AllowAPIBind && !config.Siad.AuthenticateAPI {
return errors.New("cannot use --disable-api-security without setting an api password")
}
return nil
}
// processNetAddr adds a ':' to a bare integer, so that it is a proper port
// number.
func processNetAddr(addr string) string {
_, err := strconv.Atoi(addr)
if err == nil {
return ":" + addr
}
return addr
}
// processModules makes the modules string lowercase to make checking if a
// module in the string easier, and returns an error if the string contains an
// invalid module character.
func processModules(modules string) (string, error) {
modules = strings.ToLower(modules)
validModules := "cghmrtwe"
invalidModules := modules
for _, m := range validModules {
invalidModules = strings.Replace(invalidModules, string(m), "", 1)
}
if len(invalidModules) > 0 {
return "", errors.New("Unable to parse --modules flag, unrecognized or duplicate modules: " + invalidModules)
}
return modules, nil
}
// processProfileFlags checks that the flags given for profiling are valid.
func processProfileFlags(profile string) (string, error) {
profile = strings.ToLower(profile)
validProfiles := "cmt"
invalidProfiles := profile
for _, p := range validProfiles {
invalidProfiles = strings.Replace(invalidProfiles, string(p), "", 1)
}
if len(invalidProfiles) > 0 {
return "", errors.New("Unable to parse --profile flags, unrecognized or duplicate flags: " + invalidProfiles)
}
return profile, nil
}
// processConfig checks the configuration values and performs cleanup on
// incorrect-but-allowed values.
func processConfig(config Config) (Config, error) {
var err1, err2 error
config.Siad.APIaddr = processNetAddr(config.Siad.APIaddr)
config.Siad.RPCaddr = processNetAddr(config.Siad.RPCaddr)
config.Siad.HostAddr = processNetAddr(config.Siad.HostAddr)
config.Siad.Modules, err1 = processModules(config.Siad.Modules)
config.Siad.Profile, err2 = processProfileFlags(config.Siad.Profile)
err3 := verifyAPISecurity(config)
err := build.JoinErrors([]error{err1, err2, err3}, ", and ")
if err != nil {
return Config{}, err
}
return config, nil
}
// startDaemon uses the config parameters to initialize Sia modules and start
// siad.
func startDaemon(config Config) (err error) {
// Prompt user for API password.
if config.Siad.AuthenticateAPI {
config.APIPassword, err = speakeasy.Ask("Enter API password: ")
if err != nil {
return err
}
if config.APIPassword == "" {
return errors.New("password cannot be blank")
}
}
// Process the config variables after they are parsed by cobra.
config, err = processConfig(config)
if err != nil {
return err
}
// Print a startup message.
fmt.Println("Loading...")
loadStart := time.Now()
// Create the server and start serving daemon routes immediately.
fmt.Printf("(0/%d) Loading siad...\n", len(config.Siad.Modules))
srv, err := NewServer(config.Siad.APIaddr, config.Siad.RequiredUserAgent, config.APIPassword)
if err != nil {
return err
}
servErrs := make(chan error)
go func() {
servErrs <- srv.Serve()
}()
// Initialize the Sia modules
i := 0
var g modules.Gateway
if strings.Contains(config.Siad.Modules, "g") {
i++
fmt.Printf("(%d/%d) Loading gateway...\n", i, len(config.Siad.Modules))
g, err = gateway.New(config.Siad.RPCaddr, !config.Siad.NoBootstrap, filepath.Join(config.Siad.SiaDir, modules.GatewayDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing gateway...")
err := g.Close()
if err != nil {
fmt.Println("Error during gateway shutdown:", err)
}
}()
}
var cs modules.ConsensusSet
if strings.Contains(config.Siad.Modules, "c") {
i++
fmt.Printf("(%d/%d) Loading consensus...\n", i, len(config.Siad.Modules))
cs, err = consensus.New(g, !config.Siad.NoBootstrap, filepath.Join(config.Siad.SiaDir, modules.ConsensusDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing consensus...")
err := cs.Close()
if err != nil {
fmt.Println("Error during consensus set shutdown:", err)
}
}()
}
var e modules.Explorer
if strings.Contains(config.Siad.Modules, "e") {
i++
fmt.Printf("(%d/%d) Loading explorer...\n", i, len(config.Siad.Modules))
e, err = explorer.New(cs, filepath.Join(config.Siad.SiaDir, modules.ExplorerDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing explorer...")
err := e.Close()
if err != nil {
fmt.Println("Error during explorer shutdown:", err)
}
}()
}
var tpool modules.TransactionPool
if strings.Contains(config.Siad.Modules, "t") {
i++
fmt.Printf("(%d/%d) Loading transaction pool...\n", i, len(config.Siad.Modules))
tpool, err = transactionpool.New(cs, g, filepath.Join(config.Siad.SiaDir, modules.TransactionPoolDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing transaction pool...")
err := tpool.Close()
if err != nil {
fmt.Println("Error during transaction pool shutdown:", err)
}
}()
}
var w modules.Wallet
if strings.Contains(config.Siad.Modules, "w") {
i++
fmt.Printf("(%d/%d) Loading wallet...\n", i, len(config.Siad.Modules))
w, err = wallet.New(cs, tpool, filepath.Join(config.Siad.SiaDir, modules.WalletDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing wallet...")
err := w.Close()
if err != nil {
fmt.Println("Error during wallet shutdown:", err)
}
}()
}
var m modules.Miner
if strings.Contains(config.Siad.Modules, "m") {
i++
fmt.Printf("(%d/%d) Loading miner...\n", i, len(config.Siad.Modules))
m, err = miner.New(cs, tpool, w, filepath.Join(config.Siad.SiaDir, modules.MinerDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing miner...")
err := m.Close()
if err != nil {
fmt.Println("Error during miner shutdown:", err)
}
}()
}
var h modules.Host
if strings.Contains(config.Siad.Modules, "h") {
i++
fmt.Printf("(%d/%d) Loading host...\n", i, len(config.Siad.Modules))
h, err = host.New(cs, tpool, w, config.Siad.HostAddr, filepath.Join(config.Siad.SiaDir, modules.HostDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing host...")
err := h.Close()
if err != nil {
fmt.Println("Error during host shutdown:", err)
}
}()
}
var r modules.Renter
if strings.Contains(config.Siad.Modules, "r") {
i++
fmt.Printf("(%d/%d) Loading renter...\n", i, len(config.Siad.Modules))
r, err = renter.New(g, cs, w, tpool, filepath.Join(config.Siad.SiaDir, modules.RenterDir))
if err != nil {
return err
}
defer func() {
fmt.Println("Closing renter...")
err := r.Close()
if err != nil {
fmt.Println("Error during renter shutdown:", err)
}
}()
}
// Create the Sia API
a := api.New(
config.Siad.RequiredUserAgent,
config.APIPassword,
cs,
e,
g,
h,
m,
r,
tpool,
w,
)
// connect the API to the server
srv.mux.Handle("/", a)
// stop the server if a kill signal is caught
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, os.Kill)
go func() {
<-sigChan
fmt.Println("\rCaught stop signal, quitting...")
srv.Close()
}()
// Print a 'startup complete' message.
startupTime := time.Since(loadStart)
fmt.Println("Finished loading in", startupTime.Seconds(), "seconds")
err = <-servErrs
if err != nil {
build.Critical(err)
}
return nil
}
// startDaemonCmd is a passthrough function for startDaemon.
func startDaemonCmd(cmd *cobra.Command, _ []string) {
var profileCPU, profileMem, profileTrace bool
profileCPU = strings.Contains(globalConfig.Siad.Profile, "c")
profileMem = strings.Contains(globalConfig.Siad.Profile, "m")
profileTrace = strings.Contains(globalConfig.Siad.Profile, "t")
if build.DEBUG {
profileCPU = true
profileMem = true
}
if profileCPU || profileMem || profileTrace {
go profile.StartContinuousProfile(globalConfig.Siad.ProfileDir, profileCPU, profileMem, profileTrace)
}
// Start siad. startDaemon will only return when it is shutting down.
err := startDaemon(globalConfig)
if err != nil {
die(err)
}
// Daemon seems to have closed cleanly. Print a 'closed' mesasge.
fmt.Println("Shutdown complete.")
}