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

mendersoftware / mender-artifact / 1980017761

12 Aug 2025 02:01PM UTC coverage: 76.088% (-0.1%) from 76.223%
1980017761

push

gitlab-ci

web-flow
Merge pull request #728 from michalkopczan/MEN-8428-mender-artifact-does-not-reenable-echo

fix: mender-artifact does not reenable echo on ssh error

0 of 50 new or added lines in 3 files covered. (0.0%)

4 existing lines in 2 files now uncovered.

5982 of 7862 relevant lines covered (76.09%)

137.91 hits per line

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

61.4
/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
        "regexp"
24
        "strings"
25

26
        "io"
27

28
        "github.com/pkg/errors"
29
        "github.com/urfave/cli"
30

31
        "github.com/mendersoftware/mender-artifact/artifact"
32
        "github.com/mendersoftware/mender-artifact/artifact/stage"
33
        "github.com/mendersoftware/mender-artifact/awriter"
34
        "github.com/mendersoftware/mender-artifact/cli/util"
35
        "github.com/mendersoftware/mender-artifact/handlers"
36
        "github.com/mendersoftware/mender-artifact/utils"
37
)
38

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

185✔
54
        checksumKey := "rootfs-image.checksum"
185✔
55
        if legacy {
187✔
56
                checksumKey = "rootfs_image_checksum"
2✔
57
        }
2✔
58

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

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

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

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

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

131
        }
132
        if err != nil {
×
133
                return rootfsFilename, cli.NewExitError("runFsck error: "+err.Error(), errArtifactCreate)
×
134
        }
×
135

136
        return rootfsFilename, nil
×
137
}
138

139
func makeEmptyUpdates(ctx *cli.Context) (*awriter.Updates, error) {
4✔
140
        handler := handlers.NewBootstrapArtifact()
4✔
141

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

150
        upd := &awriter.Updates{
4✔
151
                Updates: []handlers.Composer{handler},
4✔
152
        }
4✔
153
        return upd, nil
4✔
154
}
155

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

165
        if err := validateInput(c); err != nil {
4✔
166
                Log.Error(err.Error())
×
167
                return err
×
168
        }
×
169

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

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

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

194
        aw, err := artifactWriter(c, comp, w, version)
4✔
195
        if err != nil {
4✔
196
                return cli.NewExitError(err.Error(), 1)
×
197
        }
×
198

199
        depends := artifact.ArtifactDepends{
4✔
200
                ArtifactName:      c.StringSlice("artifact-name-depends"),
4✔
201
                CompatibleDevices: c.StringSlice("device-type"),
4✔
202
                ArtifactGroup:     c.StringSlice("depends-groups"),
4✔
203
        }
4✔
204

4✔
205
        provides := artifact.ArtifactProvides{
4✔
206
                ArtifactName:  c.String("artifact-name"),
4✔
207
                ArtifactGroup: c.String("provides-group"),
4✔
208
        }
4✔
209

4✔
210
        upd, err := makeEmptyUpdates(c)
4✔
211
        if err != nil {
4✔
212
                return err
×
213
        }
×
214

215
        typeInfoV3, _, err := makeTypeInfo(c)
4✔
216
        if err != nil {
4✔
217
                return err
×
218
        }
×
219

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

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

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

255
        if err := validateInput(c); err != nil {
80✔
256
                Log.Error(err.Error())
2✔
257
                return err
2✔
258
        }
2✔
259

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

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

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

295
        upd := &awriter.Updates{
70✔
296
                Updates: []handlers.Composer{h},
70✔
297
        }
70✔
298

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

314
        aw, err := artifactWriter(c, comp, w, version)
70✔
315
        if err != nil {
72✔
316
                return cli.NewExitError(err.Error(), 1)
2✔
317
        }
2✔
318

319
        scr, err := scripts(c.StringSlice("script"))
68✔
320
        if err != nil {
70✔
321
                return cli.NewExitError(err.Error(), 1)
2✔
322
        }
2✔
323

324
        depends := artifact.ArtifactDepends{
66✔
325
                ArtifactName:      c.StringSlice("artifact-name-depends"),
66✔
326
                CompatibleDevices: c.StringSlice("device-type"),
66✔
327
                ArtifactGroup:     c.StringSlice("depends-groups"),
66✔
328
        }
66✔
329

66✔
330
        provides := artifact.ArtifactProvides{
66✔
331
                ArtifactName:  c.String("artifact-name"),
66✔
332
                ArtifactGroup: c.String("provides-group"),
66✔
333
        }
