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

mendersoftware / deployments / 972678690

18 Aug 2023 07:14PM UTC coverage: 79.678% (+0.07%) from 79.613%
972678690

Pull #901

gitlab-ci

merlin-northern
test: docs and acc test

Ticket: MEN-6623
Signed-off-by: Peter Grzybowski <peter@northern.tech>
Pull Request #901: feat: save and get the update types

74 of 85 new or added lines in 4 files covered. (87.06%)

391 existing lines in 3 files now uncovered.

7810 of 9802 relevant lines covered (79.68%)

34.01 hits per line

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

77.14
/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(ctx context.Context, intentID string, skipVerify bool) error
131
        GetImage(ctx context.Context, id string) (*model.Image, error)
132
        DeleteImage(ctx context.Context, imageID string) error
133
        CreateImage(ctx context.Context,
134
                multipartUploadMsg *model.MultipartUploadMsg) (string, error)
135
        GenerateImage(ctx context.Context,
136
                multipartUploadMsg *model.MultipartGenerateImageMsg) (string, error)
137
        GenerateConfigurationImage(
138
                ctx context.Context,
139
                deviceType string,
140
                deploymentID string,
141
        ) (io.Reader, error)
142
        EditImage(ctx context.Context, id string,
143
                constructorData *model.ImageMeta) (bool, error)
144

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

190
        // releases
191
        ReplaceReleaseTags(ctx context.Context, releaseName string, tags model.Tags) error
192
        UpdateRelease(ctx context.Context, releaseName string, release model.ReleasePatch) error
193
        ListReleaseTags(ctx context.Context) (model.Tags, error)
194
}
195

196
type Deployments struct {
197
        db              store.DataStore
198
        objectStorage   storage.ObjectStorage
199
        workflowsClient workflows.Client
200
        inventoryClient inventory.Client
201
        reportingClient reporting.Client
202
}
203

204
// Compile-time check
205
var _ App = &Deployments{}
206

207
func NewDeployments(
208
        storage store.DataStore,
209
        objectStorage storage.ObjectStorage,
210
) *Deployments {
72✔
211
        return &Deployments{
72✔
212
                db:              storage,
72✔
213
                objectStorage:   objectStorage,
72✔
214
                workflowsClient: workflows.NewClient(),
72✔
215
                inventoryClient: inventory.NewClient(),
72✔
216
        }
72✔
217
}
72✔
218

219
func (d *Deployments) SetWorkflowsClient(workflowsClient workflows.Client) {
4✔
220
        d.workflowsClient = workflowsClient
4✔
221
}
4✔
222

223
func (d *Deployments) SetInventoryClient(inventoryClient inventory.Client) {
8✔
224
        d.inventoryClient = inventoryClient
8✔
225
}
8✔
226

227
func (d *Deployments) HealthCheck(ctx context.Context) error {
6✔
228
        err := d.db.Ping(ctx)
6✔
229
        if err != nil {
7✔
230
                return errors.Wrap(err, "error reaching MongoDB")
1✔
231
        }
1✔
232
        err = d.objectStorage.HealthCheck(ctx)
5✔
233
        if err != nil {
6✔
234
                return errors.Wrap(
1✔
235
                        err,
1✔
236
                        "error reaching artifact storage service",
1✔
237
                )
1✔
238
        }
1✔
239

240
        err = d.workflowsClient.CheckHealth(ctx)
4✔
241
        if err != nil {
5✔
242
                return errors.Wrap(err, "Workflows service unhealthy")
1✔
243
        }
1✔
244

245
        err = d.inventoryClient.CheckHealth(ctx)
3✔
246
        if err != nil {
4✔
247
                return errors.Wrap(err, "Inventory service unhealthy")
1✔
248
        }
1✔
249

250
        if d.reportingClient != nil {
4✔
251
                err = d.reportingClient.CheckHealth(ctx)
2✔
252
                if err != nil {
3✔
253
                        return errors.Wrap(err, "Reporting service unhealthy")
1✔
254
                }
1✔
255
        }
256
        return nil
1✔
257
}
258

259
func (d *Deployments) contextWithStorageSettings(
260
        ctx context.Context,
261
) (context.Context, error) {
26✔
262
        var err error
26✔
263
        settings, ok := storage.SettingsFromContext(ctx)
26✔
264
        if !ok {
48✔
265
                settings, err = d.db.GetStorageSettings(ctx)
22✔
266
        }
22✔
267
        if err != nil {
28✔
268
                return nil, err
2✔
269
        } else if settings != nil {
26✔
UNCOV
270
                err = settings.Validate()
×
271
                if err != nil {
×
272
                        return nil, err
×
273
                }
×
274
        }
275
        return storage.SettingsWithContext(ctx, settings), nil
24✔
276
}
277

278
func (d *Deployments) GetLimit(ctx context.Context, name string) (*model.Limit, error) {
3✔
279
        limit, err := d.db.GetLimit(ctx, name)
3✔
280
        if err == mongo.ErrLimitNotFound {
4✔
281
                return &model.Limit{
1✔
282
                        Name:  name,
1✔
283
                        Value: 0,
1✔
284
                }, nil
1✔
285

1✔
286
        } else if err != nil {
4✔
287
                return nil, errors.Wrap(err, "failed to obtain limit from storage")
1✔
288
        }
1✔
289
        return limit, nil
1✔
290
}
291

292
func (d *Deployments) ProvisionTenant(ctx context.Context, tenant_id string) error {
3✔
293
        if err := d.db.ProvisionTenant(ctx, tenant_id); err != nil {
4✔
294
                return errors.Wrap(err, "failed to provision tenant")
1✔
295
        }
1✔
296

297
        return nil
2✔
298
}
299

300
// CreateImage parses artifact and uploads artifact file to the file storage - in parallel,
301
// and creates image structure in the system.
302
// Returns image ID and nil on success.
303
func (d *Deployments) CreateImage(ctx context.Context,
304
        multipartUploadMsg *model.MultipartUploadMsg) (string, error) {
1✔
305
        return d.handleArtifact(ctx, multipartUploadMsg, false)
1✔
306
}
1✔
307

308
// handleArtifact parses artifact and uploads artifact file to the file storage - in parallel,
309
// and creates image structure in the system.
310
// Returns image ID, artifact file ID and nil on success.
311
func (d *Deployments) handleArtifact(ctx context.Context,
312
        multipartUploadMsg *model.MultipartUploadMsg,
313
        skipVerify bool,
314
) (string, error) {
5✔
315

5✔
316
        l := log.FromContext(ctx)
5✔
317
        ctx, err := d.contextWithStorageSettings(ctx)
5✔
318
        if err != nil {
5✔
UNCOV
319
                return "", err
×
320
        }
×
321

322
        // create pipe
323
        pR, pW := io.Pipe()
5✔
324

5✔
325
        artifactReader := utils.CountReads(multipartUploadMsg.ArtifactReader)
5✔
326

5✔
327
        tee := io.TeeReader(artifactReader, pW)
5✔
328

5✔
329
        uid, err := uuid.Parse(multipartUploadMsg.ArtifactID)
5✔
330
        if err != nil {
6✔
331
                uid, _ = uuid.NewRandom()
1✔
332
        }
1✔
333
        artifactID := uid.String()
5✔
334

5✔
335
        ch := make(chan error)
5✔
336
        // create goroutine for artifact upload
5✔
337
        //
5✔
338
        // reading from the pipe (which is done in UploadArtifact method) is a blocking operation
5✔
339
        // and cannot be done in the same goroutine as writing to the pipe
5✔
340
        //
5✔
341
        // uploading and parsing artifact in the same process will cause in a deadlock!
5✔
342
        //nolint:errcheck
5✔
343
        go func() (err error) {
10✔
344
                defer func() { ch <- err }()
10✔
345
                if skipVerify {
8✔
346
                        err = nil
3✔
347
                        io.Copy(io.Discard, pR)
3✔
348
                        return nil
3✔
349
                }
3✔
350
                err = d.objectStorage.PutObject(
3✔
351
                        ctx, model.ImagePathFromContext(ctx, artifactID), pR,
3✔
352
                )
3✔
353
                if err != nil {
4✔
354
                        pR.CloseWithError(err)
1✔
355
                }
1✔
356
                return err
3✔
357
        }()
358

359
        // parse artifact
360
        // artifact library reads all the data from the given reader
361
        metaArtifactConstructor, err := getMetaFromArchive(&tee, skipVerify)
5✔
362
        if err != nil {
10✔
363
                _ = pW.CloseWithError(err)
5✔
364
                <-ch
5✔
365
                return artifactID, errors.Wrap(ErrModelParsingArtifactFailed, err.Error())
5✔
366
        }
5✔
367
        // validate artifact metadata
368
        if err = metaArtifactConstructor.Validate(); err != nil {
1✔
UNCOV
369
                return artifactID, ErrModelInvalidMetadata
×
370
        }
×
371

372
        if !skipVerify {
2✔
373
                // read the rest of the data,
1✔
374
                // just in case the artifact library did not read all the data from the reader
1✔
375
                _, err = io.Copy(io.Discard, tee)
1✔
376
                if err != nil {
1✔
UNCOV
377
                        // CloseWithError will cause the reading end to abort upload.
×
378
                        _ = pW.CloseWithError(err)
×
379
                        <-ch
×
380
                        return artifactID, err
×
381
                }
×
382
        }
383

384
        // close the pipe
385
        pW.Close()
1✔
386

1✔
387
        // collect output from the goroutine
1✔
388
        if uploadResponseErr := <-ch; uploadResponseErr != nil {
1✔
UNCOV
389
                return artifactID, uploadResponseErr
×
390
        }
×
391

392
        image := model.NewImage(
1✔
393
                artifactID,
1✔
394
                multipartUploadMsg.MetaConstructor,
1✔
395
                metaArtifactConstructor,
1✔
396
                artifactReader.Count(),
1✔
397
        )
1✔
398

1✔
399
        // here
1✔
400
        // image.ArtifactMeta.Updates[0].TypeInfo
1✔
401
        // save image structure in the system
1✔
402
        if err = d.db.InsertImage(ctx, image); err != nil {
1✔
403
                // Try to remove the storage from s3.
×
404
                if errDelete := d.objectStorage.DeleteObject(
×
405
                        ctx, model.ImagePathFromContext(ctx, artifactID),
×
406
                ); errDelete != nil {
×
407
                        l.Errorf(
×
408
                                "failed to clean up artifact storage after failure: %s",
×
409
                                errDelete,
×
410
                        )
×
411
                }
×
412
                if idxErr, ok := err.(*model.ConflictError); ok {
×
413
                        return artifactID, idxErr
×
414
                }
×
UNCOV
415
                return artifactID, errors.Wrap(err, "Fail to store the metadata")
×
416
        }
417
        i := 0
1✔
418
        var updateTypes []string
1✔
419
        if image.ArtifactMeta != nil {
2✔
420
                updateTypes = make([]string, len(image.ArtifactMeta.Updates))
1✔
421
                for _, t := range image.ArtifactMeta.Updates {
2✔
422
                        if t.TypeInfo.Type == nil {
2✔
423
                                continue
1✔
424
                        }
425
                        updateTypes[i] = *t.TypeInfo.Type
1✔
426
                        i++
1✔
427
                }
428
        }
429
        if i > 0 {
2✔
430
                err = d.db.SaveUpdateTypes(ctx, updateTypes[:i])
1✔
431
                if err != nil {
1✔
NEW
432
                        l.Errorf(
×
NEW
433
                                "error while saving the update types for the artifact: %s",
×
NEW
UNCOV
434
                                err.Error(),
×
NEW
UNCOV
435
                        )
×
NEW
436
                }
×
437
        }
438
        // update release
439
        if err := d.updateRelease(ctx, image, nil); err != nil {
1✔
440
                return "", err
×
441
        }
×
442

443
        if err := d.UpdateDeploymentsWithArtifactName(ctx, metaArtifactConstructor.Name); err != nil {
1✔
UNCOV
444
                return "", errors.Wrap(err, "fail to update deployments")
×
UNCOV
445
        }
×
446

447
        return artifactID, nil
1✔
448
}
449

