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

mendersoftware / deployments / 1072216342

14 Nov 2023 12:49PM UTC coverage: 79.663% (+1.8%) from 77.876%
1072216342

Pull #961

gitlab-ci

kjaskiewiczz
test(mongo): move release related tests to separate file

Changelog: Title
Ticket: None

Signed-off-by: Krzysztof Jaskiewicz <krzysztof.jaskiewicz@northern.tech>
Pull Request #961: add support for bulk removal of releases by names

86 of 98 new or added lines in 6 files covered. (87.76%)

11 existing lines in 1 file now uncovered.

8046 of 10100 relevant lines covered (79.66%)

33.85 hits per line

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

77.37
/app/app.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 app
16

17
import (
18
        "bytes"
19
        "context"
20
        "encoding/json"
21
        "io"
22
        "path"
23
        "reflect"
24
        "strings"
25
        "time"
26

27
        "github.com/google/uuid"
28
        "github.com/pkg/errors"
29

30
        "github.com/mendersoftware/go-lib-micro/identity"
31
        "github.com/mendersoftware/go-lib-micro/log"
32
        "github.com/mendersoftware/mender-artifact/areader"
33
        "github.com/mendersoftware/mender-artifact/artifact"
34
        "github.com/mendersoftware/mender-artifact/awriter"
35
        "github.com/mendersoftware/mender-artifact/handlers"
36

37
        "github.com/mendersoftware/deployments/client/inventory"
38
        "github.com/mendersoftware/deployments/client/reporting"
39
        "github.com/mendersoftware/deployments/client/workflows"
40
        "github.com/mendersoftware/deployments/model"
41
        "github.com/mendersoftware/deployments/storage"
42
        "github.com/mendersoftware/deployments/store"
43
        "github.com/mendersoftware/deployments/store/mongo"
44
        "github.com/mendersoftware/deployments/utils"
45
)
46

47
const (
48
        ArtifactContentType              = "application/vnd.mender-artifact"
49
        ArtifactConfigureProvides        = "data-partition.mender-configure.version"
50
        ArtifactConfigureProvidesCleared = "data-partition.mender-configure.*"
51

52
        DefaultUpdateDownloadLinkExpire  = 24 * time.Hour
53
        DefaultImageGenerationLinkExpire = 7 * 24 * time.Hour
54
        PerPageInventoryDevices          = 512
55
        InventoryGroupScope              = "system"
56
        InventoryIdentityScope           = "identity"
57
        InventoryGroupAttributeName      = "group"
58
        InventoryStatusAttributeName     = "status"
59
        InventoryStatusAccepted          = "accepted"
60

61
        fileSuffixTmp = ".tmp"
62

63
        inprogressIdleTime = time.Hour
64
)
65

66
var (
67
        ArtifactConfigureType = "mender-configure"
68
)
69

70
// Errors expected from App interface
71
var (
72
        // images
73
        ErrImageMetaNotFound                = errors.New("Image metadata is not found")
74
        ErrModelMultipartUploadMsgMalformed = errors.New("Multipart upload message malformed")
75
        ErrModelMissingInputMetadata        = errors.New("Missing input metadata")
76
        ErrModelMissingInputArtifact        = errors.New("Missing input artifact")
77
        ErrModelInvalidMetadata             = errors.New("Metadata invalid")
78
        ErrModelArtifactNotUnique           = errors.New("Artifact not unique")
79
        ErrModelImageInActiveDeployment     = errors.New(
80
                "Image is used in active deployment and cannot be removed",
81
        )
82
        ErrModelImageUsedInAnyDeployment = errors.New("Image has already been used in deployment")
83
        ErrModelParsingArtifactFailed    = errors.New("Cannot parse artifact file")
84
        ErrUploadNotFound                = errors.New("artifact object not found")
85
        ErrEmptyArtifact                 = errors.New("artifact cannot be nil")
86

87
        ErrMsgArtifactConflict = "An artifact with the same name has conflicting dependencies"
88

89
        // deployments
90
        ErrModelMissingInput       = errors.New("Missing input deployment data")
91
        ErrModelInvalidDeviceID    = errors.New("Invalid device ID")
92
        ErrModelDeploymentNotFound = errors.New("Deployment not found")
93
        ErrModelInternal           = errors.New("Internal error")
94
        ErrStorageInvalidLog       = errors.New("Invalid deployment log")
95
        ErrStorageNotFound         = errors.New("Not found")
96
        ErrDeploymentAborted       = errors.New("Deployment aborted")
97
        ErrDeviceDecommissioned    = errors.New("Device decommissioned")
98
        ErrNoArtifact              = errors.New("No artifact for the deployment")
99
        ErrNoDevices               = errors.New("No devices for the deployment")
100
        ErrDuplicateDeployment     = errors.New("Deployment with given ID already exists")
101
        ErrInvalidDeploymentID     = errors.New("Deployment ID must be a valid UUID")
102
        ErrConflictingRequestData  = errors.New("Device provided conflicting request data")
103
)
104

105
//deployments
106

107
//go:generate ../utils/mockgen.sh
108
type App interface {
109
        HealthCheck(ctx context.Context) error
110
        // limits
111
        GetLimit(ctx context.Context, name string) (*model.Limit, error)
112
        ProvisionTenant(ctx context.Context, tenant_id string) error
113

114
        // Storage Settings
115
        GetStorageSettings(ctx context.Context) (*model.StorageSettings, error)
116
        SetStorageSettings(ctx context.Context, storageSettings *model.StorageSettings) error
117

118
        // images
119
        ListImages(
120
                ctx context.Context,
121
                filters *model.ReleaseOrImageFilter,
122
        ) ([]*model.Image, int, error)
123
        DownloadLink(ctx context.Context, imageID string,
124
                expire time.Duration) (*model.Link, error)
125
        UploadLink(
126
                ctx context.Context,
127
                expire time.Duration,
128
                skipVerify bool,
129
        ) (*model.UploadLink, error)
130
        CompleteUpload(
131
                ctx context.Context,
132
                intentID string,
133
                skipVerify bool,
134
                metadata *model.DirectUploadMetadata,
135
        ) error
136
        GetImage(ctx context.Context, id string) (*model.Image, error)
137
        DeleteImage(ctx context.Context, imageID string) error
138
        CreateImage(ctx context.Context,
139
                multipartUploadMsg *model.MultipartUploadMsg) (string, error)
140
        GenerateImage(ctx context.Context,
141
                multipartUploadMsg *model.MultipartGenerateImageMsg) (string, error)
142
        GenerateConfigurationImage(
143
                ctx context.Context,
144
                deviceType string,
145
                deploymentID string,
146
        ) (io.Reader, error)
147
        EditImage(ctx context.Context, id string,
148
                constructorData *model.ImageMeta) (bool, error)
149

150
        // deployments
151
        CreateDeployment(ctx context.Context,
152
                constructor *model.DeploymentConstructor) (string, error)
153
        GetDeployment(ctx context.Context, deploymentID string) (*model.Deployment, error)
154
        IsDeploymentFinished(ctx context.Context, deploymentID string) (bool, error)
155
        AbortDeployment(ctx context.Context, deploymentID string) error
156
        GetDeploymentStats(ctx context.Context, deploymentID string) (model.Stats, error)
157
        GetDeploymentsStats(ctx context.Context,
158
                deploymentIDs ...string) ([]*model.DeploymentStats, error)
159
        GetDeploymentForDeviceWithCurrent(ctx context.Context, deviceID string,
160
                request *model.DeploymentNextRequest) (*model.DeploymentInstructions, error)
161
        HasDeploymentForDevice(ctx context.Context, deploymentID string,
162
                deviceID string) (bool, error)
163
        UpdateDeviceDeploymentStatus(ctx context.Context, deploymentID string,
164
                deviceID string, state model.DeviceDeploymentState) error
165
        GetDeviceStatusesForDeployment(ctx context.Context,
166
                deploymentID string) ([]model.DeviceDeployment, error)
167
        GetDevicesListForDeployment(ctx context.Context,
168
                query store.ListQuery) ([]model.DeviceDeployment, int, error)
169
        GetDeviceDeploymentListForDevice(ctx context.Context,
170
                query store.ListQueryDeviceDeployments) ([]model.DeviceDeploymentListItem, int, error)
171
        LookupDeployment(ctx context.Context,
172
                query model.Query) ([]*model.Deployment, int64, error)
173
        SaveDeviceDeploymentLog(ctx context.Context, deviceID string,
174
                deploymentID string, logs []model.LogMessage) error
175
        GetDeviceDeploymentLog(ctx context.Context,
176
                deviceID, deploymentID string) (*model.DeploymentLog, error)
177
        AbortDeviceDeployments(ctx context.Context, deviceID string) error
178
        DeleteDeviceDeploymentsHistory(ctx context.Context, deviceId string) error
179
        DecommissionDevice(ctx context.Context, deviceID string) error
180
        CreateDeviceConfigurationDeployment(
181
                ctx context.Context, constructor *model.ConfigurationDeploymentConstructor,
182
                deviceID, deploymentID string) (string, error)
183
        UpdateDeploymentsWithArtifactName(
184
                ctx context.Context,
185
                artifactName string,
186
        ) error
187
        GetDeviceDeploymentLastStatus(
188
                ctx context.Context,
189
                devicesIds []string,
190
        ) (
191
                model.DeviceDeploymentLastStatuses,
192
                error,
193
        )
194

195
        // releases
196
        ReplaceReleaseTags(ctx context.Context, releaseName string, tags model.Tags) error
197
        UpdateRelease(ctx context.Context, releaseName string, release model.ReleasePatch) error
198
        ListReleaseTags(ctx context.Context) (model.Tags, error)
199
        GetReleasesUpdateTypes(ctx context.Context) ([]string, error)
200
        DeleteReleases(ctx context.Context, releaseNames []string) ([]string, error)
201
}
202

203
type Deployments struct {
204
        db              store.DataStore
205
        objectStorage   storage.ObjectStorage
206
        workflowsClient workflows.Client
207
        inventoryClient inventory.Client
208
        reportingClient reporting.Client
209
}
210

211
// Compile-time check
212
var _ App = &Deployments{}
213

214
func NewDeployments(
215
        storage store.DataStore,
216
        objectStorage storage.ObjectStorage,
217
        maxActiveDeployments int64,
218
        withAuditLogs bool,
219
) *Deployments {
79✔
220
        return &Deployments{
79✔
221
                db:              storage,
79✔
222
                objectStorage:   objectStorage,
79✔
223
                workflowsClient: workflows.NewClient(),
79✔
224
                inventoryClient: inventory.NewClient(),
79✔
225
        }
79✔
226
}
79✔
227

228
func (d *Deployments) SetWorkflowsClient(workflowsClient workflows.Client) {
4✔
229
        d.workflowsClient = workflowsClient
4✔
230
}
4✔
231

232
func (d *Deployments) SetInventoryClient(inventoryClient inventory.Client) {
8✔
233
        d.inventoryClient = inventoryClient
8✔
234
}
8✔
235

236
func (d *Deployments) HealthCheck(ctx context.Context) error {
6✔
237
        err := d.db.Ping(ctx)
6✔
238
        if err != nil {
7✔
239
                return errors.Wrap(err, "error reaching MongoDB")
1✔
240
        }
1✔
241
        err = d.objectStorage.HealthCheck(ctx)
5✔
242
        if err != nil {
6✔
243
                return errors.Wrap(
1✔
244
                        err,
1✔
245
                        "error reaching artifact storage service",
1✔
246
                )
1✔
247
        }
1✔
248

249
        err = d.workflowsClient.CheckHealth(ctx)
4✔
250
        if err != nil {
5✔
251
                return errors.Wrap(err, "Workflows service unhealthy")
1✔
252
        }
1✔
253

254
        err = d.inventoryClient.CheckHealth(ctx)
3✔
255
        if err != nil {
4✔
256
                return errors.Wrap(err, "Inventory service unhealthy")
1✔
257
        }
1✔
258

259
        if d.reportingClient != nil {
4✔
260
                err = d.reportingClient.CheckHealth(ctx)
2✔
261
                if err != nil {
3✔
262
                        return errors.Wrap(err, "Reporting service unhealthy")
1✔
263
                }
1✔
264
        }
265
        return nil
1✔
266
}
267