66✔
334

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

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

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

380
func reportProgress(c context.Context, state chan string) {
121✔
381
        fmt.Fprintln(os.Stderr, "Writing Artifact...")
121✔
382
        str := fmt.Sprintf("%-20s\t", <-state)
121✔
383
        fmt.Fprint(os.Stderr, str)
121✔
384
        for {
724✔
385
                select {
603✔
386
                case str = <-state:
483✔
387
                        if str == stage.Data {
604✔
388
                                fmt.Fprintf(os.Stderr, "\033[1;32m\u2713\033[0m\n")
121✔
389
                                fmt.Fprintln(os.Stderr, "Payload")
121✔
390
                        } else {
484✔
391
                                fmt.Fprintf(os.Stderr, "\033[1;32m\u2713\033[0m\n")
363✔
392
                                str = fmt.Sprintf("%-20s\t", str)
363✔
393
                                fmt.Fprint(os.Stderr, str)
363✔
394
                        }
363✔
395
                case <-c.Done():
121✔
396
                        return
121✔
397
                }
398
        }
399
}
400

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

417
func makeUpdates(ctx *cli.Context) (*awriter.Updates, error) {
51✔
418
        version := ctx.Int("version")
51✔
419

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

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

446
        upd := &awriter.Updates{
51✔
447
                Updates: []handlers.Composer{handler},
51✔
448
        }
51✔
449

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

465
        return upd, nil
51✔
466
}
467

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

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

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

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

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

516
        clearsArtifactProvides, err := makeClearsArtifactProvides(ctx)
121✔
517
        if err != nil {
121✔
518
                return nil, nil, err
×
519
        }
×
520

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

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

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

547
        augmentType := ctx.String("augment-type")
4✔
548
        augmentTypeInfoV3 := &artifact.TypeInfoV3{
4✔
549
                Type:             &augmentType,
4✔
550
                ArtifactDepends:  augmentTypeInfoDepends,
4✔
551
                ArtifactProvides: augmentTypeInfoProvides,
4✔
552
        }
4✔
553

4✔
554
        return typeInfoV3, augmentTypeInfoV3, nil
4✔
555
}
556

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

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

626
func softwareVersionOverridesProvides(ctx *cli.Context, key string) bool {
6✔
627
        mainCtx := ctx.Parent().Parent()
6✔
628
        cmdLine := strings.Join(mainCtx.Args(), " ")
6✔
629

6✔
630
        var providesVersion string = `(-p|--provides)(\s+|=)` + regexp.QuoteMeta(key) + ":"
6✔
631
        reProvidesVersion := regexp.MustCompile(providesVersion)
6✔
632
        providesIndexes := reProvidesVersion.FindAllStringIndex(cmdLine, -1)
6✔
633

6✔
634
        var softareVersion string = "--software-(name|version|filesystem)"
6✔
635
        reSoftwareVersion := regexp.MustCompile(softareVersion)
6✔
636
        softwareIndexes := reSoftwareVersion.FindAllStringIndex(cmdLine, -1)
6✔
637

6✔
638
        if len(providesIndexes) == 0 {
6✔
639
                return true
×
640
        } else if len(softwareIndexes) == 0 {
8✔
641
                return false
2✔
642
        } else {
6✔
643
                return softwareIndexes[len(softwareIndexes)-1][0] >
4✔
644
                        providesIndexes[len(providesIndexes)-1][0]
4✔
645
        }
4✔
646
}
647

648
func makeClearsArtifactProvides(ctx *cli.Context) ([]string, error) {
121✔
649
        list := ctx.StringSlice(clearsProvidesFlag)
121✔
650

121✔
651
        if ctx.Bool(noDefaultClearsProvidesFlag) ||
121✔
652
                ctx.Bool(noDefaultSoftwareVersionFlag) ||
121✔
653
                ctx.Command.Name == "bootstrap-artifact" {
153✔
654
                return list, nil
32✔
655
        }
32✔
656

657
        var softwareFilesystem string
89✔
658
        if ctx.IsSet("software-filesystem") {
97✔
659
                softwareFilesystem = ctx.String("software-filesystem")
8✔
660
        } else {
89✔
661
                softwareFilesystem = "rootfs-image"
81✔
662
        }
81✔
663

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

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

87✔
699
dontAdd:
87✔
700
        return list, nil
89✔
701
}
702