450
// GenerateImage parses raw data and uploads it to the file storage - in parallel,
451
// creates image structure in the system, and starts the workflow to generate the
452
// artifact from them.
453
// Returns image ID and nil on success.
454
func (d *Deployments) GenerateImage(ctx context.Context,
455
        multipartGenerateImageMsg *model.MultipartGenerateImageMsg) (string, error) {
11✔
456

11✔
457
        if multipartGenerateImageMsg == nil {
12✔
458
                return "", ErrModelMultipartUploadMsgMalformed
1✔
459
        }
1✔
460

461
        imgPath, err := d.handleRawFile(ctx, multipartGenerateImageMsg)
10✔
462
        if err != nil {
15✔
463
                return "", err
5✔
464
        }
5✔
465
        if id := identity.FromContext(ctx); id != nil && len(id.Tenant) > 0 {
6✔
466
                multipartGenerateImageMsg.TenantID = id.Tenant
1✔
467
        }
1✔
468
        err = d.workflowsClient.StartGenerateArtifact(ctx, multipartGenerateImageMsg)
5✔
469
        if err != nil {
7✔
470
                if cleanupErr := d.objectStorage.DeleteObject(ctx, imgPath); cleanupErr != nil {
3✔
471
                        return "", errors.Wrap(err, cleanupErr.Error())
1✔
472
                }
1✔
473
                return "", err
1✔
474
        }
475

476
        return multipartGenerateImageMsg.ArtifactID, err
3✔
477
}
478

479
func (d *Deployments) GenerateConfigurationImage(
480
        ctx context.Context,
481
        deviceType string,
482
        deploymentID string,
483
) (io.Reader, error) {
5✔
484
        var buf bytes.Buffer
5✔
485
        dpl, err := d.db.FindDeploymentByID(ctx, deploymentID)
5✔
486
        if err != nil {
6✔
487
                return nil, err
1✔
488
        } else if dpl == nil {
6✔
489
                return nil, ErrModelDeploymentNotFound
1✔
490
        }
1✔
491
        var metaData map[string]interface{}
3✔
492
        err = json.Unmarshal(dpl.Configuration, &metaData)
3✔
493
        if err != nil {
4✔
494
                return nil, errors.Wrapf(err, "malformed configuration in deployment")
1✔
495
        }
1✔
496

497
        artieWriter := awriter.NewWriter(&buf, artifact.NewCompressorNone())
2✔
498
        module := handlers.NewModuleImage(ArtifactConfigureType)
2✔
499
        err = artieWriter.WriteArtifact(&awriter.WriteArtifactArgs{
2✔
500
                Format:  "mender",
2✔
501
                Version: 3,
2✔
502
                Devices: []string{deviceType},
2✔
503
                Name:    dpl.ArtifactName,
2✔
504
                Updates: &awriter.Updates{Updates: []handlers.Composer{module}},
2✔
505
                Depends: &artifact.ArtifactDepends{
2✔
506
                        CompatibleDevices: []string{deviceType},
2✔
507
                },
2✔
508
                Provides: &artifact.ArtifactProvides{
2✔
509
                        ArtifactName: dpl.ArtifactName,
2✔
510
                },
2✔
511
                MetaData: metaData,
2✔
512
                TypeInfoV3: &artifact.TypeInfoV3{
2✔
513
                        Type: &ArtifactConfigureType,
2✔
514
                        ArtifactProvides: artifact.TypeInfoProvides{
2✔
515
                                ArtifactConfigureProvides: dpl.ArtifactName,
2✔
516
                        },
2✔
517
                        ArtifactDepends:        artifact.TypeInfoDepends{},
2✔
518
                        ClearsArtifactProvides: []string{ArtifactConfigureProvidesCleared},
2✔
519
                },
2✔
520
        })
2✔
521

2✔
522
        return &buf, err
2✔
523
}
524

525
// handleRawFile parses raw data, uploads it to the file storage,
526
// and starts the workflow to generate the artifact.
527
// Returns the object path to the file and nil on success.
528
func (d *Deployments) handleRawFile(ctx context.Context,
529
        multipartMsg *model.MultipartGenerateImageMsg) (filePath string, err error) {
10✔
530
        l := log.FromContext(ctx)
10✔
531
        uid, _ := uuid.NewRandom()
10✔
532
        artifactID := uid.String()
10✔
533
        multipartMsg.ArtifactID = artifactID
10✔
534
        filePath = model.ImagePathFromContext(ctx, artifactID+fileSuffixTmp)
10✔
535

10✔
536
        // check if artifact is unique
10✔
537
        // artifact is considered to be unique if there is no artifact with the same name
10✔
538
        // and supporting the same platform in the system
10✔
539
        isArtifactUnique, err := d.db.IsArtifactUnique(ctx,
10✔
540
                multipartMsg.Name,
10✔
541
                multipartMsg.DeviceTypesCompatible,
10✔
542
        )
10✔
543
        if err != nil {
11✔
544
                return "", errors.Wrap(err, "Fail to check if artifact is unique")
1✔
545
        }
1✔
546
        if !isArtifactUnique {
10✔
547
                return "", ErrModelArtifactNotUnique
1✔
548
        }
1✔
549

550
        ctx, err = d.contextWithStorageSettings(ctx)
8✔
551
        if err != nil {
8✔
UNCOV
552
                return "", err
×
UNCOV
553
        }
×
554
        err = d.objectStorage.PutObject(
8✔
555
                ctx, filePath, multipartMsg.FileReader,
8✔
556
        )
8✔
557
        if err != nil {
9✔
558
                return "", err
1✔
559
        }
1✔
560
        defer func() {
14✔
561
                if err != nil {
9✔
562
                        e := d.objectStorage.DeleteObject(ctx, filePath)
2✔
563
                        if e != nil {
4✔
564
                                l.Errorf("error cleaning up raw file '%s' from objectstorage: %s",
2✔
565
                                        filePath, e)
2✔
566
                        }
2✔
567
                }
568
        }()
569

570
        link, err := d.objectStorage.GetRequest(
7✔
571
                ctx,
7✔
572
                filePath,
7✔
573
                path.Base(filePath),
7✔
574
                DefaultImageGenerationLinkExpire,
7✔
575
        )
7✔
576
        if err != nil {
8✔
577
                return "", err
1✔
578
        }
1✔
579
        multipartMsg.GetArtifactURI = link.Uri
6✔
580

6✔
581
        link, err = d.objectStorage.DeleteRequest(ctx, filePath, DefaultImageGenerationLinkExpire)
6✔
582
        if err != nil {
7✔
583
                return "", err
1✔
584
        }
1✔
585
        multipartMsg.DeleteArtifactURI = link.Uri
5✔
586

5✔
587
        return artifactID, nil
5✔
588
}
589

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

1✔
594
        image, err := d.db.FindImageByID(ctx, id)
1✔
595
        if err != nil {
1✔
UNCOV
596
                return nil, errors.Wrap(err, "Searching for image with specified ID")
×
UNCOV
597
        }
×
598

599
        if image == nil {
2✔
600
                return nil, nil
1✔
601
        }
1✔
602

603
        return image, nil
1✔
604
}
605

606
// DeleteImage removes metadata and image file
607
// Noop for not existing images
608
// Allowed to remove image only if image is not scheduled or in progress for an updates - then image
609
// file is needed
610
// In case of already finished updates only image file is not needed, metadata is attached directly
611
// to device deployment therefore we still have some information about image that have been used
612
// (but not the file)
613
func (d *Deployments) DeleteImage(ctx context.Context, imageID string) error {
1✔
614
        found, err := d.GetImage(ctx, imageID)
1✔
615

1✔
616
        if err != nil {
1✔
617
                return errors.Wrap(err, "Getting image metadata")
×
618
        }
×
619

620
        if found == nil {
1✔
UNCOV
621
                return ErrImageMetaNotFound
×
622
        }
×
623

624
        inUse, err := d.ImageUsedInActiveDeployment(ctx, imageID)
1✔
625
        if err != nil {
1✔
UNCOV
626
                return errors.Wrap(err, "Checking if image is used in active deployment")
×
UNCOV
627
        }
×
628

629
        // Image is in use, not allowed to delete
630
        if inUse {
2✔
631
                return ErrModelImageInActiveDeployment
1✔
632
        }
1✔
633

634
        // Delete image file (call to external service)
635
        // Noop for not existing file
636
        ctx, err = d.contextWithStorageSettings(ctx)
1✔
637
        if err != nil {
1✔
638
                return err
×
639
        }
×
640
        imagePath := model.ImagePathFromContext(ctx, imageID)
1✔
641
        if err := d.objectStorage.DeleteObject(ctx, imagePath); err != nil {
1✔
UNCOV
642
                return errors.Wrap(err, "Deleting image file")
×
643
        }
×
644

645
        // Delete metadata
646
        if err := d.db.DeleteImage(ctx, imageID); err != nil {
1✔
UNCOV
647
                return errors.Wrap(err, "Deleting image metadata")
×
648
        }
×
649

650
        // update release
651
        if err := d.updateRelease(ctx, nil, found); err != nil {
1✔
UNCOV
652
                return err
×
UNCOV
653
        }
×
654

655
        return nil
1✔
656
}
657

