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

mendersoftware / inventory / 921200914

pending completion
921200914

Pull #396

gitlab-ci

merlin-northern
chore: additional unit tests.

Ticket: MEN-6425
Signed-off-by: Peter Grzybowski <peter@northern.tech>
Pull Request #396: feat: update inventory only when changed or outdated.

89 of 128 new or added lines in 3 files covered. (69.53%)

65 existing lines in 2 files now uncovered.

3181 of 3504 relevant lines covered (90.78%)

139.65 hits per line

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

90.47
/store/mongo/datastore_mongo.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 mongo
16

17
import (
18
        "context"
19
        "crypto/tls"
20
        "fmt"
21
        "io"
22
        "strings"
23
        "sync"
24
        "time"
25

26
        "go.mongodb.org/mongo-driver/bson"
27
        "go.mongodb.org/mongo-driver/bson/primitive"
28
        "go.mongodb.org/mongo-driver/mongo"
29
        mopts "go.mongodb.org/mongo-driver/mongo/options"
30

31
        "github.com/google/uuid"
32
        "github.com/pkg/errors"
33

34
        "github.com/mendersoftware/go-lib-micro/log"
35
        mstore "github.com/mendersoftware/go-lib-micro/store"
36

37
        "github.com/mendersoftware/inventory/model"
38
        "github.com/mendersoftware/inventory/store"
39
        "github.com/mendersoftware/inventory/utils"
40
)
41

42
const (
43
        DbVersion = "1.1.0"
44

45
        DbName        = "inventory"
46
        DbDevicesColl = "devices"
47

48
        DbDevId              = "_id"
49
        DbDevAttributes      = "attributes"
50
        DbDevGroup           = "group"
51
        DbDevRevision        = "revision"
52
        DbDevUpdatedTs       = "updated_ts"
53
        DbDevAttributesText  = "text"
54
        DbDevAttributesTs    = "timestamp"
55
        DbDevAttributesDesc  = "description"
56
        DbDevAttributesValue = "value"
57
        DbDevAttributesScope = "scope"
58
        DbDevAttributesName  = "name"
59
        DbDevAttributesGroup = DbDevAttributes + "." +
60
                model.AttrScopeSystem + "-" + model.AttrNameGroup
61
        DbDevAttributesGroupValue = DbDevAttributesGroup + "." +
62
                DbDevAttributesValue
63

64
        DbScopeInventory = "inventory"
65

66
        FiltersAttributesLimit = 500
67

68
        attrIdentityStatus = "identity-status"
69
)
70

71
var (
72
        //with offcial mongodb supported driver we keep client
73
        clientGlobal *mongo.Client
74

75
        // once ensures client is created only once
76
        once sync.Once
77
)
78

79
type DataStoreMongoConfig struct {
80
        // connection string
81
        ConnectionString string
82

83
        // SSL support
84
        SSL           bool
85
        SSLSkipVerify bool
86

87
        // Overwrites credentials provided in connection string if provided
88
        Username string
89
        Password string
90
}
91

92
type DataStoreMongo struct {
93
        client      *mongo.Client
94
        automigrate bool
95
}
96

97
func NewDataStoreMongoWithSession(client *mongo.Client) store.DataStore {
192✔
98
        return &DataStoreMongo{client: client}
192✔
99
}
192✔
100

101
// config.ConnectionString must contain a valid
102
func NewDataStoreMongo(config DataStoreMongoConfig) (store.DataStore, error) {
5✔
103
        //init master session
5✔
104
        var err error
5✔
105
        once.Do(func() {
9✔
106
                if !strings.Contains(config.ConnectionString, "://") {
8✔
107
                        config.ConnectionString = "mongodb://" + config.ConnectionString
4✔
108
                }
4✔
109
                clientOptions := mopts.Client().ApplyURI(config.ConnectionString)
4✔
110

4✔
111
                if config.Username != "" {
4✔
112
                        clientOptions.SetAuth(mopts.Credential{
×
113
                                Username: config.Username,
×
114
                                Password: config.Password,
×
115
                        })
×
116
                }
×
117

118
                if config.SSL {
4✔
119
                        tlsConfig := &tls.Config{}
×
120
                        tlsConfig.InsecureSkipVerify = config.SSLSkipVerify
×
121
                        clientOptions.SetTLSConfig(tlsConfig)
×
122
                }
×
123

124
                ctx := context.Background()
4✔
125
                l := log.FromContext(ctx)
4✔
126
                clientGlobal, err = mongo.Connect(ctx, clientOptions)
4✔
127
                if err != nil {
4✔
128
                        l.Errorf("mongo: error connecting to mongo '%s'", err.Error())
×
129
                        return
×
130
                }
×
131
                if clientGlobal == nil {
4✔
132
                        l.Errorf("mongo: client is nil. wow.")
×
133
                        return
×
134
                }
×
135
                // from: https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial
136
                /*
137
                        It is best practice to keep a client that is connected to MongoDB around so that the
138
                        application can make use of connection pooling - you don't want to open and close a
139
                        connection for each query. However, if your application no longer requires a connection,
140
                        the connection can be closed with client.Disconnect() like so:
141
                */
142
                err = clientGlobal.Ping(ctx, nil)
4✔
143
                if err != nil {
5✔
144
                        clientGlobal = nil
1✔
145
                        l.Errorf("mongo: error pinging mongo '%s'", err.Error())
1✔
146
                        return
1✔
147
                }
1✔
148
                if clientGlobal == nil {
3✔
149
                        l.Errorf("mongo: global instance of client is nil.")
×
150
                        return
×
151
                }
×
152
        })
153

154
        if clientGlobal == nil {
6✔
155
                return nil, errors.New("failed to open mongo-driver session")
1✔
156
        }
1✔
157
        db := &DataStoreMongo{client: clientGlobal}
4✔
158

4✔
159
        return db, nil
4✔
160
}
161

162
func (db *DataStoreMongo) Ping(ctx context.Context) error {
1✔
163
        res := db.client.Database(DbName).RunCommand(ctx, bson.M{"ping": 1})
1✔
164
        return res.Err()
1✔
165
}
1✔
166