268
func (d *Deployments) contextWithStorageSettings(
269
        ctx context.Context,
270
) (context.Context, error) {
26✔
271
        var err error
26✔
272
        settings, ok := storage.SettingsFromContext(ctx)
26✔
273
        if !ok {
48✔
274
                settings, err = d.db.GetStorageSettings(ctx)
22✔
275
                if err != nil {
24✔
276
                        return nil, err
2✔
277
                }
2✔
278
        }
279
        if settings != nil {
24✔
280
                if settings.UseAccelerate && settings.Uri != "" {
×
281
                        log.FromContext(ctx).
×
282
                                Warn(`storage settings: custom "uri" and "use_accelerate" ` +
×
283
                                        `are not allowed: disabling transfer acceleration`)
×
284
                        settings.UseAccelerate = false
×
285
                }
×
286
                err = settings.Validate()
×
287
                if err != nil {
×
288
                        return nil, err
×
289
                }
×
290
        }
291
        return storage.SettingsWithContext(ctx, settings), nil
24✔
292
}
293

294
func (d *Deployments) GetLimit(ctx context.Context, name string) (*model.Limit, error) {
3✔
295
        limit, err := d.db.GetLimit(ctx, name)
3✔
296
        if err == mongo.ErrLimitNotFound {
4✔
297
                return &model.Limit{
1✔
298
                        Name:  name,
1✔
299
                        Value: 0,
1✔
300
                }, nil
1✔
301

1✔
302
        } else if err != nil {
4✔
303
                return nil, errors.Wrap(err, "failed to obtain limit from storage")
1✔
304
        }
1✔
305
        return limit, nil
1✔
306
}
307

308
func (d *Deployments) ProvisionTenant(ctx context.Context, tenant_id string) error {
3✔
309
        if err := d.db.ProvisionTenant(ctx, tenant_id); err != nil {
4✔
310
                return errors.Wrap(err, "failed to provision tenant")
1✔
311
        }
1✔
312

313
        return nil
2✔
314
}
315

316
// CreateImage parses artifact and uploads artifact file to the file storage - in parallel,
317
// and creates image structure in the system.
318
// Returns image ID and nil on success.
319
func (d *Deployments) CreateImage(ctx context.Context,
320
        multipartUploadMsg *model.MultipartUploadMsg) (string, error) {
1✔
321
        return d.handleArtifact(ctx, multipartUploadMsg, false, nil)
1✔
322
}
1✔
323

324
func (d *Deployments) saveUpdateTypes(ctx context.Context, image *model.Image) {
1✔
325
        l := log.FromContext(ctx)
1✔
326
        if image != nil && image.ArtifactMeta != nil && len(image.ArtifactMeta.Updates) > 0 {
2✔
327
                i := 0
1✔
328
                updateTypes := make([]string, len(image.ArtifactMeta.Updates))
1✔
329
                for _, t := range image.ArtifactMeta.Updates {
2✔
330
                        if t.TypeInfo.Type == nil {
2✔
331
                                continue
1✔
332
                        }
333
                        updateTypes[i] = *t.TypeInfo.Type
1✔
334
                        i++
1✔
335
                }
336
                err := d.db.SaveUpdateTypes(ctx, updateTypes[:i])
1✔
337
                if err != nil {
1✔
338
                        l.Errorf(
×
339
                                "error while saving the update types for the artifact: %s",
×
340
                                err.Error(),
×
341
                        )
×
342
                }
×
343
        }
344
}
345

346
// handleArtifact parses artifact and uploads artifact file to the file storage - in parallel,
347
// and creates image structure in the system.
348
// Returns image ID, artifact file ID and nil on success.
349
func (d *Deployments) handleArtifact(ctx context.Context,
350
        multipartUploadMsg *model.MultipartUploadMsg,
351
        skipVerify bool,
352
        metadata *model.DirectUploadMetadata,
353
) (string, error) {
5✔
354

5✔
355
        l := log.FromContext(ctx)
5✔
356
        ctx, err := d.contextWithStorageSettings(ctx)
5✔
357
        if err != nil {
5✔
358
                return "", err
×
359
        }
×
360

361
        // create pipe
362
        pR, pW := io.Pipe()
5✔
363

5✔
364
        artifactReader := utils.CountReads(multipartUploadMsg.ArtifactReader)
5✔
365

5✔
366
        tee := io.TeeReader(artifactReader, pW)
5✔
367

5✔
368
        uid, err := uuid.Parse(multipartUploadMsg.ArtifactID)
5✔
369
        if err != nil {
6✔
370
                uid, _ = uuid.NewRandom()
1✔
371
        }
1✔
372
        artifactID := uid.String()
5✔
373

5✔
374
        ch := make(chan error)
5✔
375
        // create goroutine for artifact upload
5✔
376
        //
5✔
377
        // reading from the pipe (which is done in UploadArtifact method) is a blocking operation
5✔
378
        // and cannot be done in the same goroutine as writing to the pipe
5✔
379
        //
5✔
380
        // uploading and parsing artifact in the same process will cause in a deadlock!
5✔
381
        //nolint:errcheck
5✔
382
        go func() (err error) {
10✔
383
                defer func() { ch <- err }()
10✔
384
                if skipVerify {
8✔
385
                        err = nil
3✔
386
                        io.Copy(io.Discard, pR)
3✔
387
                        return nil
3✔
388
                }
3✔
389
                err = d.objectStorage.PutObject(
3✔
390
                        ctx, model.ImagePathFromContext(ctx, artifactID), pR,
3✔
391
                )
3✔
392
                if err != nil {
4✔
393
                        pR.CloseWithError(err)
1✔
394
                }
1✔
395
                return err
3✔
396
        }()
397

398
        // parse artifact
399
        // artifact library reads all the data from the given reader
400
        metaArtifactConstructor, err := getMetaFromArchive(&tee, skipVerify)
5✔
401
        if err != nil {
10✔
402
                _ = pW.CloseWithError(err)
5✔
403
                <-ch
5✔
404
                return artifactID, errors.Wrap(ErrModelParsingArtifactFailed, err.Error())
5✔
405
        }
5✔
406
        validMetadata := false
1✔
407
        if skipVerify && metadata != nil {
2✔
408
                // this means we got files and metadata separately
1✔
409
                // we can now put it in the metaArtifactConstructor
1✔
410
                // after validating that the files information match the artifact
1✔
411
                validMetadata = validUpdates(metaArtifactConstructor.Updates, metadata.Updates)
1✔
412
                if validMetadata {
2✔
413
                        metaArtifactConstructor.Updates = metadata.Updates
1✔
414
                }
1✔
415
        }
416
        // validate artifact metadata
417
        if err = metaArtifactConstructor.Validate(); err != nil {
1✔
418
                return artifactID, ErrModelInvalidMetadata
×
419
        }
×
420

421
        if !skipVerify {
2✔
422
                // read the rest of the data,
1✔
423
                // just in case the artifact library did not read all the data from the reader
1✔
424
                _, err = io.Copy(io.Discard, tee)
1✔
425
                if err != nil {
1✔
426
                        // CloseWithError will cause the reading end to abort upload.
×
427
                        _ = pW.CloseWithError(err)
×
428
                        <-ch
×
429
                        return artifactID, err
×
430
                }
×
431
        }
432

433
        // close the pipe
434
        pW.Close()
1✔
435

1✔
436
        // collect output from the goroutine
1✔
437
        if uploadResponseErr := <-ch; uploadResponseErr != nil {
1✔
438
                return artifactID, uploadResponseErr
×
439
        }
×
440

441
        size := artifactReader.Count()
1✔
442
        if skipVerify && validMetadata {
2✔
443
                size = metadata.Size
1✔
444
        }
1✔
445
        image := model.NewImage(
1✔
446
                artifactID,
1✔
447
                multipartUploadMsg.MetaConstructor,
1✔
448
                metaArtifactConstructor,
1✔
449
                size,
1✔
450
        )
1✔
451

1✔
452
        // save image structure in the system
1✔
453
        if err = d.db.InsertImage(ctx, image); err != nil {
1✔
454
                // Try to remove the storage from s3.
×
455
                if errDelete := d.objectStorage.DeleteObject(
×
456
                        ctx, model.ImagePathFromContext(ctx, artifactID),
×
457
                ); errDelete != nil {
×
458
                        l.Errorf(
×
459
                                "failed to clean up artifact storage after failure: %s",
×
460
                                errDelete,
×
461
                        )
×
462
                }
×
463
                if idxErr, ok := err.(*model.ConflictError); ok {
×
464
                        return artifactID, idxErr
×
465
                }
×
466
                return artifactID, errors.Wrap(err, "Fail to store the metadata")
×
467
        }
468
        d.saveUpdateTypes(ctx, image)
1✔
469

1✔
470
        // update release
1✔
471
        if err := d.updateRelease(ctx, image, nil); err != nil {
1✔
472
                return "", err
×
473
        }
×
474

475
        if err := d.UpdateDeploymentsWithArtifactName(ctx, metaArtifactConstructor.Name); err != nil {
1✔
476
                return "", errors.Wrap(err, "fail to update deployments")
×
477
        }
×
478

479
        return artifactID, nil
1✔
480
}
481

482
func validUpdates(constructorUpdates []model.Update, metadataUpdates []model.Update) bool {
1✔
483
        valid := false
1✔
484
        if len(constructorUpdates) == len(metadataUpdates) {
2✔
485
                valid = true
1✔
486
                for _, update := range constructorUpdates {
2✔
487
                        for _, updateExternal := range metadataUpdates {
2✔
488
                                if !update.Match(updateExternal) {
1✔
489
                                        valid = false
×
490
                                        break
×
491
                                }
492
                        }
493
                }
494
        }
495
        return valid
1✔
496
}
497

498
// GenerateImage parses raw data and uploads it to the file storage - in parallel,
499
// creates image structure in the system, and starts the workflow to generate the
500
// artifact from them.
501
// Returns image ID and nil on success.
502
func (d *Deployments) GenerateImage(ctx context.Context,
503
        multipartGenerateImageMsg *model.MultipartGenerateImageMsg) (string, error) {
11✔
504

11✔
505
        if multipartGenerateImageMsg == nil {
12✔
506
                return "", ErrModelMultipartUploadMsgMalformed
1✔
507
        }
1✔
508

509
        imgPath, err := d.handleRawFile(ctx, multipartGenerateImageMsg)
10✔
510
        if err != nil {
15✔
511
                return "", err
5✔
512
        }
5✔
513
        if id := identity.FromContext(ctx); id != nil && len(id.Tenant) > 0 {
6✔
514
                multipartGenerateImageMsg.TenantID = id.Tenant
1✔
515
        }
1✔
516
        err = d.workflowsClient.StartGenerateArtifact(ctx, multipartGenerateImageMsg)
5✔
517
        if err != nil {
7✔
518
                if cleanupErr := d.objectStorage.DeleteObject(ctx, imgPath); cleanupErr != nil {
3✔
519
                        return "", errors.Wrap(err, cleanupErr.Error())
1✔
520
                }
1✔
521
                return "", err
1✔
522
        }
523

524
        return multipartGenerateImageMsg.ArtifactID, err
3✔
525
}
526