658
// ListImages according to specified filers.
659
func (d *Deployments) ListImages(
660
        ctx context.Context,
661
        filters *model.ReleaseOrImageFilter,
662
) ([]*model.Image, int, error) {
1✔
663
        imageList, count, err := d.db.ListImages(ctx, filters)
1✔
664
        if err != nil {
1✔
UNCOV
665
                return nil, 0, errors.Wrap(err, "Searching for image metadata")
×
UNCOV
666
        }
×
667

668
        if imageList == nil {
2✔
669
                return make([]*model.Image, 0), 0, nil
1✔
670
        }
1✔
671

672
        return imageList, count, nil
1✔
673
}
674

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

×
679
        if err := constructor.Validate(); err != nil {
×
680
                return false, errors.Wrap(err, "Validating image metadata")
×
681
        }
×
682

UNCOV
683
        found, err := d.ImageUsedInDeployment(ctx, imageID)
×
684
        if err != nil {
×
685
                return false, errors.Wrap(err, "Searching for usage of the image among deployments")
×
686
        }
×
687

688
        if found {
×
689
                return false, ErrModelImageUsedInAnyDeployment
×
690
        }
×
691

UNCOV
692
        foundImage, err := d.db.FindImageByID(ctx, imageID)
×
693
        if err != nil {
×
694
                return false, errors.Wrap(err, "Searching for image with specified ID")
×
695
        }
×
696

697
        if foundImage == nil {
×
698
                return false, nil
×
699
        }
×
700

701
        foundImage.SetModified(time.Now())
×
702
        foundImage.ImageMeta = constructor
×
703

×
UNCOV
704
        _, err = d.db.Update(ctx, foundImage)
×
705
        if err != nil {
×
706
                return false, errors.Wrap(err, "Updating image matadata")
×
707
        }
×
708

709
        if err := d.updateReleaseEditArtifact(ctx, foundImage); err != nil {
×
UNCOV
710
                return false, err
×
UNCOV
711
        }
×
712

UNCOV
713
        return true, nil
×
714
}
715

716
// DownloadLink presigned GET link to download image file.
717
// Returns error if image have not been uploaded.
718
func (d *Deployments) DownloadLink(ctx context.Context, imageID string,
719
        expire time.Duration) (*model.Link, error) {
1✔
720

1✔
721
        image, err := d.GetImage(ctx, imageID)
1✔
722
        if err != nil {
1✔
723
                return nil, errors.Wrap(err, "Searching for image with specified ID")
×
724
        }
×
725

726
        if image == nil {
1✔
UNCOV
727
                return nil, nil
×
728
        }
×
729

730
        ctx, err = d.contextWithStorageSettings(ctx)
1✔
731
        if err != nil {
1✔
UNCOV
732
                return nil, err
×
733
        }
×
734
        imagePath := model.ImagePathFromContext(ctx, imageID)
1✔
735
        _, err = d.objectStorage.StatObject(ctx, imagePath)
1✔
736
        if err != nil {
1✔
UNCOV
737
                return nil, errors.Wrap(err, "Searching for image file")
×
UNCOV
738
        }
×
739

740
        link, err := d.objectStorage.GetRequest(
1✔
741
                ctx,
1✔
742
                imagePath,
1✔
743
                image.Name+model.ArtifactFileSuffix,
1✔
744
                expire,
1✔
745
        )
1✔
746
        if err != nil {
1✔
UNCOV
747
                return nil, errors.Wrap(err, "Generating download link")
×
UNCOV
748
        }
×
749

750
        return link, nil
1✔
751
}
752

753
func (d *Deployments) UploadLink(
754
        ctx context.Context,
755
        expire time.Duration,
756
        skipVerify bool,
757
) (*model.UploadLink, error) {
6✔
758
        ctx, err := d.contextWithStorageSettings(ctx)
6✔
759
        if err != nil {
7✔
760
                return nil, err
1✔
761
        }
1✔
762

763
        artifactID := uuid.New().String()
5✔
764
        path := model.ImagePathFromContext(ctx, artifactID) + fileSuffixTmp
5✔
765
        if skipVerify {
6✔
766
                path = model.ImagePathFromContext(ctx, artifactID)
1✔
767
        }
1✔
768
        link, err := d.objectStorage.PutRequest(ctx, path, expire)
5✔
769
        if err != nil {
6✔
770
                return nil, errors.WithMessage(err, "app: failed to generate signed URL")
1✔
771
        }
1✔
772
        upLink := &model.UploadLink{
4✔
773
                ArtifactID: artifactID,
4✔
774
                IssuedAt:   time.Now(),
4✔
775
                Link:       *link,
4✔
776
        }
4✔
777
        err = d.db.InsertUploadIntent(ctx, upLink)
4✔
778
        if err != nil {
5✔
779
                return nil, errors.WithMessage(err, "app: error recording the upload intent")
1✔
780
        }
1✔
781

782
        return upLink, err
3✔
783
}
784

785
func (d *Deployments) processUploadedArtifact(
786
        ctx context.Context,
787
        artifactID string,
788
        artifact io.ReadCloser,
789
        skipVerify bool,
790
) error {
5✔
791
        linkStatus := model.LinkStatusCompleted
5✔
792

5✔
793
        l := log.FromContext(ctx)
5✔
794
        defer artifact.Close()
5✔
795
        ctx, cancel := context.WithCancel(ctx)
5✔
796
        defer cancel()
5✔
797
        go func() { // Heatbeat routine
10✔
798
                ticker := time.NewTicker(inprogressIdleTime / 2)
5✔
799
                done := ctx.Done()
5✔
800
                defer ticker.Stop()
5✔
801
                for {
10✔
802
                        select {
5✔
803
                        case <-ticker.C:
×
804
                                err := d.db.UpdateUploadIntentStatus(
×
805
                                        ctx,
×
806
                                        artifactID,
×
807
                                        model.LinkStatusProcessing,
×
808
                                        model.LinkStatusProcessing,
×
809
                                )
×
810
                                if err != nil {
×
UNCOV
811
                                        l.Errorf("failed to update upload link timestamp: %s", err)
×
UNCOV
812
                                        cancel()
×
UNCOV
813
                                        return
×
UNCOV
814
                                }
×
815
                        case <-done:
5✔
816
                                return
5✔
817
                        }
818
                }
819
        }()
820
        _, err := d.handleArtifact(ctx, &model.MultipartUploadMsg{
5✔
821
                ArtifactID:     artifactID,
5✔
822
                ArtifactReader: artifact,
5✔
823
        },
5✔
824
                skipVerify,
5✔
825
        )
5✔
826
        if err != nil {
9✔
827
                l.Warnf("failed to process artifact %s: %s", artifactID, err)
4✔
828
                linkStatus = model.LinkStatusAborted
4✔
829
        }
4✔
830
        errDB := d.db.UpdateUploadIntentStatus(
5✔
831
                ctx, artifactID,
5✔
832
                model.LinkStatusProcessing, linkStatus,
5✔
833
        )
5✔
834
        if errDB != nil {
7✔
835
                l.Warnf("failed to update upload link status: %s", errDB)
2✔
836
        }
2✔
837
        return err
5✔
838
}
839

840
func (d *Deployments) CompleteUpload(
841
        ctx context.Context,
842
        intentID string,
843
        skipVerify bool,
844
) error {
10✔
845
        l := log.FromContext(ctx)
10✔
846
        idty := identity.FromContext(ctx)
10✔
847
        ctx, err := d.contextWithStorageSettings(ctx)
10✔
848
        if err != nil {
11✔
849
                return err
1✔
850
        }
1✔
851
        // Create an async context that doesn't cancel when server connection
852
        // closes.
853
        ctxAsync := context.Background()
9✔
854
        ctxAsync = log.WithContext(ctxAsync, l)
9✔
855
        ctxAsync = identity.WithContext(ctxAsync, idty)
9✔
856

9✔
857
        settings, _ := storage.SettingsFromContext(ctx)
9✔
858
        ctxAsync = storage.SettingsWithContext(ctxAsync, settings)
9✔
859
        var artifactReader io.ReadCloser
9✔
860
        if skipVerify {
12✔
861
                artifactReader, err = d.objectStorage.GetObject(
3✔
862
                        ctxAsync,
3✔
863
                        model.ImagePathFromContext(ctx, intentID),
3✔
864
                )
3✔
865
        } else {
9✔
866
                artifactReader, err = d.objectStorage.GetObject(
6✔
867
                        ctxAsync,
6✔
868
                        model.ImagePathFromContext(ctx, intentID)+fileSuffixTmp,
6✔
869
                )
6✔
870
        }
6✔
871
        if err != nil {
11✔
872
                if errors.Is(err, storage.ErrObjectNotFound) {
3✔
873
                        return ErrUploadNotFound
1✔
874
                }
1✔
875
                return err
1✔
876
        }
877

878
        err = d.db.UpdateUploadIntentStatus(
7✔
879
                ctx,
7✔
880
                intentID,
7✔
881
                model.LinkStatusPending,
7✔
882
                model.LinkStatusProcessing,
7✔
883
        )
7✔
884
        if err != nil {
9✔
885
                errClose := artifactReader.Close()
2✔
886
                if errClose != nil {
3✔
887
                        l.Warnf("failed to close artifact reader: %s", errClose)
1✔
888
                }
1✔
889
                if errors.Is(err, store.ErrNotFound) {
3✔
890
                        return ErrUploadNotFound
1✔
891
                }
1✔
892
                return err
1✔
893
        }
894
        go d.processUploadedArtifact( // nolint:errcheck
5✔
895
                ctxAsync, intentID, artifactReader, skipVerify,
5✔
896
        )
5✔
897
        return nil
5✔
898
}
899

900
func getArtifactInfo(info artifact.Info) *model.ArtifactInfo {
1✔
901
        return &model.ArtifactInfo{
1✔
902
                Format:  info.Format,
1✔
903
                Version: uint(info.Version),
1✔
904
        }
1✔
905
}
1✔
906

907
func getUpdateFiles(uFiles []*handlers.DataFile) ([]model.UpdateFile, error) {
1✔
908
        var files []model.UpdateFile
1✔
909
        for _, u := range uFiles {
2✔
910
                files = append(files, model.UpdateFile{
1✔
911
                        Name:     u.Name,
1✔
912
                        Size:     u.Size,
1✔
913
                        Date:     &u.Date,
1✔
914
                        Checksum: string(u.Checksum),
1✔
915
                })
1✔
916
        }
1✔
917
        return files, nil
1✔
918
}
919