703
func makeMetaData(ctx *cli.Context) (map[string]interface{}, map[string]interface{}, error) {
92✔
704
        var metaData map[string]interface{}
92✔
705
        var augmentMetaData map[string]interface{}
92✔
706

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

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

733
        return metaData, augmentMetaData, nil
92✔
734
}
735

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

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

51✔
752
        if version == 1 {
51✔
753
                return cli.NewExitError("Mender-Artifact version 1 is not supported", 1)
×
754
        }
×
755

756
        // The device-type flag is required
757
        if len(ctx.StringSlice("device-type")) == 0 {
51✔
758
                return cli.NewExitError("The `device-type` flag is required", 1)
×
759
        }
×
760

761
        upd, err := makeUpdates(ctx)
51✔
762
        if err != nil {
51✔
763
                return err
×
764
        }
×
765

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

781
        aw, err := artifactWriter(ctx, comp, w, version)
51✔
782
        if err != nil {
51✔
783
                return cli.NewExitError(err.Error(), 1)
×
784
        }
×
785

786
        scr, err := scripts(ctx.StringSlice("script"))
51✔
787
        if err != nil {
51✔
788
                return cli.NewExitError(err.Error(), 1)
×
789
        }
×
790

791
        depends := artifact.ArtifactDepends{
51✔
792
                ArtifactName:      ctx.StringSlice("artifact-name-depends"),
51✔
793
                CompatibleDevices: ctx.StringSlice("device-type"),
51✔
794
                ArtifactGroup:     ctx.StringSlice("depends-groups"),
51✔
795
        }
51✔
796

51✔
797
        provides := artifact.ArtifactProvides{
51✔
798
                ArtifactName:  ctx.String("artifact-name"),
51✔
799
                ArtifactGroup: ctx.String("provides-group"),
51✔
800
        }
51✔
801

51✔
802
        typeInfoV3, augmentTypeInfoV3, err := makeTypeInfo(ctx)
51✔
803
        if err != nil {
51✔
804
                return err
×
805
        }
×
806

807
        metaData, augmentMetaData, err := makeMetaData(ctx)
51✔
808
        if err != nil {
51✔
809
                return err
×
810
        }
×
811

812
        if !ctx.Bool("no-progress") {
102✔
813
                ctx, cancel := context.WithCancel(context.Background())
51✔
814
                go reportProgress(ctx, aw.State)
51✔
815
                defer cancel()
51✔
816
                aw.ProgressWriter = utils.NewProgressWriter()
51✔
817
        }
51✔
818

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

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

857
// SSH to remote host and dump rootfs snapshot to a local temporary file.
NEW
858
func getDeviceSnapshot(c *cli.Context) (filePath string, err error) {
×
NEW
859
        filePath = ""
×
860
        const sshConnectedToken = "Initializing snapshot..."
×
861
        ctx, cancel := context.WithCancel(context.Background())
×
862
        defer cancel()
×
863

×
864
        // Create tempfile for storing the snapshot
×
865
        f, err := os.CreateTemp("", "rootfs.tmp")
×
866
        if err != nil {
×
NEW
867
                return
×
868
        }
×
869

NEW
870
        defer removeOnPanic(f.Name())
×
871
        defer f.Close()
×
872
        // // First echo to stdout such that we know when ssh connection is
×
873
        // // established (password prompt is written to /dev/tty directly,
×
874
        // // and hence impossible to detect).
×
875
        // // When user id is 0 do not bother with sudo.
×
876
        snapshotArgs := `'[ $(id -u) -eq 0 ] || sudo_cmd="sudo -S"` +
×
877
                `; if which mender-snapshot 1> /dev/null` +
×
878
                `; then $sudo_cmd /bin/sh -c "echo ` + sshConnectedToken + `; mender-snapshot dump" | cat` +
×
879
                `; elif which mender 1> /dev/null` +
×
880
                `; then $sudo_cmd /bin/sh -c "echo ` + sshConnectedToken + `; mender snapshot dump" | cat` +
×
881
                `; else echo "Mender not found: Please check that Mender is installed" >&2 &&` +
×
882
                `exit 1; fi'`
×
883

×
884
        command, err := util.StartSSHCommand(c,
×
885
                ctx,
×
886
                cancel,
×
887
                snapshotArgs,
×
888
                sshConnectedToken,
×
889
        )
×
NEW
890
        defer func() {
×
NEW
891
                if cleanupErr := command.WaitForEchoRestore(); cleanupErr != nil {
×
NEW
892
                        filePath = ""
×
NEW
893
                        err = cleanupErr
×
NEW
894
                }
×
895
        }()
896

897
        if err != nil {
×
NEW
898
                return
×
899
        }
×
900

901
        _, err = recvSnapshot(f, command.Stdout)
×
902
        if err != nil {
×
903
                _ = command.Cmd.Process.Kill()
×
NEW
904
                return
×
905
        }
×
906

907
        err = command.EndSSHCommand()
×
908
        if err != nil {
×
NEW
909
                return
×
910
        }
×
911

NEW
912
        filePath = f.Name()
×
NEW
913
        return
×
914
}
915

