• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / mender-artifact / 1696787489

03 Mar 2025 12:08PM UTC coverage: 76.611%. Remained the same
1696787489

push

gitlab-ci

web-flow
Merge pull request #681 from lluiscampos/deprecate-ioutils

chore: Update the code away from deprecated `io/ioutils`

27 of 29 new or added lines in 10 files covered. (93.1%)

2 existing lines in 1 file now uncovered.

5909 of 7713 relevant lines covered (76.61%)

132.48 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

54.94
/cli/write.go
1
// Copyright 2023 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14

15
package cli
16

17
import (
18
        "bufio"
19
        "context"
20
        "encoding/json"
21
        "fmt"
22
        "os"
23
        "os/exec"
24
        "os/signal"
25
        "regexp"
26
        "strings"
27
        "syscall"
28
        "time"
29

30
        "io"
31

32
        "github.com/pkg/errors"
33
        "github.com/urfave/cli"
34

35
        "github.com/mendersoftware/mender-artifact/artifact"
36
        "github.com/mendersoftware/mender-artifact/artifact/stage"
37
        "github.com/mendersoftware/mender-artifact/awriter"
38
        "github.com/mendersoftware/mender-artifact/cli/util"
39
        "github.com/mendersoftware/mender-artifact/handlers"
40
        "github.com/mendersoftware/mender-artifact/utils"
41
)
42

43
func writeRootfsImageChecksum(rootfsFilename string,
44
        typeInfo *artifact.TypeInfoV3, legacy bool) (err error) {
187✔
45
        chk := artifact.NewWriterChecksum(io.Discard)
187✔
46
        payload, err := os.Open(rootfsFilename)
187✔
47
        if err != nil {
189✔
48
                return cli.NewExitError(
2✔
49
                        fmt.Sprintf("Failed to open the payload file: %q", rootfsFilename),
2✔
50
                        1,
2✔
51
                )
2✔
52
        }
2✔
53
        if _, err = io.Copy(chk, payload); err != nil {
185✔
54
                return cli.NewExitError("Failed to generate the checksum for the payload", 1)
×
55
        }
×
56
        checksum := string(chk.Checksum())
185✔
57

185✔
58
        checksumKey := "rootfs-image.checksum"
185✔
59
        if legacy {
187✔
60
                checksumKey = "rootfs_image_checksum"
2✔
61
        }
2✔
62

63
        Log.Debugf("Adding the `%s`: %q to Artifact provides", checksumKey, checksum)
185✔
64
        if typeInfo == nil {
185✔
65
                return errors.New("Type-info is unitialized")
×
66
        }
×
67
        if typeInfo.ArtifactProvides == nil {
187✔
68
                t, err := artifact.NewTypeInfoProvides(map[string]string{checksumKey: checksum})
2✔
69
                if err != nil {
2✔
70
                        return errors.Wrapf(err, "%s", "Failed to write the "+"`"+checksumKey+"` provides")
×
71
                }
×
72
                typeInfo.ArtifactProvides = t
2✔
73
        } else {
183✔
74
                typeInfo.ArtifactProvides[checksumKey] = checksum
183✔
75
        }
183✔
76
        return nil
185✔
77
}
78

79
func validateInput(c *cli.Context) error {
82✔
80
        // Version 2 and 3 validation.
82✔
81
        fileMissing := false
82✔
82
        if c.Command.Name != "bootstrap-artifact" {
160✔
83
                if len(c.String("file")) == 0 {
78✔
84
                        fileMissing = true
×
85
                }
×
86
        }
87
        if len(c.StringSlice("device-type")) == 0 ||
82✔
88
                len(c.String("artifact-name")) == 0 || fileMissing {
82✔
89
                return cli.NewExitError(
×
90
                        "must provide `device-type`, `artifact-name` and `file`",
×
91
                        errArtifactInvalidParameters,
×
92
                )
×
93
        }
×
94
        if len(strings.Fields(c.String("artifact-name"))) > 1 {
84✔
95
                // check for whitespace in artifact-name
2✔
96
                return cli.NewExitError(
2✔
97
                        "whitespace is not allowed in the artifact-name",
2✔
98
                        errArtifactInvalidParameters,
2✔
99
                )
2✔
100
        }
2✔
101
        return nil
80✔
102
}
103

104
func createRootfsFromSSH(c *cli.Context) (string, error) {
×
105
        _, err := utils.GetBinaryPath("blkid")
×
106
        if err != nil {
×
107
                Log.Warnf("Skipping running fsck on the Artifact: %v", errBlkidNotFound)
×
108
        }
×
109
        rootfsFilename, err := getDeviceSnapshot(c)
×
110
        if err != nil {
×
111
                return rootfsFilename, cli.NewExitError("SSH error: "+err.Error(), 1)
×
112
        }
×
113

114
        // check for blkid and get filesystem type
115
        fstype, err := imgFilesystemType(rootfsFilename)
×
116
        if err != nil {
×
117
                if err == errBlkidNotFound {
×
118
                        return rootfsFilename, nil
×
119
                }
×
120
                return rootfsFilename, cli.NewExitError(
×
121
                        "imgFilesystemType error: "+err.Error(),
×
122
                        errArtifactCreate,
×
123
                )
×
124
        }
125

126
        // run fsck
127
        switch fstype {
×
128
        case fat:
×
129
                err = runFsck(rootfsFilename, "vfat")
×
130
        case ext:
×
131
                err = runFsck(rootfsFilename, "ext4")
×
132
        case unsupported:
×
133
                err = errors.New("createRootfsFromSSH: unsupported filesystem")
×
134

135
        }
136
        if err != nil {
×
137
                return rootfsFilename, cli.NewExitError("runFsck error: "+err.Error(), errArtifactCreate)
×
138
        }
×
139

140
        return rootfsFilename, nil
×
141
}
142