920
func getMetaFromArchive(r *io.Reader, skipVerify bool) (*model.ArtifactMeta, error) {
5✔
921
        metaArtifact := model.NewArtifactMeta()
5✔
922

5✔
923
        aReader := areader.NewReader(*r)
5✔
924

5✔
925
        // There is no signature verification here.
5✔
926
        // It is just simple check if artifact is signed or not.
5✔
927
        aReader.VerifySignatureCallback = func(message, sig []byte) error {
5✔
UNCOV
928
                metaArtifact.Signed = true
×
UNCOV
929
                return nil
×
UNCOV
930
        }
×
931

932
        var err error
5✔
933
        if skipVerify {
8✔
934
                err = aReader.ReadArtifactHeaders()
3✔
935
                if err != nil {
5✔
936
                        return nil, errors.Wrap(err, "reading artifact error")
2✔
937
                }
2✔
938
        } else {
3✔
939
                err = aReader.ReadArtifact()
3✔
940
                if err != nil {
6✔
941
                        return nil, errors.Wrap(err, "reading artifact error")
3✔
942
                }
3✔
943
        }
944

945
        metaArtifact.Info = getArtifactInfo(aReader.GetInfo())
1✔
946
        metaArtifact.DeviceTypesCompatible = aReader.GetCompatibleDevices()
1✔
947

1✔
948
        metaArtifact.Name = aReader.GetArtifactName()
1✔
949
        if metaArtifact.Info.Version == 3 {
2✔
950
                metaArtifact.Depends, err = aReader.MergeArtifactDepends()
1✔
951
                if err != nil {
1✔
UNCOV
952
                        return nil, errors.Wrap(err,
×
UNCOV
953
                                "error parsing version 3 artifact")
×
954
                }
×
955

956
                metaArtifact.Provides, err = aReader.MergeArtifactProvides()
1✔
957
                if err != nil {
1✔
UNCOV
958
                        return nil, errors.Wrap(err,
×
UNCOV
959
                                "error parsing version 3 artifact")
×
UNCOV
960
                }
×
961

962
                metaArtifact.ClearsProvides = aReader.MergeArtifactClearsProvides()
1✔
963
        }
964

965
        for _, p := range aReader.GetHandlers() {
2✔
966
                uFiles, err := getUpdateFiles(p.GetUpdateFiles())
1✔
967
                if err != nil {
1✔
UNCOV
968
                        return nil, errors.Wrap(err, "Cannot get update files:")
×
969
                }
×
970

971
                uMetadata, err := p.GetUpdateMetaData()
1✔
972
                if err != nil {
1✔
UNCOV
973
                        return nil, errors.Wrap(err, "Cannot get update metadata")
×
UNCOV
974
                }
×
975

976
                metaArtifact.Updates = append(
1✔
977
                        metaArtifact.Updates,
1✔
978
                        model.Update{
1✔
979
                                TypeInfo: model.ArtifactUpdateTypeInfo{
1✔
980
                                        Type: p.GetUpdateType(),
1✔
981
                                },
1✔
982
                                Files:    uFiles,
1✔
983
                                MetaData: uMetadata,
1✔
984
                        })
1✔
985
        }
986

987
        return metaArtifact, nil
1✔
988
}
989

990
func getArtifactIDs(artifacts []*model.Image) []string {
7✔
991
        artifactIDs := make([]string, 0, len(artifacts))
7✔
992
        for _, artifact := range artifacts {
14✔
993
                artifactIDs = append(artifactIDs, artifact.Id)
7✔
994
        }
7✔
995
        return artifactIDs
7✔
996
}
997

998
// deployments
999
func inventoryDevicesToDevicesIds(devices []model.InvDevice) []string {
4✔
1000
        ids := make([]string, len(devices))
4✔
1001
        for i, d := range devices {
8✔
1002
                ids[i] = d.ID
4✔
1003
        }
4✔
1004

1005
        return ids
4✔
1006
}
1007

1008
// updateDeploymentConstructor fills devices list with device ids
1009
func (d *Deployments) updateDeploymentConstructor(ctx context.Context,
1010
        constructor *model.DeploymentConstructor) (*model.DeploymentConstructor, error) {
5✔
1011
        l := log.FromContext(ctx)
5✔
1012

5✔
1013
        id := identity.FromContext(ctx)
5✔
1014
        if id == nil {
5✔
UNCOV
1015
                l.Error("identity not present in the context")
×
UNCOV
1016
                return nil, ErrModelInternal
×
UNCOV
1017
        }
×
1018
        searchParams := model.SearchParams{
5✔
1019
                Page:    1,
5✔
1020
                PerPage: PerPageInventoryDevices,
5✔
1021
                Filters: []model.FilterPredicate{
5✔
1022
                        {
5✔
1023
                                Scope:     InventoryIdentityScope,
5✔
1024
                                Attribute: InventoryStatusAttributeName,
5✔
1025
                                Type:      "$eq",
5✔
1026
                                Value:     InventoryStatusAccepted,
5✔
1027
                        },
5✔
1028
                },
5✔
1029
        }
5✔
1030
        if len(constructor.Group) > 0 {
10✔
1031
                searchParams.Filters = append(
5✔
1032
                        searchParams.Filters,
5✔
1033
                        model.FilterPredicate{
5✔
1034
                                Scope:     InventoryGroupScope,
5✔
1035
                                Attribute: InventoryGroupAttributeName,
5✔
1036
                                Type:      "$eq",
5✔
1037
                                Value:     constructor.Group,
5✔
1038
                        })
5✔
1039
        }
5✔
1040

1041
        for {
11✔
1042
                devices, count, err := d.search(ctx, id.Tenant, searchParams)
6✔
1043
                if err != nil {
7✔
1044
                        l.Errorf("error searching for devices")
1✔
1045
                        return nil, ErrModelInternal
1✔
1046
                }
1✔
1047
                if count < 1 {
6✔
1048
                        l.Errorf("no devices found")
1✔
1049
                        return nil, ErrNoDevices
1✔
1050
                }
1✔
1051
                if len(devices) < 1 {
4✔
UNCOV
1052
                        break
×
1053
                }
1054
                constructor.Devices = append(constructor.Devices, inventoryDevicesToDevicesIds(devices)...)
4✔
1055
                if len(constructor.Devices) == count {
7✔
1056
                        break
3✔
1057
                }
1058
                searchParams.Page++
1✔
1059
        }
1060

1061
        return constructor, nil
3✔
1062
}
1063

1064
// CreateDeviceConfigurationDeployment creates new configuration deployment for the device.
1065
func (d *Deployments) CreateDeviceConfigurationDeployment(
1066
        ctx context.Context, constructor *model.ConfigurationDeploymentConstructor,
1067
        deviceID, deploymentID string) (string, error) {
5✔
1068

5✔
1069
        if constructor == nil {
6✔
1070
                return "", ErrModelMissingInput
1✔
1071
        }
1✔
1072

1073
        deployment, err := model.NewDeploymentFromConfigurationDeploymentConstructor(
4✔
1074
                constructor,
4✔
1075
                deploymentID,
4✔
1076
        )
4✔
1077
        if err != nil {
4✔
UNCOV
1078
                return "", errors.Wrap(err, "failed to create deployment")
×
UNCOV
1079
        }
×
1080

1081
        deployment.DeviceList = []string{deviceID}
4✔
1082
        deployment.MaxDevices = 1
4✔
1083
        deployment.Configuration = []byte(constructor.Configuration)
4✔
1084
        deployment.Type = model.DeploymentTypeConfiguration
4✔
1085

4✔
1086
        groups, err := d.getDeploymentGroups(ctx, []string{deviceID})
4✔
1087
        if err != nil {
5✔
1088
                return "", err
1✔
1089
        }
1✔
1090
        deployment.Groups = groups
3✔
1091

3✔
1092
        if err := d.db.InsertDeployment(ctx, deployment); err != nil {
5✔
1093
                if strings.Contains(err.Error(), "duplicate key error") {
3✔
1094
                        return "", ErrDuplicateDeployment
1✔
1095
                }
1✔
1096
                if strings.Contains(err.Error(), "id: must be a valid UUID") {
3✔
1097
                        return "", ErrInvalidDeploymentID
1✔
1098
                }
1✔
1099
                return "", errors.Wrap(err, "Storing deployment data")
1✔
1100
        }
1101

1102
        return deployment.Id, nil
2✔
1103
}
1104

1105
// CreateDeployment precomputes new deployment and schedules it for devices.
1106
func (d *Deployments) CreateDeployment(ctx context.Context,
1107
        constructor *model.DeploymentConstructor) (string, error) {
9✔
1108

9✔
1109
        var err error
9✔
1110

9✔
1111
        if constructor == nil {
10✔
1112
                return "", ErrModelMissingInput
1✔
1113
        }
1✔
1114

1115
        if err := constructor.Validate(); err != nil {
8✔
UNCOV
1116
                return "", errors.Wrap(err, "Validating deployment")
×
UNCOV
1117
        }
×
1118

1119
        if len(constructor.Group) > 0 || constructor.AllDevices {
13✔
1120
                constructor, err = d.updateDeploymentConstructor(ctx, constructor)
5✔
1121
                if err != nil {
7✔
1122
                        return "", err
2✔
1123
                }
2✔
1124
        }
1125

1126
        deployment, err := model.NewDeploymentFromConstructor(constructor)
6✔
1127
        if err != nil {
6✔
UNCOV
1128
                return "", errors.Wrap(err, "failed to create deployment")
×
UNCOV
1129
        }
×
1130

1131
        // Assign artifacts to the deployment.
1132
        // When new artifact(s) with the artifact name same as the one in the deployment
1133
        // will be uploaded to the backend, it will also become part of this deployment.
1134
        artifacts, err := d.db.ImagesByName(ctx, deployment.ArtifactName)
6✔
1135
        if err != nil {
6✔
UNCOV
1136
                return "", errors.Wrap(err, "Finding artifact with given name")
×
UNCOV
1137
        }
×
1138

1139
        if len(artifacts) == 0 {
7✔
1140
                return "", ErrNoArtifact
1✔
1141
        }
1✔
1142

1143
        deployment.Artifacts = getArtifactIDs(artifacts)
6✔
1144
        deployment.DeviceList = constructor.Devices
6✔
1145
        deployment.MaxDevices = len(constructor.Devices)
6✔
1146
        deployment.Type = model.DeploymentTypeSoftware
6✔
1147
        if len(constructor.Group) > 0 {
9✔
1148
                deployment.Groups = []string{constructor.Group}
3✔
1149
        }
3✔
1150

1151
        // single device deployment case
1152
        if len(deployment.Groups) == 0 && len(constructor.Devices) == 1 {
9✔
1153
                groups, err := d.getDeploymentGroups(ctx, constructor.Devices)
3✔
1154
                if err != nil {
3✔
UNCOV
1155
                        return "", err
×
UNCOV
1156
                }
×
1157
                deployment.Groups = groups
3✔
1158
        }
1159

1160
        if err := d.db.InsertDeployment(ctx, deployment); err != nil {
7✔
1161
                return "", errors.Wrap(err, "Storing deployment data")
1✔
1162
        }
1✔
1163

1164
        return deployment.Id, nil
5✔
1165
}
1166