167
func (db *DataStoreMongo) GetDevices(
168
        ctx context.Context,
169
        q store.ListQuery,
170
) ([]model.Device, int, error) {
53✔
171
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
53✔
172

53✔
173
        queryFilters := make([]bson.M, 0)
53✔
174
        for _, filter := range q.Filters {
60✔
175
                op := mongoOperator(filter.Operator)
7✔
176
                name := fmt.Sprintf(
7✔
177
                        "%s-%s",
7✔
178
                        filter.AttrScope,
7✔
179
                        model.GetDeviceAttributeNameReplacer().Replace(filter.AttrName),
7✔
180
                )
7✔
181
                field := fmt.Sprintf("%s.%s.%s", DbDevAttributes, name, DbDevAttributesValue)
7✔
182
                switch filter.Operator {
7✔
183
                default:
7✔
184
                        if filter.ValueFloat != nil {
11✔
185
                                queryFilters = append(queryFilters, bson.M{"$or": []bson.M{
4✔
186
                                        {field: bson.M{op: filter.Value}},
4✔
187
                                        {field: bson.M{op: filter.ValueFloat}},
4✔
188
                                }})
4✔
189
                        } else if filter.ValueTime != nil {
8✔
190
                                queryFilters = append(queryFilters, bson.M{"$or": []bson.M{
1✔
191
                                        {field: bson.M{op: filter.Value}},
1✔
192
                                        {field: bson.M{op: filter.ValueTime}},
1✔
193
                                }})
1✔
194
                        } else {
3✔
195
                                queryFilters = append(queryFilters, bson.M{field: bson.M{op: filter.Value}})
2✔
196
                        }
2✔
197
                }
198
        }
199
        if q.GroupName != "" {
85✔
200
                groupFilter := bson.M{DbDevAttributesGroupValue: q.GroupName}
32✔
201
                queryFilters = append(queryFilters, groupFilter)
32✔
202
        }
32✔
203
        if q.GroupName != "" {
85✔
204
                groupFilter := bson.M{DbDevAttributesGroupValue: q.GroupName}
32✔
205
                queryFilters = append(queryFilters, groupFilter)
32✔
206
        }
32✔
207
        if q.HasGroup != nil {
89✔
208
                groupExistenceFilter := bson.M{
36✔
209
                        DbDevAttributesGroup: bson.M{
36✔
210
                                "$exists": *q.HasGroup,
36✔
211
                        },
36✔
212
                }
36✔
213
                queryFilters = append(queryFilters, groupExistenceFilter)
36✔
214
        }
36✔
215

216
        findQuery := bson.M{}
53✔
217
        if len(queryFilters) > 0 {
96✔
218
                findQuery["$and"] = queryFilters
43✔
219
        }
43✔
220

221
        findOptions := mopts.Find()
53✔
222
        if q.Skip > 0 {
63✔
223
                findOptions.SetSkip(int64(q.Skip))
10✔
224
        }
10✔
225
        if q.Limit > 0 {
101✔
226
                findOptions.SetLimit(int64(q.Limit))
48✔
227
        }
48✔
228
        if q.Sort != nil {
58✔
229
                name := fmt.Sprintf(
5✔
230
                        "%s-%s",
5✔
231
                        q.Sort.AttrScope,
5✔
232
                        model.GetDeviceAttributeNameReplacer().Replace(q.Sort.AttrName),
5✔
233
                )
5✔
234
                sortField := fmt.Sprintf("%s.%s.%s", DbDevAttributes, name, DbDevAttributesValue)
5✔
235
                sortFieldQuery := bson.D{{Key: sortField, Value: 1}}
5✔
236
                if !q.Sort.Ascending {
8✔
237
                        sortFieldQuery[0].Value = -1
3✔
238
                }
3✔
239
                findOptions.SetSort(sortFieldQuery)
5✔
240
        }
241

242
        cursor, err := c.Find(ctx, findQuery, findOptions)
53✔
243
        if err != nil {
53✔
244
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
245
        }
×
246
        defer cursor.Close(ctx)
53✔
247

53✔
248
        devices := []model.Device{}
53✔
249
        if err = cursor.All(ctx, &devices); err != nil {
53✔
250
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
251
        }
×
252

253
        count, err := c.CountDocuments(ctx, findQuery)
53✔
254
        if err != nil {
53✔
255
                return nil, -1, errors.Wrap(err, "failed to count devices")
×
256
        }
×
257

258
        return devices, int(count), nil
53✔
259
}
260

261
func (db *DataStoreMongo) GetDevice(
262
        ctx context.Context,
263
        id model.DeviceID,
264
) (*model.Device, error) {
316✔
265
        var res model.Device
316✔
266
        c := db.client.
316✔
267
                Database(mstore.DbFromContext(ctx, DbName)).
316✔
268
                Collection(DbDevicesColl)
316✔
269
        l := log.FromContext(ctx)
316✔
270

316✔
271
        if id == model.NilDeviceID {
318✔
272
                return nil, nil
2✔
273
        }
2✔
274
        if err := c.FindOne(ctx, bson.M{DbDevId: id}).Decode(&res); err != nil {
576✔
275
                switch err {
262✔
276
                case mongo.ErrNoDocuments:
262✔
277
                        return nil, nil
262✔
278
                default:
×
279
                        l.Errorf("GetDevice: %v", err)
×
280
                        return nil, errors.Wrap(err, "failed to fetch device")
×
281
                }
282
        }
283
        return &res, nil
52✔
284
}
285

286
// AddDevice inserts a new device, initializing the inventory data.
287
func (db *DataStoreMongo) AddDevice(ctx context.Context, dev *model.Device) error {
256✔
288
        if dev.Group != "" {
296✔
289
                dev.Attributes = append(dev.Attributes, model.DeviceAttribute{
40✔
290
                        Scope: model.AttrScopeSystem,
40✔
291
                        Name:  model.AttrNameGroup,
40✔
292
                        Value: dev.Group,
40✔
293
                })
40✔
294
        }
40✔
295
        _, err := db.UpsertDevicesAttributesWithUpdated(
256✔
296
                ctx, []model.DeviceID{dev.ID}, dev.Attributes, "", "",
256✔
297
        )
256✔
298
        if err != nil {
256✔
299
                return errors.Wrap(err, "failed to store device")
×
300
        }
×
301
        return nil
256✔
302
}
303

304
func (db *DataStoreMongo) UpsertDevicesAttributesWithRevision(
305
        ctx context.Context,
306
        devices []model.DeviceUpdate,
307
        attrs model.DeviceAttributes,
308
) (*model.UpdateResult, error) {
3✔
309
        return db.upsertAttributes(ctx, devices, attrs, false, true, "", "")
3✔
310
}
3✔
311

312
func (db *DataStoreMongo) inventoryNeedsUpdate(
313
        ctx context.Context,
314
        id model.DeviceID,
315
        newAttributes model.DeviceAttributes,
316
) (rc bool) {
280✔
317
        rc = false
280✔
318
        device, err := db.GetDevice(ctx, id)
280✔
319
        if device == nil || err != nil {
538✔
320
                return true
258✔
321
        }
258✔
322

323
        a := device.Attributes.GetByName(model.AttrNameUpdated)
22✔
324
        if a == nil {
26✔
325
                return true
4✔
326
        }
4✔
327

328
        if v, ok := a.Value.(primitive.DateTime); ok {
36✔
329
                v := v.Time()
18✔
330
                lastUpdatedDate := utils.TruncateToDay(v)
18✔
331
                now := utils.TruncateToDay(time.Now())
18✔
332
                if now.Day() != lastUpdatedDate.Day() {
18✔
NEW
UNCOV
333
                        if now.Month() != lastUpdatedDate.Month() {
×
NEW
UNCOV
334
                                if now.Year() != lastUpdatedDate.Year() {
×
NEW
UNCOV
335
                                        return true
×
NEW
UNCOV
336
                                }
×
337
                        }
338
                }
339
        }
340

341
        return !device.Attributes.Equal(newAttributes)
18✔
342
}
343