143
func makeEmptyUpdates(ctx *cli.Context) (*awriter.Updates, error) {
4✔
144
        handler := handlers.NewBootstrapArtifact()
4✔
145

4✔
146
        dataFiles := make([](*handlers.DataFile), 0)
4✔
147
        if err := handler.SetUpdateFiles(dataFiles); err != nil {
4✔
148
                return nil, cli.NewExitError(
×
149
                        err,
×
150
                        1,
×
151
                )
×
152
        }
×
153

154
        upd := &awriter.Updates{
4✔
155
                Updates: []handlers.Composer{handler},
4✔
156
        }
4✔
157
        return upd, nil
4✔
158
}
159

160
func writeBootstrapArtifact(c *cli.Context) error {
4✔
161
        comp, err := artifact.NewCompressorFromId(c.GlobalString("compression"))
4✔
162
        if err != nil {
4✔
163
                return cli.NewExitError(
×
164
                        "compressor '"+c.GlobalString("compression")+"' is not supported: "+err.Error(),
×
165
                        1,
×
166
                )
×
167
        }
×
168

169
        if err := validateInput(c); err != nil {
4✔
170
                Log.Error(err.Error())
×
171
                return err
×
172
        }
×
173

174
        // set the default name
175
        name := "artifact.mender"
4✔
176
        if len(c.String("output-path")) > 0 {
8✔
177
                name = c.String("output-path")
4✔
178
        }
4✔
179
        version := c.Int("version")
4✔
180

4✔
181
        Log.Debugf("creating bootstrap artifact [%s], version: %d", name, version)
4✔
182

4✔
183
        var w io.Writer
4✔
184
        if name == "-" {
4✔
185
                w = os.Stdout
×
186
        } else {
4✔
187
                f, err := os.Create(name)
4✔
188
                if err != nil {
4✔
189
                        return cli.NewExitError(
×
190
                                "can not create bootstrap artifact file: "+err.Error(),
×
191
                                errArtifactCreate,
×
192
                        )
×
193
                }
×
194
                defer f.Close()
4✔
195
                w = f
4✔
196
        }
197

198
        aw, err := artifactWriter(c, comp, w, version)
4✔
199
        if err != nil {
4✔
200
                return cli.NewExitError(err.Error(), 1)
×
201
        }
×
202

203
        depends := artifact.ArtifactDepends{
4✔
204
                ArtifactName:      c.StringSlice("artifact-name-depends"),
4✔
205
                CompatibleDevices: c.StringSlice("device-type"),
4✔
206
                ArtifactGroup:     c.StringSlice("depends-groups"),
4✔
207
        }
4✔
208

4✔
209
        provides := artifact.ArtifactProvides{
4✔
210
                ArtifactName:  c.String("artifact-name"),
4✔
211
                ArtifactGroup: c.String("provides-group"),
4✔
212
        }
4✔
213

4✔
214
        upd, err := makeEmptyUpdates(c)
4✔
215
        if err != nil {
4✔
216
                return err
×
217
        }
×
218

219
        typeInfoV3, _, err := makeTypeInfo(c)
4✔
220
        if err != nil {
4✔
221
                return err
×
222
        }
×
223

224
        if !c.Bool("no-progress") {
8✔
225
                ctx, cancel := context.WithCancel(context.Background())
4✔
226
                go reportProgress(ctx, aw.State)
4✔
227
                defer cancel()
4✔
228
                aw.ProgressWriter = utils.NewProgressWriter()
4✔
229
        }
4✔
230

231
        err = aw.WriteArtifact(
4✔
232
                &awriter.WriteArtifactArgs{
4✔
233
                        Format:     "mender",
4✔
234
                        Version:    version,
4✔
235
                        Devices:    c.StringSlice("device-type"),
4✔
236
                        Name:       c.String("artifact-name"),
4✔
237
                        Updates:    upd,
4✔
238
                        Scripts:    nil,
4✔
239
                        Depends:    &depends,
4✔
240
                        Provides:   &provides,
4✔
241
                        TypeInfoV3: typeInfoV3,
4✔
242
                        Bootstrap:  true,
4✔
243
                })
4✔
244
        if err != nil {
4✔
245
                return cli.NewExitError(err.Error(), 1)
×
246
        }
×
247
        return nil
4✔
248
}
249