1167
func (d *Deployments) getDeploymentGroups(
1168
        ctx context.Context,
1169
        devices []string,
1170
) ([]string, error) {
6✔
1171
        id := identity.FromContext(ctx)
6✔
1172

6✔
1173
        //only for single device deployment case
6✔
1174
        if len(devices) != 1 {
6✔
UNCOV
1175
                return nil, nil
×
UNCOV
1176
        }
×
1177

1178
        if id == nil {
7✔
1179
                id = &identity.Identity{}
1✔
1180
        }
1✔
1181

1182
        groups, err := d.inventoryClient.GetDeviceGroups(ctx, id.Tenant, devices[0])
6✔
1183
        if err != nil && err != inventory.ErrDevNotFound {
7✔
1184
                return nil, err
1✔
1185
        }
1✔
1186
        return groups, nil
5✔
1187
}
1188

1189
// IsDeploymentFinished checks if there is unfinished deployment with given ID
1190
func (d *Deployments) IsDeploymentFinished(
1191
        ctx context.Context,
1192
        deploymentID string,
1193
) (bool, error) {
1✔
1194
        deployment, err := d.db.FindUnfinishedByID(ctx, deploymentID)
1✔
1195
        if err != nil {
1✔
UNCOV
1196
                return false, errors.Wrap(err, "Searching for unfinished deployment by ID")
×
UNCOV
1197
        }
×
1198
        if deployment == nil {
2✔
1199
                return true, nil
1✔
1200
        }
1✔
1201

1202
        return false, nil
1✔
1203
}
1204

1205
// GetDeployment fetches deployment by ID
1206
func (d *Deployments) GetDeployment(ctx context.Context,
1207
        deploymentID string) (*model.Deployment, error) {
1✔
1208

1✔
1209
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1210
        if err != nil {
1✔
1211
                return nil, errors.Wrap(err, "Searching for deployment by ID")
×
1212
        }
×
1213

1214
        if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
1✔
UNCOV
1215
                return nil, err
×
UNCOV
1216
        }
×
1217

1218
        return deployment, nil
1✔
1219
}
1220

1221
// ImageUsedInActiveDeployment checks if specified image is in use by deployments Image is
1222
// considered to be in use if it's participating in at lest one non success/error deployment.
1223
func (d *Deployments) ImageUsedInActiveDeployment(ctx context.Context,
1224
        imageID string) (bool, error) {
4✔
1225

4✔
1226
        var found bool
4✔
1227

4✔
1228
        found, err := d.db.ExistUnfinishedByArtifactId(ctx, imageID)
4✔
1229
        if err != nil {
5✔
1230
                return false, errors.Wrap(err, "Checking if image is used by active deployment")
1✔
1231
        }
1✔
1232

1233
        if found {
4✔
1234
                return found, nil
1✔
1235
        }
1✔
1236

1237
        found, err = d.db.ExistAssignedImageWithIDAndStatuses(ctx,
3✔
1238
                imageID, model.ActiveDeploymentStatuses()...)
3✔
1239
        if err != nil {
4✔
1240
                return false, errors.Wrap(err, "Checking if image is used by active deployment")
1✔
1241
        }
1✔
1242

1243
        return found, nil
2✔
1244
}
1245

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

×
1250
        var found bool
×
1251

×
UNCOV
1252
        found, err := d.db.ExistUnfinishedByArtifactId(ctx, imageID)
×
1253
        if err != nil {
×
1254
                return false, errors.Wrap(err, "Checking if image is used by active deployment")
×
1255
        }
×
1256

1257
        if found {
×
1258
                return found, nil
×
1259
        }
×
1260

UNCOV
1261
        found, err = d.db.ExistAssignedImageWithIDAndStatuses(ctx, imageID)
×
1262
        if err != nil {
×
UNCOV
1263
                return false, errors.Wrap(err, "Checking if image is used in deployment")
×
UNCOV
1264
        }
×
1265

UNCOV
1266
        return found, nil
×
1267
}
1268

1269
// Retrieves the model.Deployment and model.DeviceDeployment structures
1270
// for the device. Upon error, nil is returned for both deployment structures.
1271
func (d *Deployments) getDeploymentForDevice(ctx context.Context,
1272
        deviceID string) (*model.Deployment, *model.DeviceDeployment, error) {
2✔
1273

2✔
1274
        // Retrieve device deployment
2✔
1275
        deviceDeployment, err := d.db.FindOldestActiveDeviceDeployment(ctx, deviceID)
2✔
1276

2✔
1277
        if err != nil {
2✔
UNCOV
1278
                return nil, nil, errors.Wrap(err,
×
UNCOV
1279
                        "Searching for oldest active deployment for the device")
×
1280
        } else if deviceDeployment == nil {
3✔
1281
                return d.getNewDeploymentForDevice(ctx, deviceID)
1✔
1282
        }
1✔
1283

1284
        deployment, err := d.db.FindDeploymentByID(ctx, deviceDeployment.DeploymentId)
2✔
1285
        if err != nil {
2✔
1286
                return nil, nil, errors.Wrap(err, "checking deployment id")
×
UNCOV
1287
        }
×
1288
        if deployment == nil {
2✔
UNCOV
1289
                return nil, nil, errors.New("No deployment corresponding to device deployment")
×
UNCOV
1290
        }
×
1291

1292
        return deployment, deviceDeployment, nil
2✔
1293
}
1294

1295
// getNewDeploymentForDevice returns deployment object and creates and returns
1296
// new device deployment for the device;
1297
//
1298
// we are interested only in the deployments that are newer than the latest
1299
// deployment applied by the device;
1300
// this way we guarantee that the device will not receive deployment
1301
// that is older than the one installed on the device;
1302
func (d *Deployments) getNewDeploymentForDevice(ctx context.Context,
1303
        deviceID string) (*model.Deployment, *model.DeviceDeployment, error) {
1✔
1304

1✔
1305
        var lastDeployment *time.Time
1✔
1306
        //get latest device deployment for the device;
1✔
1307
        deviceDeployment, err := d.db.FindLatestInactiveDeviceDeployment(ctx, deviceID)
1✔
1308
        if err != nil {
1✔
UNCOV
1309
                return nil, nil, errors.Wrap(err,
×
UNCOV
1310
                        "Searching for latest active deployment for the device")
×
1311
        } else if deviceDeployment == nil {
2✔
1312
                lastDeployment = &time.Time{}
1✔
1313
        } else {
2✔
1314
                lastDeployment = deviceDeployment.Created
1✔
1315
        }
1✔
1316

1317
        //get deployments newer then last device deployment
1318
        //iterate over deployments and check if the device is part of the deployment or not
1319
        for skip := 0; true; skip += 100 {
2✔
1320
                deployments, err := d.db.FindNewerActiveDeployments(ctx, lastDeployment, skip, 100)
1✔
1321
                if err != nil {
1✔
UNCOV
1322
                        return nil, nil, errors.Wrap(err,
×
UNCOV
1323
                                "Failed to search for newer active deployments")
×
UNCOV
1324
                }
×
1325
                if len(deployments) == 0 {
2✔
1326
                        return nil, nil, nil
1✔
1327
                }
1✔
1328

1329
                for _, deployment := range deployments {
2✔
1330
                        ok, err := d.isDevicePartOfDeployment(ctx, deviceID, deployment)
1✔
1331
                        if err != nil {
1✔
UNCOV
1332
                                return nil, nil, err
×
UNCOV
1333
                        }
×
1334
                        if ok {
2✔
1335
                                deviceDeployment, err := d.createDeviceDeploymentWithStatus(ctx,
1✔
1336
                                        deviceID, deployment, model.DeviceDeploymentStatusPending)
1✔
1337
                                if err != nil {
1✔
UNCOV
1338
                                        return nil, nil, err
×
UNCOV
1339
                                }
×
1340
                                return deployment, deviceDeployment, nil
1✔
1341
                        }
1342
                }
1343
        }
1344

UNCOV
1345
        return nil, nil, nil
×
1346
}
1347

1348
func (d *Deployments) createDeviceDeploymentWithStatus(
1349
        ctx context.Context, deviceID string,
1350
        deployment *model.Deployment, status model.DeviceDeploymentStatus,
1351
) (*model.DeviceDeployment, error) {
6✔
1352
        prevStatus := model.DeviceDeploymentStatusNull
6✔
1353
        deviceDeployment, err := d.db.GetDeviceDeployment(ctx, deployment.Id, deviceID, true)
6✔
1354
        if err != nil && err != mongo.ErrStorageNotFound {
6✔
UNCOV
1355
                return nil, err
×
1356
        } else if deviceDeployment != nil {
6✔
UNCOV
1357
                prevStatus = deviceDeployment.Status
×
UNCOV
1358
        }
×
1359

1360
        deviceDeployment = model.NewDeviceDeployment(deviceID, deployment.Id)
6✔
1361
        deviceDeployment.Status = status
6✔
1362
        deviceDeployment.Active = status.Active()
6✔
1363
        deviceDeployment.Created = deployment.Created
6✔
1364

6✔
1365
        if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
6✔
UNCOV
1366
                return nil, err
×
1367
        }
×
1368

1369
        if err := d.db.InsertDeviceDeployment(ctx, deviceDeployment,
6✔
1370
                prevStatus == model.DeviceDeploymentStatusNull); err != nil {
6✔
UNCOV
1371
                return nil, err
×
UNCOV
1372
        }
×
1373

1374
        // after inserting new device deployment update deployment stats
1375
        // in the database and locally, and update deployment status
1376
        if err := d.db.UpdateStatsInc(
6✔
1377
                ctx, deployment.Id,
6✔
1378
                prevStatus, status,
6✔
1379
        ); err != nil {
6✔
UNCOV
1380
                return nil, err
×
UNCOV
1381
        }
×
1382

1383
        deployment.Stats.Inc(status)
6✔
1384

6✔
1385
        err = d.recalcDeploymentStatus(ctx, deployment)
6✔
1386
        if err != nil {
6✔
UNCOV
1387
                return nil, errors.Wrap(err, "failed to update deployment status")
×
UNCOV
1388
        }
×
1389

1390
        if !status.Active() {
11✔
1391
                err := d.reindexDevice(ctx, deviceID)
5✔
1392
                if err != nil {
5✔
UNCOV
1393
                        l := log.FromContext(ctx)
×
1394
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1395
                }
×
1396
                if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
5✔
1397
                        deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
5✔
UNCOV
1398
                        l := log.FromContext(ctx)
×
UNCOV
1399
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1400
                }
×
1401
        }
1402

1403
        return deviceDeployment, nil
6✔
1404
}
1405

1406
func (d *Deployments) isDevicePartOfDeployment(
1407
        ctx context.Context,
1408
        deviceID string,
1409
        deployment *model.Deployment,
1410
) (bool, error) {
8✔
1411
        for _, id := range deployment.DeviceList {
14✔
1412
                if id == deviceID {
12✔
1413
                        return true, nil
6✔
1414
                }
6✔
1415
        }
1416
        return false, nil
3✔
1417
}
1418