527
func (d *Deployments) GenerateConfigurationImage(
528
        ctx context.Context,
529
        deviceType string,
530
        deploymentID string,
531
) (io.Reader, error) {
5✔
532
        var buf bytes.Buffer
5✔
533
        dpl, err := d.db.FindDeploymentByID(ctx, deploymentID)
5✔
534
        if err != nil {
6✔
535
                return nil, err
1✔
536
        } else if dpl == nil {
6✔
537
                return nil, ErrModelDeploymentNotFound
1✔
538
        }
1✔
539
        var metaData map[string]interface{}
3✔
540
        err = json.Unmarshal(dpl.Configuration, &metaData)
3✔
541
        if err != nil {
4✔
542
                return nil, errors.Wrapf(err, "malformed configuration in deployment")
1✔
543
        }
1✔
544

545
        artieWriter := awriter.NewWriter(&buf, artifact.NewCompressorNone())
2✔
546
        module := handlers.NewModuleImage(ArtifactConfigureType)
2✔
547
        err = artieWriter.WriteArtifact(&awriter.WriteArtifactArgs{
2✔
548
                Format:  "mender",
2✔
549
                Version: 3,
2✔
550
                Devices: []string{deviceType},
2✔
551
                Name:    dpl.ArtifactName,
2✔
552
                Updates: &awriter.Updates{Updates: []handlers.Composer{module}},
2✔
553
                Depends: &artifact.ArtifactDepends{
2✔
554
                        CompatibleDevices: []string{deviceType},
2✔
555
                },
2✔
556
                Provides: &artifact.ArtifactProvides{
2✔
557
                        ArtifactName: dpl.ArtifactName,
2✔
558
                },
2✔
559
                MetaData: metaData,
2✔
560
                TypeInfoV3: &artifact.TypeInfoV3{
2✔
561
                        Type: &ArtifactConfigureType,
2✔
562
                        ArtifactProvides: artifact.TypeInfoProvides{
2✔
563
                                ArtifactConfigureProvides: dpl.ArtifactName,
2✔
564
                        },
2✔
565
                        ArtifactDepends:        artifact.TypeInfoDepends{},
2✔
566
                        ClearsArtifactProvides: []string{ArtifactConfigureProvidesCleared},
2✔
567
                },
2✔
568
        })
2✔
569

2✔
570
        return &buf, err
2✔
571
}
572

573
// handleRawFile parses raw data, uploads it to the file storage,
574
// and starts the workflow to generate the artifact.
575
// Returns the object path to the file and nil on success.
576
func (d *Deployments) handleRawFile(ctx context.Context,
577
        multipartMsg *model.MultipartGenerateImageMsg) (filePath string, err error) {
10✔
578
        l := log.FromContext(ctx)
10✔
579
        uid, _ := uuid.NewRandom()
10✔
580
        artifactID := uid.String()
10✔
581
        multipartMsg.ArtifactID = artifactID
10✔
582
        filePath = model.ImagePathFromContext(ctx, artifactID+fileSuffixTmp)
10✔
583

10✔
584
        // check if artifact is unique
10✔
585
        // artifact is considered to be unique if there is no artifact with the same name
10✔
586
        // and supporting the same platform in the system
10✔
587
        isArtifactUnique, err := d.db.IsArtifactUnique(ctx,
10✔
588
                multipartMsg.Name,
10✔
589
                multipartMsg.DeviceTypesCompatible,
10✔
590
        )
10✔
591
        if err != nil {
11✔
592
                return "", errors.Wrap(err, "Fail to check if artifact is unique")
1✔
593
        }
1✔
594
        if !isArtifactUnique {
10✔
595
                return "", ErrModelArtifactNotUnique
1✔
596
        }
1✔
597

598
        ctx, err = d.contextWithStorageSettings(ctx)
8✔
599
        if err != nil {
8✔
600
                return "", err
×
601
        }
×
602
        err = d.objectStorage.PutObject(
8✔
603
                ctx, filePath, multipartMsg.FileReader,
8✔
604
        )
8✔
605
        if err != nil {
9✔
606
                return "", err
1✔
607
        }
1✔
608
        defer func() {
14✔
609
                if err != nil {
9✔
610
                        e := d.objectStorage.DeleteObject(ctx, filePath)
2✔
611
                        if e != nil {
4✔
612
                                l.Errorf("error cleaning up raw file '%s' from objectstorage: %s",
2✔
613
                                        filePath, e)
2✔
614
                        }
2✔
615
                }
616
        }()
617

618
        link, err := d.objectStorage.GetRequest(
7✔
619
                ctx,
7✔
620
                filePath,
7✔
621
                path.Base(filePath),
7✔
622
                DefaultImageGenerationLinkExpire,
7✔
623
        )
7✔
624
        if err != nil {
8✔
625
                return "", err
1✔
626
        }
1✔
627
        multipartMsg.GetArtifactURI = link.Uri
6✔
628

6✔
629
        link, err = d.objectStorage.DeleteRequest(ctx, filePath, DefaultImageGenerationLinkExpire)
6✔
630
        if err != nil {
7✔
631
                return "", err
1✔
632
        }
1✔
633
        multipartMsg.DeleteArtifactURI = link.Uri
5✔
634

5✔
635
        return artifactID, nil
5✔
636
}
637

638
// GetImage allows to fetch image object with specified id
639
// Nil if not found
640
func (d *Deployments) GetImage(ctx context.Context, id string) (*model.Image, error) {
1✔
641

1✔
642
        image, err := d.db.FindImageByID(ctx, id)
1✔
643
        if err != nil {
1✔
644
                return nil, errors.Wrap(err, "Searching for image with specified ID")
×
645
        }
×
646

647
        if image == nil {
2✔
648
                return nil, nil
1✔
649
        }
1✔
650

651
        return image, nil
1✔
652
}
653

654
// DeleteImage removes metadata and image file
655
// Noop for not existing images
656
// Allowed to remove image only if image is not scheduled or in progress for an updates - then image
657
// file is needed
658
// In case of already finished updates only image file is not needed, metadata is attached directly
659
// to device deployment therefore we still have some information about image that have been used
660
// (but not the file)
661
func (d *Deployments) DeleteImage(ctx context.Context, imageID string) error {
1✔
662
        found, err := d.GetImage(ctx, imageID)
1✔
663

1✔
664
        if err != nil {
1✔
665
                return errors.Wrap(err, "Getting image metadata")
×
666
        }
×
667

668
        if found == nil {
1✔
669
                return ErrImageMetaNotFound
×
670
        }
×
671

672
        inUse, err := d.ImageUsedInActiveDeployment(ctx, imageID)
1✔
673
        if err != nil {
1✔
674
                return errors.Wrap(err, "Checking if image is used in active deployment")
×
675
        }
×
676

677
        // Image is in use, not allowed to delete
678
        if inUse {
2✔
679
                return ErrModelImageInActiveDeployment
1✔
680
        }
1✔
681

682
        // Delete image file (call to external service)
683
        // Noop for not existing file
684
        ctx, err = d.contextWithStorageSettings(ctx)
1✔
685
        if err != nil {
1✔
686
                return err
×
687
        }
×
688
        imagePath := model.ImagePathFromContext(ctx, imageID)
1✔
689
        if err := d.objectStorage.DeleteObject(ctx, imagePath); err != nil {
1✔
690
                return errors.Wrap(err, "Deleting image file")
×
691
        }
×
692

693
        // Delete metadata
694
        if err := d.db.DeleteImage(ctx, imageID); err != nil {
1✔
695
                return errors.Wrap(err, "Deleting image metadata")
×
696
        }
×
697

698
        // update release
699
        if err := d.updateRelease(ctx, nil, found); err != nil {
1✔
700
                return err
×
701
        }
×
702

703
        return nil
1✔
704
}
705

706
// ListImages according to specified filers.
707
func (d *Deployments) ListImages(
708
        ctx context.Context,
709
        filters *model.ReleaseOrImageFilter,
710
) ([]*model.Image, int, error) {
1✔
711
        imageList, count, err := d.db.ListImages(ctx, filters)
1✔
712
        if err != nil {
1✔
713
                return nil, 0, errors.Wrap(err, "Searching for image metadata")
×
714
        }
×
715

716
        if imageList == nil {
2✔
717
                return make([]*model.Image, 0), 0, nil
1✔
718
        }
1✔
719

720
        return imageList, count, nil
1✔
721
}
722

723
// EditObject allows editing only if image have not been used yet in any deployment.
724
func (d *Deployments) EditImage(ctx context.Context, imageID string,
725
        constructor *model.ImageMeta) (bool, error) {
×
726

×
727
        if err := constructor.Validate(); err != nil {
×
728
                return false, errors.Wrap(err, "Validating image metadata")
×
729
        }
×
730

731
        found, err := d.ImageUsedInDeployment(ctx, imageID)
×
732
        if err != nil {
×
733
                return false, errors.Wrap(err, "Searching for usage of the image among deployments")
×
734
        }
×
735

736
        if found {
×
737
                return false, ErrModelImageUsedInAnyDeployment
×
738
        }
×
739

740
        foundImage, err := d.db.FindImageByID(ctx, imageID)
×
741
        if err != nil {
×
742
                return false, errors.Wrap(err, "Searching for image with specified ID")
×
743
        }
×
744

745
        if foundImage == nil {
×
746
                return false, nil
×
747
        }
×
748

749
        foundImage.SetModified(time.Now())
×
750
        foundImage.ImageMeta = constructor
×
751

×
752
        _, err = d.db.Update(ctx, foundImage)
×
753
        if err != nil {
×
754
                return false, errors.Wrap(err, "Updating image matadata")
×
755
        }
×
756

757
        if err := d.updateReleaseEditArtifact(ctx, foundImage); err != nil {
×
758
                return false, err
×
759
        }
×
760

761
        return true, nil
×
762
}
763

764
// DownloadLink presigned GET link to download image file.
765
// Returns error if image have not been uploaded.
766
func (d *Deployments) DownloadLink(ctx context.Context, imageID string,
767
        expire time.Duration) (*model.Link, error) {
1✔
768

1✔
769
        image, err := d.GetImage(ctx, imageID)
1✔
770
        if err != nil {
1✔
771
                return nil, errors.Wrap(err, "Searching for image with specified ID")
×
772
        }
×
773

774
        if image == nil {
1✔
775
                return nil, nil
×
776
        }
×
777

778
        ctx, err = d.contextWithStorageSettings(ctx)
1✔
779
        if err != nil {
1✔
780
                return nil, err
×
781
        }
×
782
        imagePath := model.ImagePathFromContext(ctx, imageID)
1✔
783
        _, err = d.objectStorage.StatObject(ctx, imagePath)
1✔
784
        if err != nil {
1✔
785
                return nil, errors.Wrap(err, "Searching for image file")
×
786
        }
×
787

788
        link, err := d.objectStorage.GetRequest(
1✔
789
                ctx,
1✔
790
                imagePath,
1✔
791
                image.Name+model.ArtifactFileSuffix,
1✔
792
                expire,
1✔
793
        )
1✔
794
        if err != nil {
1✔
795
                return nil, errors.Wrap(err, "Generating download link")
×
796
        }
×
797

798
        return link, nil
1✔
799
}
800

801
func (d *Deployments) UploadLink(
802
        ctx context.Context,
803
        expire time.Duration,
804
        skipVerify bool,
805
) (*model.UploadLink, error) {
6✔
806
        ctx, err := d.contextWithStorageSettings(ctx)
6✔
807
        if err != nil {
7✔
808
                return nil, err
1✔
809
        }
1✔
810

811
        artifactID := uuid.New().String()
5✔
812
        path := model.ImagePathFromContext(ctx, artifactID) + fileSuffixTmp
5✔
813
        if skipVerify {
6✔
814
                path = model.ImagePathFromContext(ctx, artifactID)
1✔
815
        }
1✔
816
        link, err := d.objectStorage.PutRequest(ctx, path, expire)
5✔
817
        if err != nil {
6✔
818
                return nil, errors.WithMessage(err, "app: failed to generate signed URL")
1✔
819
        }
1✔
820
        upLink := &model.UploadLink{
4✔
821
                ArtifactID: artifactID,
4✔
822
                IssuedAt:   time.Now(),
4✔
823
                Link:       *link,
4✔
824
        }
4✔
825
        err = d.db.InsertUploadIntent(ctx, upLink)
4✔
826
        if err != nil {
5✔
827
                return nil, errors.WithMessage(err, "app: error recording the upload intent")
1✔
828
        }
1✔
829

830
        return upLink, err
3✔
831
}
832