250
func writeRootfs(c *cli.Context) error {
78✔
251
        comp, err := artifact.NewCompressorFromId(c.GlobalString("compression"))
78✔
252
        if err != nil {
78✔
253
                return cli.NewExitError(
×
254
                        "compressor '"+c.GlobalString("compression")+"' is not supported: "+err.Error(),
×
255
                        1,
×
256
                )
×
257
        }
×
258

259
        if err := validateInput(c); err != nil {
80✔
260
                Log.Error(err.Error())
2✔
261
                return err
2✔
262
        }
2✔
263

264
        // set the default name
265
        name := "artifact.mender"
76✔
266
        if len(c.String("output-path")) > 0 {
152✔
267
                name = c.String("output-path")
76✔
268
        }
76✔
269
        version := c.Int("version")
76✔
270
        var showprovides map[string]string
76✔
271

76✔
272
        Log.Debugf("creating artifact [%s], version: %d", name, version)
76✔
273
        rootfsFilename := c.String("file")
76✔
274
        if strings.HasPrefix(rootfsFilename, "ssh://") {
76✔
275
                rootfsFilename, err = createRootfsFromSSH(c)
×
276
                defer os.Remove(rootfsFilename)
×
277
                if err != nil {
×
278
                        return cli.NewExitError(err.Error(), errArtifactCreate)
×
279
                }
×
280
                showprovides, err = showProvides(c)
×
281
                if err != nil {
×
282
                        return cli.NewExitError(err.Error(), errArtifactCreate)
×
283
                }
×
284
        }
285

286
        var h handlers.Composer
76✔
287
        switch version {
76✔
288
        case 2:
2✔
289
                h = handlers.NewRootfsV2(rootfsFilename)
2✔
290
        case 3:
68✔
291
                h = handlers.NewRootfsV3(rootfsFilename)
68✔
292
        default:
6✔
293
                return cli.NewExitError(
6✔
294
                        fmt.Sprintf("Artifact version %d is not supported", version),
6✔
295
                        errArtifactUnsupportedVersion,
6✔
296
                )
6✔
297
        }
298

299
        upd := &awriter.Updates{
70✔
300
                Updates: []handlers.Composer{h},
70✔
301
        }
70✔
302

70✔
303
        var w io.Writer
70✔
304
        if name == "-" {
70✔
305
                w = os.Stdout
×
306
        } else {
70✔
307
                f, err := os.Create(name)
70✔
308
                if err != nil {
70✔
309
                        return cli.NewExitError(
×
310
                                "can not create artifact file: "+err.Error(),
×
311
                                errArtifactCreate,
×
312
                        )
×
313
                }
×
314
                defer f.Close()
70✔
315
                w = f
70✔
316
        }
317

318
        aw, err := artifactWriter(c, comp, w, version)
70✔
319
        if err != nil {
72✔
320
                return cli.NewExitError(err.Error(), 1)
2✔
321
        }
2✔
322

323
        scr, err := scripts(c.StringSlice("script"))
68✔
324
        if err != nil {
70✔
325
                return cli.NewExitError(err.Error(), 1)
2✔
326
        }
2✔
327

328
        depends := artifact.ArtifactDepends{
66✔
329
                ArtifactName:      c.StringSlice("artifact-name-depends"),
66✔
330
                CompatibleDevices: c.StringSlice("device-type"),
66✔
331
                ArtifactGroup:     c.StringSlice("depends-groups"),
66✔
332
        }
66✔
333

66✔
334
        provides := artifact.ArtifactProvides{
66✔
335
                ArtifactName:  c.String("artifact-name"),
66✔
336
                ArtifactGroup: c.String("provides-group"),
66✔
337
        }
66✔
338

66✔
339
        typeInfoV3, _, err := makeTypeInfo(c)
66✔
340
        if err != nil {
66✔
341
                return err
×
342
        }
×
343
        for k, v := range showprovides {
66✔
344
                _, exist := typeInfoV3.ArtifactProvides[k]
×
345
                if !exist {
×
346
                        typeInfoV3.ArtifactProvides[k] = v
×
347
                }
×
348
        }
349

350
        if !c.Bool("no-checksum-provide") {
128✔
351
                legacy := c.Bool("legacy-rootfs-image-checksum")
62✔
352
                if err = writeRootfsImageChecksum(rootfsFilename, typeInfoV3, legacy); err != nil {
62✔
353
                        return cli.NewExitError(
×
354
                                errors.Wrap(err, "Failed to write the `rootfs-image.checksum` to the artifact"),
×
355
                                1,
×
356
                        )
×
357
                }
×
358
        }
359
        if !c.Bool("no-progress") {
132✔
360
                ctx, cancel := context.WithCancel(context.Background())
66✔
361
                go reportProgress(ctx, aw.State)
66✔
362
                defer cancel()
66✔
363
                aw.ProgressWriter = utils.NewProgressWriter()
66✔
364
        }
66✔
365

366
        err = aw.WriteArtifact(
66✔
367
                &awriter.WriteArtifactArgs{
66✔
368
                        Format:     "mender",
66✔
369
                        Version:    version,
66✔
370
                        Devices:    c.StringSlice("device-type"),
66✔
371
                        Name:       c.String("artifact-name"),
66✔
372
                        Updates:    upd,
66✔
373
                        Scripts:    scr,
66✔
374
                        Depends:    &depends,
66✔
375
                        Provides:   &provides,
66✔
376
                        TypeInfoV3: typeInfoV3,
66✔
377
                })
66✔
378
        if err != nil {
66✔
379
                return cli.NewExitError(err.Error(), 1)
×
380
        }
×
381
        return nil
66✔
382
}
383

384
func reportProgress(c context.Context, state chan string) {
70✔
385
        fmt.Fprintln(os.Stderr, "Writing Artifact...")
70✔
386
        str := fmt.Sprintf("%-20s\t", <-state)
70✔
387
        fmt.Fprint(os.Stderr, str)
70✔
388
        for {
418✔
389
                select {
348✔
390
                case str = <-state:
278✔
391
                        if str == stage.Data {
348✔
392
                                fmt.Fprintf(os.Stderr, "\033[1;32m\u2713\033[0m\n")
70✔
393
                                fmt.Fprintln(os.Stderr, "Payload")
70✔
394
                        } else {
278✔
395
                                fmt.Fprintf(os.Stderr, "\033[1;32m\u2713\033[0m\n")
208✔
396
                                str = fmt.Sprintf("%-20s\t", str)
208✔
397
                                fmt.Fprint(os.Stderr, str)
208✔
398
                        }
208✔
399
                case <-c.Done():
70✔
400
                        return
70✔
401
                }
402
        }
403
}
404

405
func artifactWriter(c *cli.Context, comp artifact.Compressor, w io.Writer,
406
        ver int) (*awriter.Writer, error) {
125✔
407
        privateKey, err := getKey(c)
125✔
408
        if err != nil {
127✔
409
                return nil, err
2✔
410
        }
2✔
411
        if privateKey != nil {
133✔
412
                if ver == 0 {
10✔
413
                        // check if we are having correct version
×
414
                        return nil, errors.New("can not use signed artifact with version 0")
×
415
                }
×
416
                return awriter.NewWriterSigned(w, comp, privateKey), nil
10✔
417
        }
418
        return awriter.NewWriter(w, comp), nil
113✔
419
}
420