1419
// GetDeploymentForDeviceWithCurrent returns deployment for the device
1420
func (d *Deployments) GetDeploymentForDeviceWithCurrent(ctx context.Context, deviceID string,
1421
        request *model.DeploymentNextRequest) (*model.DeploymentInstructions, error) {
2✔
1422

2✔
1423
        deployment, deviceDeployment, err := d.getDeploymentForDevice(ctx, deviceID)
2✔
1424
        if err != nil {
2✔
UNCOV
1425
                return nil, ErrModelInternal
×
1426
        } else if deployment == nil {
3✔
1427
                return nil, nil
1✔
1428
        }
1✔
1429

1430
        err = d.saveDeviceDeploymentRequest(ctx, deviceID, deviceDeployment, request)
2✔
1431
        if err != nil {
3✔
1432
                return nil, err
1✔
1433
        }
1✔
1434
        return d.getDeploymentInstructions(ctx, deployment, deviceDeployment, request)
2✔
1435
}
1436

1437
func (d *Deployments) getDeploymentInstructions(
1438
        ctx context.Context,
1439
        deployment *model.Deployment,
1440
        deviceDeployment *model.DeviceDeployment,
1441
        request *model.DeploymentNextRequest,
1442
) (*model.DeploymentInstructions, error) {
2✔
1443

2✔
1444
        var newArtifactAssigned bool
2✔
1445

2✔
1446
        l := log.FromContext(ctx)
2✔
1447

2✔
1448
        if deployment.Type == model.DeploymentTypeConfiguration {
3✔
1449
                // There's nothing more we need to do, the link must be filled
1✔
1450
                // in by the API layer.
1✔
1451
                return &model.DeploymentInstructions{
1✔
1452
                        ID: deployment.Id,
1✔
1453
                        Artifact: model.ArtifactDeploymentInstructions{
1✔
1454
                                // configuration artifacts are created on demand, so they do not have IDs
1✔
1455
                                // use deployment ID togheter with device ID as artifact ID
1✔
1456
                                ID:                    deployment.Id + deviceDeployment.DeviceId,
1✔
1457
                                ArtifactName:          deployment.ArtifactName,
1✔
1458
                                DeviceTypesCompatible: []string{request.DeviceProvides.DeviceType},
1✔
1459
                        },
1✔
1460
                        Type: model.DeploymentTypeConfiguration,
1✔
1461
                }, nil
1✔
1462
        }
1✔
1463

1464
        // assing artifact to the device deployment
1465
        // only if it was not assgined previously
1466
        if deviceDeployment.Image == nil {
4✔
1467
                if err := d.assignArtifact(
2✔
1468
                        ctx, deployment, deviceDeployment, request.DeviceProvides); err != nil {
2✔
UNCOV
1469
                        return nil, err
×
UNCOV
1470
                }
×
1471
                newArtifactAssigned = true
2✔
1472
        }
1473

1474
        if deviceDeployment.Image == nil {
2✔
UNCOV
1475
                // No artifact - return empty response
×
UNCOV
1476
                return nil, nil
×
UNCOV
1477
        }
×
1478

1479
        // if the deployment is not forcing the installation, and
1480
        // if artifact was recognized as already installed, and this is
1481
        // a new device deployment - indicated by device deployment status "pending",
1482
        // handle already installed artifact case
1483
        if !deployment.ForceInstallation &&
2✔
1484
                d.isAlreadyInstalled(request, deviceDeployment) &&
2✔
1485
                deviceDeployment.Status == model.DeviceDeploymentStatusPending {
4✔
1486
                return nil, d.handleAlreadyInstalled(ctx, deviceDeployment)
2✔
1487
        }
2✔
1488

1489
        // if new artifact has been assigned to device deployment
1490
        // add artifact size to deployment total size,
1491
        // before returning deployment instruction to the device
1492
        if newArtifactAssigned {
2✔
1493
                if err := d.db.IncrementDeploymentTotalSize(
1✔
1494
                        ctx, deviceDeployment.DeploymentId, deviceDeployment.Image.Size); err != nil {
1✔
UNCOV
1495
                        l.Errorf("failed to increment deployment total size: %s", err.Error())
×
UNCOV
1496
                }
×
1497
        }
1498

1499
        ctx, err := d.contextWithStorageSettings(ctx)
1✔
1500
        if err != nil {
1✔
UNCOV
1501
                return nil, err
×
UNCOV
1502
        }
×
1503

1504
        imagePath := model.ImagePathFromContext(ctx, deviceDeployment.Image.Id)
1✔
1505
        link, err := d.objectStorage.GetRequest(
1✔
1506
                ctx,
1✔
1507
                imagePath,
1✔
1508
                deviceDeployment.Image.Name+model.ArtifactFileSuffix,
1✔
1509
                DefaultUpdateDownloadLinkExpire,
1✔
1510
        )
1✔
1511
        if err != nil {
1✔
UNCOV
1512
                return nil, errors.Wrap(err, "Generating download link for the device")
×
UNCOV
1513
        }
×
1514

1515
        instructions := &model.DeploymentInstructions{
1✔
1516
                ID: deviceDeployment.DeploymentId,
1✔
1517
                Artifact: model.ArtifactDeploymentInstructions{
1✔
1518
                        ID: deviceDeployment.Image.Id,
1✔
1519
                        ArtifactName: deviceDeployment.Image.
1✔
1520
                                ArtifactMeta.Name,
1✔
1521
                        Source: *link,
1✔
1522
                        DeviceTypesCompatible: deviceDeployment.Image.
1✔
1523
                                ArtifactMeta.DeviceTypesCompatible,
1✔
1524
                },
1✔
1525
        }
1✔
1526

1✔
1527
        return instructions, nil
1✔
1528
}
1529

1530
func (d *Deployments) saveDeviceDeploymentRequest(ctx context.Context, deviceID string,
1531
        deviceDeployment *model.DeviceDeployment, request *model.DeploymentNextRequest) error {
2✔
1532
        if deviceDeployment.Request != nil {
3✔
1533
                if !reflect.DeepEqual(deviceDeployment.Request, request) {
2✔
1534
                        // the device reported different device type and/or artifact name
1✔
1535
                        // during the update process, which should never happen;
1✔
1536
                        // mark deployment for this device as failed to force client to rollback
1✔
1537
                        l := log.FromContext(ctx)
1✔
1538
                        l.Errorf(
1✔
1539
                                "Device with id %s reported new data: %s during update process;"+
1✔
1540
                                        "old data: %s",
1✔
1541
                                deviceID, request, deviceDeployment.Request)
1✔
1542

1✔
1543
                        if err := d.UpdateDeviceDeploymentStatus(ctx, deviceDeployment.DeploymentId, deviceID,
1✔
1544
                                model.DeviceDeploymentState{
1✔
1545
                                        Status: model.DeviceDeploymentStatusFailure,
1✔
1546
                                }); err != nil {
1✔
1547
                                return errors.Wrap(err, "Failed to update deployment status")
×
UNCOV
1548
                        }
×
1549
                        if err := d.reindexDevice(ctx, deviceDeployment.DeviceId); err != nil {
1✔
1550
                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
1551
                        }
×
1552
                        if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
1✔
1553
                                deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
1✔
UNCOV
1554
                                l := log.FromContext(ctx)
×
UNCOV
1555
                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1556
                        }
×
1557
                        return ErrConflictingRequestData
1✔
1558
                }
1559
        } else {
2✔
1560
                // save the request
2✔
1561
                if err := d.db.SaveDeviceDeploymentRequest(
2✔
1562
                        ctx, deviceDeployment.Id, request); err != nil {
2✔
UNCOV
1563
                        return err
×
UNCOV
1564
                }
×
1565
        }
1566
        return nil
2✔
1567
}
1568

1569
// UpdateDeviceDeploymentStatus will update the deployment status for device of
1570
// ID `deviceID`. Returns nil if update was successful.
1571
func (d *Deployments) UpdateDeviceDeploymentStatus(ctx context.Context, deploymentID string,
1572
        deviceID string, ddState model.DeviceDeploymentState) error {
6✔
1573

6✔
1574
        l := log.FromContext(ctx)
6✔
1575

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

6✔
1578
        var finishTime *time.Time = nil
6✔
1579
        if model.IsDeviceDeploymentStatusFinished(ddState.Status) {
10✔
1580
                now := time.Now()
4✔
1581
                finishTime = &now
4✔
1582
        }
4✔
1583

1584
        dd, err := d.db.GetDeviceDeployment(ctx, deploymentID, deviceID, false)
6✔
1585
        if err == mongo.ErrStorageNotFound {
7✔
1586
                return ErrStorageNotFound
1✔
1587
        } else if err != nil {
6✔
UNCOV
1588
                return err
×
UNCOV
1589
        }
×
1590

1591
        currentStatus := dd.Status
5✔
1592

5✔
1593
        if currentStatus == model.DeviceDeploymentStatusAborted {
5✔
1594
                return ErrDeploymentAborted
×
1595
        }
×
1596

1597
        if currentStatus == model.DeviceDeploymentStatusDecommissioned {
5✔
UNCOV
1598
                return ErrDeviceDecommissioned
×
1599
        }
×
1600

1601
        // nothing to do
1602
        if ddState.Status == currentStatus {
5✔
UNCOV
1603
                return nil
×
UNCOV
1604
        }
×
1605

1606
        // update finish time
1607
        ddState.FinishTime = finishTime
5✔
1608

5✔
1609
        old, err := d.db.UpdateDeviceDeploymentStatus(ctx,
5✔
1610
                deviceID, deploymentID, ddState)
5✔
1611
        if err != nil {
5✔
1612
                return err
×
1613
        }
×
1614

1615
        if err = d.db.UpdateStatsInc(ctx, deploymentID, old, ddState.Status); err != nil {
5✔
UNCOV
1616
                return err
×
UNCOV
1617
        }
×
1618

1619
        // fetch deployment stats and update deployment status
1620
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
5✔
1621
        if err != nil {
5✔
UNCOV
1622
                return errors.Wrap(err, "failed when searching for deployment")
×
1623
        }
×
1624

1625
        err = d.recalcDeploymentStatus(ctx, deployment)
5✔
1626
        if err != nil {
5✔
UNCOV
1627
                return errors.Wrap(err, "failed to update deployment status")
×
UNCOV
1628
        }
×
1629

1630
        if !ddState.Status.Active() {
9✔
1631
                l := log.FromContext(ctx)
4✔
1632
                ldd := model.DeviceDeployment{
4✔
1633
                        DeviceId:     dd.DeviceId,
4✔
1634
                        DeploymentId: dd.DeploymentId,
4✔
1635
                        Id:           dd.Id,
4✔
1636
                        Status:       ddState.Status,
4✔
1637
                }
4✔
1638
                if err := d.db.SaveLastDeviceDeploymentStatus(ctx, ldd); err != nil {
4✔
1639
                        l.Error(errors.Wrap(err, "failed to save last device deployment status").Error())
×
UNCOV
1640
                }
×
1641
                if err := d.reindexDevice(ctx, deviceID); err != nil {
4✔
1642
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1643
                }
×
1644
                if err := d.reindexDeployment(ctx, dd.DeviceId, dd.DeploymentId, dd.Id); err != nil {
4✔
UNCOV
1645
                        l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1646
                }
×
1647
        }
1648

1649
        return nil
5✔
1650
}
1651

