-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathmender.go
503 lines (434 loc) · 12.9 KB
/
mender.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
// Copyright 2016 Mender Software 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"
"encoding/json"
"fmt"
"io"
"os"
"path"
"strings"
"time"
"github.com/mendersoftware/log"
"github.com/mendersoftware/mender/client"
"github.com/mendersoftware/mender/installer"
"github.com/pkg/errors"
)
type BootVars map[string]string
type BootEnvReadWriter interface {
ReadEnv(...string) (BootVars, error)
WriteEnv(BootVars) error
}
type UInstallCommitRebooter interface {
installer.UInstaller
CommitUpdate() error
Reboot() error
Rollback() error
HasUpdate() (bool, error)
}
type Controller interface {
Authorize() menderError
Bootstrap() menderError
GetCurrentArtifactName() string
GetUpdatePollInterval() time.Duration
GetInventoryPollInterval() time.Duration
GetRetryPollInterval() time.Duration
HasUpgrade() (bool, menderError)
CheckUpdate() (*client.UpdateResponse, menderError)
FetchUpdate(url string) (io.ReadCloser, int64, error)
ReportUpdateStatus(update client.UpdateResponse, status string) menderError
UploadLog(update client.UpdateResponse, logs []byte) menderError
InventoryRefresh() error
UInstallCommitRebooter
StateRunner
}
const (
defaultKeyFile = "mender-agent.pem"
)
var (
defaultArtifactInfoFile = path.Join(getConfDirPath(), "artifact_info")
defaultDeviceTypeFile = path.Join(getStateDirPath(), "device_type")
defaultDataStore = getStateDirPath()
)
type MenderState int
const (
// initial state
MenderStateInit MenderState = iota
// client is bootstrapped, i.e. ready to go
MenderStateBootstrapped
// client has all authorization data available
MenderStateAuthorized
// wait before authorization attempt
MenderStateAuthorizeWait
// inventory update
MenderStateInventoryUpdate
// wait for new update or inventory sending
MenderStateCheckWait
// check update
MenderStateUpdateCheck
// update fetch
MenderStateUpdateFetch
// update install
MenderStateUpdateInstall
// wait before retrying fetch & install after first failing (timeout,
// for example)
MenderStateFetchInstallRetryWait
// varify update
MenderStateUpdateVerify
// commit needed
MenderStateUpdateCommit
// status report
MenderStateUpdateStatusReport
// errro reporting status
MenderStateReportStatusError
// reboot
MenderStateReboot
//rollback
MenderStateRollback
// error
MenderStateError
// update error
MenderStateUpdateError
// exit state
MenderStateDone
)
var (
stateNames = map[MenderState]string{
MenderStateInit: "init",
MenderStateBootstrapped: "bootstrapped",
MenderStateAuthorized: "authorized",
MenderStateAuthorizeWait: "authorize-wait",
MenderStateInventoryUpdate: "inventory-update",
MenderStateCheckWait: "check-wait",
MenderStateUpdateCheck: "update-check",
MenderStateUpdateFetch: "update-fetch",
MenderStateUpdateInstall: "update-install",
MenderStateFetchInstallRetryWait: "fetch-install-retry-wait",
MenderStateUpdateVerify: "update-verify",
MenderStateUpdateCommit: "update-commit",
MenderStateUpdateStatusReport: "update-status-report",
MenderStateReportStatusError: "status-report-error",
MenderStateReboot: "reboot",
MenderStateRollback: "rollback",
MenderStateError: "error",
MenderStateUpdateError: "update-error",
MenderStateDone: "finished",
}
)
func (m MenderState) MarshalJSON() ([]byte, error) {
n, ok := stateNames[m]
if !ok {
return nil, fmt.Errorf("marshal error; unknown state %v", m)
}
return json.Marshal(n)
}
func (m MenderState) String() string {
return stateNames[m]
}
func (m *MenderState) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
for k, v := range stateNames {
if v == s {
*m = k
return nil
}
}
return fmt.Errorf("unmarshal error; unknown state %s", s)
}
type mender struct {
UInstallCommitRebooter
updater client.Updater
state State
config menderConfig
artifactInfoFile string
deviceTypeFile string
forceBootstrap bool
authReq client.AuthRequester
authMgr AuthManager
api *client.ApiClient
authToken client.AuthToken
}
type MenderPieces struct {
device UInstallCommitRebooter
store Store
authMgr AuthManager
}
func NewMender(config menderConfig, pieces MenderPieces) (*mender, error) {
api, err := client.New(config.GetHttpConfig())
if err != nil {
return nil, errors.Wrap(err, "error creating HTTP client")
}
m := &mender{
UInstallCommitRebooter: pieces.device,
updater: client.NewUpdate(),
artifactInfoFile: defaultArtifactInfoFile,
deviceTypeFile: defaultDeviceTypeFile,
state: initState,
config: config,
authMgr: pieces.authMgr,
authReq: client.NewAuth(),
api: api,
authToken: noAuthToken,
}
return m, nil
}
func getManifestData(dataType, manifestFile string) string {
// This is where Yocto stores buid information
manifest, err := os.Open(manifestFile)
if err != nil {
log.Error("Can not read manifest data.")
return ""
}
scanner := bufio.NewScanner(manifest)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
log.Debug("Read data from device manifest file: ", line)
if strings.HasPrefix(line, dataType) {
log.Debug("Found needed line: ", line)
lineID := strings.Split(line, "=")
if len(lineID) != 2 {
log.Errorf("Broken device manifest file: (%v)", lineID)
return ""
}
log.Debug("Current manifest data: ", strings.TrimSpace(lineID[1]))
return strings.TrimSpace(lineID[1])
}
}
if err := scanner.Err(); err != nil {
log.Error(err)
}
return ""
}
func (m *mender) GetCurrentArtifactName() string {
return getManifestData("artifact_name", m.artifactInfoFile)
}
func (m *mender) GetDeviceType() string {
return getManifestData("device_type", m.deviceTypeFile)
}
func GetCurrentArtifactName(artifactInfoFile string) string {
return getManifestData("artifact_name", artifactInfoFile)
}
func GetDeviceType(deviceTypeFile string) string {
return getManifestData("device_type", deviceTypeFile)
}
func (m *mender) HasUpgrade() (bool, menderError) {
has, err := m.UInstallCommitRebooter.HasUpdate()
if err != nil {
return false, NewFatalError(err)
}
return has, nil
}
func (m *mender) ForceBootstrap() {
m.forceBootstrap = true
}
func (m *mender) needsBootstrap() bool {
if m.forceBootstrap {
return true
}
if !m.authMgr.HasKey() {
log.Debugf("needs keys")
return true
}
return false
}
func (m *mender) Bootstrap() menderError {
if !m.needsBootstrap() {
return nil
}
return m.doBootstrap()
}
// cache authorization code
func (m *mender) loadAuth() menderError {
if m.authToken != noAuthToken {
return nil
}
code, err := m.authMgr.AuthToken()
if err != nil {
return NewFatalError(errors.Wrap(err, "failed to cache authorization code"))
}
m.authToken = code
return nil
}
func (m *mender) Authorize() menderError {
if m.authMgr.IsAuthorized() {
log.Info("authorization data present and valid, skipping authorization attempt")
return m.loadAuth()
}
m.authToken = noAuthToken
rsp, err := m.authReq.Request(m.api, m.config.ServerURL, m.authMgr)
if err != nil {
if err == client.AuthErrorUnauthorized {
// make sure to remove auth token once device is rejected
if remErr := m.authMgr.RemoveAuthToken(); remErr != nil {
log.Warn("can not remove rejected authentication token")
}
}
return NewTransientError(errors.Wrap(err, "authorization request failed"))
}
err = m.authMgr.RecvAuthResponse(rsp)
if err != nil {
return NewTransientError(errors.Wrap(err, "failed to parse authorization response"))
}
log.Info("successfuly received new authorization data")
return m.loadAuth()
}
func (m *mender) doBootstrap() menderError {
if !m.authMgr.HasKey() || m.forceBootstrap {
log.Infof("device keys not present or bootstrap forced, generating")
if err := m.authMgr.GenerateKey(); err != nil {
return NewFatalError(err)
}
}
m.forceBootstrap = false
return nil
}
func (m *mender) FetchUpdate(url string) (io.ReadCloser, int64, error) {
return m.updater.FetchUpdate(m.api, url)
}
// Check if new update is available. In case of errors, returns nil and error
// that occurred. If no update is available *UpdateResponse is nil, otherwise it
// contains update information.
func (m *mender) CheckUpdate() (*client.UpdateResponse, menderError) {
currentArtifactName := m.GetCurrentArtifactName()
//TODO: if currentArtifactName == "" {
// return errors.New("")
// }
haveUpdate, err := m.updater.GetScheduledUpdate(m.api.Request(m.authToken),
m.config.ServerURL, client.CurrentUpdate{
Artifact: currentArtifactName,
DeviceType: m.GetDeviceType(),
})
if err != nil {
// remove authentication token if device is not authorized
if err == client.ErrNotAuthorized {
if remErr := m.authMgr.RemoveAuthToken(); remErr != nil {
log.Warn("can not remove rejected authentication token")
}
}
log.Error("Error receiving scheduled update data: ", err)
return nil, NewTransientError(err)
}
if haveUpdate == nil {
log.Debug("no updates available")
return nil, nil
}
update, ok := haveUpdate.(client.UpdateResponse)
if !ok {
return nil, NewTransientError(errors.Errorf("not an update response?"))
}
log.Debugf("received update response: %v", update)
if update.ArtifactName() == currentArtifactName {
log.Info("Attempting to upgrade to currently installed artifact name, not performing upgrade.")
return &update, NewTransientError(os.ErrExist)
}
return &update, nil
}
func (m *mender) ReportUpdateStatus(update client.UpdateResponse, status string) menderError {
s := client.NewStatus()
err := s.Report(m.api.Request(m.authToken), m.config.ServerURL,
client.StatusReport{
DeploymentID: update.ID,
Status: status,
})
if err != nil {
log.Error("error reporting update status: ", err)
if err == client.ErrDeploymentAborted {
return NewFatalError(err)
}
return NewTransientError(err)
}
return nil
}
func (m *mender) UploadLog(update client.UpdateResponse, logs []byte) menderError {
s := client.NewLog()
err := s.Upload(m.api.Request(m.authToken), m.config.ServerURL,
client.LogData{
DeploymentID: update.ID,
Messages: logs,
})
if err != nil {
log.Error("error uploading logs: ", err)
return NewTransientError(err)
}
return nil
}
func (m mender) GetUpdatePollInterval() time.Duration {
t := time.Duration(m.config.UpdatePollIntervalSeconds) * time.Second
if t == 0 {
log.Warn("UpdatePollIntervalSeconds is not defined")
t = 30 * time.Minute
}
return t
}
func (m mender) GetInventoryPollInterval() time.Duration {
t := time.Duration(m.config.InventoryPollIntervalSeconds) * time.Second
if t == 0 {
log.Warn("InventoryPollIntervalSeconds is not defined")
t = 30 * time.Minute
}
return t
}
func (m mender) GetRetryPollInterval() time.Duration {
t := time.Duration(m.config.RetryPollIntervalSeconds) * time.Second
if t == 0 {
log.Warn("RetryPollIntervalSeconds is not defined")
t = 5 * time.Minute
}
return t
}
func (m *mender) SetState(s State) {
log.Infof("Mender state: %s -> %s", m.state.Id(), s.Id())
m.state = s
}
func (m *mender) GetState() State {
return m.state
}
func (m *mender) RunState(ctx *StateContext) (State, bool) {
return m.state.Handle(ctx, m)
}
func (m *mender) InventoryRefresh() error {
ic := client.NewInventory()
idg := NewInventoryDataRunner(path.Join(getDataDirPath(), "inventory"))
idata, err := idg.Get()
if err != nil {
// at least report device type
log.Errorf("failed to obtain inventory data: %s", err.Error())
}
reqAttr := []client.InventoryAttribute{
{Name: "device_type", Value: m.GetDeviceType()},
{Name: "artifact_name", Value: m.GetCurrentArtifactName()},
{Name: "mender_client_version", Value: VersionString()},
}
if idata == nil {
idata = make(client.InventoryData, 0, len(reqAttr))
}
idata.ReplaceAttributes(reqAttr)
if idata == nil {
log.Infof("no inventory data to submit")
return nil
}
err = ic.Submit(m.api.Request(m.authToken), m.config.ServerURL, idata)
if err != nil {
return errors.Wrapf(err, "failed to submit inventory data")
}
return nil
}
func (m *mender) InstallUpdate(from io.ReadCloser, size int64) error {
return installer.Install(from, m.GetDeviceType(), m.UInstallCommitRebooter)
}