833
func (d *Deployments) processUploadedArtifact(
834
        ctx context.Context,
835
        artifactID string,
836
        artifact io.ReadCloser,
837
        skipVerify bool,
838
        metadata *model.DirectUploadMetadata,
839
) error {
5✔
840
        linkStatus := model.LinkStatusCompleted
5✔
841

5✔
842
        l := log.FromContext(ctx)
5✔
843
        defer artifact.Close()
5✔
844
        ctx, cancel := context.WithCancel(ctx)
5✔
845
        defer cancel()
5✔
846
        go func() { // Heatbeat routine
10✔
847
                ticker := time.NewTicker(inprogressIdleTime / 2)
5✔
848
                done := ctx.Done()
5✔
849
                defer ticker.Stop()
5✔
850
                for {
10✔
851
                        select {
5✔
852
                        case <-ticker.C:
×
853
                                err := d.db.UpdateUploadIntentStatus(
×
854
                                        ctx,
×
855
                                        artifactID,
×
856
                                        model.LinkStatusProcessing,
×
857
                                        model.LinkStatusProcessing,
×
858
                                )
×
859
                                if err != nil {
×
860
                                        l.Errorf("failed to update upload link timestamp: %s", err)
×
861
                                        cancel()
×
862
                                        return
×
863
                                }
×
864
                        case <-done:
5✔
865
                                return
5✔
866
                        }
867
                }
868
        }()
869
        _, err := d.handleArtifact(ctx, &model.MultipartUploadMsg{
5✔
870
                ArtifactID:     artifactID,
5✔
871
                ArtifactReader: artifact,
5✔
872
        },
5✔
873
                skipVerify,
5✔
874
                metadata,
5✔
875
        )
5✔
876
        if err != nil {
9✔
877
                l.Warnf("failed to process artifact %s: %s", artifactID, err)
4✔
878
                linkStatus = model.LinkStatusAborted
4✔
879
        }
4✔
880
        errDB := d.db.UpdateUploadIntentStatus(
5✔
881
                ctx, artifactID,
5✔
882
                model.LinkStatusProcessing, linkStatus,
5✔
883
        )
5✔
884
        if errDB != nil {
7✔
885
                l.Warnf("failed to update upload link status: %s", errDB)
2✔
886
        }
2✔
887
        return err
5✔
888
}
889

890
func (d *Deployments) CompleteUpload(
891
        ctx context.Context,
892
        intentID string,
893
        skipVerify bool,
894
        metadata *model.DirectUploadMetadata,
895
) error {
10✔
896
        l := log.FromContext(ctx)
10✔
897
        idty := identity.FromContext(ctx)
10✔
898
        ctx, err := d.contextWithStorageSettings(ctx)
10✔
899
        if err != nil {
11✔
900
                return err
1✔
901
        }
1✔
902
        // Create an async context that doesn't cancel when server connection
903
        // closes.
904
        ctxAsync := context.Background()
9✔
905
        ctxAsync = log.WithContext(ctxAsync, l)
9✔
906
        ctxAsync = identity.WithContext(ctxAsync, idty)
9✔
907

9✔
908
        settings, _ := storage.SettingsFromContext(ctx)
9✔
909
        ctxAsync = storage.SettingsWithContext(ctxAsync, settings)
9✔
910
        var artifactReader io.ReadCloser
9✔
911
        if skipVerify {
12✔
912
                artifactReader, err = d.objectStorage.GetObject(
3✔
913
                        ctxAsync,
3✔
914
                        model.ImagePathFromContext(ctx, intentID),
3✔
915
                )
3✔
916
        } else {
9✔
917
                artifactReader, err = d.objectStorage.GetObject(
6✔
918
                        ctxAsync,
6✔
919
                        model.ImagePathFromContext(ctx, intentID)+fileSuffixTmp,
6✔
920
                )
6✔
921
        }
6✔
922
        if err != nil {
11✔
923
                if errors.Is(err, storage.ErrObjectNotFound) {
3✔
924
                        return ErrUploadNotFound
1✔
925
                }
1✔
926
                return err
1✔
927
        }
928

929
        err = d.db.UpdateUploadIntentStatus(
7✔
930
                ctx,
7✔
931
                intentID,
7✔
932
                model.LinkStatusPending,
7✔
933
                model.LinkStatusProcessing,
7✔
934
        )
7✔
935
        if err != nil {
9✔
936
                errClose := artifactReader.Close()
2✔
937
                if errClose != nil {
3✔
938
                        l.Warnf("failed to close artifact reader: %s", errClose)
1✔
939
                }
1✔
940
                if errors.Is(err, store.ErrNotFound) {
3✔
941
                        return ErrUploadNotFound
1✔
942
                }
1✔
943
                return err
1✔
944
        }
945
        go d.processUploadedArtifact( // nolint:errcheck
5✔
946
                ctxAsync, intentID, artifactReader, skipVerify, metadata,
5✔
947
        )
5✔
948
        return nil
5✔
949
}
950

951
func getArtifactInfo(info artifact.Info) *model.ArtifactInfo {
1✔
952
        return &model.ArtifactInfo{
1✔
953
                Format:  info.Format,
1✔
954
                Version: uint(info.Version),
1✔
955
        }
1✔
956
}
1✔
957

958
func getUpdateFiles(uFiles []*handlers.DataFile) ([]model.UpdateFile, error) {
1✔
959
        var files []model.UpdateFile
1✔
960
        for _, u := range uFiles {
2✔
961
                files = append(files, model.UpdateFile{
1✔
962
                        Name:     u.Name,
1✔
963
                        Size:     u.Size,
1✔
964
                        Date:     &u.Date,
1✔
965
                        Checksum: string(u.Checksum),
1✔
966
                })
1✔
967
        }
1✔
968
        return files, nil
1✔
969
}
970

971
func getMetaFromArchive(r *io.Reader, skipVerify bool) (*model.ArtifactMeta, error) {
5✔
972
        metaArtifact := model.NewArtifactMeta()
5✔
973

5✔
974
        aReader := areader.NewReader(*r)
5✔
975

5✔
976
        // There is no signature verification here.
5✔
977
        // It is just simple check if artifact is signed or not.
5✔
978
        aReader.VerifySignatureCallback = func(message, sig []byte) error {
5✔
979
                metaArtifact.Signed = true
×
980
                return nil
×
981
        }
×
982

983
        var err error
5✔
984
        if skipVerify {
8✔
985
                err = aReader.ReadArtifactHeaders()
3✔
986
                if err != nil {
5✔
987
                        return nil, errors.Wrap(err, "reading artifact error")
2✔
988
                }
2✔
989
        } else {
3✔
990
                err = aReader.ReadArtifact()
3✔
991
                if err != nil {
6✔
992
                        return nil, errors.Wrap(err, "reading artifact error")
3✔
993
                }
3✔
994
        }
995

996
        metaArtifact.Info = getArtifactInfo(aReader.GetInfo())
1✔
997
        metaArtifact.DeviceTypesCompatible = aReader.GetCompatibleDevices()
1✔
998

1✔
999
        metaArtifact.Name = aReader.GetArtifactName()
1✔
1000
        if metaArtifact.Info.Version == 3 {
2✔
1001
                metaArtifact.Depends, err = aReader.MergeArtifactDepends()
1✔
1002
                if err != nil {
1✔
1003
                        return nil, errors.Wrap(err,
×
1004
                                "error parsing version 3 artifact")
×
1005
                }
×
1006

1007
                metaArtifact.Provides, err = aReader.MergeArtifactProvides()
1✔
1008
                if err != nil {
1✔
1009
                        return nil, errors.Wrap(err,
×
1010
                                "error parsing version 3 artifact")
×
1011
                }
×
1012

1013
                metaArtifact.ClearsProvides = aReader.MergeArtifactClearsProvides()
1✔
1014
        }
1015

1016
        for _, p := range aReader.GetHandlers() {
2✔
1017
                uFiles, err := getUpdateFiles(p.GetUpdateFiles())
1✔
1018
                if err != nil {
1✔
1019
                        return nil, errors.Wrap(err, "Cannot get update files:")
×
1020
                }
×
1021

1022
                uMetadata, err := p.GetUpdateMetaData()
1✔
1023
                if err != nil {
1✔
1024
                        return nil, errors.Wrap(err, "Cannot get update metadata")
×
1025
                }
×
1026

1027
                metaArtifact.Updates = append(
1✔
1028
                        metaArtifact.Updates,
1✔
1029
                        model.Update{
1✔
1030
                                TypeInfo: model.ArtifactUpdateTypeInfo{
1✔
1031
                                        Type: p.GetUpdateType(),
1✔
1032
                                },
1✔
1033
                                Files:    uFiles,
1✔
1034
                                MetaData: uMetadata,
1✔
1035
                        })
1✔
1036
        }
1037

1038
        return metaArtifact, nil
1✔
1039
}
1040

1041
func getArtifactIDs(artifacts []*model.Image) []string {
7✔
1042
        artifactIDs := make([]string, 0, len(artifacts))
7✔
1043
        for _, artifact := range artifacts {
14✔
1044
                artifactIDs = append(artifactIDs, artifact.Id)
7✔
1045
        }
7✔
1046
        return artifactIDs
7✔
1047
}
1048

1049
// deployments
1050
func inventoryDevicesToDevicesIds(devices []model.InvDevice) []string {
4✔
1051
        ids := make([]string, len(devices))
4✔
1052
        for i, d := range devices {
8✔
1053
                ids[i] = d.ID
4✔
1054
        }
4✔
1055

1056
        return ids
4✔
1057
}
1058

1059
// updateDeploymentConstructor fills devices list with device ids
1060
func (d *Deployments) updateDeploymentConstructor(ctx context.Context,
1061
        constructor *model.DeploymentConstructor) (*model.DeploymentConstructor, error) {
5✔
1062
        l := log.FromContext(ctx)
5✔
1063

5✔
1064
        id := identity.FromContext(ctx)
5✔
1065
        if id == nil {
5✔
1066
                l.Error("identity not present in the context")
×
1067
                return nil, ErrModelInternal
×
1068
        }
×
1069
        searchParams := model.SearchParams{
5✔
1070
                Page:    1,
5✔
1071
                PerPage: PerPageInventoryDevices,
5✔
1072
                Filters: []model.FilterPredicate{
5✔
1073
                        {
5✔
1074
                                Scope:     InventoryIdentityScope,
5✔
1075
                                Attribute: InventoryStatusAttributeName,
5✔
1076
                                Type:      "$eq",
5✔
1077
                                Value:     InventoryStatusAccepted,
5✔
1078
                        },
5✔
1079
                },
5✔
1080
        }
5✔
1081
        if len(constructor.Group) > 0 {
10✔
1082
                searchParams.Filters = append(
5✔
1083
                        searchParams.Filters,
5✔
1084
                        model.FilterPredicate{
5✔
1085
                                Scope:     InventoryGroupScope,
5✔
1086
                                Attribute: InventoryGroupAttributeName,
5✔
1087
                                Type:      "$eq",
5✔
1088
                                Value:     constructor.Group,
5✔
1089
                        })
5✔
1090
        }
5✔
1091

1092
        for {
11✔
1093
                devices, count, err := d.search(ctx, id.Tenant, searchParams)
6✔
1094
                if err != nil {
7✔
1095
                        l.Errorf("error searching for devices")
1✔
1096
                        return nil, ErrModelInternal
1✔
1097
                }
1✔
1098
                if count < 1 {
6✔
1099
                        l.Errorf("no devices found")
1✔
1100
                        return nil, ErrNoDevices
1✔
1101
                }
1✔
1102
                if len(devices) < 1 {
4✔
1103
                        break
×
1104
                }
1105
                constructor.Devices = append(constructor.Devices, inventoryDevicesToDevicesIds(devices)...)
4✔
1106
                if len(constructor.Devices) == count {
7✔
1107
                        break
3✔
1108
                }
1109
                searchParams.Page++
1✔
1110
        }
1111

1112
        return constructor, nil
3✔
1113
}
1114

