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

mendersoftware / mender-artifact / 2085858528

07 Oct 2025 02:29PM UTC coverage: 76.3% (+0.2%) from 76.088%
2085858528

Pull #754

gitlab-ci

lluiscampos
wip-refact-TODO-RENAME
Pull Request #754: MEN-8567: Warn and optionally fail on large Artifact sizes

111 of 123 new or added lines in 3 files covered. (90.24%)

2 existing lines in 1 file now uncovered.

6091 of 7983 relevant lines covered (76.3%)

141.39 hits per line

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

61.38
/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) {
203✔
41
        chk := artifact.NewWriterChecksum(io.Discard)
203✔
42
        payload, err := os.Open(rootfsFilename)
203✔
43
        if err != nil {
205✔
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 {
201✔
50
                return cli.NewExitError("Failed to generate the checksum for the payload", 1)
×
51
        }
×
52
        checksum := string(chk.Checksum())
201✔
53

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

59
        Log.Debugf("Adding the `%s`: %q to Artifact provides", checksumKey, checksum)
201✔
60
        if typeInfo == nil {
201✔
61
                return errors.New("Type-info is unitialized")
×
62
        }
×
63
        if typeInfo.ArtifactProvides == nil {
203✔
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 {
199✔
70
                typeInfo.ArtifactProvides[checksumKey] = checksum
199✔
71
        }
199✔
72
        return nil
201✔
73
}
74

75
func validateInput(c *cli.Context) error {
98✔
76
        // Version 2 and 3 validation.
98✔
77
        fileMissing := false
98✔
78
        if c.Command.Name != "bootstrap-artifact" {
192✔
79
                if len(c.String("file")) == 0 {
94✔
80
                        fileMissing = true
×
81
                }
×
82
        }
83
        if len(c.StringSlice("device-type")) == 0 ||
98✔
84
                len(c.String("artifact-name")) == 0 || fileMissing {
98✔
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 {
100✔
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
96✔
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 {
94✔
247
        comp, err := artifact.NewCompressorFromId(c.GlobalString("compression"))
94✔
248
        if err != nil {
94✔
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 {
96✔
256
                Log.Error(err.Error())
2✔
257
                return err
2✔
258
        }
2✔
259

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

92✔
268
        Log.Debugf("creating artifact [%s], version: %d", name, version)
92✔
269
        rootfsFilename := c.String("file")
92✔
270
        if strings.HasPrefix(rootfsFilename, "ssh://") {
92✔
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
92✔
283
        switch version {
92✔
284
        case 2:
2✔
285
                h = handlers.NewRootfsV2(rootfsFilename)
2✔
286
        case 3:
84✔
287
                h = handlers.NewRootfsV3(rootfsFilename)
84✔
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{
86✔
296
                Updates: []handlers.Composer{h},
86✔
297
        }
86✔
298

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

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

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

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

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

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

346
        if !c.Bool("no-checksum-provide") {
160✔
347
                legacy := c.Bool("legacy-rootfs-image-checksum")
78✔
348
                if err = writeRootfsImageChecksum(rootfsFilename, typeInfoV3, legacy); err != nil {
78✔
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") {
164✔
356
                ctx, cancel := context.WithCancel(context.Background())
82✔
357
                go reportProgress(ctx, aw.State)
82✔
358
                defer cancel()
82✔
359
                aw.ProgressWriter = utils.NewProgressWriter()
82✔
360
        }
82✔
361

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

378
        return checkArtifactSizeLimits(name, c)
82✔
379
}
380

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

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

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

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

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

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

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

466
        return upd, nil
55✔
467
}
468

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

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

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

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

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

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

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

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

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

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

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

558
func getSoftwareVersion(
559
        artifactName,
560
        softwareFilesystem,
561
        softwareName,
562
        softwareNameDefault,
563
        softwareVersion string,
564
        noDefaultSoftwareVersion bool,
565
) map[string]string {
155✔
566
        result := map[string]string{}
155✔
567
        softwareVersionName := "rootfs-image"
155✔
568
        if softwareFilesystem != "" {
171✔
569
                softwareVersionName = softwareFilesystem
16✔
570
        }
16✔
571
        if !noDefaultSoftwareVersion {
282✔
572
                if softwareName == "" {
242✔
573
                        softwareName = softwareNameDefault
115✔
574
                }
115✔
575
                if softwareVersion == "" {
242✔
576
                        softwareVersion = artifactName
115✔
577
                }
115✔
578
        }
579
        if softwareName != "" {
210✔
580
                softwareVersionName += fmt.Sprintf(".%s", softwareName)
55✔
581
        }
55✔
582
        if softwareVersionName != "" && softwareVersion != "" {
286✔
583
                result[softwareVersionName+".version"] = softwareVersion
131✔
584
        }
131✔
585
        return result
155✔
586
}
587

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

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

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

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

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

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

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

658
        var softwareFilesystem string
109✔
659
        if ctx.IsSet("software-filesystem") {
117✔
660
                softwareFilesystem = ctx.String("software-filesystem")
8✔
661
        } else {
109✔
662
                softwareFilesystem = "rootfs-image"
101✔
663
        }
101✔
664

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

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

107✔
700
dontAdd:
107✔
701
        return list, nil
109✔
702
}
703

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

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

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

734
        return metaData, augmentMetaData, nil
96✔
735
}
736

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

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

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

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

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

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

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

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

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

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

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

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

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

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

839
        return checkArtifactSizeLimits(name, ctx)
55✔
840
}
841

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

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

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

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

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

899
        if err != nil {
×
900
                return
×
901
        }
×
902

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

909
        err = command.EndSSHCommand()
×
910
        if err != nil {
×
911
                return
×
912
        }
×
913

914
        filePath = f.Name()
×
915
        return
×
916
}
917

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

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

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

946
        if err != nil {
×
947
                return
×
948
        }
×
949

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

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

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

995
func checkArtifactSizeLimits(name string, c *cli.Context) error {
137✔
996
        if name != "-" {
274✔
997
                if err := CheckArtifactSize(name, c); err != nil {
143✔
998
                        return cli.NewExitError(err.Error(), errArtifactCreate)
6✔
999
                }
6✔
NEW
1000
        } else {
×
NEW
1001
                if c.String("max-payload-size") != "" || c.String("warn-payload-size") != "" {
×
NEW
1002
                        Log.Info("Note: Payload size limits are not enforced when writing to stdout")
×
NEW
1003
                }
×
1004
        }
1005
        return nil
131✔
1006
}
1007

1008
func removeOnPanic(filename string) {
×
1009
        if r := recover(); r != nil {
×
1010
                err := os.Remove(filename)
×
1011
                if err != nil {
×
1012
                        switch v := r.(type) {
×
1013
                        case string:
×
1014
                                err = errors.Wrap(errors.New(v), err.Error())
×
1015
                                panic(err)
×
1016
                        case error:
×
1017
                                err = errors.Wrap(v, err.Error())
×
1018
                                panic(err)
×
1019
                        default:
×
1020
                                panic(r)
×
1021
                        }
1022
                }
1023
                panic(r)
×
1024
        }
1025
}
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