1652
// recalcDeploymentStatus inspects the deployment stats and
1653
// recalculates and updates its status
1654
// it should be used whenever deployment stats are touched
1655
func (d *Deployments) recalcDeploymentStatus(ctx context.Context, dep *model.Deployment) error {
10✔
1656
        status := dep.GetStatus()
10✔
1657

10✔
1658
        if err := d.db.SetDeploymentStatus(ctx, dep.Id, status, time.Now()); err != nil {
10✔
UNCOV
1659
                return err
×
UNCOV
1660
        }
×
1661

1662
        return nil
10✔
1663
}
1664

1665
func (d *Deployments) GetDeploymentStats(ctx context.Context,
1666
        deploymentID string) (model.Stats, error) {
1✔
1667

1✔
1668
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1669

1✔
1670
        if err != nil {
1✔
1671
                return nil, errors.Wrap(err, "checking deployment id")
×
1672
        }
×
1673

1674
        if deployment == nil {
1✔
UNCOV
1675
                return nil, nil
×
UNCOV
1676
        }
×
1677

1678
        return deployment.Stats, nil
1✔
1679
}
1680
func (d *Deployments) GetDeploymentsStats(ctx context.Context,
1681
        deploymentIDs ...string) (deploymentStats []*model.DeploymentStats, err error) {
×
1682

×
1683
        deploymentStats, err = d.db.FindDeploymentStatsByIDs(ctx, deploymentIDs...)
×
UNCOV
1684

×
1685
        if err != nil {
×
1686
                return nil, errors.Wrap(err, "checking deployment statistics for IDs")
×
1687
        }
×
1688

1689
        if deploymentStats == nil {
×
UNCOV
1690
                return nil, ErrModelDeploymentNotFound
×
UNCOV
1691
        }
×
1692

UNCOV
1693
        return deploymentStats, nil
×
1694
}
1695

1696
// GetDeviceStatusesForDeployment retrieve device deployment statuses for a given deployment.
1697
func (d *Deployments) GetDeviceStatusesForDeployment(ctx context.Context,
1698
        deploymentID string) ([]model.DeviceDeployment, error) {
1✔
1699

1✔
1700
        deployment, err := d.db.FindDeploymentByID(ctx, deploymentID)
1✔
1701
        if err != nil {
1✔
1702
                return nil, ErrModelInternal
×
1703
        }
×
1704

1705
        if deployment == nil {
1✔
UNCOV
1706
                return nil, ErrModelDeploymentNotFound
×
1707
        }
×
1708

1709
        statuses, err := d.db.GetDeviceStatusesForDeployment(ctx, deploymentID)
1✔
1710
        if err != nil {
1✔
UNCOV
1711
                return nil, ErrModelInternal
×
UNCOV
1712
        }
×
1713

1714
        return statuses, nil
1✔
1715
}
1716

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

1✔
1720
        deployment, err := d.db.FindDeploymentByID(ctx, query.DeploymentID)
1✔
1721
        if err != nil {
1✔
1722
                return nil, -1, ErrModelInternal
×
1723
        }
×
1724

1725
        if deployment == nil {
1✔
UNCOV
1726
                return nil, -1, ErrModelDeploymentNotFound
×
1727
        }
×
1728

1729
        statuses, totalCount, err := d.db.GetDevicesListForDeployment(ctx, query)
1✔
1730
        if err != nil {
1✔
UNCOV
1731
                return nil, -1, ErrModelInternal
×
UNCOV
1732
        }
×
1733

1734
        return statuses, totalCount, nil
1✔
1735
}
1736

1737
func (d *Deployments) GetDeviceDeploymentListForDevice(ctx context.Context,
1738
        query store.ListQueryDeviceDeployments) ([]model.DeviceDeploymentListItem, int, error) {
4✔
1739
        deviceDeployments, totalCount, err := d.db.GetDeviceDeploymentsForDevice(ctx, query)
4✔
1740
        if err != nil {
5✔
1741
                return nil, -1, errors.Wrap(err, "retrieving the list of deployment statuses")
1✔
1742
        }
1✔
1743

1744
        deploymentIDs := make([]string, len(deviceDeployments))
3✔
1745
        for i, deviceDeployment := range deviceDeployments {
9✔
1746
                deploymentIDs[i] = deviceDeployment.DeploymentId
6✔
1747
        }
6✔
1748

1749
        deployments, _, err := d.db.Find(ctx, model.Query{
3✔
1750
                IDs:          deploymentIDs,
3✔
1751
                Limit:        len(deviceDeployments),
3✔
1752
                DisableCount: true,
3✔
1753
        })
3✔
1754
        if err != nil {
4✔
1755
                return nil, -1, errors.Wrap(err, "retrieving the list of deployments")
1✔
1756
        }
1✔
1757

1758
        deploymentsMap := make(map[string]*model.Deployment, len(deployments))
2✔
1759
        for _, deployment := range deployments {
5✔
1760
                deploymentsMap[deployment.Id] = deployment
3✔
1761
        }
3✔
1762

1763
        res := make([]model.DeviceDeploymentListItem, 0, len(deviceDeployments))
2✔
1764
        for i, deviceDeployment := range deviceDeployments {
6✔
1765
                if deployment, ok := deploymentsMap[deviceDeployment.DeploymentId]; ok {
7✔
1766
                        res = append(res, model.DeviceDeploymentListItem{
3✔
1767
                                Id:         deviceDeployment.Id,
3✔
1768
                                Deployment: deployment,
3✔
1769
                                Device:     &deviceDeployments[i],
3✔
1770
                        })
3✔
1771
                } else {
4✔
1772
                        res = append(res, model.DeviceDeploymentListItem{
1✔
1773
                                Id:     deviceDeployment.Id,
1✔
1774
                                Device: &deviceDeployments[i],
1✔
1775
                        })
1✔
1776
                }
1✔
1777
        }
1778

1779
        return res, totalCount, nil
2✔
1780
}
1781

1782
func (d *Deployments) setDeploymentDeviceCountIfUnset(
1783
        ctx context.Context,
1784
        deployment *model.Deployment,
1785
) error {
6✔
1786
        if deployment.DeviceCount == nil {
6✔
1787
                deviceCount, err := d.db.DeviceCountByDeployment(ctx, deployment.Id)
×
1788
                if err != nil {
×
1789
                        return errors.Wrap(err, "counting device deployments")
×
1790
                }
×
1791
                err = d.db.SetDeploymentDeviceCount(ctx, deployment.Id, deviceCount)
×
UNCOV
1792
                if err != nil {
×
UNCOV
1793
                        return errors.Wrap(err, "setting the device count for the deployment")
×
UNCOV
1794
                }
×
UNCOV
1795
                deployment.DeviceCount = &deviceCount
×
1796
        }
1797

1798
        return nil
6✔
1799
}
1800

1801
func (d *Deployments) LookupDeployment(ctx context.Context,
1802
        query model.Query) ([]*model.Deployment, int64, error) {
1✔
1803
        list, totalCount, err := d.db.Find(ctx, query)
1✔
1804

1✔
1805
        if err != nil {
1✔
UNCOV
1806
                return nil, 0, errors.Wrap(err, "searching for deployments")
×
UNCOV
1807
        }
×
1808

1809
        if list == nil {
2✔
1810
                return make([]*model.Deployment, 0), 0, nil
1✔
1811
        }
1✔
1812

UNCOV
1813
        for _, deployment := range list {
×
UNCOV
1814
                if err := d.setDeploymentDeviceCountIfUnset(ctx, deployment); err != nil {
×
1815
                        return nil, 0, err
×
UNCOV
1816
                }
×
1817
        }
1818

UNCOV
1819
        return list, totalCount, nil
×
1820
}
1821

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

1✔
1827
        // repack to temporary deployment log and validate
1✔
1828
        dlog := model.DeploymentLog{
1✔
1829
                DeviceID:     deviceID,
1✔
1830
                DeploymentID: deploymentID,
1✔
1831
                Messages:     logs,
1✔
1832
        }
1✔
1833
        if err := dlog.Validate(); err != nil {
1✔
1834
                return errors.Wrapf(err, ErrStorageInvalidLog.Error())
×
1835
        }
×
1836

1837
        if has, err := d.HasDeploymentForDevice(ctx, deploymentID, deviceID); !has {
1✔
1838
                if err != nil {
×
UNCOV
1839
                        return err
×
UNCOV
1840
                } else {
×
UNCOV
1841
                        return ErrModelDeploymentNotFound
×
1842
                }
×
1843
        }
1844

1845
        if err := d.db.SaveDeviceDeploymentLog(ctx, dlog); err != nil {
1✔
UNCOV
1846
                return err
×
UNCOV
1847
        }
×
1848

1849
        return d.db.UpdateDeviceDeploymentLogAvailability(ctx,
1✔
1850
                deviceID, deploymentID, true)
1✔
1851
}
1852

1853
func (d *Deployments) GetDeviceDeploymentLog(ctx context.Context,
1854
        deviceID, deploymentID string) (*model.DeploymentLog, error) {
1✔
1855

1✔
1856
        return d.db.GetDeviceDeploymentLog(ctx,
1✔
1857
                deviceID, deploymentID)
1✔
1858
}
1✔
1859

1860
func (d *Deployments) HasDeploymentForDevice(ctx context.Context,
1861
        deploymentID string, deviceID string) (bool, error) {
1✔
1862
        return d.db.HasDeploymentForDevice(ctx, deploymentID, deviceID)
1✔
1863
}
1✔
1864

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

5✔
1868
        if err := d.db.AbortDeviceDeployments(ctx, deploymentID); err != nil {
6✔
1869
                return err
1✔
1870
        }
1✔
1871

1872
        stats, err := d.db.AggregateDeviceDeploymentByStatus(
4✔
1873
                ctx, deploymentID)
4✔
1874
        if err != nil {
5✔
1875
                return err
1✔
1876
        }
1✔
1877

1878
        // update statistics
1879
        if err := d.db.UpdateStats(ctx, deploymentID, stats); err != nil {
4✔
1880
                return errors.Wrap(err, "failed to update deployment stats")
1✔
1881
        }
1✔
1882

1883
        // when aborting the deployment we need to set status directly instead of
1884
        // using recalcDeploymentStatus method;
1885
        // it is possible that the deployment does not have any device deployments yet;