344
func (db *DataStoreMongo) UpsertDevicesAttributesWithUpdated(
345
        ctx context.Context,
346
        ids []model.DeviceID,
347
        attrs model.DeviceAttributes,
348
        scope string,
349
        etag string,
350
) (*model.UpdateResult, error) {
277✔
351
        var idsToUpdate = []model.DeviceID{}
277✔
352
        for _, id := range ids {
557✔
353
                if db.inventoryNeedsUpdate(ctx, id, attrs) {
560✔
354
                        idsToUpdate = append(idsToUpdate, id)
280✔
355
                }
280✔
356
        }
357
        if len(idsToUpdate) < 1 {
278✔
358
                return nil, nil
1✔
359
        }
1✔
360
        return db.upsertAttributes(ctx, makeDevsWithIds(idsToUpdate), attrs, true, false, scope, etag)
276✔
361
}
362

363
func (db *DataStoreMongo) UpsertDevicesAttributes(
364
        ctx context.Context,
365
        ids []model.DeviceID,
366
        attrs model.DeviceAttributes,
367
) (*model.UpdateResult, error) {
16✔
368
        return db.upsertAttributes(ctx, makeDevsWithIds(ids), attrs, false, false, "", "")
16✔
369
}
16✔
370

371
func makeDevsWithIds(ids []model.DeviceID) []model.DeviceUpdate {
292✔
372
        devices := make([]model.DeviceUpdate, len(ids))
292✔
373
        for i, id := range ids {
591✔
374
                devices[i].Id = id
299✔
375
        }
299✔
376
        return devices
292✔
377
}
378

379
func (db *DataStoreMongo) upsertAttributes(
380
        ctx context.Context,
381
        devices []model.DeviceUpdate,
382
        attrs model.DeviceAttributes,
383
        withUpdated bool,
384
        withRevision bool,
385
        scope string,
386
        etag string,
387
) (*model.UpdateResult, error) {
295✔
388
        const systemScope = DbDevAttributes + "." + model.AttrScopeSystem
295✔
389
        const createdField = systemScope + "-" + model.AttrNameCreated
295✔
390
        const etagField = model.AttrNameTagsEtag
295✔
391
        var (
295✔
392
                result *model.UpdateResult
295✔
393
                filter interface{}
295✔
394
                err    error
295✔
395
        )
295✔
396

295✔
397
        c := db.client.
295✔
398
                Database(mstore.DbFromContext(ctx, DbName)).
295✔
399
                Collection(DbDevicesColl)
295✔
400

295✔
401
        update, err := makeAttrUpsert(attrs)
295✔
402
        if err != nil {
297✔
403
                return nil, err
2✔
404
        }
2✔
405

406
        now := time.Now()
293✔
407
        oninsert := bson.M{
293✔
408
                createdField: model.DeviceAttribute{
293✔
409
                        Scope: model.AttrScopeSystem,
293✔
410
                        Name:  model.AttrNameCreated,
293✔
411
                        Value: now,
293✔
412
                },
293✔
413
        }
293✔
414
        if !withRevision {
583✔
415
                oninsert["revision"] = 0
290✔
416
        }
290✔
417

418
        const updatedField = systemScope + "-" + model.AttrNameUpdated
293✔
419
        if withUpdated {
568✔
420
                update[updatedField] = model.DeviceAttribute{
275✔
421
                        Scope: model.AttrScopeSystem,
275✔
422
                        Name:  model.AttrNameUpdated,
275✔
423
                        Value: now,
275✔
424
                }
275✔
425
        } else {
293✔
426
                oninsert[updatedField] = model.DeviceAttribute{
18✔
427
                        Scope: model.AttrScopeSystem,
18✔
428
                        Name:  model.AttrNameUpdated,
18✔
429
                        Value: now,
18✔
430
                }
18✔
431
        }
18✔
432

433
        switch len(devices) {
293✔
434
        case 0:
1✔
435
                return &model.UpdateResult{}, nil
1✔
436
        case 1:
289✔
437
                filter := bson.M{
289✔
438
                        "_id": devices[0].Id,
289✔
439
                }
289✔
440
                updateOpts := mopts.FindOneAndUpdate().
289✔
441
                        SetUpsert(true).
289✔
442
                        SetReturnDocument(mopts.After)
289✔
443

289✔
444
                if withRevision {
291✔
445
                        filter[DbDevRevision] = bson.M{"$lt": devices[0].Revision}
2✔
446
                        update[DbDevRevision] = devices[0].Revision
2✔
447
                }
2✔
448
                if scope == model.AttrScopeTags {
294✔
449
                        update[etagField] = uuid.New().String()
5✔
450
                        updateOpts = mopts.FindOneAndUpdate().
5✔
451
                                SetUpsert(false).
5✔
452
                                SetReturnDocument(mopts.After)
5✔
453
                }
5✔
454
                if etag != "" {
290✔
455
                        filter[etagField] = bson.M{"$eq": etag}
1✔
456
                }
1✔
457

458
                update = bson.M{
289✔
459
                        "$set":         update,
289✔
460
                        "$setOnInsert": oninsert,
289✔
461
                }
289✔
462

289✔
463
                device := &model.Device{}
289✔
464
                res := c.FindOneAndUpdate(ctx, filter, update, updateOpts)
289✔
465
                err = res.Decode(device)
289✔
466
                if err != nil {
291✔
467
                        if mongo.IsDuplicateKeyError(err) {
3✔
468
                                return nil, store.ErrWriteConflict
1✔
469
                        } else if err == mongo.ErrNoDocuments {
3✔
470
                                return &model.UpdateResult{}, nil
1✔
471
                        } else {
1✔
UNCOV
472
                                return nil, err
×
UNCOV
473
                        }
×
474
                }
475
                result = &model.UpdateResult{
287✔
476
                        MatchedCount: 1,
287✔
477
                        CreatedCount: 0,
287✔
478
                        Devices:      []*model.Device{device},
287✔
479
                }
287✔
480
        default:
3✔
481
                var bres *mongo.BulkWriteResult
3✔
482
                // Perform single bulk-write operation
3✔
483
                // NOTE: Can't use UpdateMany as $in query operator does not
3✔
484
                //       upsert missing devices.
3✔
485

3✔
486
                models := make([]mongo.WriteModel, len(devices))
3✔
487
                for i, dev := range devices {
12✔
488
                        umod := mongo.NewUpdateOneModel()
9✔
489
                        if withRevision {
12✔
490
                                filter = bson.M{
3✔
491
                                        "_id":         dev.Id,
3✔
492
                                        DbDevRevision: bson.M{"$lt": dev.Revision},
3✔
493
                                }
3✔
494
                                update[DbDevRevision] = dev.Revision
3✔
495
                                umod.Update = bson.M{
3✔
496
                                        "$set":         update,
3✔
497
                                        "$setOnInsert": oninsert,
3✔
498
                                }
3✔
499
                        } else {
9✔
500
                                filter = map[string]interface{}{"_id": dev.Id}
6✔
501
                                umod.Update = bson.M{
6✔
502
                                        "$set":         update,
6✔
503
                                        "$setOnInsert": oninsert,
6✔
504
                                }
6✔
505
                        }
6✔
506
                        umod.Filter = filter
9✔
507
                        umod.SetUpsert(true)
9✔
508
                        models[i] = umod
9✔
509
                }
510
                bres, err = c.BulkWrite(
3✔
511
                        ctx, models, mopts.BulkWrite().SetOrdered(false),
3✔
512
                )
3✔
513
                if err != nil {
4✔
514
                        if mongo.IsDuplicateKeyError(err) {
2✔
515
                                // bulk mode, swallow the error as we already updated the other devices
1✔
516
                                // and the Matchedcount and CreatedCount values will tell the caller if
1✔
517
                                // all the operations succeeded or not
1✔
518
                                err = nil
1✔
519
                        } else {
1✔
520
                                return nil, err
×
UNCOV
521
                        }
×
522
                }
523
                result = &model.UpdateResult{
3✔
524
                        MatchedCount: bres.MatchedCount,
3✔
525
                        CreatedCount: bres.UpsertedCount,
3✔
526
                }
3✔
527
        }
528
        return result, err
290✔
529
}
530