1115
// CreateDeviceConfigurationDeployment creates new configuration deployment for the device.
1116
func (d *Deployments) CreateDeviceConfigurationDeployment(
1117
        ctx context.Context, constructor *model.ConfigurationDeploymentConstructor,
1118
        deviceID, deploymentID string) (string, error) {
5✔
1119

5✔
1120
        if constructor == nil {
6✔
1121
                return "", ErrModelMissingInput
1✔
1122
        }
1✔
1123

1124
        deployment, err := model.NewDeploymentFromConfigurationDeploymentConstructor(
4✔
1125
                constructor,
4✔
1126
                deploymentID,
4✔
1127
        )
4✔
1128
        if err != nil {
4✔
1129
                return "", errors.Wrap(err, "failed to create deployment")
×
1130
        }
×
1131

1132
        deployment.DeviceList = []string{deviceID}
4✔
1133
        deployment.MaxDevices = 1
4✔
1134
        deployment.Configuration = []byte(constructor.Configuration)
4✔
1135
        deployment.Type = model.DeploymentTypeConfiguration
4✔
1136

4✔
1137
        groups, err := d.getDeploymentGroups(ctx, []string{deviceID})
4✔
1138
        if err != nil {
5✔
1139
                return "", err
1✔
1140
        }
1✔
1141
        deployment.Groups = groups
3✔
1142

3✔
1143
        if err := d.db.InsertDeployment(ctx, deployment); err != nil {
5✔
1144
                if strings.Contains(err.Error(), "duplicate key error") {
3✔
1145
                        return "", ErrDuplicateDeployment
1✔
1146
                }
1✔
1147
                if strings.Contains(err.Error(), "id: must be a valid UUID") {
3✔
1148
                        return "", ErrInvalidDeploymentID
1✔
1149
                }
1✔
1150
                return "", errors.Wrap(err, "Storing deployment data")
1✔
1151
        }
1152

1153
        return deployment.Id, nil
2✔
1154
}
1155

1156
// CreateDeployment precomputes new deployment and schedules it for devices.
1157
func (d *Deployments) CreateDeployment(ctx context.Context,
1158
        constructor *model.DeploymentConstructor) (string, error) {
9✔
1159

9✔
1160
        var err error
9✔
1161

9✔
1162
        if constructor == nil {
10✔
1163
                return "", ErrModelMissingInput
1✔
1164
        }
1✔
1165

1166
        if err := constructor.Validate(); err != nil {
8✔
1167
                return "", errors.Wrap(err, "Validating deployment")
×
1168
        }
×
1169

1170
        if len(constructor.Group) > 0 || constructor.AllDevices {
13✔
1171
                constructor, err = d.updateDeploymentConstructor(ctx, constructor)
5✔
1172
                if err != nil {
7✔
1173
                        return "", err
2✔
1174
                }
2✔
1175
        }
1176

1177
        deployment, err := model.NewDeploymentFromConstructor(constructor)
6✔
1178
        if err != nil {
6✔
1179
                return "", errors.Wrap(err, "failed to create deployment")
×
1180
        }
×
1181

1182
        // Assign artifacts to the deployment.
1183
        // When new artifact(s) with the artifact name same as the one in the deployment
1184
        // will be uploaded to the backend, it will also become part of this deployment.
1185
        artifacts, err := d.db.ImagesByName(ctx, deployment.ArtifactName)
6✔
1186
        if err != nil {
6✔
1187
                return "", errors.Wrap(err, "Finding artifact with given name")
×
1188
        }
×
1189

1190
        if len(artifacts) == 0 {
7✔
1191
                return "", ErrNoArtifact
1✔
1192
        }
1✔
1193

1194
        deployment.Artifacts = getArtifactIDs(artifacts)
6✔
1195
        deployment.DeviceList = constructor.Devices
6✔
1196
        deployment.MaxDevices = len(constructor.Devices)
6✔
1197
        deployment.Type = model.DeploymentTypeSoftware
6✔
1198
        if len(constructor.Group) > 0 {
9✔
1199
                deployment.Groups = []string{constructor.Group}
3✔
1200
        }
3✔
1201

1202
        // single device deployment case
1203
        if len(deployment.Groups) == 0 && len(constructor.Devices) == 1 {
9✔
1204
                groups, err := d.getDeploymentGroups(ctx, constructor.Devices)
3✔
1205
                if err != nil {
3✔
1206
                        return "", err
×
1207
                }
×
1208
                deployment.Groups = groups
3✔
1209
        }
1210

1211
        if err := d.db.InsertDeployment(ctx, deployment); err != nil {
7✔
1212
                return "", errors.Wrap(err, "Storing deployment data")
1✔
1213
        }
1✔
1214

1215
        return deployment.Id, nil
5✔
1216
}
1217

1218
func (d *Deployments) getDeploymentGroups(
1219
        ctx context.Context,
1220
        devices []string,
1221
) ([]string, error) {
6✔
1222
        id := identity.FromContext(ctx)
6✔
1223

6✔
1224
        //only for single device deployment case
6✔
1225
        if len(devices) != 1 {
6✔
1226
                return nil, nil
×
1227
        }
×
1228

1229
        if id == nil {
7✔
1230
                id = &identity.Identity{}
1✔
1231
        }
1✔
1232

1233
        groups, err := d.inventoryClient.GetDeviceGroups(ctx, id.Tenant, devices[0])
6✔
1234
        if err != nil && err != inventory.ErrDevNotFound {
7✔
1235
                return nil, err
1✔
1236
        }
1✔
1237
        return groups, nil
5✔
1238
}
1239

1240
// IsDeploymentFinished checks if there is unfinished deployment with given ID
1241
func (d *Deployments) IsDeploymentFinished(
1242
        ctx context.Context,
1243
        deploymentID string,
1244
) (bool, error) {
1✔
1245
        deployment, err := d.db.FindUnfinishedByID(ctx, deploymentID)
1✔
1246
        if err != nil {
1✔
1247
                return false, errors.Wrap(err, "Searching for unfinished deployment by ID")
×
1248
        }
×
1249
        if deployment == nil {
2✔
1250
                return true, nil
1✔
1251
        }
1✔
1252

1253
        return false, nil
1✔
1254
}
1255

1256
// GetDeployment fetches deployment by ID
1257
func (d *Deployments) GetDeployment(ctx context.Context,
1258
        deploymentID string) (*model.Deployment, error) {
1✔
1259

1✔
1260
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1261
        if err != nil {
1✔
1262
                return nil, errors.Wrap(err, "Searching for deployment by ID")
×
1263
        }
×
1264

1265
        if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
1✔
1266
                return nil, err
×
1267
        }
×
1268

1269
        return deployment, nil
1✔
1270
}
1271

1272
// ImageUsedInActiveDeployment checks if specified image is in use by deployments. Image is
1273
// considered to be in use if it's participating in at lest one non success/error deployment.
1274
func (d *Deployments) ImageUsedInActiveDeployment(ctx context.Context,
1275
        imageID string) (bool, error) {
3✔
1276

3✔
1277
        var found bool
3✔
1278

3✔
1279
        found, err := d.db.ExistUnfinishedByArtifactId(ctx, imageID)
3✔
1280
        if err != nil {
4✔
1281
                return false, errors.Wrap(err, "Checking if image is used by active deployment")
1✔
1282
        }
1✔
1283

1284
        return found, nil
2✔
1285
}
1286

1287
// ImageUsedInDeployment checks if specified image is in use by deployments.
1288
// Image is considered to be in use if it's participating in any deployment.
1289
func (d *Deployments) ImageUsedInDeployment(ctx context.Context, imageID string) (bool, error) {
×
1290

×
1291
        var found bool
×
1292

×
NEW
1293
        found, err := d.db.ExistByArtifactId(ctx, imageID)
×
1294
        if err != nil {
×
1295
                return false, errors.Wrap(err, "Checking if image is used by active deployment")
×
1296
        }
×
1297

1298
        return found, nil
×
1299
}
1300

1301
// Retrieves the model.Deployment and model.DeviceDeployment structures
1302
// for the device. Upon error, nil is returned for both deployment structures.
1303
func (d *Deployments) getDeploymentForDevice(ctx context.Context,
1304
        deviceID string) (*model.Deployment, *model.DeviceDeployment, error) {
2✔
1305

2✔
1306
        // Retrieve device deployment
2✔
1307
        deviceDeployment, err := d.db.FindOldestActiveDeviceDeployment(ctx, deviceID)
2✔
1308

2✔
1309
        if err != nil {
2✔
1310
                return nil, nil, errors.Wrap(err,
×
1311
                        "Searching for oldest active deployment for the device")
×
1312
        } else if deviceDeployment == nil {
3✔
1313
                return d.getNewDeploymentForDevice(ctx, deviceID)
1✔
1314
        }
1✔
1315

1316
        deployment, err := d.db.FindDeploymentByID(ctx, deviceDeployment.DeploymentId)
2✔
1317
        if err != nil {
2✔
1318
                return nil, nil, errors.Wrap(err, "checking deployment id")
×
1319
        }
×
1320
        if deployment == nil {
2✔
1321
                return nil, nil, errors.New("No deployment corresponding to device deployment")
×
1322
        }
×
1323

1324
        return deployment, deviceDeployment, nil
2✔
1325
}
1326

1327
// getNewDeploymentForDevice returns deployment object and creates and returns
1328
// new device deployment for the device;
1329
//
1330
// we are interested only in the deployments that are newer than the latest
1331
// deployment applied by the device;
1332
// this way we guarantee that the device will not receive deployment
1333
// that is older than the one installed on the device;
1334
func (d *Deployments) getNewDeploymentForDevice(ctx context.Context,
1335
        deviceID string) (*model.Deployment, *model.DeviceDeployment, error) {
1✔
1336

1✔
1337
        var lastDeployment *time.Time
1✔
1338
        //get latest device deployment for the device;
1✔
1339
        deviceDeployment, err := d.db.FindLatestInactiveDeviceDeployment(ctx, deviceID)
1✔
1340
        if err != nil {
1✔
1341
                return nil, nil, errors.Wrap(err,
×
1342
                        "Searching for latest active deployment for the device")
×
1343
        } else if deviceDeployment == nil {
2✔
1344
                lastDeployment = &time.Time{}
1✔
1345
        } else {
2✔
1346
                lastDeployment = deviceDeployment.Created
1✔
1347
        }
1✔
1348

1349
        //get deployments newer then last device deployment
1350
        //iterate over deployments and check if the device is part of the deployment or not
1351
        for skip := 0; true; skip += 100 {
2✔
1352
                deployments, err := d.db.FindNewerActiveDeployments(ctx, lastDeployment, skip, 100)
1✔
1353
                if err != nil {
1✔
1354
                        return nil, nil, errors.Wrap(err,
×
1355
                                "Failed to search for newer active deployments")
×
1356
                }
×
1357
                if len(deployments) == 0 {
2✔
1358
                        return nil, nil, nil
1✔
1359
                }
1✔
1360

1361
                for _, deployment := range deployments {
2✔
1362
                        ok, err := d.isDevicePartOfDeployment(ctx, deviceID, deployment)
1✔
1363
                        if err != nil {
1✔
1364
                                return nil, nil, err
×
1365
                        }
×
1366
                        if ok {
2✔
1367
                                deviceDeployment, err := d.createDeviceDeploymentWithStatus(ctx,
1✔
1368
                                        deviceID, deployment, model.DeviceDeploymentStatusPending)
1✔
1369
                                if err != nil {
1✔
1370
                                        return nil, nil, err
×
1371
                                }
×
1372
                                return deployment, deviceDeployment, nil
1✔
1373
                        }
1374
                }
1375
        }
1376

1377
        return nil, nil, nil
×
1378
}
1379