NEW
916
func showProvides(c *cli.Context) (providesMap map[string]string, err error) {
×
917
        const sshConnectedToken = "Initializing show-provides..."
×
918
        ctx, cancel := context.WithCancel(context.Background())
×
919
        defer cancel()
×
NEW
920
        providesMap = nil
×
NEW
921
        tmpMap := make(map[string]string)
×
922

×
923
        providesArgs := `'[ $(id -u) -eq 0 ] || sudo_cmd="sudo -S"` +
×
924
                `; if which mender-update 1> /dev/null` +
×
925
                `; then $sudo_cmd /bin/sh -c "echo ` + sshConnectedToken + `;mender-update show-provides"` +
×
926
                `; elif which mender 1> /dev/null` +
×
927
                `; then $sudo_cmd /bin/sh -c "echo ` + sshConnectedToken + `;mender show-provides"` +
×
928
                `; else echo "Mender not found: Please check that Mender is installed" >&2 &&` +
×
929
                ` exit 1; fi'`
×
930

×
931
        command, err := util.StartSSHCommand(c,
×
932
                ctx,
×
933
                cancel,
×
934
                providesArgs,
×
935
                sshConnectedToken,
×
936
        )
×
NEW
937
        defer func() {
×
NEW
938
                if cleanupErr := command.WaitForEchoRestore(); cleanupErr != nil {
×
NEW
939
                        providesMap = nil
×
NEW
940
                        err = cleanupErr
×
NEW
941
                }
×
942
        }()
943

944
        if err != nil {
×
NEW
945
                return
×
946
        }
×
947

948
        scanner := bufio.NewScanner(command.Stdout)
×
949
        for scanner.Scan() {
×
950
                line := scanner.Text()
×
951
                if strings.HasPrefix(line, "rootfs-image.") {
×
952
                        parts := strings.SplitN(line, "=", 2)
×
953
                        if len(parts) == 2 {
×
NEW
954
                                tmpMap[parts[0]] = parts[1]
×
955
                        }
×
956
                }
957
        }
958

959
        err = command.EndSSHCommand()
×
960
        if err != nil {
×
NEW
961
                return
×
962
        }
×
NEW
963
        providesMap = tmpMap
×
NEW
964
        return
×
965
}
966

967
// Performs the same operation as io.Copy while at the same time prining
968
// the number of bytes written at any time.
969
func recvSnapshot(dst io.Writer, src io.Reader) (int64, error) {
×
970
        buf := make([]byte, 1024*1024*32)
×
971
        var written int64
×
972
        for {
×
973
                nr, err := src.Read(buf)
×
974
                if err == io.EOF {
×
975
                        fmt.Println()
×
976
                        break
×
977
                } else if err != nil {
×
978
                        return written, errors.Wrap(err,
×
979
                                "Error receiving snapshot from device")
×
980
                }
×
981
                nw, err := dst.Write(buf[:nr])
×
982
                if err != nil {
×
983
                        return written, errors.Wrap(err,
×
984
                                "Error storing snapshot locally")
×
985
                } else if nw < nr {
×
986
                        return written, io.ErrShortWrite
×
987
                }
×
988
                written += int64(nw)
×
989
        }
990
        return written, nil
×
991
}
992

993
func removeOnPanic(filename string) {
×
994
        if r := recover(); r != nil {
×
995
                err := os.Remove(filename)
×
996
                if err != nil {
×
997
                        switch v := r.(type) {
×
998
                        case string:
×
999
                                err = errors.Wrap(errors.New(v), err.Error())
×
1000
                                panic(err)
×
1001
                        case error:
×
1002
                                err = errors.Wrap(v, err.Error())
×
1003
                                panic(err)
×
1004
                        default:
×
1005
                                panic(r)
×
1006
                        }
1007
                }
1008
                panic(r)
×
1009
        }
1010
}
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