1886
        // in that case, all statistics are 0 and calculating status based on statistics
1887
        // will not work - the calculated status will be "pending"
1888
        if err := d.db.SetDeploymentStatus(ctx,
2✔
1889
                deploymentID, model.DeploymentStatusFinished, time.Now()); err != nil {
2✔
UNCOV
1890
                return errors.Wrap(err, "failed to update deployment status")
×
UNCOV
1891
        }
×
1892

1893
        return nil
2✔
1894
}
1895

1896
func (d *Deployments) updateDeviceDeploymentsStatus(
1897
        ctx context.Context,
1898
        deviceId string,
1899
        status model.DeviceDeploymentStatus,
1900
) error {
15✔
1901
        var latestDeployment *time.Time
15✔
1902
        // Retrieve active device deployment for the device
15✔
1903
        deviceDeployment, err := d.db.FindOldestActiveDeviceDeployment(ctx, deviceId)
15✔
1904
        if err != nil {
17✔
1905
                return errors.Wrap(err, "Searching for active deployment for the device")
2✔
1906
        } else if deviceDeployment != nil {
17✔
1907
                now := time.Now()
2✔
1908
                ddStatus := model.DeviceDeploymentState{
2✔
1909
                        Status:     status,
2✔
1910
                        FinishTime: &now,
2✔
1911
                }
2✔
1912
                if err := d.UpdateDeviceDeploymentStatus(ctx, deviceDeployment.DeploymentId,
2✔
1913
                        deviceId, ddStatus); err != nil {
2✔
UNCOV
1914
                        return errors.Wrap(err, "updating device deployment status")
×
UNCOV
1915
                }
×
1916
                latestDeployment = deviceDeployment.Created
2✔
1917
        } else {
11✔
1918
                // get latest device deployment for the device
11✔
1919
                deviceDeployment, err := d.db.FindLatestInactiveDeviceDeployment(ctx, deviceId)
11✔
1920
                if err != nil {
11✔
UNCOV
1921
                        return errors.Wrap(err, "Searching for latest active deployment for the device")
×
1922
                } else if deviceDeployment == nil {
20✔
1923
                        latestDeployment = &time.Time{}
9✔
1924
                } else {
11✔
1925
                        latestDeployment = deviceDeployment.Created
2✔
1926
                }
2✔
1927
        }
1928

1929
        // get deployments newer then last device deployment
1930
        // iterate over deployments and check if the device is part of the deployment or not
1931
        // if the device is part of the deployment create new, decommisioned device deployment
1932
        for skip := 0; true; skip += 100 {
33✔
1933
                deployments, err := d.db.FindNewerActiveDeployments(ctx, latestDeployment, skip, 100)
20✔
1934
                if err != nil {
20✔
UNCOV
1935
                        return errors.Wrap(err, "Failed to search for newer active deployments")
×
UNCOV
1936
                }
×
1937
                if len(deployments) == 0 {
33✔
1938
                        break
13✔
1939
                }
1940
                for _, deployment := range deployments {
14✔
1941
                        ok, err := d.isDevicePartOfDeployment(ctx, deviceId, deployment)
7✔
1942
                        if err != nil {
7✔
UNCOV
1943
                                return err
×
UNCOV
1944
                        }
×
1945
                        if ok {
12✔
1946
                                deviceDeployment, err := d.createDeviceDeploymentWithStatus(ctx,
5✔
1947
                                        deviceId, deployment, status)
5✔
1948
                                if err != nil {
5✔
UNCOV
1949
                                        return err
×
1950
                                }
×
1951
                                if !status.Active() {
10✔
1952
                                        if err := d.reindexDeployment(ctx, deviceDeployment.DeviceId,
5✔
1953
                                                deviceDeployment.DeploymentId, deviceDeployment.Id); err != nil {
5✔
UNCOV
1954
                                                l := log.FromContext(ctx)
×
UNCOV
1955
                                                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1956
                                        }
×
1957
                                }
1958
                        }
1959
                }
1960
        }
1961

1962
        if err := d.reindexDevice(ctx, deviceId); err != nil {
13✔
UNCOV
1963
                l := log.FromContext(ctx)
×
UNCOV
1964
                l.Warn(errors.Wrap(err, "failed to trigger a device reindex"))
×
UNCOV
1965
        }
×
1966

1967
        return nil
13✔
1968
}
1969

1970
// DecommissionDevice updates the status of all the pending and active deployments for a device
1971
// to decommissioned
1972
func (d *Deployments) DecommissionDevice(ctx context.Context, deviceId string) error {
7✔
1973
        return d.updateDeviceDeploymentsStatus(
7✔
1974
                ctx,
7✔
1975
                deviceId,
7✔
1976
                model.DeviceDeploymentStatusDecommissioned,
7✔
1977
        )
7✔
1978
}
7✔
1979

1980
// AbortDeviceDeployments aborts all the pending and active deployments for a device
1981
func (d *Deployments) AbortDeviceDeployments(ctx context.Context, deviceId string) error {
8✔
1982
        return d.updateDeviceDeploymentsStatus(
8✔
1983
                ctx,
8✔
1984
                deviceId,
8✔
1985
                model.DeviceDeploymentStatusAborted,
8✔
1986
        )
8✔
1987
}
8✔
1988

1989
// DeleteDeviceDeploymentsHistory deletes the device deployments history
1990
func (d *Deployments) DeleteDeviceDeploymentsHistory(ctx context.Context, deviceId string) error {
2✔
1991
        // get device deployments which will be marked as deleted
2✔
1992
        f := false
2✔
1993
        dd, err := d.db.GetDeviceDeployments(ctx, 0, 0, deviceId, &f, false)
2✔
1994
        if err != nil {
2✔
UNCOV
1995
                return err
×
1996
        }
×
1997

1998
        // no device deployments to update
1999
        if len(dd) <= 0 {
2✔
UNCOV
2000
                return nil
×
UNCOV
2001
        }
×
2002

2003
        // mark device deployments as deleted
2004
        if err := d.db.DeleteDeviceDeploymentsHistory(ctx, deviceId); err != nil {
3✔
2005
                return err
1✔
2006
        }
1✔
2007

2008
        // trigger reindexing of updated device deployments
2009
        deviceDeployments := make([]workflows.DeviceDeploymentShortInfo, len(dd))
1✔
2010
        for i, d := range dd {
2✔
2011
                deviceDeployments[i].ID = d.Id
1✔
2012
                deviceDeployments[i].DeviceID = d.DeviceId
1✔
2013
                deviceDeployments[i].DeploymentID = d.DeploymentId
1✔
2014
        }
1✔
2015
        if d.reportingClient != nil {
2✔
2016
                err = d.workflowsClient.StartReindexReportingDeploymentBatch(ctx, deviceDeployments)
1✔
2017
        }
1✔
2018
        return err
1✔
2019
}
2020

2021
// Storage settings
2022
func (d *Deployments) GetStorageSettings(ctx context.Context) (*model.StorageSettings, error) {
3✔
2023
        settings, err := d.db.GetStorageSettings(ctx)
3✔
2024
        if err != nil {
4✔
2025
                return nil, errors.Wrap(err, "Searching for settings failed")
1✔
2026
        }
1✔
2027

2028
        return settings, nil
2✔
2029
}
2030

2031
func (d *Deployments) SetStorageSettings(
2032
        ctx context.Context,
2033
        storageSettings *model.StorageSettings,
2034
) error {
4✔
2035
        if storageSettings != nil {
8✔
2036
                ctx = storage.SettingsWithContext(ctx, storageSettings)
4✔
2037
                if err := d.objectStorage.HealthCheck(ctx); err != nil {
4✔
UNCOV
2038
                        return errors.WithMessage(err,
×
UNCOV
2039
                                "the provided storage settings failed the health check",
×
UNCOV
2040
                        )
×
UNCOV
2041
                }
×
2042
        }
2043
        if err := d.db.SetStorageSettings(ctx, storageSettings); err != nil {
6✔
2044
                return errors.Wrap(err, "Failed to save settings")
2✔
2045
        }
2✔
2046

2047
        return nil
2✔
2048
}
2049

2050
func (d *Deployments) WithReporting(c reporting.Client) *Deployments {
8✔
2051
        d.reportingClient = c
8✔
2052
        return d
8✔
2053
}
8✔
2054

2055
func (d *Deployments) haveReporting() bool {
6✔
2056
        return d.reportingClient != nil
6✔
2057
}
6✔
2058

2059
func (d *Deployments) search(
2060
        ctx context.Context,
2061
        tid string,
2062
        parms model.SearchParams,
2063
) ([]model.InvDevice, int, error) {
6✔
2064
        if d.haveReporting() {
7✔
2065
                return d.reportingClient.Search(ctx, tid, parms)
1✔
2066
        } else {
6✔
2067
                return d.inventoryClient.Search(ctx, tid, parms)
5✔
2068
        }
5✔
2069
}
2070

2071
func (d *Deployments) UpdateDeploymentsWithArtifactName(
2072
        ctx context.Context,
2073
        artifactName string,
2074
) error {
2✔
2075
        // first check if there are pending deployments with given artifact name
2✔
2076
        exists, err := d.db.ExistUnfinishedByArtifactName(ctx, artifactName)
2✔
2077
        if err != nil {
2✔
UNCOV
2078
                return errors.Wrap(err, "looking for deployments with given artifact name")
×
UNCOV
2079
        }
×
2080
        if !exists {
3✔
2081
                return nil
1✔
2082
        }
1✔
2083

2084
        // Assign artifacts to the deployments with given artifact name
2085
        artifacts, err := d.db.ImagesByName(ctx, artifactName)
1✔
2086
        if err != nil {
1✔
2087
                return errors.Wrap(err, "Finding artifact with given name")
×
2088
        }
×
2089

2090
        if len(artifacts) == 0 {
1✔
UNCOV
2091
                return ErrNoArtifact
×
UNCOV
2092
        }
×
2093
        artifactIDs := getArtifactIDs(artifacts)
1✔
2094
        return d.db.UpdateDeploymentsWithArtifactName(ctx, artifactName, artifactIDs)
1✔
2095
}
2096

2097
func (d *Deployments) reindexDevice(ctx context.Context, deviceID string) error {
25✔
2098
        if d.reportingClient != nil {
28✔
2099
                return d.workflowsClient.StartReindexReporting(ctx, deviceID)
3✔
2100
        }
3✔
2101
        return nil
22✔
2102
}
2103

2104
func (d *Deployments) reindexDeployment(ctx context.Context,
2105
        deviceID, deploymentID, ID string) error {
17✔
2106
        if d.reportingClient != nil {
20✔
2107
                return d.workflowsClient.StartReindexReportingDeployment(ctx, deviceID, deploymentID, ID)
3✔
2108
        }
3✔
2109
        return nil
14✔
2110
}
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