forked from mendersoftware/mender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
594 lines (486 loc) · 15.5 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// Copyright 2019 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 (
"bytes"
"flag"
"fmt"
"os"
"os/exec"
"os/signal"
"runtime"
"strings"
"syscall"
"github.com/mendersoftware/log"
"github.com/mendersoftware/mender/client"
"github.com/mendersoftware/mender/installer"
"github.com/mendersoftware/mender/store"
"github.com/mendersoftware/mender/system"
"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
commit *bool
rollback *bool
bootstrap *bool
daemon *bool
bootstrapForce *bool
showArtifact *bool
updateCheck *bool
updateInventory *bool
client.Config
}
var (
actionArguments = "-install, -commit, -rollback, -daemon, -bootstrap, -version -check-update," +
"-send-inventory or -show-artifact"
errMsgNoArgumentsGiven = errors.Errorf("Must give one of %s arguments", actionArguments)
errMsgAmbiguousArgumentsGiven = errors.Errorf("Ambiguous parameters given "+
"- must give exactly one from: %s", actionArguments)
errMsgIncompatibleLogOptions = errors.New("One or more " +
"incompatible log options specified.")
errMissingServerCertstr = "IGNORING ERROR: The client server-certificate can not be loaded error: (%s). The client will " +
"continue running, but will not be able to communicate with the server. If this is not your intention " +
"please add a valid server certificate"
)
var DeploymentLogger *DeploymentLogManager
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.")
imageFile := parsing.String("install", "",
"Mender Artifact to install. Can be either a local file or a URL.")
commit := parsing.Bool("commit", false,
"Commit current Artifact. Returns (2) if no update in progress")
rollback := parsing.Bool("rollback", false,
"Rollback current Artifact. 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")
daemon := parsing.Bool("daemon", false, "Run as a daemon.")
updateCheck := parsing.Bool("check-update", false, "force update check")
updateInventory := parsing.Bool("send-inventory", false, "force inventory update")
// 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,
commit: commit,
rollback: rollback,
bootstrap: bootstrap,
daemon: daemon,
bootstrapForce: forcebootstrap,
showArtifact: showArtifact,
updateCheck: updateCheck,
updateInventory: updateInventory,
Config: client.Config{
ServerCert: *serverCert,
NoVerify: *skipVerify,
},
}
// set info as a default log level
log.SetLevel(log.InfoLevel)
//runOptions.bootstrap = httpsClientConfig{}
// FLAG LOGIC ----------------------------------------------------------
if moreThanOneActionSelected(runOptions) {
return runOptions, errMsgAmbiguousArgumentsGiven
}
if *version || *showArtifact {
// Limit informational output for pure information queries, to
// make it easier to use in scripts. This can still be
// overridden by dedicated log arguments.
log.SetLevel(log.ErrorLevel)
}
// we just want to see the version string check for an update,
// or update inventory, the rest does not
// matter.
if *version || *updateCheck || *updateInventory {
return runOptions, nil
}
if err := parseLogFlags(logFlags); err != nil {
return runOptions, err
}
return runOptions, nil
}
func moreThanOneActionSelected(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.rollback {
runOptionsCount++
}
if *runOptions.daemon {
runOptionsCount++
}
if *runOptions.bootstrap {
runOptionsCount++
}
if *runOptions.version {
runOptionsCount++
}
if *runOptions.showArtifact {
runOptionsCount++
}
if *runOptions.updateCheck {
runOptionsCount++
}
if *runOptions.updateInventory {
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 '-log-level debug'.")
logOptions.info = f.Bool("info", false, "Info log level. This is a "+
"shorthand for '-log-level 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
}
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() {
fmt.Printf("%s\nruntime: %s\n", VersionString(), runtime.Version())
}
func PrintArtifactName(device *deviceManager) error {
name, err := device.GetCurrentArtifactName()
if err != nil {
return err
}
if name == "" {
return errors.New("The Artifact name is empty. Please set a valid name for the Artifact!")
}
fmt.Println(name)
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")
}
stat, err := os.Stat(*opts.dataStore)
if os.IsNotExist(err) {
// Create data directory if it does not exist.
err = os.MkdirAll(*opts.dataStore, 0700)
if err != nil {
return nil, err
}
} else if err != nil {
return nil, errors.Wrapf(err, "Could not stat data directory: %s", *opts.dataStore)
} else if !stat.IsDir() {
return nil, errors.Errorf("%s is not a directory", *opts.dataStore)
}
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 installer.DualRootfsDevice, env installer.BootEnvReadWriter,
opts *runOptionsType) (*menderDaemon, error) {
mp, err := commonInit(config, opts)
if err != nil {
return nil, err
}
mp.dualRootfsDevice = dev
controller, err := NewMender(config, *mp)
if err != nil {
// Ignore server certificate error (See: MEN-2378)
if _, ok := errors.Cause(err).(*client.ClientServerCertificateError); ok {
log.Warningf(errMissingServerCertstr, err)
} else {
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 or inventory-update is triggered.
if *runOptions.updateCheck {
return updateCheck(exec.Command("kill", "-USR1"), exec.Command("systemctl", "show", "-p", "MainPID", "mender"))
}
if *runOptions.updateInventory {
return updateCheck(exec.Command("kill", "-USR2"), 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 := installer.NewEnvironment(new(system.OsCalls))
dualRootfsDevice := installer.NewDualRootfsDevice(env, new(system.OsCalls), config.GetDeviceConfig())
if dualRootfsDevice == nil {
log.Info("No dual rootfs configuration present")
} else {
ap, err := dualRootfsDevice.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, dualRootfsDevice, config)
}
func handleCLIOptions(runOptions runOptionsType, env *installer.UBootEnv,
dualRootfsDevice installer.DualRootfsDevice, config *menderConfig) error {
switch {
case *runOptions.version:
ShowVersion()
return nil
case *runOptions.showArtifact,
*runOptions.imageFile != "",
*runOptions.commit,
*runOptions.rollback:
return handleArtifactOperations(runOptions, dualRootfsDevice, config)
case *runOptions.bootstrap:
return doBootstrapAuthorize(config, &runOptions)
case *runOptions.daemon:
d, err := initDaemon(config, dualRootfsDevice, env, &runOptions)
if err != nil {
return err
}
defer d.Cleanup()
return runDaemon(d)
default:
return errMsgNoArgumentsGiven
}
}
func handleArtifactOperations(runOptions runOptionsType, dualRootfsDevice installer.DualRootfsDevice,
config *menderConfig) error {
menderPieces, err := commonInit(config, &runOptions)
if err != nil {
return err
}
stateExec := newStateScriptExecutor(config)
deviceManager := NewDeviceManager(dualRootfsDevice, config, menderPieces.store)
switch {
case *runOptions.showArtifact:
return PrintArtifactName(deviceManager)
case *runOptions.imageFile != "":
vKey := config.GetVerificationKey()
return doStandaloneInstall(deviceManager, runOptions, vKey, stateExec)
case *runOptions.commit:
return doStandaloneCommit(deviceManager, stateExec)
case *runOptions.rollback:
return doStandaloneRollback(deviceManager, stateExec)
default:
return errors.New("handleArtifactOperations: Should never get here")
}
}
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 SIGUSR{1,2} 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 send %s the mender process, pid: %s", cmdKill.Args[len(cmdKill.Args)-1], pid)
}
return nil
}
func runDaemon(d *menderDaemon) error {
// Handle user forcing update check.
go func() {
c := make(chan os.Signal, 2)
signal.Notify(c, syscall.SIGUSR1) // SIGUSR1 forces an update check.
signal.Notify(c, syscall.SIGUSR2) // SIGUSR2 forces an inventory update.
defer signal.Stop(c)
for {
s := <-c // Block until a signal is received.
if s == syscall.SIGUSR1 {
log.Debug("SIGUSR1 signal received.")
d.forceToState <- updateCheckState
} else if s == syscall.SIGUSR2 {
log.Debug("SIGUSR2 signal received.")
d.forceToState <- inventoryUpdateState
}
d.sctx.wakeupChan <- true
log.Debug("Sent wake up!")
}
}()
return d.Run()
}
func main() {
if err := doMain(os.Args[1:]); err != nil {
var returnCode int
if err == installer.ErrorNothingToCommit {
log.Warnln(err.Error())
returnCode = 2
} else {
if err != flag.ErrHelp {
log.Errorln(err.Error())
}
returnCode = 1
}
os.Exit(returnCode)
}
}