forked from skycoin/skywire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
root.go
326 lines (281 loc) · 8.37 KB
/
root.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
package commands
import (
"context"
"embed"
"fmt"
"io"
"io/fs"
"io/ioutil"
"net/http"
_ "net/http/pprof" // nolint:gosec // https://golang.org/doc/diagnostics.html#profiling
"os"
"os/exec"
"runtime"
"strings"
"sync"
"syscall"
"time"
"github.com/pkg/profile"
"github.com/skycoin/dmsg/buildinfo"
"github.com/skycoin/dmsg/cmdutil"
"github.com/skycoin/skycoin/src/util/logging"
"github.com/spf13/cobra"
"github.com/toqueteos/webbrowser"
"github.com/skycoin/skywire/pkg/restart"
"github.com/skycoin/skywire/pkg/syslog"
"github.com/skycoin/skywire/pkg/visor"
"github.com/skycoin/skywire/pkg/visor/logstore"
"github.com/skycoin/skywire/pkg/visor/visorconfig"
)
var uiAssets fs.FS
var restartCtx = restart.CaptureContext()
const (
defaultConfigName = "skywire-config.json"
runtimeLogMaxEntries = 300
)
var (
tag string
syslogAddr string
pprofMode string
pprofAddr string
confPath string
delay string
launchBrowser bool
stopVisorFn func() // nolint:unused
stopVisorWg sync.WaitGroup
)
var rootCmd = &cobra.Command{
Use: "skywire-visor",
Short: "Skywire visor",
Run: func(_ *cobra.Command, args []string) {
runApp(args...)
},
Version: buildinfo.Version(),
}
func init() {
rootCmd.Flags().StringVar(&tag, "tag", "skywire", "logging tag")
rootCmd.Flags().StringVar(&syslogAddr, "syslog", "", "syslog server address. E.g. localhost:514")
rootCmd.Flags().StringVarP(&pprofMode, "pprofmode", "p", "", "pprof profiling mode. Valid values: cpu, mem, mutex, block, trace, http")
rootCmd.Flags().StringVar(&pprofAddr, "pprofaddr", "localhost:6060", "pprof http port if mode is 'http'")
rootCmd.Flags().StringVarP(&confPath, "config", "c", "", "config file location. If the value is 'STDIN', config file will be read from stdin.")
rootCmd.Flags().StringVar(&delay, "delay", "0ns", "start delay (deprecated)") // deprecated
rootCmd.Flags().BoolVar(&launchBrowser, "launch-browser", false, "open hypervisor web ui (hypervisor only) with system browser")
extraFlags()
}
func runVisor(args []string) {
log := initLogger(tag, syslogAddr)
store, hook := logstore.MakeStore(runtimeLogMaxEntries)
log.AddHook(hook)
delayDuration, err := time.ParseDuration(delay)
if err != nil {
log.WithError(err).Error("Failed to parse delay duration.")
delayDuration = time.Duration(0)
}
log.WithField("delay", delayDuration).
WithField("systemd", restartCtx.Systemd()).
WithField("parent_systemd", restartCtx.ParentSystemd()).
WithField("skybian_build_version", os.Getenv("SKYBIAN_BUILD_VERSION")).
Debugf("Process info")
// Versions v0.2.3 and below return 0 exit-code after update and do not trigger systemd to restart a process
// and therefore do not support restart via systemd.
// If --delay flag is passed, version is v0.2.3 or below.
// Systemd has PID 1. If PPID is not 1 and PPID of parent process is 1, then
// this process is a child process that is run after updating by a skywire-visor that is run by systemd.
if delayDuration != 0 && !restartCtx.Systemd() && restartCtx.ParentSystemd() {
// As skywire-visor checks if new process is run successfully in `restart.DefaultCheckDelay` after update,
// new process should be alive after `restart.DefaultCheckDelay`.
time.Sleep(restart.DefaultCheckDelay)
// When a parent process exits, systemd kills child processes as well,
// so a child process can ask systemd to restart service between after restart.DefaultCheckDelay
// but before (restart.DefaultCheckDelay + restart.extraWaitingTime),
// because after that time a parent process would exit and then systemd would kill its children.
// In this case, systemd would kill both parent and child processes,
// then restart service using an updated binary.
cmd := exec.Command("systemctl", "restart", "skywire-visor") // nolint:gosec
if err := cmd.Run(); err != nil {
log.WithError(err).Errorf("Failed to restart skywire-visor service")
} else {
log.WithError(err).Infof("Restarted skywire-visor service")
}
// Detach child from parent.
if _, err := syscall.Setsid(); err != nil {
log.WithError(err).Errorf("Failed to call setsid()")
}
}
time.Sleep(delayDuration)
if _, err := buildinfo.Get().WriteTo(log.Out); err != nil {
log.WithError(err).Error("Failed to output build info.")
}
stopPProf := initPProf(log, tag, pprofMode, pprofAddr)
defer stopPProf()
conf := initConfig(log, args, confPath)
v, ok := visor.NewVisor(conf, restartCtx)
if !ok {
log.Errorln("Failed to start visor.")
quitSystray()
return
}
v.SetLogstore(store)
if launchBrowser {
runBrowser(conf, log)
}
ctx, cancel := cmdutil.SignalContext(context.Background(), log)
setStopFunction(log, cancel, v.Close)
defer cancel()
// Wait.
<-ctx.Done()
if err = v.Close(); err != nil {
log.Error("Error closing visor: ", err)
}
}
// Execute executes root CLI command.
func Execute(ui embed.FS) {
uiFS, err := fs.Sub(ui, "static")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
uiAssets = uiFS
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
}
}
func initLogger(tag string, syslogAddr string) *logging.MasterLogger {
log := logging.NewMasterLogger()
if syslogAddr != "" {
hook, err := syslog.SetupHook(syslogAddr, tag)
if err != nil {
log.WithError(err).Error("Failed to connect to the syslog daemon.")
} else {
log.AddHook(hook)
log.Out = ioutil.Discard
}
}
return log
}
func initPProf(log *logging.MasterLogger, tag string, profMode string, profAddr string) (stop func()) {
var optFunc func(*profile.Profile)
switch profMode {
case "none", "":
case "http":
go func() {
err := http.ListenAndServe(profAddr, nil)
log.WithError(err).
WithField("mode", profMode).
WithField("addr", profAddr).
Info("Stopped serving pprof on http.")
}()
case "cpu":
optFunc = profile.CPUProfile
case "mem":
optFunc = profile.MemProfile
case "mutex":
optFunc = profile.MutexProfile
case "block":
optFunc = profile.BlockProfile
case "trace":
optFunc = profile.TraceProfile
}
if optFunc != nil {
stop = profile.Start(profile.ProfilePath("./logs/"+tag), optFunc).Stop
}
if stop == nil {
stop = func() {}
}
return stop
}
func initConfig(mLog *logging.MasterLogger, args []string, confPath string) *visorconfig.V1 {
log := mLog.PackageLogger("visor:config")
var r io.Reader
switch confPath {
case visorconfig.StdinName:
log.Info("Reading config from STDIN.")
r = os.Stdin
case "":
// TODO: More robust solution.
for _, arg := range args {
if strings.HasSuffix(arg, ".json") {
confPath = arg
break
}
}
if confPath == "" {
if runtime.GOOS == "darwin" {
confPath = os.Getenv("HOME") + "/Skywire/" + defaultConfigName
} else {
confPath = "/opt/skywire/" + defaultConfigName
}
}
fallthrough
default:
log.WithField("filepath", confPath).Info("Reading config from file.")
f, err := os.Open(confPath) //nolint:gosec
if err != nil {
log.WithError(err).
WithField("filepath", confPath).
Fatal("Failed to read config file.")
}
defer func() {
if err := f.Close(); err != nil {
log.WithError(err).Error("Closing config file resulted in error.")
}
}()
r = f
}
raw, err := ioutil.ReadAll(r)
if err != nil {
log.WithError(err).Fatal("Failed to read in config.")
}
conf, err := visorconfig.Parse(mLog, confPath, raw)
if err != nil {
log.WithError(err).Fatal("Failed to parse config.")
}
if conf.Hypervisor != nil {
conf.Hypervisor.UIAssets = uiAssets
}
return conf
}
func runBrowser(conf *visorconfig.V1, log *logging.MasterLogger) {
if conf.Hypervisor == nil {
log.Errorln("Cannot start browser with a regular visor")
return
}
addr := conf.Hypervisor.HTTPAddr
if addr[0] == ':' {
addr = "localhost" + addr
}
if addr[:4] != "http" {
if conf.Hypervisor.EnableTLS {
addr = "https://" + addr
} else {
addr = "http://" + addr
}
}
go func() {
if !checkHvIsRunning(addr, 5) {
log.Error("Cannot open hypervisor in browser: status check failed")
return
}
if err := webbrowser.Open(addr); err != nil {
log.WithError(err).Error("webbrowser.Open failed")
}
}()
}
func checkHvIsRunning(addr string, retries int) bool {
url := addr + "/api/ping"
for i := 0; i < retries; i++ {
time.Sleep(500 * time.Millisecond)
resp, err := http.Get(url) // nolint: gosec
if err != nil {
continue
}
err = resp.Body.Close()
if err != nil {
continue
}
if resp.StatusCode < 400 {
return true
}
}
return false
}