421
func makeUpdates(ctx *cli.Context) (*awriter.Updates, error) {
51✔
422
        version := ctx.Int("version")
51✔
423

51✔
424
        var handler, augmentHandler handlers.Composer
51✔
425
        switch version {
51✔
426
        case 2:
×
427
                return nil, cli.NewExitError(
×
428
                        "Module images need at least artifact format version 3",
×
429
                        errArtifactInvalidParameters)
×
430
        case 3:
51✔
431
                handler = handlers.NewModuleImage(ctx.String("type"))
51✔
432
        default:
×
433
                return nil, cli.NewExitError(
×
434
                        fmt.Sprintf("unsupported artifact version: %v", version),
×
435
                        errArtifactUnsupportedVersion,
×
436
                )
×
437
        }
438

439
        dataFiles := make([](*handlers.DataFile), 0, len(ctx.StringSlice("file")))
51✔
440
        for _, file := range ctx.StringSlice("file") {
105✔
441
                dataFiles = append(dataFiles, &handlers.DataFile{Name: file})
54✔
442
        }
54✔
443
        if err := handler.SetUpdateFiles(dataFiles); err != nil {
51✔
444
                return nil, cli.NewExitError(
×
445
                        err,
×
446
                        1,
×
447
                )
×
448
        }
×
449

450
        upd := &awriter.Updates{
51✔
451
                Updates: []handlers.Composer{handler},
51✔
452
        }
51✔
453

51✔
454
        if ctx.String("augment-type") != "" {
55✔
455
                augmentHandler = handlers.NewAugmentedModuleImage(handler, ctx.String("augment-type"))
4✔
456
                dataFiles = make([](*handlers.DataFile), 0, len(ctx.StringSlice("augment-file")))
4✔
457
                for _, file := range ctx.StringSlice("augment-file") {
8✔
458
                        dataFiles = append(dataFiles, &handlers.DataFile{Name: file})
4✔
459
                }
4✔
460
                if err := augmentHandler.SetUpdateAugmentFiles(dataFiles); err != nil {
4✔
461
                        return nil, cli.NewExitError(
×
462
                                err,
×
463
                                1,
×
464
                        )
×
465
                }
×
466
                upd.Augments = []handlers.Composer{augmentHandler}
4✔
467
        }
468

469
        return upd, nil
51✔
470
}
471

472
// makeTypeInfo returns the type-info provides and depends and the augmented
473
// type-info provides and depends, or nil.
474
func makeTypeInfo(ctx *cli.Context) (*artifact.TypeInfoV3, *artifact.TypeInfoV3, error) {
121✔
475
        // Make key value pairs from the type-info fields supplied on command
121✔
476
        // line.
121✔
477
        var keyValues *map[string]string
121✔
478

121✔
479
        var typeInfoDepends artifact.TypeInfoDepends
121✔
480
        keyValues, err := extractKeyValues(ctx.StringSlice("depends"))
121✔
481
        if err != nil {
121✔
482
                return nil, nil, err
×
483
        } else if keyValues != nil {
151✔
484
                if typeInfoDepends, err = artifact.NewTypeInfoDepends(*keyValues); err != nil {
30✔
485
                        return nil, nil, err
×
486
                }
×
487
        }
488

489
        var typeInfoProvides artifact.TypeInfoProvides
121✔
490
        keyValues, err = extractKeyValues(ctx.StringSlice("provides"))
121✔
491
        if err != nil {
121✔
492
                return nil, nil, err
×
493
        } else if keyValues != nil {
153✔
494
                if typeInfoProvides, err = artifact.NewTypeInfoProvides(*keyValues); err != nil {
32✔
495
                        return nil, nil, err
×
496
                }
×
497
        }
498
        typeInfoProvides = applySoftwareVersionToTypeInfoProvides(ctx, typeInfoProvides)
121✔
499

121✔
500
        var augmentTypeInfoDepends artifact.TypeInfoDepends
121✔
501
        keyValues, err = extractKeyValues(ctx.StringSlice("augment-depends"))
121✔
502
        if err != nil {
121✔
503
                return nil, nil, err
×
504
        } else if keyValues != nil {
125✔
505
                if augmentTypeInfoDepends, err = artifact.NewTypeInfoDepends(*keyValues); err != nil {
4✔
506
                        return nil, nil, err
×
507
                }
×
508
        }
509

510
        var augmentTypeInfoProvides artifact.TypeInfoProvides
121✔
511
        keyValues, err = extractKeyValues(ctx.StringSlice("augment-provides"))
121✔
512
        if err != nil {
121✔
513
                return nil, nil, err
×
514
        } else if keyValues != nil {
125✔
515
                if augmentTypeInfoProvides, err = artifact.NewTypeInfoProvides(*keyValues); err != nil {
4✔
516
                        return nil, nil, err
×
517
                }
×
518
        }
519

520
        clearsArtifactProvides, err := makeClearsArtifactProvides(ctx)
121✔
521
        if err != nil {
121✔
522
                return nil, nil, err
×
523
        }
×
524

525
        var typeInfo *string
121✔
526
        if ctx.Command.Name != "bootstrap-artifact" {
238✔
527
                typeFlag := ctx.String("type")
117✔
528
                typeInfo = &typeFlag
117✔
529
        }
117✔
530
        typeInfoV3 := &artifact.TypeInfoV3{
121✔
531
                Type:                   typeInfo,
121✔
532
                ArtifactDepends:        typeInfoDepends,
121✔
533
                ArtifactProvides:       typeInfoProvides,
121✔
534
                ClearsArtifactProvides: clearsArtifactProvides,
121✔
535
        }
121✔
536

121✔
537
        if ctx.String("augment-type") == "" {
238✔
538
                // Non-augmented artifact
117✔
539
                if len(ctx.StringSlice("augment-file")) != 0 ||
117✔
540
                        len(ctx.StringSlice("augment-depends")) != 0 ||
117✔
541
                        len(ctx.StringSlice("augment-provides")) != 0 ||
117✔
542
                        ctx.String("augment-meta-data") != "" {
117✔
543

×
544
                        err = errors.New("Must give --augment-type argument if making augmented artifact")
×
545
                        fmt.Println(err.Error())
×
546
                        return nil, nil, err
×
547
                }
×
548
                return typeInfoV3, nil, nil
117✔
549
        }
550

551
        augmentType := ctx.String("augment-type")
4✔
552
        augmentTypeInfoV3 := &artifact.TypeInfoV3{
4✔
553
                Type:             &augmentType,
4✔
554
                ArtifactDepends:  augmentTypeInfoDepends,
4✔
555
                ArtifactProvides: augmentTypeInfoProvides,
4✔
556
        }
4✔
557

4✔
558
        return typeInfoV3, augmentTypeInfoV3, nil
4✔
559
}
560

