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

mendersoftware / inventory / 955593424

pending completion
955593424

Pull #401

gitlab-ci

merlin-northern
fix: attributes udpate: be mindful of the subset of attributes being patched.

Changelog: Title
Ticket: MEN-6643
Signed-off-by: Peter Grzybowski <peter@northern.tech>
Pull Request #401: fix: attributes udpate: be mindful of the subset of attributes being …

15 of 38 new or added lines in 3 files covered. (39.47%)

21 existing lines in 2 files now uncovered.

3200 of 3562 relevant lines covered (89.84%)

135.41 hits per line

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

88.38
/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) {
36✔
265
        var res model.Device
36✔
266
        c := db.client.
36✔
267
                Database(mstore.DbFromContext(ctx, DbName)).
36✔
268
                Collection(DbDevicesColl)
36✔
269
        l := log.FromContext(ctx)
36✔
270

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

286
func (db *DataStoreMongo) GetDevicesById(
287
        ctx context.Context,
288
        id []model.DeviceID,
UNCOV
289
) ([]model.Device, error) {
×
UNCOV
290
        var res []model.Device
×
UNCOV
291
        c := db.client.
×
UNCOV
292
                Database(mstore.DbFromContext(ctx, DbName)).
×
UNCOV
293
                Collection(DbDevicesColl)
×
UNCOV
294
        l := log.FromContext(ctx)
×
UNCOV
295

×
UNCOV
296
        if len(id) < 1 {
×
UNCOV
297
                return nil, nil
×
UNCOV
298
        }
×
UNCOV
299
        r, err := c.Find(ctx, bson.M{DbDevId: bson.M{"$in": id}})
×
UNCOV
300
        if err != nil {
×
301
                switch err {
×
302
                case mongo.ErrNoDocuments:
×
303
                        return nil, nil
×
304
                default:
×
305
                        l.Errorf("GetDevicesById Find: %v", err)
×
306
                        return nil, errors.Wrap(err, "failed to fetch devices")
×
307
                }
308
        }
UNCOV
309
        err = r.All(ctx, &res)
×
UNCOV
310
        if err != nil {
×
311
                l.Errorf("GetDevicesById deocde: %v", err)
×
312
                return nil, errors.Wrap(err, "failed to decode devices")
×
313
        }
×
UNCOV
314
        return res, nil
×
315
}
316

317
// AddDevice inserts a new device, initializing the inventory data.
318
func (db *DataStoreMongo) AddDevice(ctx context.Context, dev *model.Device) error {
256✔
319
        if dev.Group != "" {
296✔
320
                dev.Attributes = append(dev.Attributes, model.DeviceAttribute{
40✔
321
                        Scope: model.AttrScopeSystem,
40✔
322
                        Name:  model.AttrNameGroup,
40✔
323
                        Value: dev.Group,
40✔
324
                })
40✔
325
        }
40✔
326
        _, err := db.UpsertDevicesAttributesWithUpdated(
256✔
327
                ctx, []model.DeviceID{dev.ID}, dev.Attributes, "", "", 0,
256✔
328
        )
256✔
329
        if err != nil {
256✔
330
                return errors.Wrap(err, "failed to store device")
×
331
        }
×
332
        return nil
256✔
333
}
334

335
func (db *DataStoreMongo) UpsertDevicesAttributesWithRevision(
336
        ctx context.Context,
337
        devices []model.DeviceUpdate,
338
        attrs model.DeviceAttributes,
339
) (*model.UpdateResult, error) {
3✔
340
        return db.upsertAttributes(ctx, devices, attrs, false, true, "", "")
3✔
341
}
3✔
342

343
func (db *DataStoreMongo) UpsertDevicesAttributesWithUpdated(
344
        ctx context.Context,
345
        ids []model.DeviceID,
346
        attrs model.DeviceAttributes,
347
        scope string,
348
        etag string,
349
        lastUpdateDurationThreshold time.Duration,
350
) (*model.UpdateResult, error) {
277✔
351
        if len(ids) < 1 {
278✔
352
                return nil, nil
1✔
353
        }
1✔
354
        return db.upsertAttributes(ctx, makeDevsWithIds(ids), attrs, true, false, scope, etag)
276✔
355
}
356

357
func (db *DataStoreMongo) UpsertDevicesAttributes(
358
        ctx context.Context,
359
        ids []model.DeviceID,
360
        attrs model.DeviceAttributes,
361
) (*model.UpdateResult, error) {
16✔
362
        return db.upsertAttributes(ctx, makeDevsWithIds(ids), attrs, false, false, "", "")
16✔
363
}
16✔
364

365
func makeDevsWithIds(ids []model.DeviceID) []model.DeviceUpdate {
292✔
366
        devices := make([]model.DeviceUpdate, len(ids))
292✔
367
        for i, id := range ids {
591✔
368
                devices[i].Id = id
299✔
369
        }
299✔
370
        return devices
292✔
371
}
372

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

295✔
391
        c := db.client.
295✔
392
                Database(mstore.DbFromContext(ctx, DbName)).
295✔
393
                Collection(DbDevicesColl)
295✔
394

295✔
395
        update, err := makeAttrUpsert(attrs)
295✔
396
        if err != nil {
297✔
397
                return nil, err
2✔
398
        }
2✔
399

400
        now := time.Now()
293✔
401
        oninsert := bson.M{
293✔
402
                createdField: model.DeviceAttribute{
293✔
403
                        Scope: model.AttrScopeSystem,
293✔
404
                        Name:  model.AttrNameCreated,
293✔
405
                        Value: now,
293✔
406
                },
293✔
407
        }
293✔
408
        if !withRevision {
583✔
409
                oninsert["revision"] = 0
290✔
410
        }
290✔
411

412
        const updatedField = systemScope + "-" + model.AttrNameUpdated
293✔
413
        if withUpdated {
568✔
414
                update[updatedField] = model.DeviceAttribute{
275✔
415
                        Scope: model.AttrScopeSystem,
275✔
416
                        Name:  model.AttrNameUpdated,
275✔
417
                        Value: now,
275✔
418
                }
275✔
419
        } else {
293✔
420
                oninsert[updatedField] = model.DeviceAttribute{
18✔
421
                        Scope: model.AttrScopeSystem,
18✔
422
                        Name:  model.AttrNameUpdated,
18✔
423
                        Value: now,
18✔
424
                }
18✔
425
        }
18✔
426

427
        switch len(devices) {
293✔
428
        case 0:
1✔
429
                return &model.UpdateResult{}, nil
1✔
430
        case 1:
289✔
431
                filter := bson.M{
289✔
432
                        "_id": devices[0].Id,
289✔
433
                }
289✔
434
                updateOpts := mopts.FindOneAndUpdate().
289✔
435
                        SetUpsert(true).
289✔
436
                        SetReturnDocument(mopts.After)
289✔
437

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

452
                update = bson.M{
289✔
453
                        "$set":         update,
289✔
454
                        "$setOnInsert": oninsert,
289✔
455
                }
289✔
456

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

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

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

541
// makeAttrUpsert creates a new upsert document for the given attributes.
542
func makeAttrUpsert(attrs model.DeviceAttributes) (bson.M, error) {
322✔
543
        var fieldName string
322✔
544
        upsert := make(bson.M)
322✔
545

322✔
546
        for i := range attrs {
1,753✔
547
                if attrs[i].Name == "" {
1,434✔
548
                        return nil, store.ErrNoAttrName
3✔
549
                }
3✔
550
                if attrs[i].Scope == "" {
1,434✔
551
                        // Default to inventory scope
6✔
552
                        attrs[i].Scope = model.AttrScopeInventory
6✔
553
                }
6✔
554

555
                fieldName = makeAttrField(
1,428✔
556
                        attrs[i].Name,
1,428✔
557
                        attrs[i].Scope,
1,428✔
558
                        DbDevAttributesScope,
1,428✔
559
                )
1,428✔
560
                upsert[fieldName] = attrs[i].Scope
1,428✔
561

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

1,428✔
569
                if attrs[i].Value != nil {
2,851✔
570
                        fieldName = makeAttrField(
1,423✔
571
                                attrs[i].Name,
1,423✔
572
                                attrs[i].Scope,
1,423✔
573
                                DbDevAttributesValue,
1,423✔
574
                        )
1,423✔
575
                        upsert[fieldName] = attrs[i].Value
1,423✔
576
                }
1,423✔
577

578
                if attrs[i].Description != nil {
1,884✔
579
                        fieldName = makeAttrField(
456✔
580
                                attrs[i].Name,
456✔
581
                                attrs[i].Scope,
456✔
582
                                DbDevAttributesDesc,
456✔
583
                        )
456✔
584
                        upsert[fieldName] = attrs[i].Description
456✔
585
                }
456✔
586

587
                if attrs[i].Timestamp != nil {
1,440✔
588
                        fieldName = makeAttrField(
12✔
589
                                attrs[i].Name,
12✔
590
                                attrs[i].Scope,
12✔
591
                                DbDevAttributesTs,
12✔
592
                        )
12✔
593
                        upsert[fieldName] = attrs[i].Timestamp
12✔
594
                }
12✔
595
        }
596
        return upsert, nil
319✔
597
}
598

599
// makeAttrRemove creates a new unset document to remove attributes
600
func makeAttrRemove(attrs model.DeviceAttributes) (bson.M, error) {
26✔
601
        var fieldName string
26✔
602
        remove := make(bson.M)
26✔
603

26✔
604
        for i := range attrs {
27✔
605
                if attrs[i].Name == "" {
1✔
606
                        return nil, store.ErrNoAttrName
×
607
                }
×
608
                if attrs[i].Scope == "" {
1✔
609
                        // Default to inventory scope
×
610
                        attrs[i].Scope = model.AttrScopeInventory
×
611
                }
×
612
                fieldName = makeAttrField(
1✔
613
                        attrs[i].Name,
1✔
614
                        attrs[i].Scope,
1✔
615
                )
1✔
616
                remove[fieldName] = true
1✔
617
        }
618
        return remove, nil
26✔
619
}
620

621
func mongoOperator(co store.ComparisonOperator) string {
7✔
622
        switch co {
7✔
623
        case store.Eq:
7✔
624
                return "$eq"
7✔
625
        }
626
        return ""
×
627
}
628

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

27✔
645
        c := db.client.
27✔
646
                Database(mstore.DbFromContext(ctx, DbName)).
27✔
647
                Collection(DbDevicesColl)
27✔
648

27✔
649
        update, err := makeAttrUpsert(updateAttrs)
27✔
650
        if err != nil {
28✔
651
                return nil, err
1✔
652
        }
1✔
653
        remove, err := makeAttrRemove(removeAttrs)
26✔
654
        if err != nil {
26✔
655
                return nil, err
×
656
        }
×
657
        filter := bson.M{"_id": id}
26✔
658
        if etag != "" {
31✔
659
                filter[etagField] = bson.M{"$eq": etag}
5✔
660
        }
5✔
661

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

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

710
func (db *DataStoreMongo) UpdateDevicesGroup(
711
        ctx context.Context,
712
        devIDs []model.DeviceID,
713
        group model.GroupName,
714
) (*model.UpdateResult, error) {
61✔
715
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
61✔
716
        collDevs := database.Collection(DbDevicesColl)
61✔
717

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

746
// UpdateDeviceText updates the device text field
747
func (db *DataStoreMongo) UpdateDeviceText(
748
        ctx context.Context,
749
        deviceID model.DeviceID,
750
        text string,
751
) error {
22✔
752
        filter := bson.M{
22✔
753
                DbDevId: deviceID.String(),
22✔
754
        }
22✔
755

22✔
756
        update := bson.M{
22✔
757
                "$set": bson.M{
22✔
758
                        DbDevAttributesText: text,
22✔
759
                },
22✔
760
        }
22✔
761

22✔
762
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
22✔
763
        collDevs := database.Collection(DbDevicesColl)
22✔
764

22✔
765
        _, err := collDevs.UpdateOne(ctx, filter, update)
22✔
766
        return err
22✔
767
}
22✔
768

769
func (db *DataStoreMongo) GetFiltersAttributes(
770
        ctx context.Context,
771
) ([]model.FilterAttribute, error) {
4✔
772
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
4✔
773
        collDevs := database.Collection(DbDevicesColl)
4✔
774

4✔
775
        const DbCount = "count"
4✔
776

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

4✔
829
        var attributes []model.FilterAttribute
4✔
830
        err = cur.All(ctx, &attributes)
4✔
831
        if err != nil {
4✔
832
                return nil, err
×
833
        }
×
834

835
        return attributes, nil
4✔
836
}
837

838
func (db *DataStoreMongo) DeleteGroup(
839
        ctx context.Context,
840
        group model.GroupName,
841
) (chan model.DeviceID, error) {
1✔
842
        deviceIDs := make(chan model.DeviceID)
1✔
843

1✔
844
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
1✔
845
        collDevs := database.Collection(DbDevicesColl)
1✔
846

1✔
847
        filter := bson.M{DbDevAttributesGroupValue: group}
1✔
848

1✔
849
        const batchMaxSize = 100
1✔
850
        batchSize := int32(batchMaxSize)
1✔
851
        findOptions := &mopts.FindOptions{
1✔
852
                Projection: bson.M{DbDevId: 1},
1✔
853
                BatchSize:  &batchSize,
1✔
854
        }
1✔
855
        cursor, err := collDevs.Find(ctx, filter, findOptions)
1✔
856
        if err != nil {
1✔
857
                return nil, err
×
858
        }
×
859

860
        go func() {
2✔
861
                defer cursor.Close(ctx)
1✔
862
                batch := make([]model.DeviceID, batchMaxSize)
1✔
863
                batchSize := 0
1✔
864

1✔
865
                update := bson.M{"$unset": bson.M{DbDevAttributesGroup: 1}}
1✔
866
                device := &model.Device{}
1✔
867
                defer close(deviceIDs)
1✔
868

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

887
                _, _ = collDevs.UpdateMany(ctx, bson.M{DbDevId: bson.M{"$in": batch[:batchSize]}}, update)
1✔
888
                for _, item := range batch[:batchSize] {
3✔
889
                        deviceIDs <- item
2✔
890
                }
2✔
891
                batchSize = 0
1✔
892
                goto next
1✔
893
        }()
894

895
        return deviceIDs, nil
1✔
896
}
897

898
func (db *DataStoreMongo) UnsetDevicesGroup(
899
        ctx context.Context,
900
        deviceIDs []model.DeviceID,
901
        group model.GroupName,
902
) (*model.UpdateResult, error) {
14✔
903
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
14✔
904
        collDevs := database.Collection(DbDevicesColl)
14✔
905

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

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

952
func (db *DataStoreMongo) ListGroups(
953
        ctx context.Context,
954
        filters []model.FilterPredicate,
955
) ([]model.GroupName, error) {
12✔
956
        c := db.client.
12✔
957
                Database(mstore.DbFromContext(ctx, DbName)).
12✔
958
                Collection(DbDevicesColl)
12✔
959

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

981
        groups := make([]model.GroupName, len(results))
11✔
982
        for i, d := range results {
47✔
983
                groups[i] = model.GroupName(d.(string))
36✔
984
        }
36✔
985
        return groups, nil
11✔
986
}
987

988
func (db *DataStoreMongo) GetDevicesByGroup(
989
        ctx context.Context,
990
        group model.GroupName,
991
        skip,
992
        limit int,
993
) ([]model.DeviceID, int, error) {
37✔
994
        c := db.client.
37✔
995
                Database(mstore.DbFromContext(ctx, DbName)).
37✔
996
                Collection(DbDevicesColl)
37✔
997

37✔
998
        filter := bson.M{DbDevAttributesGroupValue: group}
37✔
999
        result := c.FindOne(ctx, filter)
37✔
1000
        if result == nil {
37✔
1001
                return nil, -1, store.ErrGroupNotFound
×
1002
        }
×
1003

1004
        var dev model.Device
37✔
1005
        err := result.Decode(&dev)
37✔
1006
        if err != nil {
43✔
1007
                return nil, -1, store.ErrGroupNotFound
6✔
1008
        }
6✔
1009

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

1023
        resIds := make([]model.DeviceID, len(devices))
31✔
1024
        for i, d := range devices {
84✔
1025
                resIds[i] = d.ID
53✔
1026
        }
53✔
1027
        return resIds, totalDevices, nil
31✔
1028
}
1029

1030
func (db *DataStoreMongo) GetDeviceGroup(
1031
        ctx context.Context,
1032
        id model.DeviceID,
1033
) (model.GroupName, error) {
6✔
1034
        dev, err := db.GetDevice(ctx, id)
6✔
1035
        if err != nil || dev == nil {
8✔
1036
                return "", store.ErrDevNotFound
2✔
1037
        }
2✔
1038

1039
        return dev.Group, nil
4✔
1040
}
1041

1042
func (db *DataStoreMongo) DeleteDevices(
1043
        ctx context.Context, ids []model.DeviceID,
1044
) (*model.UpdateResult, error) {
3✔
1045
        var filter = bson.M{}
3✔
1046
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
3✔
1047
        collDevs := database.Collection(DbDevicesColl)
3✔
1048

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

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

31✔
1070
        project := bson.M{
31✔
1071
                "$project": bson.M{
31✔
1072
                        "arrayofkeyvalue": bson.M{
31✔
1073
                                "$objectToArray": "$$ROOT.attributes",
31✔
1074
                        },
31✔
1075
                },
31✔
1076
        }
31✔
1077

31✔
1078
        unwind := bson.M{
31✔
1079
                "$unwind": "$arrayofkeyvalue",
31✔
1080
        }
31✔
1081

31✔
1082
        group := bson.M{
31✔
1083
                "$group": bson.M{
31✔
1084
                        "_id": nil,
31✔
1085
                        "allkeys": bson.M{
31✔
1086
                                "$addToSet": "$arrayofkeyvalue.v.name",
31✔
1087
                        },
31✔
1088
                },
31✔
1089
        }
31✔
1090

31✔
1091
        l := log.FromContext(ctx)
31✔
1092
        cursor, err := c.Aggregate(ctx, []bson.M{
31✔
1093
                project,
31✔
1094
                unwind,
31✔
1095
                group,
31✔
1096
        })
31✔
1097
        if err != nil {
31✔
1098
                return nil, err
×
1099
        }
×
1100
        defer cursor.Close(ctx)
31✔
1101

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

1120
        return attributeNames, nil
17✔
1121
}
1122

1123
func (db *DataStoreMongo) SearchDevices(
1124
        ctx context.Context,
1125
        searchParams model.SearchParams,
1126
) ([]model.Device, int, error) {
15✔
1127
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
15✔
1128

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

1146
        // FIXME: remove after migrating ids to attributes
1147
        if len(searchParams.DeviceIDs) > 0 {
16✔
1148
                queryFilters = append(queryFilters, bson.M{"_id": bson.M{"$in": searchParams.DeviceIDs}})
1✔
1149
        }
1✔
1150

1151
        if searchParams.Text != "" {
16✔
1152
                queryFilters = append(queryFilters, bson.M{
1✔
1153
                        "$text": bson.M{
1✔
1154
                                "$search": utils.TextToKeywords(searchParams.Text),
1✔
1155
                        },
1✔
1156
                })
1✔
1157
        }
1✔
1158

1159
        findQuery := bson.M{}
15✔
1160
        if len(queryFilters) > 0 {
28✔
1161
                findQuery["$and"] = queryFilters
13✔
1162
        }
13✔
1163

1164
        findOptions := mopts.Find()
15✔
1165
        findOptions.SetSkip(int64((searchParams.Page - 1) * searchParams.PerPage))
15✔
1166
        findOptions.SetLimit(int64(searchParams.PerPage))
15✔
1167

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

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

1212
        cursor, err := c.Find(ctx, findQuery, findOptions)
15✔
1213
        if err != nil {
16✔
1214
                return nil, -1, errors.Wrap(err, "failed to search devices")
1✔
1215
        }
1✔
1216
        defer cursor.Close(ctx)
14✔
1217

14✔
1218
        devices := []model.Device{}
14✔
1219

14✔
1220
        if err = cursor.All(ctx, &devices); err != nil {
14✔
1221
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1222
        }
×
1223

1224
        count, err := c.CountDocuments(ctx, findQuery)
14✔
1225
        if err != nil {
14✔
1226
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1227
        }
×
1228

1229
        return devices, int(count), nil
14✔
1230
}
1231

1232
func indexAttr(s *mongo.Client, ctx context.Context, attr string) error {
68✔
1233
        l := log.FromContext(ctx)
68✔
1234
        c := s.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
68✔
1235

68✔
1236
        indexView := c.Indexes()
68✔
1237
        keys := bson.D{
68✔
1238
                {Key: indexAttrName(attrIdentityStatus), Value: 1},
68✔
1239
                {Key: indexAttrName(attr), Value: 1},
68✔
1240
        }
68✔
1241
        _, err := indexView.CreateOne(ctx, mongo.IndexModel{Keys: keys, Options: &mopts.IndexOptions{
68✔
1242
                Name: &attr,
68✔
1243
        }})
68✔
1244

68✔
1245
        if err != nil {
68✔
1246
                if isTooManyIndexes(err) {
×
1247
                        l.Warnf(
×
1248
                                "failed to index attr %s in db %s: too many indexes",
×
1249
                                attr,
×
1250
                                mstore.DbFromContext(ctx, DbName),
×
1251
                        )
×
1252
                } else {
×
1253
                        return errors.Wrapf(
×
1254
                                err,
×
1255
                                "failed to index attr %s in db %s",
×
1256
                                attr,
×
1257
                                mstore.DbFromContext(ctx, DbName),
×
1258
                        )
×
1259
                }
×
1260
        }
1261

1262
        return nil
68✔
1263
}
1264

1265
func indexAttrName(attr string) string {
152✔
1266
        return fmt.Sprintf("attributes.%s.value", attr)
152✔
1267
}
152✔
1268

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