531
// makeAttrField is a convenience function for composing attribute field names.
532
func makeAttrField(attrName, attrScope string, subFields ...string) string {
4,748✔
533
        field := fmt.Sprintf(
4,748✔
534
                "%s.%s-%s",
4,748✔
535
                DbDevAttributes,
4,748✔
536
                attrScope,
4,748✔
537
                model.GetDeviceAttributeNameReplacer().Replace(attrName),
4,748✔
538
        )
4,748✔
539
        if len(subFields) > 0 {
9,495✔
540
                field = strings.Join(
4,747✔
541
                        append([]string{field}, subFields...), ".",
4,747✔
542
                )
4,747✔
543
        }
4,747✔
544
        return field
4,748✔
545
}
546

547
// makeAttrUpsert creates a new upsert document for the given attributes.
548
func makeAttrUpsert(attrs model.DeviceAttributes) (bson.M, error) {
322✔
549
        var fieldName string
322✔
550
        upsert := make(bson.M)
322✔
551

322✔
552
        for i := range attrs {
1,753✔
553
                if attrs[i].Name == "" {
1,434✔
554
                        return nil, store.ErrNoAttrName
3✔
555
                }
3✔
556
                if attrs[i].Scope == "" {
1,434✔
557
                        // Default to inventory scope
6✔
558
                        attrs[i].Scope = model.AttrScopeInventory
6✔
559
                }
6✔
560

561
                fieldName = makeAttrField(
1,428✔
562
                        attrs[i].Name,
1,428✔
563
                        attrs[i].Scope,
1,428✔
564
                        DbDevAttributesScope,
1,428✔
565
                )
1,428✔
566
                upsert[fieldName] = attrs[i].Scope
1,428✔
567

1,428✔
568
                fieldName = makeAttrField(
1,428✔
569
                        attrs[i].Name,
1,428✔
570
                        attrs[i].Scope,
1,428✔
571
                        DbDevAttributesName,
1,428✔
572
                )
1,428✔
573
                upsert[fieldName] = attrs[i].Name
1,428✔
574

1,428✔
575
                if attrs[i].Value != nil {
2,851✔
576
                        fieldName = makeAttrField(
1,423✔
577
                                attrs[i].Name,
1,423✔
578
                                attrs[i].Scope,
1,423✔
579
                                DbDevAttributesValue,
1,423✔
580
                        )
1,423✔
581
                        upsert[fieldName] = attrs[i].Value
1,423✔
582
                }
1,423✔
583

584
                if attrs[i].Description != nil {
1,884✔
585
                        fieldName = makeAttrField(
456✔
586
                                attrs[i].Name,
456✔
587
                                attrs[i].Scope,
456✔
588
                                DbDevAttributesDesc,
456✔
589
                        )
456✔
590
                        upsert[fieldName] = attrs[i].Description
456✔
591
                }
456✔
592

593
                if attrs[i].Timestamp != nil {
1,440✔
594
                        fieldName = makeAttrField(
12✔
595
                                attrs[i].Name,
12✔
596
                                attrs[i].Scope,
12✔
597
                                DbDevAttributesTs,
12✔
598
                        )
12✔
599
                        upsert[fieldName] = attrs[i].Timestamp
12✔
600
                }
12✔
601
        }
602
        return upsert, nil
319✔
603
}
604

605
// makeAttrRemove creates a new unset document to remove attributes
606
func makeAttrRemove(attrs model.DeviceAttributes) (bson.M, error) {
26✔
607
        var fieldName string
26✔
608
        remove := make(bson.M)
26✔
609

26✔
610
        for i := range attrs {
27✔
611
                if attrs[i].Name == "" {
1✔
UNCOV
612
                        return nil, store.ErrNoAttrName
×
UNCOV
613
                }
×
614
                if attrs[i].Scope == "" {
1✔
UNCOV
615
                        // Default to inventory scope
×
UNCOV
616
                        attrs[i].Scope = model.AttrScopeInventory
×
UNCOV
617
                }
×
618
                fieldName = makeAttrField(
1✔
619
                        attrs[i].Name,
1✔
620
                        attrs[i].Scope,
1✔
621
                )
1✔
622
                remove[fieldName] = true
1✔
623
        }
624
        return remove, nil
26✔
625
}
626

627
func mongoOperator(co store.ComparisonOperator) string {
7✔
628
        switch co {
7✔
629
        case store.Eq:
7✔
630
                return "$eq"
7✔
631
        }
UNCOV
632
        return ""
×
633
}
634