1380
func (d *Deployments) createDeviceDeploymentWithStatus(
1381
        ctx context.Context, deviceID string,
1382
        deployment *model.Deployment, status model.DeviceDeploymentStatus,
1383
) (*model.DeviceDeployment, error) {
6✔
1384
        prevStatus := model.DeviceDeploymentStatusNull
6✔
1385
        deviceDeployment, err := d.db.GetDeviceDeployment(ctx, deployment.Id, deviceID, true)
6✔
1386
        if err != nil && err != mongo.ErrStorageNotFound {
6✔
1387
                return nil, err
×
1388
        } else if deviceDeployment != nil {
6✔
1389
                prevStatus = deviceDeployment.Status
×
1390
        }
×
1391

1392
        deviceDeployment = model.NewDeviceDeployment(deviceID, deployment.Id)
6✔
1393
        deviceDeployment.Status = status
6✔
1394
        deviceDeployment.Active = status.Active()
6✔
1395
        deviceDeployment.Created = deployment.Created
6✔
1396

6✔
1397
        if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
6✔
1398
                return nil, err
×
1399
        }
×
1400

1401
        if err := d.db.InsertDeviceDeployment(ctx, deviceDeployment,
6✔
1402
                prevStatus == model.DeviceDeploymentStatusNull); err != nil {
6✔
1403
                return nil, err
×
1404
        }
×
1405

1406
        // after inserting new device deployment update deployment stats
1407
        // in the database and locally, and update deployment status
1408
        if err := d.db.UpdateStatsInc(
6✔
1409
                ctx, deployment.Id,
6✔
1410
                prevStatus, status,
6✔
1411
        ); err != nil {
6✔
1412
                return nil, err
×
1413
        }
×
1414

1415
        deployment.Stats.Inc(status)
6✔
1416

6✔
1417
        err = d.recalcDeploymentStatus(ctx, deployment)
6✔
1418
        if err != nil {
6✔
1419
                return nil, errors.Wrap(err, "failed to update deployment status")
×
1420
        }
×
1421

1422
        if !status.Active() {
11✔
1423
                err := d.reindexDevice(ctx, deviceID)
5✔
1424
                if err != nil {
5✔
1425
                        l := log.FromContext(ctx)
×
1426
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1427
                }
×
1428
                if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
5✔
1429
                        deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
5✔
1430
                        l := log.FromContext(ctx)
×
1431
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1432
                }
×
1433
        }
1434

1435
        return deviceDeployment, nil
6✔
1436
}
1437

1438
func (d *Deployments) isDevicePartOfDeployment(
1439
        ctx context.Context,
1440
        deviceID string,
1441
        deployment *model.Deployment,
1442
) (bool, error) {
8✔
1443
        for _, id := range deployment.DeviceList {
14✔
1444
                if id == deviceID {
12✔
1445
                        return true, nil
6✔
1446
                }
6✔
1447
        }
1448
        return false, nil
3✔
1449
}
1450

1451
// GetDeploymentForDeviceWithCurrent returns deployment for the device
1452
func (d *Deployments) GetDeploymentForDeviceWithCurrent(ctx context.Context, deviceID string,
1453
        request *model.DeploymentNextRequest) (*model.DeploymentInstructions, error) {
2✔
1454

2✔
1455
        deployment, deviceDeployment, err := d.getDeploymentForDevice(ctx, deviceID)
2✔
1456
        if err != nil {
2✔
1457
                return nil, ErrModelInternal
×
1458
        } else if deployment == nil {
3✔
1459
                return nil, nil
1✔
1460
        }
1✔
1461

1462
        err = d.saveDeviceDeploymentRequest(ctx, deviceID, deviceDeployment, request)
2✔
1463
        if err != nil {
3✔
1464
                return nil, err
1✔
1465
        }
1✔
1466
        return d.getDeploymentInstructions(ctx, deployment, deviceDeployment, request)
2✔
1467
}
1468

1469
func (d *Deployments) getDeploymentInstructions(
1470
        ctx context.Context,
1471
        deployment *model.Deployment,
1472
        deviceDeployment *model.DeviceDeployment,
1473
        request *model.DeploymentNextRequest,
1474
) (*model.DeploymentInstructions, error) {
2✔
1475

2✔
1476
        var newArtifactAssigned bool
2✔
1477

2✔
1478
        l := log.FromContext(ctx)
2✔
1479

2✔
1480
        if deployment.Type == model.DeploymentTypeConfiguration {
3✔
1481
                // There's nothing more we need to do, the link must be filled
1✔
1482
                // in by the API layer.
1✔
1483
                return &model.DeploymentInstructions{
1✔
1484
                        ID: deployment.Id,
1✔
1485
                        Artifact: model.ArtifactDeploymentInstructions{
1✔
1486
                                // configuration artifacts are created on demand, so they do not have IDs
1✔
1487
                                // use deployment ID togheter with device ID as artifact ID
1✔
1488
                                ID:                    deployment.Id + deviceDeployment.DeviceId,
1✔
1489
                                ArtifactName:          deployment.ArtifactName,
1✔
1490
                                DeviceTypesCompatible: []string{request.DeviceProvides.DeviceType},
1✔
1491
                        },
1✔
1492
                        Type: model.DeploymentTypeConfiguration,
1✔
1493
                }, nil
1✔
1494
        }
1✔
1495

1496
        // assing artifact to the device deployment
1497
        // only if it was not assgined previously
1498
        if deviceDeployment.Image == nil {
4✔
1499
                if err := d.assignArtifact(
2✔
1500
                        ctx, deployment, deviceDeployment, request.DeviceProvides); err != nil {
2✔
1501
                        return nil, err
×
1502
                }
×
1503
                newArtifactAssigned = true
2✔
1504
        }
1505

1506
        if deviceDeployment.Image == nil {
2✔
1507
                // No artifact - return empty response
×
1508
                return nil, nil
×
1509
        }
×
1510

1511
        // if the deployment is not forcing the installation, and
1512
        // if artifact was recognized as already installed, and this is
1513
        // a new device deployment - indicated by device deployment status "pending",
1514
        // handle already installed artifact case
1515
        if !deployment.ForceInstallation &&
2✔
1516
                d.isAlreadyInstalled(request, deviceDeployment) &&
2✔
1517
                deviceDeployment.Status == model.DeviceDeploymentStatusPending {
4✔
1518
                return nil, d.handleAlreadyInstalled(ctx, deviceDeployment)
2✔
1519
        }
2✔
1520

1521
        // if new artifact has been assigned to device deployment
1522
        // add artifact size to deployment total size,
1523
        // before returning deployment instruction to the device
1524
        if newArtifactAssigned {
2✔
1525
                if err := d.db.IncrementDeploymentTotalSize(
1✔
1526
                        ctx, deviceDeployment.DeploymentId, deviceDeployment.Image.Size); err != nil {
1✔
1527
                        l.Errorf("failed to increment deployment total size: %s", err.Error())
×
1528
                }
×
1529
        }
1530

1531
        ctx, err := d.contextWithStorageSettings(ctx)
1✔
1532
        if err != nil {
1✔
1533
                return nil, err
×
1534
        }
×
1535

1536
        imagePath := model.ImagePathFromContext(ctx, deviceDeployment.Image.Id)
1✔
1537
        link, err := d.objectStorage.GetRequest(
1✔
1538
                ctx,
1✔
1539
                imagePath,
1✔
1540
                deviceDeployment.Image.Name+model.ArtifactFileSuffix,
1✔
1541
                DefaultUpdateDownloadLinkExpire,
1✔
1542
        )
1✔
1543
        if err != nil {
1✔
1544
                return nil, errors.Wrap(err, "Generating download link for the device")
×
1545
        }
×
1546

1547
        instructions := &model.DeploymentInstructions{
1✔
1548
                ID: deviceDeployment.DeploymentId,
1✔
1549
                Artifact: model.ArtifactDeploymentInstructions{
1✔
1550
                        ID: deviceDeployment.Image.Id,
1✔
1551
                        ArtifactName: deviceDeployment.Image.
1✔
1552
                                ArtifactMeta.Name,
1✔
1553
                        Source: *link,
1✔
1554
                        DeviceTypesCompatible: deviceDeployment.Image.
1✔
1555
                                ArtifactMeta.DeviceTypesCompatible,
1✔
1556
                },
1✔
1557
        }
1✔
1558

1✔
1559
        return instructions, nil
1✔
1560
}
1561

1562
func (d *Deployments) saveDeviceDeploymentRequest(ctx context.Context, deviceID string,
1563
        deviceDeployment *model.DeviceDeployment, request *model.DeploymentNextRequest) error {
2✔
1564
        if deviceDeployment.Request != nil {
3✔
1565
                if !reflect.DeepEqual(deviceDeployment.Request, request) {
2✔
1566
                        // the device reported different device type and/or artifact name during the
1✔
1567
                        // update process, this can happen if the mender-store DB in the client is not
1✔
1568
                        // persistent so a new deployment start without a previous one is still ongoing;
1✔
1569
                        // mark deployment for this device as failed to force client to rollback
1✔
1570
                        l := log.FromContext(ctx)
1✔
1571
                        l.Errorf(
1✔
1572
                                "Device with id %s reported new data: %s during update process;"+
1✔
1573
                                        "old data: %s",
1✔
1574
                                deviceID, request, deviceDeployment.Request)
1✔
1575

1✔
1576
                        if err := d.UpdateDeviceDeploymentStatus(ctx, deviceDeployment.DeploymentId, deviceID,
1✔
1577
                                model.DeviceDeploymentState{
1✔
1578
                                        Status: model.DeviceDeploymentStatusFailure,
1✔
1579
                                }); err != nil {
1✔
1580
                                return errors.Wrap(err, "Failed to update deployment status")
×
1581
                        }
×
1582
                        if err := d.reindexDevice(ctx, deviceDeployment.DeviceId); err != nil {
1✔
1583
                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1584
                        }
×
1585
                        if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
1✔
1586
                                deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
1✔
1587
                                l := log.FromContext(ctx)
×
1588
                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1589
                        }
×
1590
                        return ErrConflictingRequestData
1✔
1591
                }
1592
        } else {
2✔
1593
                // save the request
2✔
1594
                if err := d.db.SaveDeviceDeploymentRequest(
2✔
1595
                        ctx, deviceDeployment.Id, request); err != nil {
2✔
1596
                        return err
×
1597
                }
×
1598
        }
1599
        return nil
2✔
1600
}
1601