561
func getSoftwareVersion(
562
        artifactName,
563
        softwareFilesystem,
564
        softwareName,
565
        softwareNameDefault,
566
        softwareVersion string,
567
        noDefaultSoftwareVersion bool,
568
) map[string]string {
135✔
569
        result := map[string]string{}
135✔
570
        softwareVersionName := "rootfs-image"
135✔
571
        if softwareFilesystem != "" {
151✔
572
                softwareVersionName = softwareFilesystem
16✔
573
        }
16✔
574
        if !noDefaultSoftwareVersion {
242✔
575
                if softwareName == "" {
202✔
576
                        softwareName = softwareNameDefault
95✔
577
                }
95✔
578
                if softwareVersion == "" {
202✔
579
                        softwareVersion = artifactName
95✔
580
                }
95✔
581
        }
582
        if softwareName != "" {
186✔
583
                softwareVersionName += fmt.Sprintf(".%s", softwareName)
51✔
584
        }
51✔
585
        if softwareVersionName != "" && softwareVersion != "" {
246✔
586
                result[softwareVersionName+".version"] = softwareVersion
111✔
587
        }
111✔
588
        return result
135✔
589
}
590

591
// applySoftwareVersionToTypeInfoProvides returns a new mapping, enriched with provides
592
// for the software version; the mapping provided as argument is not modified
593
func applySoftwareVersionToTypeInfoProvides(
594
        ctx *cli.Context,
595
        typeInfoProvides artifact.TypeInfoProvides,
596
) artifact.TypeInfoProvides {
121✔
597
        result := make(map[string]string)
121✔
598
        for key, value := range typeInfoProvides {
185✔
599
                result[key] = value
64✔
600
        }
64✔
601
        artifactName := ctx.String("artifact-name")
121✔
602
        softwareFilesystem := ctx.String(softwareFilesystemFlag)
121✔
603
        softwareName := ctx.String(softwareNameFlag)
121✔
604
        softwareNameDefault := ""
121✔
605
        if ctx.Command.Name == "module-image" {
172✔
606
                softwareNameDefault = ctx.String("type")
51✔
607
        }
51✔
608
        if ctx.Command.Name == "bootstrap-artifact" {
125✔
609
                return result
4✔
610
        }
4✔
611
        softwareVersion := ctx.String(softwareVersionFlag)
117✔
612
        noDefaultSoftwareVersion := ctx.Bool(noDefaultSoftwareVersionFlag)
117✔
613
        if softwareVersionMapping := getSoftwareVersion(
117✔
614
                artifactName,
117✔
615
                softwareFilesystem,
117✔
616
                softwareName,
117✔
617
                softwareNameDefault,
117✔
618
                softwareVersion,
117✔
619
                noDefaultSoftwareVersion,
117✔
620
        ); len(softwareVersionMapping) > 0 {
214✔
621
                for key, value := range softwareVersionMapping {
194✔
622
                        if result[key] == "" || softwareVersionOverridesProvides(ctx, key) {
190✔
623
                                result[key] = value
93✔
624
                        }
93✔
625
                }
626
        }
627
        return result
117✔
628
}
629

630
func softwareVersionOverridesProvides(ctx *cli.Context, key string) bool {
6✔
631
        mainCtx := ctx.Parent().Parent()
6✔
632
        cmdLine := strings.Join(mainCtx.Args(), " ")
6✔
633

6✔
634
        var providesVersion string = `(-p|--provides)(\s+|=)` + regexp.QuoteMeta(key) + ":"
6✔
635
        reProvidesVersion := regexp.MustCompile(providesVersion)
6✔
636
        providesIndexes := reProvidesVersion.FindAllStringIndex(cmdLine, -1)
6✔
637

6✔
638
        var softareVersion string = "--software-(name|version|filesystem)"
6✔
639
        reSoftwareVersion := regexp.MustCompile(softareVersion)
6✔
640
        softwareIndexes := reSoftwareVersion.FindAllStringIndex(cmdLine, -1)
6✔
641

6✔
642
        if len(providesIndexes) == 0 {
6✔
643
                return true
×
644
        } else if len(softwareIndexes) == 0 {
8✔
645
                return false
2✔
646
        } else {
6✔
647
                return softwareIndexes[len(softwareIndexes)-1][0] >
4✔
648
                        providesIndexes[len(providesIndexes)-1][0]
4✔
649
        }
4✔
650
}
651