635
func (db *DataStoreMongo) UpsertRemoveDeviceAttributes(
636
        ctx context.Context,
637
        id model.DeviceID,
638
        updateAttrs model.DeviceAttributes,
639
        removeAttrs model.DeviceAttributes,
640
        scope string,
641
        etag string,
642
) (*model.UpdateResult, error) {
27✔
643
        const systemScope = DbDevAttributes + "." + model.AttrScopeSystem
27✔
644
        const updatedField = systemScope + "-" + model.AttrNameUpdated
27✔
645
        const createdField = systemScope + "-" + model.AttrNameCreated
27✔
646
        const etagField = model.AttrNameTagsEtag
27✔
647
        var (
27✔
648
                err error
27✔
649
        )
27✔
650

27✔
651
        c := db.client.
27✔
652
                Database(mstore.DbFromContext(ctx, DbName)).
27✔
653
                Collection(DbDevicesColl)
27✔
654

27✔
655
        update, err := makeAttrUpsert(updateAttrs)
27✔
656
        if err != nil {
28✔
657
                return nil, err
1✔
658
        }
1✔
659
        remove, err := makeAttrRemove(removeAttrs)
26✔
660
        if err != nil {
26✔
UNCOV
661
                return nil, err
×
662
        }
×
663
        filter := bson.M{"_id": id}
26✔
664
        if etag != "" {
31✔
665
                filter[etagField] = bson.M{"$eq": etag}
5✔
666
        }
5✔
667

668
        updateOpts := mopts.FindOneAndUpdate().
26✔
669
                SetUpsert(true).
26✔
670
                SetReturnDocument(mopts.After)
26✔
671
        if scope == model.AttrScopeTags {
38✔
672
                update[etagField] = uuid.New().String()
12✔
673
                updateOpts = updateOpts.SetUpsert(false)
12✔
674
        }
12✔
675
        now := time.Now()
26✔
676
        if scope != model.AttrScopeTags {
40✔
677
                update[updatedField] = model.DeviceAttribute{
14✔
678
                        Scope: model.AttrScopeSystem,
14✔
679
                        Name:  model.AttrNameUpdated,
14✔
680
                        Value: now,
14✔
681
                }
14✔
682
        }
14✔
683
        update = bson.M{
26✔
684
                "$set": update,
26✔
685
                "$setOnInsert": bson.M{
26✔
686
                        createdField: model.DeviceAttribute{
26✔
687
                                Scope: model.AttrScopeSystem,
26✔
688
                                Name:  model.AttrNameCreated,
26✔
689
                                Value: now,
26✔
690
                        },
26✔
691
                },
26✔
692
        }
26✔
693
        if len(remove) > 0 {
27✔
694
                update["$unset"] = remove
1✔
695
        }
1✔
696

697
        device := &model.Device{}
26✔
698
        res := c.FindOneAndUpdate(ctx, filter, update, updateOpts)
26✔
699
        err = res.Decode(device)
26✔
700
        if err == mongo.ErrNoDocuments {
28✔
701
                return &model.UpdateResult{
2✔
702
                        MatchedCount: 0,
2✔
703
                        CreatedCount: 0,
2✔
704
                        Devices:      []*model.Device{},
2✔
705
                }, nil
2✔
706
        } else if err == nil {
50✔
707
                return &model.UpdateResult{
24✔
708
                        MatchedCount: 1,
24✔
709
                        CreatedCount: 0,
24✔
710
                        Devices:      []*model.Device{device},
24✔
711
                }, nil
24✔
712
        }
24✔
UNCOV
713
        return nil, err
×
714
}
715

716
func (db *DataStoreMongo) UpdateDevicesGroup(
717
        ctx context.Context,
718
        devIDs []model.DeviceID,
719
        group model.GroupName,
720
) (*model.UpdateResult, error) {
61✔
721
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
61✔
722
        collDevs := database.Collection(DbDevicesColl)
61✔
723

61✔
724
        var filter = bson.M{}
61✔
725
        switch len(devIDs) {
61✔
726
        case 0:
3✔
727
                return &model.UpdateResult{}, nil
3✔
728
        case 1:
54✔
729
                filter[DbDevId] = devIDs[0]
54✔
730
        default:
4✔
731
                filter[DbDevId] = bson.M{"$in": devIDs}
4✔
732
        }
733
        update := bson.M{
58✔
734
                "$set": bson.M{
58✔
735
                        DbDevAttributesGroup: model.DeviceAttribute{
58✔
736
                                Scope: model.AttrScopeSystem,
58✔
737
                                Name:  DbDevGroup,
58✔
738
                                Value: group,
58✔
739
                        },
58✔
740
                },
58✔
741
        }
58✔
742
        res, err := collDevs.UpdateMany(ctx, filter, update)
58✔
743
        if err != nil {
58✔
UNCOV
744
                return nil, err
×
UNCOV
745
        }
×
746
        return &model.UpdateResult{
58✔
747
                MatchedCount: res.MatchedCount,
58✔
748
                UpdatedCount: res.ModifiedCount,
58✔
749
        }, nil
58✔
750
}
751

752
// UpdateDeviceText updates the device text field
753
func (db *DataStoreMongo) UpdateDeviceText(
754
        ctx context.Context,
755
        deviceID model.DeviceID,
756
        text string,
757
) error {
22✔
758
        filter := bson.M{
22✔
759
                DbDevId: deviceID.String(),
22✔
760
        }
22✔
761

22✔
762
        update := bson.M{
22✔
763
                "$set": bson.M{
22✔
764
                        DbDevAttributesText: text,
22✔
765
                },
22✔
766
        }
22✔
767

22✔
768
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
22✔
769
        collDevs := database.Collection(DbDevicesColl)
22✔
770

22✔
771
        _, err := collDevs.UpdateOne(ctx, filter, update)
22✔
772
        return err
22✔
773
}
22✔
774

775
func (db *DataStoreMongo) GetFiltersAttributes(
776
        ctx context.Context,
777
) ([]model.FilterAttribute, error) {
4✔
778
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
4✔
779
        collDevs := database.Collection(DbDevicesColl)
4✔
780

4✔
781
        const DbCount = "count"
4✔
782

4✔
783
        cur, err := collDevs.Aggregate(ctx, []bson.M{
4✔
784
                {
4✔
785
                        "$project": bson.M{
4✔
786
                                "attributes": bson.M{
4✔
787
                                        "$objectToArray": "$" + DbDevAttributes,
4✔
788
                                },
4✔
789
                        },
4✔
790
                },
4✔
791
                {
4✔
792
                        "$unwind": "$" + DbDevAttributes,
4✔
793
                },
4✔
794
                {
4✔
795
                        "$project": bson.M{
4✔
796
                                DbDevAttributesName:  "$" + DbDevAttributes + ".v." + DbDevAttributesName,
4✔
797
                                DbDevAttributesScope: "$" + DbDevAttributes + ".v." + DbDevAttributesScope,
4✔
798
                        },
4✔
799
                },
4✔
800
                {
4✔
801
                        "$group": bson.M{
4✔
802
                                DbDevId: bson.M{
4✔
803
                                        DbDevAttributesName:  "$" + DbDevAttributesName,
4✔
804
                                        DbDevAttributesScope: "$" + DbDevAttributesScope,
4✔
805
                                },
4✔
806
                                DbCount: bson.M{
4✔
807
                                        "$sum": 1,
4✔
808
                                },
4✔
809
                        },
4✔
810
                },
4✔
811
                {
4✔
812
                        "$project": bson.M{
4✔
813
                                DbDevId:              0,
4✔
814
                                DbDevAttributesName:  "$" + DbDevId + "." + DbDevAttributesName,
4✔
815
                                DbDevAttributesScope: "$" + DbDevId + "." + DbDevAttributesScope,
4✔
816
                                DbCount:              "$" + DbCount,
4✔
817
                        },
4✔
818
                },
4✔
819
                {
4✔
820
                        "$sort": bson.D{
4✔
821
                                {Key: DbCount, Value: -1},
4✔
822
                                {Key: DbDevAttributesScope, Value: 1},
4✔
823
                                {Key: DbDevAttributesName, Value: 1},
4✔
824
                        },
4✔
825
                },
4✔
826
                {
4✔
827
                        "$limit": FiltersAttributesLimit,
4✔
828
                },
4✔
829
        })
4✔
830
        if err != nil {
4✔
UNCOV
831
                return nil, err
×
UNCOV
832
        }
×
833
        defer cur.Close(ctx)
4✔
834

4✔
835
        var attributes []model.FilterAttribute
4✔
836
        err = cur.All(ctx, &attributes)
4✔
837
        if err != nil {
4✔
UNCOV
838
                return nil, err
×
UNCOV
839
        }
×
840

841
        return attributes, nil
4✔
842
}
843