1602
// UpdateDeviceDeploymentStatus will update the deployment status for device of
1603
// ID `deviceID`. Returns nil if update was successful.
1604
func (d *Deployments) UpdateDeviceDeploymentStatus(ctx context.Context, deploymentID string,
1605
        deviceID string, ddState model.DeviceDeploymentState) error {
6✔
1606

6✔
1607
        l := log.FromContext(ctx)
6✔
1608

6✔
1609
        l.Infof("New status: %s for device %s deployment: %v", ddState.Status, deviceID, deploymentID)
6✔
1610

6✔
1611
        var finishTime *time.Time = nil
6✔
1612
        if model.IsDeviceDeploymentStatusFinished(ddState.Status) {
10✔
1613
                now := time.Now()
4✔
1614
                finishTime = &now
4✔
1615
        }
4✔
1616

1617
        dd, err := d.db.GetDeviceDeployment(ctx, deploymentID, deviceID, false)
6✔
1618
        if err == mongo.ErrStorageNotFound {
7✔
1619
                return ErrStorageNotFound
1✔
1620
        } else if err != nil {
6✔
1621
                return err
×
1622
        }
×
1623

1624
        currentStatus := dd.Status
5✔
1625

5✔
1626
        if currentStatus == model.DeviceDeploymentStatusAborted {
5✔
1627
                return ErrDeploymentAborted
×
1628
        }
×
1629

1630
        if currentStatus == model.DeviceDeploymentStatusDecommissioned {
5✔
1631
                return ErrDeviceDecommissioned
×
1632
        }
×
1633

1634
        // nothing to do
1635
        if ddState.Status == currentStatus {
5✔
1636
                return nil
×
1637
        }
×
1638

1639
        // update finish time
1640
        ddState.FinishTime = finishTime
5✔
1641

5✔
1642
        old, err := d.db.UpdateDeviceDeploymentStatus(ctx,
5✔
1643
                deviceID, deploymentID, ddState, dd.Status)
5✔
1644
        if err != nil {
5✔
1645
                return err
×
1646
        }
×
1647

1648
        if err = d.db.UpdateStatsInc(ctx, deploymentID, old, ddState.Status); err != nil {
5✔
1649
                return err
×
1650
        }
×
1651

1652
        // fetch deployment stats and update deployment status
1653
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
5✔
1654
        if err != nil {
5✔
1655
                return errors.Wrap(err, "failed when searching for deployment")
×
1656
        }
×
1657

1658
        err = d.recalcDeploymentStatus(ctx, deployment)
5✔
1659
        if err != nil {
5✔
1660
                return errors.Wrap(err, "failed to update deployment status")
×
1661
        }
×
1662

1663
        if !ddState.Status.Active() {
9✔
1664
                l := log.FromContext(ctx)
4✔
1665
                ldd := model.DeviceDeployment{
4✔
1666
                        DeviceId:     dd.DeviceId,
4✔
1667
                        DeploymentId: dd.DeploymentId,
4✔
1668
                        Id:           dd.Id,
4✔
1669
                        Status:       ddState.Status,
4✔
1670
                }
4✔
1671
                if err := d.db.SaveLastDeviceDeploymentStatus(ctx, ldd); err != nil {
4✔
1672
                        l.Error(errors.Wrap(err, "failed to save last device deployment status").Error())
×
1673
                }
×
1674
                if err := d.reindexDevice(ctx, deviceID); err != nil {
4✔
1675
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1676
                }
×
1677
                if err := d.reindexDeployment(ctx, dd.DeviceId, dd.DeploymentId, dd.Id); err != nil {
4✔
1678
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1679
                }
×
1680
        }
1681

1682
        return nil
5✔
1683
}
1684

1685
// recalcDeploymentStatus inspects the deployment stats and
1686
// recalculates and updates its status
1687
// it should be used whenever deployment stats are touched
1688
func (d *Deployments) recalcDeploymentStatus(ctx context.Context, dep *model.Deployment) error {
10✔
1689
        status := dep.GetStatus()
10✔
1690

10✔
1691
        if err := d.db.SetDeploymentStatus(ctx, dep.Id, status, time.Now()); err != nil {
10✔
1692
                return err
×
1693
        }
×
1694

1695
        return nil
10✔
1696
}
1697

1698
func (d *Deployments) GetDeploymentStats(ctx context.Context,
1699
        deploymentID string) (model.Stats, error) {
1✔
1700

1✔
1701
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1702

1✔
1703
        if err != nil {
1✔
1704
                return nil, errors.Wrap(err, "checking deployment id")
×
1705
        }
×
1706

1707
        if deployment == nil {
1✔
1708
                return nil, nil
×
1709
        }
×
1710

1711
        return deployment.Stats, nil
1✔
1712
}
1713
func (d *Deployments) GetDeploymentsStats(ctx context.Context,
1714
        deploymentIDs ...string) (deploymentStats []*model.DeploymentStats, err error) {
×
1715

×
1716
        deploymentStats, err = d.db.FindDeploymentStatsByIDs(ctx, deploymentIDs...)
×
1717

×
1718
        if err != nil {
×
1719
                return nil, errors.Wrap(err, "checking deployment statistics for IDs")
×
1720
        }
×
1721

1722
        if deploymentStats == nil {
×
1723
                return nil, ErrModelDeploymentNotFound
×
1724
        }
×
1725

1726
        return deploymentStats, nil
×
1727
}
1728

1729
// GetDeviceStatusesForDeployment retrieve device deployment statuses for a given deployment.
1730
func (d *Deployments) GetDeviceStatusesForDeployment(ctx context.Context,
1731
        deploymentID string) ([]model.DeviceDeployment, error) {
1✔
1732

1✔
1733
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1734
        if err != nil {
1✔
1735
                return nil, ErrModelInternal
×
1736
        }
×
1737

1738
        if deployment == nil {
1✔
1739
                return nil, ErrModelDeploymentNotFound
×
1740
        }
×
1741

1742
        statuses, err := d.db.GetDeviceStatusesForDeployment(ctx, deploymentID)
1✔
1743
        if err != nil {
1✔
1744
                return nil, ErrModelInternal
×
1745
        }
×
1746

1747
        return statuses, nil
1✔
1748
}
1749

1750
func (d *Deployments) GetDevicesListForDeployment(ctx context.Context,
1751
        query store.ListQuery) ([]model.DeviceDeployment, int, error) {
1✔
1752

1✔
1753
        deployment, err := d.db.FindDeploymentByID(ctx, query.DeploymentID)
1✔
1754
        if err != nil {
1✔
1755
                return nil, -1, ErrModelInternal
×
1756
        }
×
1757

1758
        if deployment == nil {
1✔
1759
                return nil, -1, ErrModelDeploymentNotFound
×
1760
        }
×
1761

1762
        statuses, totalCount, err := d.db.GetDevicesListForDeployment(ctx, query)
1✔
1763
        if err != nil {
1✔
1764
                return nil, -1, ErrModelInternal
×
1765
        }
×
1766

1767
        return statuses, totalCount, nil
1✔
1768
}
1769

1770
func (d *Deployments) GetDeviceDeploymentListForDevice(ctx context.Context,
1771
        query store.ListQueryDeviceDeployments) ([]model.DeviceDeploymentListItem, int, error) {
4✔
1772
        deviceDeployments, totalCount, err := d.db.GetDeviceDeploymentsForDevice(ctx, query)
4✔
1773
        if err != nil {
5✔
1774
                return nil, -1, errors.Wrap(err, "retrieving the list of deployment statuses")
1✔
1775
        }
1✔
1776

1777
        deploymentIDs := make([]string, len(deviceDeployments))
3✔
1778
        for i, deviceDeployment := range deviceDeployments {
9✔
1779
                deploymentIDs[i] = deviceDeployment.DeploymentId
6✔
1780
        }
6✔
1781
        var deployments []*model.Deployment
3✔
1782
        if len(deviceDeployments) > 0 {
6✔
1783
                deployments, _, err = d.db.Find(ctx, model.Query{
3✔
1784
                        IDs:          deploymentIDs,
3✔
1785
                        Limit:        len(deviceDeployments),
3✔
1786
                        DisableCount: true,
3✔
1787
                })
3✔
1788
                if err != nil {
4✔
1789
                        return nil, -1, errors.Wrap(err, "retrieving the list of deployments")
1✔
1790
                }
1✔
1791
        }
1792

1793
        deploymentsMap := make(map[string]*model.Deployment, len(deployments))
2✔
1794
        for _, deployment := range deployments {
5✔
1795
                deploymentsMap[deployment.Id] = deployment
3✔
1796
        }
3✔
1797

1798
        res := make([]model.DeviceDeploymentListItem, 0, len(deviceDeployments))
2✔
1799
        for i, deviceDeployment := range deviceDeployments {
6✔
1800
                if deployment, ok := deploymentsMap[deviceDeployment.DeploymentId]; ok {
7✔
1801
                        res = append(res, model.DeviceDeploymentListItem{
3✔
1802
                                Id:         deviceDeployment.Id,
3✔
1803
                                Deployment: deployment,
3✔
1804
                                Device:     &deviceDeployments[i],
3✔
1805
                        })
3✔
1806
                } else {
4✔
1807
                        res = append(res, model.DeviceDeploymentListItem{
1✔
1808
                                Id:     deviceDeployment.Id,
1✔
1809
                                Device: &deviceDeployments[i],
1✔
1810
                        })
1✔
1811
                }
1✔
1812
        }
1813

1814
        return res, totalCount, nil
2✔
1815
}
1816

1817
func (d *Deployments) setDeploymentDeviceCountIfUnset(
1818
        ctx context.Context,
1819
        deployment *model.Deployment,
1820
) error {
6✔
1821
        if deployment.DeviceCount == nil {
6✔
1822
                deviceCount, err := d.db.DeviceCountByDeployment(ctx, deployment.Id)
×
1823
                if err != nil {
×
1824
                        return errors.Wrap(err, "counting device deployments")
×
1825
                }
×
1826
                err = d.db.SetDeploymentDeviceCount(ctx, deployment.Id, deviceCount)
×
1827
                if err != nil {
×
1828
                        return errors.Wrap(err, "setting the device count for the deployment")
×
1829
                }
×
1830
                deployment.DeviceCount = &deviceCount
×
1831
        }
1832

1833
        return nil
6✔
1834
}
1835

1836
func (d *Deployments) LookupDeployment(ctx context.Context,
1837
        query model.Query) ([]*model.Deployment, int64, error) {
1✔
1838
        list, totalCount, err := d.db.Find(ctx, query)
1✔
1839

1✔
1840
        if err != nil {
1✔
1841
                return nil, 0, errors.Wrap(err, "searching for deployments")
×
1842
        }
×
1843

1844
        if list == nil {
2✔
1845
                return make([]*model.Deployment, 0), 0, nil
1✔
1846
        }
1✔
1847

1848
        for _, deployment := range list {
×
1849
                if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
×
1850
                        return nil, 0, err
×
1851
                }
×
1852
        }
1853

1854
        return list, totalCount, nil
×
1855
}
1856

1857
// SaveDeviceDeploymentLog will save the deployment log for device of
1858
// ID `deviceID`. Returns nil if log was saved successfully.
1859
func (d *Deployments) SaveDeviceDeploymentLog(ctx context.Context, deviceID string,
1860
        deploymentID string, logs []model.LogMessage) error {
1✔
1861

1✔
1862
        // repack to temporary deployment log and validate
1✔
1863
        dlog := model.DeploymentLog{
1✔
1864
                DeviceID:     deviceID,
1✔
1865
                DeploymentID: deploymentID,
1✔
1866
                Messages:     logs,
1✔
1867
        }
1✔
1868
        if err := dlog.Validate(); err != nil {
1✔
1869
                return errors.Wrapf(err, ErrStorageInvalidLog.Error())
×
1870
        }
×
1871

1872
        if has, err := d.HasDeploymentForDevice(ctx, deploymentID, deviceID); !has {
1✔
1873
                if err != nil {
×
1874
                        return err
×
1875
                } else {
×
1876
                        return ErrModelDeploymentNotFound
×
1877
                }
×
1878
        }
1879

1880
        if err := d.db.SaveDeviceDeploymentLog(ctx, dlog); err != nil {
1✔
1881
                return err
×
1882
        }
×
1883

1884
        return d.db.UpdateDeviceDeploymentLogAvailability(ctx,
1✔
1885
                deviceID, deploymentID, true)
1✔
1886
}
1887