652
func makeClearsArtifactProvides(ctx *cli.Context) ([]string, error) {
121✔
653
        list := ctx.StringSlice(clearsProvidesFlag)
121✔
654

121✔
655
        if ctx.Bool(noDefaultClearsProvidesFlag) ||
121✔
656
                ctx.Bool(noDefaultSoftwareVersionFlag) ||
121✔
657
                ctx.Command.Name == "bootstrap-artifact" {
153✔
658
                return list, nil
32✔
659
        }
32✔
660

661
        var softwareFilesystem string
89✔
662
        if ctx.IsSet("software-filesystem") {
97✔
663
                softwareFilesystem = ctx.String("software-filesystem")
8✔
664
        } else {
89✔
665
                softwareFilesystem = "rootfs-image"
81✔
666
        }
81✔
667

668
        var softwareName string
89✔
669
        if len(ctx.String("software-name")) > 0 {
97✔
670
                softwareName = ctx.String("software-name") + "."
8✔
671
        } else if ctx.Command.Name == "rootfs-image" {
141✔
672
                softwareName = ""
52✔
673
                // "rootfs_image_checksum" is included for legacy
52✔
674
                // reasons. Previously, "rootfs_image_checksum" was the name
52✔
675
                // given to the checksum, but new artifacts follow the new dot
52✔
676
                // separated scheme, "rootfs-image.checksum", which also has the
52✔
677
                // correct dash instead of the incorrect underscore.
52✔
678
                //
52✔
679
                // "artifact_group" is included as a sane default for
52✔
680
                // rootfs-image updates. A standard rootfs-image update should
52✔
681
                // clear the group if it does not have one.
52✔
682
                if softwareFilesystem == "rootfs-image" {
102✔
683
                        list = append(list, "artifact_group", "rootfs_image_checksum")
50✔
684
                }
50✔
685
        } else if ctx.Command.Name == "module-image" {
58✔
686
                softwareName = ctx.String("type") + "."
29✔
687
        } else {
29✔
688
                return nil, errors.New(
×
689
                        "Unknown write command in makeClearsArtifactProvides(), this is a bug.",
×
690
                )
×
691
        }
×
692

693
        defaultCap := fmt.Sprintf("%s.%s*", softwareFilesystem, softwareName)
89✔
694
        for _, cap := range list {
195✔
695
                if defaultCap == cap {
108✔
696
                        // Avoid adding it twice if the default is the same as a
2✔
697
                        // specified provide.
2✔
698
                        goto dontAdd
2✔
699
                }
700
        }
701
        list = append(list, defaultCap)
87✔
702

87✔
703
dontAdd:
87✔
704
        return list, nil
89✔
705
}
706

707
func makeMetaData(ctx *cli.Context) (map[string]interface{}, map[string]interface{}, error) {
92✔
708
        var metaData map[string]interface{}
92✔
709
        var augmentMetaData map[string]interface{}
92✔
710

92✔
711
        if len(ctx.String("meta-data")) > 0 {
113✔
712
                file, err := os.Open(ctx.String("meta-data"))
21✔
713
                if err != nil {
21✔
714
                        return metaData, augmentMetaData, cli.NewExitError(err, errArtifactInvalidParameters)
×
715
                }
×
716
                defer file.Close()
21✔
717
                dec := json.NewDecoder(file)
21✔
718
                err = dec.Decode(&metaData)
21✔
719
                if err != nil {
21✔
720
                        return metaData, augmentMetaData, cli.NewExitError(err, errArtifactInvalidParameters)
×
721
                }
×
722
        }
723

724
        if len(ctx.String("augment-meta-data")) > 0 {
96✔
725
                file, err := os.Open(ctx.String("augment-meta-data"))
4✔
726
                if err != nil {
4✔
727
                        return metaData, augmentMetaData, cli.NewExitError(err, errArtifactInvalidParameters)
×
728
                }
×
729
                defer file.Close()
4✔
730
                dec := json.NewDecoder(file)
4✔
731
                err = dec.Decode(&augmentMetaData)
4✔
732
                if err != nil {
4✔
733
                        return metaData, augmentMetaData, cli.NewExitError(err, errArtifactInvalidParameters)
×
734
                }
×
735
        }
736

737
        return metaData, augmentMetaData, nil
92✔
738
}
739

740
func writeModuleImage(ctx *cli.Context) error {
51✔
741
        comp, err := artifact.NewCompressorFromId(ctx.GlobalString("compression"))
51✔
742
        if err != nil {
51✔
743
                return cli.NewExitError(
×
744
                        "compressor '"+ctx.GlobalString("compression")+"' is not supported: "+err.Error(),
×
745
                        1,
×
746
                )
×
747
        }
×
748

749
        // set the default name
750
        name := "artifact.mender"
51✔
751
        if len(ctx.String("output-path")) > 0 {
102✔
752
                name = ctx.String("output-path")
51✔
753
        }
51✔
754
        version := ctx.Int("version")
51✔
755

51✔
756
        if version == 1 {
51✔
757
                return cli.NewExitError("Mender-Artifact version 1 is not supported", 1)
×
758
        }
×
759

760
        // The device-type flag is required
761
        if len(ctx.StringSlice("device-type")) == 0 {
51✔
762
                return cli.NewExitError("The `device-type` flag is required", 1)
×
763
        }
×
764

765
        upd, err := makeUpdates(ctx)
51✔
766
        if err != nil {
51✔
767
                return err
×
768
        }
×
769

770
        var w io.Writer
51✔
771
        if name == "-" {
51✔
772
                w = os.Stdout
×
773
        } else {
51✔
774
                f, err := os.Create(name)
51✔
775
                if err != nil {
51✔
776
                        return cli.NewExitError(
×
777
                                "can not create artifact file: "+err.Error(),
×
778
                                errArtifactCreate,
×
779
                        )
×
780
                }
×
781
                defer f.Close()
51✔
782
                w = f
51✔
783
        }
784

785
        aw, err := artifactWriter(ctx, comp, w, version)
51✔
786
        if err != nil {
51✔
787
                return cli.NewExitError(err.Error(), 1)
×
788
        }
×
789

790
        scr, err := scripts(ctx.StringSlice("script"))
51✔
791
        if err != nil {
51✔
792
                return cli.NewExitError(err.Error(), 1)
×
793
        }
×
794

795
        depends := artifact.ArtifactDepends{
51✔
796
                ArtifactName:      ctx.StringSlice("artifact-name-depends"),
51✔
797
                CompatibleDevices: ctx.StringSlice("device-type"),
51✔
798
                ArtifactGroup:     ctx.StringSlice("depends-groups"),
51✔
799
        }
51✔
800

51✔
801
        provides := artifact.ArtifactProvides{
51✔
802
                ArtifactName:  ctx.String("artifact-name"),
51✔
803
                ArtifactGroup: ctx.String("provides-group"),
51✔
804
        }
51✔
805

51✔
806
        typeInfoV3, augmentTypeInfoV3, err := makeTypeInfo(ctx)
51✔
807
        if err != nil {
51✔
808
                return err
×
809
        }
×
810

811
        metaData, augmentMetaData, err := makeMetaData(ctx)
51✔
812
        if err != nil {
51✔
813
                return err
×
814
        }
×
815

816
        err = aw.WriteArtifact(
51✔
817
                &awriter.WriteArtifactArgs{
51✔
818
                        Format:            "mender",
51✔
819
                        Version:           version,
51✔
820
                        Devices:           ctx.StringSlice("device-type"),
51✔
821
                        Name:              ctx.String("artifact-name"),
51✔
822
                        Updates:           upd,
51✔
823
                        Scripts:           scr,
51✔
824
                        Depends:           &depends,
51✔
825
                        Provides:          &provides,
51✔
826
                        TypeInfoV3:        typeInfoV3,
51✔
827
                        MetaData:          metaData,
51✔
828
                        AugmentTypeInfoV3: augmentTypeInfoV3,
51✔
829
                        AugmentMetaData:   augmentMetaData,
51✔
830
                })
51✔
831
        if err != nil {
51✔
832
                return cli.NewExitError(err.Error(), 1)
×
833
        }
×
834
        return nil
51✔
835
}
836