844
func (db *DataStoreMongo) DeleteGroup(
845
        ctx context.Context,
846
        group model.GroupName,
847
) (chan model.DeviceID, error) {
1✔
848
        deviceIDs := make(chan model.DeviceID)
1✔
849

1✔
850
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
1✔
851
        collDevs := database.Collection(DbDevicesColl)
1✔
852

1✔
853
        filter := bson.M{DbDevAttributesGroupValue: group}
1✔
854

1✔
855
        const batchMaxSize = 100
1✔
856
        batchSize := int32(batchMaxSize)
1✔
857
        findOptions := &mopts.FindOptions{
1✔
858
                Projection: bson.M{DbDevId: 1},
1✔
859
                BatchSize:  &batchSize,
1✔
860
        }
1✔
861
        cursor, err := collDevs.Find(ctx, filter, findOptions)
1✔
862
        if err != nil {
1✔
UNCOV
863
                return nil, err
×
UNCOV
864
        }
×
865

866
        go func() {
2✔
867
                defer cursor.Close(ctx)
1✔
868
                batch := make([]model.DeviceID, batchMaxSize)
1✔
869
                batchSize := 0
1✔
870

1✔
871
                update := bson.M{"$unset": bson.M{DbDevAttributesGroup: 1}}
1✔
872
                device := &model.Device{}
1✔
873
                defer close(deviceIDs)
1✔
874

1✔
875
        next:
1✔
876
                for {
5✔
877
                        hasNext := cursor.Next(ctx)
4✔
878
                        if !hasNext {
6✔
879
                                if batchSize > 0 {
3✔
880
                                        break
1✔
881
                                }
882
                                return
1✔
883
                        }
884
                        if err = cursor.Decode(&device); err == nil {
4✔
885
                                batch[batchSize] = device.ID
2✔
886
                                batchSize++
2✔
887
                                if len(batch) == batchSize {
2✔
UNCOV
888
                                        break
×
889
                                }
890
                        }
891
                }
892

893
                _, _ = collDevs.UpdateMany(ctx, bson.M{DbDevId: bson.M{"$in": batch[:batchSize]}}, update)
1✔
894
                for _, item := range batch[:batchSize] {
3✔
895
                        deviceIDs <- item
2✔
896
                }
2✔
897
                batchSize = 0
1✔
898
                goto next
1✔
899
        }()
900

901
        return deviceIDs, nil
1✔
902
}
903

904
func (db *DataStoreMongo) UnsetDevicesGroup(
905
        ctx context.Context,
906
        deviceIDs []model.DeviceID,
907
        group model.GroupName,
908
) (*model.UpdateResult, error) {
14✔
909
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
14✔
910
        collDevs := database.Collection(DbDevicesColl)
14✔
911

14✔
912
        var filter bson.D
14✔
913
        // Add filter on device id (either $in or direct indexing)
14✔
914
        switch len(deviceIDs) {
14✔
915
        case 0:
1✔
916
                return &model.UpdateResult{}, nil
1✔
917
        case 1:
10✔
918
                filter = bson.D{{Key: DbDevId, Value: deviceIDs[0]}}
10✔
919
        default:
3✔
920
                filter = bson.D{{Key: DbDevId, Value: bson.M{"$in": deviceIDs}}}
3✔
921
        }
922
        // Append filter on group
923
        filter = append(
13✔
924
                filter,
13✔
925
                bson.E{Key: DbDevAttributesGroupValue, Value: group},
13✔
926
        )
13✔
927
        // Create unset operation on group attribute
13✔
928
        update := bson.M{
13✔
929
                "$unset": bson.M{
13✔
930
                        DbDevAttributesGroup: "",
13✔
931
                },
13✔
932
        }
13✔
933
        res, err := collDevs.UpdateMany(ctx, filter, update)
13✔
934
        if err != nil {
13✔
935
                return nil, err
×
UNCOV
936
        }
×
937
        return &model.UpdateResult{
13✔
938
                MatchedCount: res.MatchedCount,
13✔
939
                UpdatedCount: res.ModifiedCount,
13✔
940
        }, nil
13✔
941
}
942

943
func predicateToQuery(pred model.FilterPredicate) (bson.D, error) {
2✔
944
        if err := pred.Validate(); err != nil {
3✔
945
                return nil, err
1✔
946
        }
1✔
947
        name := fmt.Sprintf(
1✔
948
                "%s.%s-%s.value",
1✔
949
                DbDevAttributes,
1✔
950
                pred.Scope,
1✔
951
                model.GetDeviceAttributeNameReplacer().Replace(pred.Attribute),
1✔
952
        )
1✔
953
        return bson.D{{
1✔
954
                Key: name, Value: bson.D{{Key: pred.Type, Value: pred.Value}},
1✔
955
        }}, nil
1✔
956
}
957

958
func (db *DataStoreMongo) ListGroups(
959
        ctx context.Context,
960
        filters []model.FilterPredicate,
961
) ([]model.GroupName, error) {
12✔
962
        c := db.client.
12✔
963
                Database(mstore.DbFromContext(ctx, DbName)).
12✔
964
                Collection(DbDevicesColl)
12✔
965

12✔
966
        fltr := bson.D{{
12✔
967
                Key: DbDevAttributesGroupValue, Value: bson.M{"$exists": true},
12✔
968
        }}
12✔
969
        if len(fltr) > 0 {
24✔
970
                for _, p := range filters {
14✔
971
                        q, err := predicateToQuery(p)
2✔
972
                        if err != nil {
3✔
973
                                return nil, errors.Wrap(
1✔
974
                                        err, "store: bad filter predicate",
1✔
975
                                )
1✔
976
                        }
1✔
977
                        fltr = append(fltr, q...)
1✔
978
                }
979
        }
980
        results, err := c.Distinct(
11✔
981
                ctx, DbDevAttributesGroupValue, fltr,
11✔
982
        )
11✔
983
        if err != nil {
11✔
UNCOV
984
                return nil, err
×
UNCOV
985
        }
×
986

987
        groups := make([]model.GroupName, len(results))
11✔
988
        for i, d := range results {
47✔
989
                groups[i] = model.GroupName(d.(string))
36✔
990
        }
36✔
991
        return groups, nil
11✔
992
}
993