1888
func (d *Deployments) GetDeviceDeploymentLog(ctx context.Context,
1889
        deviceID, deploymentID string) (*model.DeploymentLog, error) {
1✔
1890

1✔
1891
        return d.db.GetDeviceDeploymentLog(ctx,
1✔
1892
                deviceID, deploymentID)
1✔
1893
}
1✔
1894

1895
func (d *Deployments) HasDeploymentForDevice(ctx context.Context,
1896
        deploymentID string, deviceID string) (bool, error) {
1✔
1897
        return d.db.HasDeploymentForDevice(ctx, deploymentID, deviceID)
1✔
1898
}
1✔
1899

1900
// AbortDeployment aborts deployment for devices and updates deployment stats
1901
func (d *Deployments) AbortDeployment(ctx context.Context, deploymentID string) error {
5✔
1902

5✔
1903
        if err := d.db.AbortDeviceDeployments(ctx, deploymentID); err != nil {
6✔
1904
                return err
1✔
1905
        }
1✔
1906

1907
        stats, err := d.db.AggregateDeviceDeploymentByStatus(
4✔
1908
                ctx, deploymentID)
4✔
1909
        if err != nil {
5✔
1910
                return err
1✔
1911
        }
1✔
1912

1913
        // update statistics
1914
        if err := d.db.UpdateStats(ctx, deploymentID, stats); err != nil {
4✔
1915
                return errors.Wrap(err, "failed to update deployment stats")
1✔
1916
        }
1✔
1917

1918
        // when aborting the deployment we need to set status directly instead of
1919
        // using recalcDeploymentStatus method;
1920
        // it is possible that the deployment does not have any device deployments yet;
1921
        // in that case, all statistics are 0 and calculating status based on statistics
1922
        // will not work - the calculated status will be "pending"
1923
        if err := d.db.SetDeploymentStatus(ctx,
2✔
1924
                deploymentID, model.DeploymentStatusFinished, time.Now()); err != nil {
2✔
1925
                return errors.Wrap(err, "failed to update deployment status")
×
1926
        }
×
1927

1928
        return nil
2✔
1929
}
1930

1931
func (d *Deployments) updateDeviceDeploymentsStatus(
1932
        ctx context.Context,
1933
        deviceId string,
1934
        status model.DeviceDeploymentStatus,
1935
) error {
15✔
1936
        var latestDeployment *time.Time
15✔
1937
        // Retrieve active device deployment for the device
15✔
1938
        deviceDeployment, err := d.db.FindOldestActiveDeviceDeployment(ctx, deviceId)
15✔
1939
        if err != nil {
17✔
1940
                return errors.Wrap(err, "Searching for active deployment for the device")
2✔
1941
        } else if deviceDeployment != nil {
17✔
1942
                now := time.Now()
2✔
1943
                ddStatus := model.DeviceDeploymentState{
2✔
1944
                        Status:     status,
2✔
1945
                        FinishTime: &now,
2✔
1946
                }
2✔
1947
                if err := d.UpdateDeviceDeploymentStatus(ctx, deviceDeployment.DeploymentId,
2✔
1948
                        deviceId, ddStatus); err != nil {
2✔
1949
                        return errors.Wrap(err, "updating device deployment status")
×
1950
                }
×
1951
                latestDeployment = deviceDeployment.Created
2✔
1952
        } else {
11✔
1953
                // get latest device deployment for the device
11✔
1954
                deviceDeployment, err := d.db.FindLatestInactiveDeviceDeployment(ctx, deviceId)
11✔
1955
                if err != nil {
11✔
1956
                        return errors.Wrap(err, "Searching for latest active deployment for the device")
×
1957
                } else if deviceDeployment == nil {
20✔
1958
                        latestDeployment = &time.Time{}
9✔
1959
                } else {
11✔
1960
                        latestDeployment = deviceDeployment.Created
2✔
1961
                }
2✔
1962
        }
1963

1964
        // get deployments newer then last device deployment
1965
        // iterate over deployments and check if the device is part of the deployment or not
1966
        // if the device is part of the deployment create new, decommisioned device deployment
1967
        for skip := 0; true; skip += 100 {
33✔
1968
                deployments, err := d.db.FindNewerActiveDeployments(ctx, latestDeployment, skip, 100)
20✔
1969
                if err != nil {
20✔
1970
                        return errors.Wrap(err, "Failed to search for newer active deployments")
×
1971
                }
×
1972
                if len(deployments) == 0 {
33✔
1973
                        break
13✔
1974
                }
1975
                for _, deployment := range deployments {
14✔
1976
                        ok, err := d.isDevicePartOfDeployment(ctx, deviceId, deployment)
7✔
1977
                        if err != nil {
7✔
1978
                                return err
×
1979
                        }
×
1980
                        if ok {
12✔
1981
                                deviceDeployment, err := d.createDeviceDeploymentWithStatus(ctx,
5✔
1982
                                        deviceId, deployment, status)
5✔
1983
                                if err != nil {
5✔
1984
                                        return err
×
1985
                                }
×
1986
                                if !status.Active() {
10✔
1987
                                        if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
5✔
1988
                                                deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
5✔
1989
                                                l := log.FromContext(ctx)
×
1990
                                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1991
                                        }
×
1992
                                }
1993
                        }
1994
                }
1995
        }
1996

1997
        if err := d.reindexDevice(ctx, deviceId); err != nil {
13✔
1998
                l := log.FromContext(ctx)
×
1999
                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
2000
        }
×
2001

2002
        return nil
13✔
2003
}
2004

2005
// DecommissionDevice updates the status of all the pending and active deployments for a device
2006
// to decommissioned
2007
func (d *Deployments) DecommissionDevice(ctx context.Context, deviceId string) error {
7✔
2008
        return d.updateDeviceDeploymentsStatus(
7✔
2009
                ctx,
7✔
2010
                deviceId,
7✔
2011
                model.DeviceDeploymentStatusDecommissioned,
7✔
2012
        )
7✔
2013
}
7✔
2014

2015
// AbortDeviceDeployments aborts all the pending and active deployments for a device
2016
func (d *Deployments) AbortDeviceDeployments(ctx context.Context, deviceId string) error {
8✔
2017
        return d.updateDeviceDeploymentsStatus(
8✔
2018
                ctx,
8✔
2019
                deviceId,
8✔
2020
                model.DeviceDeploymentStatusAborted,
8✔
2021
        )
8✔
2022
}
8✔
2023

2024
// DeleteDeviceDeploymentsHistory deletes the device deployments history
2025
func (d *Deployments) DeleteDeviceDeploymentsHistory(ctx context.Context, deviceId string) error {
2✔
2026
        // get device deployments which will be marked as deleted
2✔
2027
        f := false
2✔
2028
        dd, err := d.db.GetDeviceDeployments(ctx, 0, 0, deviceId, &f, false)
2✔
2029
        if err != nil {
2✔
2030
                return err
×
2031
        }
×
2032

2033
        // no device deployments to update
2034
        if len(dd) <= 0 {
2✔
2035
                return nil
×
2036
        }
×
2037

2038
        // mark device deployments as deleted
2039
        if err := d.db.DeleteDeviceDeploymentsHistory(ctx, deviceId); err != nil {
3✔
2040
                return err
1✔
2041
        }
1✔
2042

2043
        // trigger reindexing of updated device deployments
2044
        deviceDeployments := make([]workflows.DeviceDeploymentShortInfo, len(dd))
1✔
2045
        for i, d := range dd {
2✔
2046
                deviceDeployments[i].ID = d.Id
1✔
2047
                deviceDeployments[i].DeviceID = d.DeviceId
1✔
2048
                deviceDeployments[i].DeploymentID = d.DeploymentId
1✔
2049
        }
1✔
2050
        if d.reportingClient != nil {
2✔
2051
                err = d.workflowsClient.StartReindexReportingDeploymentBatch(ctx, deviceDeployments)
1✔
2052
        }
1✔
2053
        return err
1✔
2054
}
2055

2056
// Storage settings
2057
func (d *Deployments) GetStorageSettings(ctx context.Context) (*model.StorageSettings, error) {
3✔
2058
        settings, err := d.db.GetStorageSettings(ctx)
3✔
2059
        if err != nil {
4✔
2060
                return nil, errors.Wrap(err, "Searching for settings failed")
1✔
2061
        }
1✔
2062

2063
        return settings, nil
2✔
2064
}
2065

2066
func (d *Deployments) SetStorageSettings(
2067
        ctx context.Context,
2068
        storageSettings *model.StorageSettings,
2069
) error {
4✔
2070
        if storageSettings != nil {
8✔
2071
                ctx = storage.SettingsWithContext(ctx, storageSettings)
4✔
2072
                if err := d.objectStorage.HealthCheck(ctx); err != nil {
4✔
2073
                        return errors.WithMessage(err,
×
2074
                                "the provided storage settings failed the health check",
×
2075
                        )
×
2076
                }
×
2077
        }
2078
        if err := d.db.SetStorageSettings(ctx, storageSettings); err != nil {
6✔
2079
                return errors.Wrap(err, "Failed to save settings")
2✔
2080
        }
2✔
2081

2082
        return nil
2✔
2083
}
2084

2085
func (d *Deployments) WithReporting(c reporting.Client) *Deployments {
7✔
2086
        d.reportingClient = c
7✔
2087
        return d
7✔
2088
}
7✔
2089

2090
func (d *Deployments) haveReporting() bool {
6✔
2091
        return d.reportingClient != nil
6✔
2092
}
6✔
2093

2094
func (d *Deployments) search(
2095
        ctx context.Context,
2096
        tid string,
2097
        parms model.SearchParams,
2098
) ([]model.InvDevice, int, error) {
6✔
2099
        if d.haveReporting() {
7✔
2100
                return d.reportingClient.Search(ctx, tid, parms)
1✔
2101
        } else {
6✔
2102
                return d.inventoryClient.Search(ctx, tid, parms)
5✔
2103
        }
5✔
2104
}
2105

2106
func (d *Deployments) UpdateDeploymentsWithArtifactName(
2107
        ctx context.Context,
2108
        artifactName string,
2109
) error {
2✔
2110
        // first check if there are pending deployments with given artifact name
2✔
2111
        exists, err := d.db.ExistUnfinishedByArtifactName(ctx, artifactName)
2✔
2112
        if err != nil {
2✔
2113
                return errors.Wrap(err, "looking for deployments with given artifact name")
×
2114
        }
×
2115
        if !exists {
3✔
2116
                return nil
1✔
2117
        }
1✔
2118

2119
        // Assign artifacts to the deployments with given artifact name
2120
        artifacts, err := d.db.ImagesByName(ctx, artifactName)
1✔
2121
        if err != nil {
1✔
2122
                return errors.Wrap(err, "Finding artifact with given name")
×
2123
        }
×
2124

2125
        if len(artifacts) == 0 {
1✔
2126
                return ErrNoArtifact
×
2127
        }
×
2128
        artifactIDs := getArtifactIDs(artifacts)
1✔
2129
        return d.db.UpdateDeploymentsWithArtifactName(ctx, artifactName, artifactIDs)
1✔
2130
}
2131

2132
func (d *Deployments) reindexDevice(ctx context.Context, deviceID string) error {
25✔
2133
        if d.reportingClient != nil {
27✔
2134
                return d.workflowsClient.StartReindexReporting(ctx, deviceID)
2✔
2135
        }
2✔
2136
        return nil
23✔
2137
}
2138

2139
func (d *Deployments) reindexDeployment(ctx context.Context,
2140
        deviceID, deploymentID, ID string) error {
17✔
2141
        if d.reportingClient != nil {
19✔
2142
                return d.workflowsClient.StartReindexReportingDeployment(ctx, deviceID, deploymentID, ID)
2✔
2143
        }
2✔
2144
        return nil
15✔
2145
}
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