837
func extractKeyValues(params []string) (*map[string]string, error) {
648✔
838
        var keyValues *map[string]string
648✔
839
        if len(params) > 0 {
724✔
840
                keyValues = &map[string]string{}
76✔
841
                for _, arg := range params {
232✔
842
                        split := strings.SplitN(arg, ":", 2)
156✔
843
                        if len(split) != 2 {
156✔
844
                                return nil, cli.NewExitError(
×
845
                                        fmt.Sprintf("argument must have a delimiting colon: %s", arg),
×
846
                                        errArtifactInvalidParameters)
×
847
                        }
×
848
                        (*keyValues)[split[0]] = split[1]
156✔
849
                }
850
        }
851
        return keyValues, nil
648✔
852
}
853

854
// SSH to remote host and dump rootfs snapshot to a local temporary file.
855
func getDeviceSnapshot(c *cli.Context) (string, error) {
×
856

×
857
        const sshInitMagic = "Initializing snapshot..."
×
858
        var userAtHost string
×
859
        var sigChan chan os.Signal
×
860
        var errChan chan error
×
861
        ctx, cancel := context.WithCancel(context.Background())
×
862
        defer cancel()
×
863
        port := "22"
×
864
        host := strings.TrimPrefix(c.String("file"), "ssh://")
×
865

×
866
        if remotePort := strings.Split(host, ":"); len(remotePort) == 2 {
×
867
                port = remotePort[1]
×
868
                userAtHost = remotePort[0]
×
869
        } else {
×
870
                userAtHost = host
×
871
        }
×
872

873
        // Prepare command-line arguments
874
        args := c.StringSlice("ssh-args")
×
875
        // Check if port is specified explicitly with the --ssh-args flag
×
876
        addPort := true
×
877
        for _, arg := range args {
×
878
                if strings.Contains(arg, "-p") {
×
879
                        addPort = false
×
880
                        break
×
881
                }
882
        }
883
        if addPort {
×
884
                args = append(args, "-p", port)
×
885
        }
×
886
        args = append(args, userAtHost)
×
887
        // First echo to stdout such that we know when ssh connection is
×
888
        // established (password prompt is written to /dev/tty directly,
×
889
        // and hence impossible to detect).
×
890
        // When user id is 0 do not bother with sudo.
×
891
        args = append(
×
892
                args,
×
893
                "/bin/sh",
×
894
                "-c",
×
895
                `'[ $(id -u) -eq 0 ] || sudo_cmd="sudo -S"`+
×
896
                        `; if which mender-snapshot 1> /dev/null`+
×
897
                        `; then $sudo_cmd /bin/sh -c "echo `+sshInitMagic+`; mender-snapshot dump" | cat`+
×
898
                        `; elif which mender 1> /dev/null`+
×
899
                        `; then $sudo_cmd /bin/sh -c "echo `+sshInitMagic+`; mender snapshot dump" | cat`+
×
900
                        `; else echo "Mender not found: Please check that Mender is installed" >&2 &&`+
×
901
                        `exit 1; fi'`,
×
902
        )
×
903

×
904
        cmd := exec.Command("ssh", args...)
×
905

×
906
        // Simply connect stdin/stderr
×
907
        cmd.Stdin = os.Stdin
×
908
        cmd.Stderr = os.Stderr
×
909
        stdout, err := cmd.StdoutPipe()
×
910
        if err != nil {
×
911
                return "", errors.New("Error redirecting stdout on exec")
×
912
        }
×
913

914
        // Create tempfile for storing the snapshot
NEW
915
        f, err := os.CreateTemp("", "rootfs.tmp")
×
916
        if err != nil {
×
917
                return "", err
×
918
        }
×
919
        filePath := f.Name()
×
920

×
921
        defer removeOnPanic(filePath)
×
922
        defer f.Close()
×
923

×
924
        // Disable tty echo before starting
×
925
        term, err := util.DisableEcho(int(os.Stdin.Fd()))
×
926
        if err == nil {
×
927
                sigChan = make(chan os.Signal, 1)
×
928
                errChan = make(chan error, 1)
×
929
                // Make sure that echo is enabled if the process gets
×
930
                // interrupted
×
931
                signal.Notify(sigChan)
×
932
                go util.EchoSigHandler(ctx, sigChan, errChan, term)
×
933
        } else if err != syscall.ENOTTY {
×
934
                return "", err
×
935
        }
×
936

937
        if err := cmd.Start(); err != nil {
×
938
                return "", err
×
939
        }
×
940

941
        // Wait for 60 seconds for ssh to establish connection
942
        err = waitForBufferSignal(stdout, os.Stdout, sshInitMagic, 2*time.Minute)
×
943
        if err != nil {
×
944
                _ = cmd.Process.Kill()
×
945
                return "", errors.Wrap(err,
×
946
                        "Error waiting for ssh session to be established.")
×
947
        }
×
948

949
        _, err = recvSnapshot(f, stdout)
×
950
        if err != nil {
×
951
                _ = cmd.Process.Kill()
×
952
                return "", err
×
953
        }
×
954

955
        if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
×
956
                return "", errors.New("SSH session closed unexpectedly")
×
957
        }
