forked from mendersoftware/mender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
556 lines (456 loc) · 14 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// Copyright 2018 Northern.tech AS
//
// 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"
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/mendersoftware/log"
"github.com/mendersoftware/mender/client"
"github.com/mendersoftware/mender/store"
"github.com/pkg/errors"
)
type logOptionsType struct {
debug *bool
info *bool
logLevel *string
logModules *string
logFile *string
noSyslog *bool
}
type runOptionsType struct {
version *bool
config *string
fallbackConfig *string
dataStore *string
imageFile *string
runStateScripts *bool
commit *bool
bootstrap *bool
daemon *bool
bootstrapForce *bool
showArtifact *bool
updateCheck *bool
client.Config
}
var (
errMsgNoArgumentsGiven = errors.New("Must give one of -rootfs, " +
"-commit, -bootstrap or -daemon arguments")
errMsgAmbiguousArgumentsGiven = errors.New("Ambiguous parameters given " +
"- must give exactly one from: -rootfs, -commit, -bootstrap, -authorize or -daemon")
errMsgIncompatibleLogOptions = errors.New("One or more " +
"incompatible log log options specified.")
)
var defaultConfFile string = path.Join(getConfDirPath(), "mender.conf")
var defaultFallbackConfFile string = path.Join(getStateDirPath(), "mender.conf")
var DeploymentLogger *DeploymentLogManager
type Commander interface {
Command(name string, arg ...string) *exec.Cmd
}
type StatCommander interface {
Stat(string) (os.FileInfo, error)
Commander
}
// we need real OS implementation
type osCalls struct {
}
func (osCalls) Command(name string, arg ...string) *exec.Cmd {
return exec.Command(name, arg...)
}
func (osCalls) Stat(name string) (os.FileInfo, error) {
return os.Stat(name)
}
func argsParse(args []string) (runOptionsType, error) {
parsing := flag.NewFlagSet("mender", flag.ContinueOnError)
// FLAGS ---------------------------------------------------------------
version := parsing.Bool("version", false, "Show mender agent version and exit.")
config := parsing.String("config", defaultConfFile,
"Configuration file location.")
fallbackConfig := parsing.String("fallback-config", defaultFallbackConfFile,
"Fallback configuration file location.")
data := parsing.String("data", defaultDataStore,
"Mender state data location.")
commit := parsing.Bool("commit", false,
"Commit current update. Returns (2) if no update in progress")
bootstrap := parsing.Bool("bootstrap", false, "Perform bootstrap and exit.")
showArtifact := parsing.Bool("show-artifact", false, "print the current artifact name to the command line and exit")
imageFile := parsing.String("rootfs", "",
"Root filesystem URI to use for update. Can be either a local "+
"file or a URL.")
forceStateScripts := parsing.Bool("f", false, "force installation of artifacts with state-scripts")
daemon := parsing.Bool("daemon", false, "Run as a daemon.")
updateCheck := parsing.Bool("check-update", false, "force update check")
// add bootstrap related command line options
serverCert := parsing.String("trusted-certs", "", "Trusted server certificates")
forcebootstrap := parsing.Bool("forcebootstrap", false, "Force bootstrap")
skipVerify := parsing.Bool("skipverify", false, "Skip certificate verification")
// add log related command line options
logFlags := addLogFlags(parsing)
// PARSING -------------------------------------------------------------
if err := parsing.Parse(args); err != nil {
return runOptionsType{}, err
}
runOptions := runOptionsType{
version: version,
config: config,
fallbackConfig: fallbackConfig,
dataStore: data,
imageFile: imageFile,
runStateScripts: forceStateScripts,
commit: commit,
bootstrap: bootstrap,
daemon: daemon,
bootstrapForce: forcebootstrap,
showArtifact: showArtifact,
updateCheck: updateCheck,
Config: client.Config{
ServerCert: *serverCert,
NoVerify: *skipVerify,
},
}
//runOptions.bootstrap = httpsClientConfig{}
// FLAG LOGIC ----------------------------------------------------------
// we just want to see the version string or check for an update, the rest does not
// matter
if *version == true {
return runOptions, nil
}
if *updateCheck == true {
return runOptions, nil
}
if err := parseLogFlags(logFlags); err != nil {
return runOptions, err
}
if moreThanOneRunOptionSelected(runOptions) {
return runOptions, errMsgAmbiguousArgumentsGiven
}
return runOptions, nil
}
func moreThanOneRunOptionSelected(runOptions runOptionsType) bool {
// check if more than one command line action is selected
var runOptionsCount int
if *runOptions.imageFile != "" {
runOptionsCount++
}
if *runOptions.commit {
runOptionsCount++
}
if *runOptions.daemon {
runOptionsCount++
}
if runOptionsCount > 1 {
return true
}
return false
}
func addLogFlags(f *flag.FlagSet) logOptionsType {
var logOptions logOptionsType
logOptions.debug = f.Bool("debug", false, "Debug log level. This is a "+
"shorthand for '-l debug'.")
logOptions.info = f.Bool("info", false, "Info log level. This is a "+
"shorthand for '-l info'.")
logOptions.logLevel = f.String("log-level", "", "Log level, which can be "+
"'debug', 'info', 'warning', 'error', 'fatal' or 'panic'. "+
"Earlier log levels will also log the subsequent levels (so "+
"'debug' will log everything). The default log level is "+
"'info'.")
logOptions.logModules = f.String("log-modules", "", "Filter logging by "+
"module. This is a comma separated list of modules to log, "+
"other modules will be omitted. To see which modules are "+
"available, take a look at a non-filtered log and select "+
"the modules appropriate for you.")
logOptions.noSyslog = f.Bool("no-syslog", false, "Disable logging to "+
"syslog. Note that debug message are never logged to syslog.")
logOptions.logFile = f.String("log-file", "", "File to log to.")
return logOptions
}
func parseLogFlags(args logOptionsType) error {
var logOptCount int
if *args.logLevel != "" {
level, err := log.ParseLevel(*args.logLevel)
if err != nil {
return err
}
log.SetLevel(level)
logOptCount++
}
if *args.info {
log.SetLevel(log.InfoLevel)
logOptCount++
}
if *args.debug {
log.SetLevel(log.DebugLevel)
logOptCount++
}
if logOptCount > 1 {
return errMsgIncompatibleLogOptions
} else if logOptCount == 0 {
// set info as a default log level
log.SetLevel(log.InfoLevel)
}
if *args.logFile != "" {
fd, err := os.Create(*args.logFile)
if err != nil {
return err
}
log.SetOutput(fd)
}
if *args.logModules != "" {
modules := strings.Split(*args.logModules, ",")
log.SetModuleFilter(modules)
}
if !*args.noSyslog {
if err := log.AddSyslogHook(); err != nil {
log.Warnf("Could not connect to syslog daemon: %s. "+
"(use -no-syslog to disable completely)",
err.Error())
}
}
return nil
}
func ShowVersion() {
v := fmt.Sprintf("%s\nruntime: %s\n", VersionString(), runtime.Version())
os.Stdout.Write([]byte(v))
}
func PrintArtifactName(fpath string) error {
afile, err := ioutil.ReadFile(fpath)
if err != nil {
return fmt.Errorf("failed to read artifact name: err: %v", err)
}
s := bufio.NewScanner(bytes.NewBuffer(afile))
var aname string
acnt := 0
for s.Scan() {
if strings.HasPrefix(s.Text(), "artifact_name=") {
a := strings.Split(s.Text(), "=")
if len(a) == 2 {
aname = a[1]
acnt++
} else {
return errors.New("Wrong formatting of the artifact_info file")
}
}
}
if acnt > 1 {
return errors.New("there seems to be two instances of artifact_name in the artifact info file (located at /etc/mender/artifact_info). Please remove the duplicate(s)")
}
if aname == "" {
return errors.New("the artifact_name is empty. Please set a valid name for the artifact")
}
fmt.Println(aname)
return nil
}
func doBootstrapAuthorize(config *menderConfig, opts *runOptionsType) error {
mp, err := commonInit(config, opts)
if err != nil {
return err
}
// need to close DB store manually, since we're not running under a
// daemonized version
defer mp.store.Close()
controller, err := NewMender(*config, *mp)
if err != nil {
return errors.Wrap(err, "error initializing mender controller")
}
if *opts.bootstrapForce {
controller.ForceBootstrap()
}
if merr := controller.Bootstrap(); merr != nil {
return merr.Cause()
}
if merr := controller.Authorize(); merr != nil {
return merr.Cause()
}
return nil
}
func getKeyStore(datastore string, keyName string) *store.Keystore {
dirstore := store.NewDirStore(datastore)
return store.NewKeystore(dirstore, keyName)
}
func commonInit(config *menderConfig, opts *runOptionsType) (*MenderPieces, error) {
tentok := config.GetTenantToken()
ks := getKeyStore(*opts.dataStore, defaultKeyFile)
if ks == nil {
return nil, errors.New("failed to setup key storage")
}
dbstore := store.NewDBStore(*opts.dataStore)
if dbstore == nil {
return nil, errors.New("failed to initialize DB store")
}
authmgr := NewAuthManager(AuthManagerConfig{
AuthDataStore: dbstore,
KeyStore: ks,
IdentitySource: NewIdentityDataGetter(),
TenantToken: tentok,
})
if authmgr == nil {
// close DB store explicitly
dbstore.Close()
return nil, errors.New("error initializing authentication manager")
}
mp := MenderPieces{
store: dbstore,
authMgr: authmgr,
}
return &mp, nil
}
func initDaemon(config *menderConfig, dev *device, env BootEnvReadWriter,
opts *runOptionsType) (*menderDaemon, error) {
mp, err := commonInit(config, opts)
if err != nil {
return nil, err
}
mp.device = dev
controller, err := NewMender(*config, *mp)
if controller == nil {
mp.store.Close()
return nil, errors.Wrap(err, "error initializing mender controller")
}
if *opts.bootstrapForce {
controller.ForceBootstrap()
}
daemon := NewDaemon(controller, mp.store)
// add logging hook; only daemon needs this
log.AddHook(NewDeploymentLogHook(DeploymentLogger))
return daemon, nil
}
func doMain(args []string) error {
runOptions, err := argsParse(args)
if err != nil {
return err
}
// Do not run anything else if update-check is triggered.
if *runOptions.updateCheck {
return updateCheck(exec.Command("kill", "-USR1"), exec.Command("systemctl", "show", "-p", "MainPID", "mender"))
}
config, err := loadConfig(*runOptions.config, *runOptions.fallbackConfig)
if err != nil {
return err
}
if runOptions.Config.NoVerify {
config.HttpsClient.SkipVerify = true
}
env := NewEnvironment(new(osCalls))
device := NewDevice(env, new(osCalls), config.GetDeviceConfig())
ap, err := device.GetActive()
if err != nil {
log.Errorf("Failed to read the current active partition: %s", err.Error())
} else {
log.Infof("Mender running on partition: %s", ap)
}
DeploymentLogger = NewDeploymentLogManager(*runOptions.dataStore)
return handleCLIOptions(runOptions, env, device, config)
}
func handleCLIOptions(runOptions runOptionsType, env *uBootEnv, device *device, config *menderConfig) error {
switch {
case *runOptions.version:
ShowVersion()
return nil
case *runOptions.showArtifact:
return PrintArtifactName(filepath.Join(getConfDirPath(), "artifact_info"))
case *runOptions.imageFile != "":
dt, err := GetDeviceType(defaultDeviceTypeFile)
if err != nil {
log.Errorf("Unable to verify the existing hardware. Update will continue anyways: %v : %v", defaultDeviceTypeFile, err)
}
vKey := config.GetVerificationKey()
return doRootfs(device, runOptions, dt, vKey)
case *runOptions.commit:
return device.CommitUpdate()
case *runOptions.bootstrap:
return doBootstrapAuthorize(config, &runOptions)
case *runOptions.daemon:
d, err := initDaemon(config, device, env, &runOptions)
if err != nil {
return err
}
defer d.Cleanup()
return runDaemon(d)
case *runOptions.imageFile == "" && !*runOptions.commit &&
!*runOptions.daemon && !*runOptions.bootstrap:
return errMsgNoArgumentsGiven
}
return nil
}
func getMenderDaemonPID(cmd *exec.Cmd) (string, error) {
buf := bytes.NewBuffer(nil)
cmd.Stdout = buf
err := cmd.Run()
if err != nil {
return "", errors.New("getMenderDaemonPID: Failed to run systemctl")
}
if buf.Len() == 0 {
return "", errors.New("could not find the PID of the mender daemon")
}
return strings.Trim(buf.String(), "MainPID=\n"), nil
}
// updateCheck sends a SIGUSR1 signal to the running mender daemon.
func updateCheck(cmdKill, cmdGetPID *exec.Cmd) error {
pid, err := getMenderDaemonPID(cmdGetPID)
if err != nil {
return errors.Wrap(err, "failed to force updateCheck: ")
}
cmdKill.Args = append(cmdKill.Args, pid)
err = cmdKill.Run()
if err != nil {
return fmt.Errorf("updateCheck: Failed to kill the mender process, pid: %s", pid)
}
return nil
}
func runDaemon(d *menderDaemon) error {
// Handle user forcing update check.
go func() {
for {
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGUSR1) // Relay the usr1-signal into our channel.
defer signal.Stop(c)
s := <-c // Block until a signal is recieved.
if s == syscall.SIGUSR1 {
log.Debug("SIGUSR1 signal received.")
d.updateCheck <- true
// If the state machine is in a wait state - force a wake-up.
ws, ok := d.mender.GetCurrentState().(WaitState)
if ok {
ws.Wake()
}
}
}
}()
return d.Run()
}
func main() {
if err := doMain(os.Args[1:]); err != nil {
var returnCode int
if err == errorNoUpgradeMounted {
log.Warnln(err.Error())
returnCode = 2
} else {
if err != flag.ErrHelp {
log.Errorln(err.Error())
}
returnCode = 1
}
os.Exit(returnCode)
}
}