994
func (db *DataStoreMongo) GetDevicesByGroup(
995
        ctx context.Context,
996
        group model.GroupName,
997
        skip,
998
        limit int,
999
) ([]model.DeviceID, int, error) {
37✔
1000
        c := db.client.
37✔
1001
                Database(mstore.DbFromContext(ctx, DbName)).
37✔
1002
                Collection(DbDevicesColl)
37✔
1003

37✔
1004
        filter := bson.M{DbDevAttributesGroupValue: group}
37✔
1005
        result := c.FindOne(ctx, filter)
37✔
1006
        if result == nil {
37✔
UNCOV
1007
                return nil, -1, store.ErrGroupNotFound
×
UNCOV
1008
        }
×
1009

1010
        var dev model.Device
37✔
1011
        err := result.Decode(&dev)
37✔
1012
        if err != nil {
43✔
1013
                return nil, -1, store.ErrGroupNotFound
6✔
1014
        }
6✔
1015

1016
        hasGroup := group != ""
31✔
1017
        devices, totalDevices, e := db.GetDevices(ctx,
31✔
1018
                store.ListQuery{
31✔
1019
                        Skip:      skip,
31✔
1020
                        Limit:     limit,
31✔
1021
                        Filters:   nil,
31✔
1022
                        Sort:      nil,
31✔
1023
                        HasGroup:  &hasGroup,
31✔
1024
                        GroupName: string(group)})
31✔
1025
        if e != nil {
31✔
UNCOV
1026
                return nil, -1, errors.Wrap(e, "failed to get device list for group")
×
UNCOV
1027
        }
×
1028

1029
        resIds := make([]model.DeviceID, len(devices))
31✔
1030
        for i, d := range devices {
84✔
1031
                resIds[i] = d.ID
53✔
1032
        }
53✔
1033
        return resIds, totalDevices, nil
31✔
1034
}
1035

1036
func (db *DataStoreMongo) GetDeviceGroup(
1037
        ctx context.Context,
1038
        id model.DeviceID,
1039
) (model.GroupName, error) {
6✔
1040
        dev, err := db.GetDevice(ctx, id)
6✔
1041
        if err != nil || dev == nil {
8✔
1042
                return "", store.ErrDevNotFound
2✔
1043
        }
2✔
1044

1045
        return dev.Group, nil
4✔
1046
}
1047

1048
func (db *DataStoreMongo) DeleteDevices(
1049
        ctx context.Context, ids []model.DeviceID,
1050
) (*model.UpdateResult, error) {
3✔
1051
        var filter = bson.M{}
3✔
1052
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
3✔
1053
        collDevs := database.Collection(DbDevicesColl)
3✔
1054

3✔
1055
        switch len(ids) {
3✔
UNCOV
1056
        case 0:
×
UNCOV
1057
                // This is a no-op, don't bother requesting mongo.
×
UNCOV
1058
                return &model.UpdateResult{DeletedCount: 0}, nil
×
1059
        case 1:
2✔
1060
                filter[DbDevId] = ids[0]
2✔
1061
        default:
1✔
1062
                filter[DbDevId] = bson.M{"$in": ids}
1✔
1063
        }
1064
        res, err := collDevs.DeleteMany(ctx, filter)
3✔
1065
        if err != nil {
3✔
UNCOV
1066
                return nil, err
×
UNCOV
1067
        }
×
1068
        return &model.UpdateResult{
3✔
1069
                DeletedCount: res.DeletedCount,
3✔
1070
        }, nil
3✔
1071
}
1072

1073
func (db *DataStoreMongo) GetAllAttributeNames(ctx context.Context) ([]string, error) {
31✔
1074
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
31✔
1075

31✔
1076
        project := bson.M{
31✔
1077
                "$project": bson.M{
31✔
1078
                        "arrayofkeyvalue": bson.M{
31✔
1079
                                "$objectToArray": "$$ROOT.attributes",
31✔
1080
                        },
31✔
1081
                },
31✔
1082
        }
31✔
1083

31✔
1084
        unwind := bson.M{
31✔
1085
                "$unwind": "$arrayofkeyvalue",
31✔
1086
        }
31✔
1087

31✔
1088
        group := bson.M{
31✔
1089
                "$group": bson.M{
31✔
1090
                        "_id": nil,
31✔
1091
                        "allkeys": bson.M{
31✔
1092
                                "$addToSet": "$arrayofkeyvalue.v.name",
31✔
1093
                        },
31✔
1094
                },
31✔
1095
        }
31✔
1096

31✔
1097
        l := log.FromContext(ctx)
31✔
1098
        cursor, err := c.Aggregate(ctx, []bson.M{
31✔
1099
                project,
31✔
1100
                unwind,
31✔
1101
                group,
31✔
1102
        })
31✔
1103
        if err != nil {
31✔
1104
                return nil, err
×
1105
        }
×
1106
        defer cursor.Close(ctx)
31✔
1107

31✔
1108
        cursor.Next(ctx)
31✔
1109
        elem := &bson.D{}
31✔
1110
        err = cursor.Decode(elem)
31✔
1111
        if err != nil {
45✔
1112
                if err != io.EOF {
14✔
1113
                        return nil, errors.Wrap(err, "failed to get attributes")
×
1114
                } else {
14✔
1115
                        return make([]string, 0), nil
14✔
1116
                }
14✔
1117
        }
1118
        m := elem.Map()
17✔
1119
        results := m["allkeys"].(primitive.A)
17✔
1120
        attributeNames := make([]string, len(results))
17✔
1121
        for i, d := range results {
76✔
1122
                attributeNames[i] = d.(string)
59✔
1123
                l.Debugf("GetAllAttributeNames got: '%v'", d)
59✔
1124
        }
59✔
1125

1126
        return attributeNames, nil
17✔
1127
}
1128

1129
func (db *DataStoreMongo) SearchDevices(
1130
        ctx context.Context,
1131
        searchParams model.SearchParams,
1132
) ([]model.Device, int, error) {
15✔
1133
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
15✔
1134

15✔
1135
        queryFilters := make([]bson.M, 0)
15✔
1136
        for _, filter := range searchParams.Filters {
29✔
1137
                op := filter.Type
14✔
1138
                var field string
14✔
1139
                if filter.Scope == model.AttrScopeIdentity && filter.Attribute == model.AttrNameID {
16✔
1140
                        field = DbDevId
2✔
1141
                } else {
14✔
1142
                        name := fmt.Sprintf(
12✔
1143
                                "%s-%s",
12✔
1144
                                filter.Scope,
12✔
1145
                                model.GetDeviceAttributeNameReplacer().Replace(filter.Attribute),
12✔
1146
                        )
12✔
1147
                        field = fmt.Sprintf("%s.%s.%s", DbDevAttributes, name, DbDevAttributesValue)
12✔
1148
                }
12✔
1149
                queryFilters = append(queryFilters, bson.M{field: bson.M{op: filter.Value}})
14✔
1150
        }
1151

1152
        // FIXME: remove after migrating ids to attributes
1153
        if len(searchParams.DeviceIDs) > 0 {
16✔
1154
                queryFilters = append(queryFilters, bson.M{"_id": bson.M{"$in": searchParams.DeviceIDs}})
1✔
1155
        }
1✔
1156

1157
        if searchParams.Text != "" {
16✔
1158
                queryFilters = append(queryFilters, bson.M{
1✔
1159
                        "$text": bson.M{
1✔
1160
                                "$search": utils.TextToKeywords(searchParams.Text),
1✔
1161
                        },
1✔
1162
                })
1✔
1163
        }
1✔
1164

1165
        findQuery := bson.M{}
15✔
1166
        if len(queryFilters) > 0 {
28✔
1167
                findQuery["$and"] = queryFilters
13✔
1168
        }
13✔
1169

1170
        findOptions := mopts.Find()
15✔
1171
        findOptions.SetSkip(int64((searchParams.Page - 1) * searchParams.PerPage))
15✔
1172
        findOptions.SetLimit(int64(searchParams.PerPage))
15✔
1173

15✔
1174
        if len(searchParams.Attributes) > 0 {
17✔
1175
                name := fmt.Sprintf(
2✔
1176
                        "%s-%s",
2✔
1177
                        model.AttrScopeSystem,
2✔
1178
                        model.GetDeviceAttributeNameReplacer().Replace(DbDevUpdatedTs),
2✔
1179
                )
2✔
1180
                field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
2✔
1181
                projection := bson.M{field: 1}
2✔
1182
                for _, attribute := range searchParams.Attributes {
5✔
1183
                        name := fmt.Sprintf(
3✔
1184
                                "%s-%s",
3✔
1185
                                attribute.Scope,
3✔
1186
                                model.GetDeviceAttributeNameReplacer().Replace(attribute.Attribute),
3✔
1187
                        )
3✔
1188
                        field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
3✔
1189
                        projection[field] = 1
3✔
1190
                }
3✔
1191
                findOptions.SetProjection(projection)
2✔
1192
        }
1193

1194
        if searchParams.Text != "" {
16✔
1195
                findOptions.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
1✔
1196
        } else if len(searchParams.Sort) > 0 {
19✔
1197
                sortField := make(bson.D, len(searchParams.Sort))
4✔
1198
                for i, sortQ := range searchParams.Sort {
9✔
1199
                        var field string
5✔
1200
                        if sortQ.Scope == model.AttrScopeIdentity && sortQ.Attribute == model.AttrNameID {
6✔
1201
                                field = DbDevId
1✔
1202
                        } else {
5✔
1203
                                name := fmt.Sprintf(
4✔
1204
                                        "%s-%s",
4✔
1205
                                        sortQ.Scope,
4✔
1206
                                        model.GetDeviceAttributeNameReplacer().Replace(sortQ.Attribute),
4✔
1207
                                )
4✔
1208
                                field = fmt.Sprintf("%s.%s", DbDevAttributes, name)
4✔
1209
                        }
4✔
1210
                        sortField[i] = bson.E{Key: field, Value: 1}
5✔
1211
                        if sortQ.Order == "desc" {
8✔
1212
                                sortField[i].Value = -1
3✔
1213
                        }
3✔
1214
                }
1215
                findOptions.SetSort(sortField)
4✔
1216
        }
1217

1218
        cursor, err := c.Find(ctx, findQuery, findOptions)
15✔
1219
        if err != nil {
16✔
1220
                return nil, -1, errors.Wrap(err, "failed to search devices")
1✔
1221
        }
1✔
1222
        defer cursor.Close(ctx)
14✔
1223

14✔
1224
        devices := []model.Device{}
14✔
1225

14✔
1226
        if err = cursor.All(ctx, &devices); err != nil {
14✔
UNCOV
1227
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
UNCOV
1228
        }
×
1229

1230
        count, err := c.CountDocuments(ctx, findQuery)
14✔
1231
        if err != nil {
14✔
UNCOV
1232
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
UNCOV
1233
        }
×
1234

1235
        return devices, int(count), nil
14✔
1236
}
1237

1238
func indexAttr(s *mongo.Client, ctx context.Context, attr string) error {
68✔
1239
        l := log.FromContext(ctx)
68✔
1240
        c := s.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
68✔
1241

68✔
1242
        indexView := c.Indexes()
68✔
1243
        keys := bson.D{
68✔
1244
                {Key: indexAttrName(attrIdentityStatus), Value: 1},
68✔
1245
                {Key: indexAttrName(attr), Value: 1},
68✔
1246
        }
68✔
1247
        _, err := indexView.CreateOne(ctx, mongo.IndexModel{Keys: keys, Options: &mopts.IndexOptions{
68✔
1248
                Name: &attr,
68✔
1249
        }})
68✔
1250

68✔
1251
        if err != nil {
68✔
UNCOV
1252
                if isTooManyIndexes(err) {
×
UNCOV
1253
                        l.Warnf(
×
UNCOV
1254
                                "failed to index attr %s in db %s: too many indexes",
×
UNCOV
1255
                                attr,
×
UNCOV
1256
                                mstore.DbFromContext(ctx, DbName),
×
UNCOV
1257
                        )
×
UNCOV
1258
                } else {
×
UNCOV
1259
                        return errors.Wrapf(
×
UNCOV
1260
                                err,
×
UNCOV
1261
                                "failed to index attr %s in db %s",
×
UNCOV
1262
                                attr,
×
UNCOV
1263
                                mstore.DbFromContext(ctx, DbName),
×
UNCOV
1264
                        )
×
UNCOV
1265
                }
×
1266
        }
1267

1268
        return nil
68✔
1269
}
1270

1271
func indexAttrName(attr string) string {
152✔
1272
        return fmt.Sprintf("attributes.%s.value", attr)
152✔
1273
}
152✔
1274

1275
func isTooManyIndexes(e error) bool {
×
UNCOV
1276
        return strings.HasPrefix(e.Error(), "add index fails, too many indexes for inventory.devices")
×
UNCOV
1277
}
×
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