×
958

959
        if err = cmd.Wait(); err != nil {
×
960
                return "", errors.Wrap(err,
×
961
                        "SSH session closed with error")
×
962
        }
×
963

964
        if sigChan != nil {
×
965
                // Wait for signal handler to execute
×
966
                signal.Stop(sigChan)
×
967
                cancel()
×
968
                err = <-errChan
×
969
        }
×
970

971
        return filePath, err
×
972
}
973
func showProvides(c *cli.Context) (map[string]string, error) {
×
974
        var userAtHost string
×
975
        providesMap := make(map[string]string)
×
976
        port := "22"
×
977
        host := strings.TrimPrefix(c.String("file"), "ssh://")
×
978

×
979
        if remotePort := strings.Split(host, ":"); len(remotePort) == 2 {
×
980
                port = remotePort[1]
×
981
                userAtHost = remotePort[0]
×
982
        } else {
×
983
                userAtHost = host
×
984
        }
×
985

986
        args := c.StringSlice("ssh-args")
×
987
        // Check if port is specified explicitly with the --ssh-args flag
×
988
        addPort := true
×
989
        for _, arg := range args {
×
990
                if strings.Contains(arg, "-p") {
×
991
                        addPort = false
×
992
                        break
×
993
                }
994
        }
995
        if addPort {
×
996
                args = append(args, "-p", port)
×
997
        }
×
998
        args = append(args, userAtHost)
×
999

×
1000
        providesArgs := ` 'if which mender-update 1> /dev/null` +
×
1001
                `; then mender-update show-provides` +
×
1002
                `; elif which mender 1> /dev/null` +
×
1003
                `; then mender show-provides` +
×
1004
                `; else echo "Mender not found: Please check that Mender is installed" >&2 &&` +
×
1005
                ` exit 1; fi'`
×
1006

×
1007
        args = append(
×
1008
                args,
×
1009
                "/bin/sh",
×
1010
                "-c",
×
1011
                providesArgs)
×
1012

×
1013
        cmd := exec.Command("ssh", args...)
×
1014

×
1015
        stdout, err := cmd.CombinedOutput()
×
1016

×
1017
        if err != nil {
×
1018
                return nil, err
×
1019
        }
×
1020
        if len(stdout) == 0 {
×
1021
                return nil, nil
×
1022
        }
×
1023
        provides := strings.Split(string(stdout), "\n")
×
1024

×
1025
        for _, p := range provides {
×
1026
                if p == "" || !strings.HasPrefix(p, "rootfs-image.") {
×
1027
                        continue
×
1028
                }
1029
                info := strings.Split(p, "=")
×
1030
                if len(info) != 2 {
×
1031
                        continue
×
1032
                }
1033
                providesMap[info[0]] = info[1]
×
1034
        }
1035
        return providesMap, nil
×
1036
}
1037

1038
// Reads from src waiting for the string specified by signal, writing all other
1039
// output appearing at src to sink. The function returns an error if occurs
1040
// reading from the stream or the deadline exceeds.
1041
func waitForBufferSignal(src io.Reader, sink io.Writer,
1042
        signal string, deadline time.Duration) error {
×
1043

×
1044
        var err error
×
1045
        errChan := make(chan error)
×
1046

×
1047
        go func() {
×
1048
                stdoutRdr := bufio.NewReader(src)
×
1049
                for {
×
1050
                        line, err := stdoutRdr.ReadString('\n')
×
1051
                        if err != nil {
×
1052
                                errChan <- err
×
1053
                                break
×
1054
                        }
1055
                        if strings.Contains(line, signal) {
×
1056
                                errChan <- nil
×
1057
                                break
×
1058
                        }
1059
                        _, err = sink.Write([]byte(line + "\n"))
×
1060
                        if err != nil {
×
1061
                                errChan <- err
×
1062
                                break
×
1063
                        }
1064
                }
1065
        }()
1066

1067
        select {
×
1068
        case err = <-errChan:
×
1069
                // Error from goroutine
1070
        case <-time.After(deadline):
×
1071
                err = errors.New("Input deadline exceeded")
×
1072
        }
1073
        return err
×
1074
}
1075

1076
// Performs the same operation as io.Copy while at the same time prining
1077
// the number of bytes written at any time.
1078
func recvSnapshot(dst io.Writer, src io.Reader) (int64, error) {
×
1079
        buf := make([]byte, 1024*1024*32)
×
1080
        var written int64
×
1081
        for {
×
1082
                nr, err := src.Read(buf)
×
1083
                if err == io.EOF {
×
1084
                        fmt.Println()
×
1085
                        break
×
1086
                } else if err != nil {
×
1087
                        return written, errors.Wrap(err,
×
1088
                                "Error receiving snapshot from device")
×
1089
                }
×
1090
                nw, err := dst.Write(buf[:nr])
×
1091
                if err != nil {
×
1092
                        return written, errors.Wrap(err,
×
1093
                                "Error storing snapshot locally")
×
1094
                } else if nw < nr {
×
1095
                        return written, io.ErrShortWrite
×
1096
                }
×
1097
                written += int64(nw)
×
1098
        }
1099
        return written, nil
×
1100
}
1101

1102
func removeOnPanic(filename string) {
×
1103
        if r := recover(); r != nil {
×
1104
                err := os.Remove(filename)
×
1105
                if err != nil {
×
1106
                        switch v := r.(type) {
×
1107
                        case string:
×
1108
                                err = errors.Wrap(errors.New(v), err.Error())
×
1109
                                panic(err)
×
1110
                        case error:
×
1111
                                err = errors.Wrap(v, err.Error())
×
1112
                                panic(err)
×
1113
                        default:
×
1114
                                panic(r)
×
1115
                        }
1116
                }
1117
                panic(r)
×
1118
        }
1119
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc