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

mendersoftware / inventory / 986921609

30 Aug 2023 05:48PM UTC coverage: 91.65% (+0.6%) from 91.042%
986921609

Pull #404

gitlab-ci

alfrunes
chore: Combine limits check and attribute diff computation

Signed-off-by: Alf-Rune Siqveland <alf.rune@northern.tech>
Pull Request #404: MEN-6425: Only update device inventory when changed

159 of 160 new or added lines in 4 files covered. (99.38%)

16 existing lines in 3 files now uncovered.

3183 of 3473 relevant lines covered (91.65%)

146.59 hits per line

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

90.41
/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
        ErrNotFound = errors.New("mongo: no documents in result")
79
)
80

81
type DataStoreMongoConfig struct {
82
        // connection string
83
        ConnectionString string
84

85
        // SSL support
86
        SSL           bool
87
        SSLSkipVerify bool
88

89
        // Overwrites credentials provided in connection string if provided
90
        Username string
91
        Password string
92
}
93

94
type DataStoreMongo struct {
95
        client      *mongo.Client
96
        automigrate bool
97
}
98

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

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

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

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

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

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

4✔
161
        return db, nil
4✔
162
}
163

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

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

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

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

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

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

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

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

260
        return devices, int(count), nil
53✔
261
}
262

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

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

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

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

314
func (db *DataStoreMongo) UpsertDevicesAttributesWithUpdated(
315
        ctx context.Context,
316
        ids []model.DeviceID,
317
        attrs model.DeviceAttributes,
318
        scope string,
319
        etag string,
320
) (*model.UpdateResult, error) {
277✔
321
        return db.upsertAttributes(ctx, makeDevsWithIds(ids), attrs, true, false, scope, etag)
277✔
322
}
277✔
323

324
func (db *DataStoreMongo) UpsertDevicesAttributes(
325
        ctx context.Context,
326
        ids []model.DeviceID,
327
        attrs model.DeviceAttributes,
328
) (*model.UpdateResult, error) {
16✔
329
        return db.upsertAttributes(ctx, makeDevsWithIds(ids), attrs, false, false, "", "")
16✔
330
}
16✔
331

332
func makeDevsWithIds(ids []model.DeviceID) []model.DeviceUpdate {
293✔
333
        devices := make([]model.DeviceUpdate, len(ids))
293✔
334
        for i, id := range ids {
586✔
335
                devices[i].Id = id
293✔
336
        }
293✔
337
        return devices
293✔
338
}
339

340
func (db *DataStoreMongo) upsertAttributes(
341
        ctx context.Context,
342
        devices []model.DeviceUpdate,
343
        attrs model.DeviceAttributes,
344
        withUpdated bool,
345
        withRevision bool,
346
        scope string,
347
        etag string,
348
) (*model.UpdateResult, error) {
296✔
349
        const systemScope = DbDevAttributes + "." + model.AttrScopeSystem
296✔
350
        const createdField = systemScope + "-" + model.AttrNameCreated
296✔
351
        const etagField = model.AttrNameTagsEtag
296✔
352
        var (
296✔
353
                result *model.UpdateResult
296✔
354
                filter interface{}
296✔
355
                err    error
296✔
356
        )
296✔
357

296✔
358
        c := db.client.
296✔
359
                Database(mstore.DbFromContext(ctx, DbName)).
296✔
360
                Collection(DbDevicesColl)
296✔
361

296✔
362
        update, err := makeAttrUpsert(attrs)
296✔
363
        if err != nil {
298✔
364
                return nil, err
2✔
365
        }
2✔
366

367
        now := time.Now()
294✔
368
        oninsert := bson.M{
294✔
369
                createdField: model.DeviceAttribute{
294✔
370
                        Scope: model.AttrScopeSystem,
294✔
371
                        Name:  model.AttrNameCreated,
294✔
372
                        Value: now,
294✔
373
                },
294✔
374
        }
294✔
375
        if !withRevision {
585✔
376
                oninsert["revision"] = 0
291✔
377
        }
291✔
378

379
        const updatedField = systemScope + "-" + model.AttrNameUpdated
294✔
380
        if withUpdated {
570✔
381
                update[updatedField] = model.DeviceAttribute{
276✔
382
                        Scope: model.AttrScopeSystem,
276✔
383
                        Name:  model.AttrNameUpdated,
276✔
384
                        Value: now,
276✔
385
                }
276✔
386
        } else {
294✔
387
                oninsert[updatedField] = model.DeviceAttribute{
18✔
388
                        Scope: model.AttrScopeSystem,
18✔
389
                        Name:  model.AttrNameUpdated,
18✔
390
                        Value: now,
18✔
391
                }
18✔
392
        }
18✔
393

394
        switch len(devices) {
294✔
395
        case 0:
2✔
396
                return &model.UpdateResult{}, nil
2✔
397
        case 1:
289✔
398
                filter := bson.M{
289✔
399
                        "_id": devices[0].Id,
289✔
400
                }
289✔
401
                updateOpts := mopts.FindOneAndUpdate().
289✔
402
                        SetUpsert(true).
289✔
403
                        SetReturnDocument(mopts.After)
289✔
404

289✔
405
                if withRevision {
291✔
406
                        filter[DbDevRevision] = bson.M{"$lt": devices[0].Revision}
2✔
407
                        update[DbDevRevision] = devices[0].Revision
2✔
408
                }
2✔
409
                if scope == model.AttrScopeTags {
294✔
410
                        update[etagField] = uuid.New().String()
5✔
411
                        updateOpts = mopts.FindOneAndUpdate().
5✔
412
                                SetUpsert(false).
5✔
413
                                SetReturnDocument(mopts.After)
5✔
414
                }
5✔
415
                if etag != "" {
290✔
416
                        filter[etagField] = bson.M{"$eq": etag}
1✔
417
                }
1✔
418

419
                update = bson.M{
289✔
420
                        "$set":         update,
289✔
421
                        "$setOnInsert": oninsert,
289✔
422
                }
289✔
423

289✔
424
                device := &model.Device{}
289✔
425
                res := c.FindOneAndUpdate(ctx, filter, update, updateOpts)
289✔
426
                err = res.Decode(device)
289✔
427
                if err != nil {
290✔
428
                        if mongo.IsDuplicateKeyError(err) {
2✔
429
                                return nil, store.ErrWriteConflict
1✔
430
                        } else if err == mongo.ErrNoDocuments {
1✔
UNCOV
431
                                return &model.UpdateResult{}, nil
×
UNCOV
432
                        } else {
×
433
                                return nil, err
×
434
                        }
×
435
                }
436
                result = &model.UpdateResult{
288✔
437
                        MatchedCount: 1,
288✔
438
                        CreatedCount: 0,
288✔
439
                        Devices:      []*model.Device{device},
288✔
440
                }
288✔
441
        default:
3✔
442
                var bres *mongo.BulkWriteResult
3✔
443
                // Perform single bulk-write operation
3✔
444
                // NOTE: Can't use UpdateMany as $in query operator does not
3✔
445
                //       upsert missing devices.
3✔
446

3✔
447
                models := make([]mongo.WriteModel, len(devices))
3✔
448
                for i, dev := range devices {
12✔
449
                        umod := mongo.NewUpdateOneModel()
9✔
450
                        if withRevision {
12✔
451
                                filter = bson.M{
3✔
452
                                        "_id":         dev.Id,
3✔
453
                                        DbDevRevision: bson.M{"$lt": dev.Revision},
3✔
454
                                }
3✔
455
                                update[DbDevRevision] = dev.Revision
3✔
456
                                umod.Update = bson.M{
3✔
457
                                        "$set":         update,
3✔
458
                                        "$setOnInsert": oninsert,
3✔
459
                                }
3✔
460
                        } else {
9✔
461
                                filter = map[string]interface{}{"_id": dev.Id}
6✔
462
                                umod.Update = bson.M{
6✔
463
                                        "$set":         update,
6✔
464
                                        "$setOnInsert": oninsert,
6✔
465
                                }
6✔
466
                        }
6✔
467
                        umod.Filter = filter
9✔
468
                        umod.SetUpsert(true)
9✔
469
                        models[i] = umod
9✔
470
                }
471
                bres, err = c.BulkWrite(
3✔
472
                        ctx, models, mopts.BulkWrite().SetOrdered(false),
3✔
473
                )
3✔
474
                if err != nil {
4✔
475
                        if mongo.IsDuplicateKeyError(err) {
2✔
476
                                // bulk mode, swallow the error as we already updated the other devices
1✔
477
                                // and the Matchedcount and CreatedCount values will tell the caller if
1✔
478
                                // all the operations succeeded or not
1✔
479
                                err = nil
1✔
480
                        } else {
1✔
481
                                return nil, err
×
482
                        }
×
483
                }
484
                result = &model.UpdateResult{
3✔
485
                        MatchedCount: bres.MatchedCount,
3✔
486
                        CreatedCount: bres.UpsertedCount,
3✔
487
                }
3✔
488
        }
489
        return result, err
291✔
490
}
491

492
// makeAttrField is a convenience function for composing attribute field names.
493
func makeAttrField(attrName, attrScope string, subFields ...string) string {
4,746✔
494
        field := fmt.Sprintf(
4,746✔
495
                "%s.%s-%s",
4,746✔
496
                DbDevAttributes,
4,746✔
497
                attrScope,
4,746✔
498
                model.GetDeviceAttributeNameReplacer().Replace(attrName),
4,746✔
499
        )
4,746✔
500
        if len(subFields) > 0 {
9,491✔
501
                field = strings.Join(
4,745✔
502
                        append([]string{field}, subFields...), ".",
4,745✔
503
                )
4,745✔
504
        }
4,745✔
505
        return field
4,746✔
506
}
507

508
// makeAttrUpsert creates a new upsert document for the given attributes.
509
func makeAttrUpsert(attrs model.DeviceAttributes) (bson.M, error) {
321✔
510
        var fieldName string
321✔
511
        upsert := make(bson.M)
321✔
512

321✔
513
        for i := range attrs {
1,752✔
514
                if attrs[i].Name == "" {
1,434✔
515
                        return nil, store.ErrNoAttrName
3✔
516
                }
3✔
517
                if attrs[i].Scope == "" {
1,434✔
518
                        // Default to inventory scope
6✔
519
                        attrs[i].Scope = model.AttrScopeInventory
6✔
520
                }
6✔
521

522
                fieldName = makeAttrField(
1,428✔
523
                        attrs[i].Name,
1,428✔
524
                        attrs[i].Scope,
1,428✔
525
                        DbDevAttributesScope,
1,428✔
526
                )
1,428✔
527
                upsert[fieldName] = attrs[i].Scope
1,428✔
528

1,428✔
529
                fieldName = makeAttrField(
1,428✔
530
                        attrs[i].Name,
1,428✔
531
                        attrs[i].Scope,
1,428✔
532
                        DbDevAttributesName,
1,428✔
533
                )
1,428✔
534
                upsert[fieldName] = attrs[i].Name
1,428✔
535

1,428✔
536
                if attrs[i].Value != nil {
2,851✔
537
                        fieldName = makeAttrField(
1,423✔
538
                                attrs[i].Name,
1,423✔
539
                                attrs[i].Scope,
1,423✔
540
                                DbDevAttributesValue,
1,423✔
541
                        )
1,423✔
542
                        upsert[fieldName] = attrs[i].Value
1,423✔
543
                }
1,423✔
544

545
                if attrs[i].Description != nil {
1,882✔
546
                        fieldName = makeAttrField(
454✔
547
                                attrs[i].Name,
454✔
548
                                attrs[i].Scope,
454✔
549
                                DbDevAttributesDesc,
454✔
550
                        )
454✔
551
                        upsert[fieldName] = attrs[i].Description
454✔
552
                }
454✔
553

554
                if attrs[i].Timestamp != nil {
1,440✔
555
                        fieldName = makeAttrField(
12✔
556
                                attrs[i].Name,
12✔
557
                                attrs[i].Scope,
12✔
558
                                DbDevAttributesTs,
12✔
559
                        )
12✔
560
                        upsert[fieldName] = attrs[i].Timestamp
12✔
561
                }
12✔
562
        }
563
        return upsert, nil
318✔
564
}
565

566
// makeAttrRemove creates a new unset document to remove attributes
567
func makeAttrRemove(attrs model.DeviceAttributes) (bson.M, error) {
24✔
568
        var fieldName string
24✔
569
        remove := make(bson.M)
24✔
570

24✔
571
        for i := range attrs {
25✔
572
                if attrs[i].Name == "" {
1✔
573
                        return nil, store.ErrNoAttrName
×
574
                }
×
575
                if attrs[i].Scope == "" {
1✔
576
                        // Default to inventory scope
×
577
                        attrs[i].Scope = model.AttrScopeInventory
×
578
                }
×
579
                fieldName = makeAttrField(
1✔
580
                        attrs[i].Name,
1✔
581
                        attrs[i].Scope,
1✔
582
                )
1✔
583
                remove[fieldName] = true
1✔
584
        }
585
        return remove, nil
24✔
586
}
587

588
func mongoOperator(co store.ComparisonOperator) string {
7✔
589
        switch co {
7✔
590
        case store.Eq:
7✔
591
                return "$eq"
7✔
592
        }
593
        return ""
×
594
}
595

596
func (db *DataStoreMongo) UpsertRemoveDeviceAttributes(
597
        ctx context.Context,
598
        id model.DeviceID,
599
        updateAttrs model.DeviceAttributes,
600
        removeAttrs model.DeviceAttributes,
601
        scope string,
602
        etag string,
603
) (*model.UpdateResult, error) {
25✔
604
        const systemScope = DbDevAttributes + "." + model.AttrScopeSystem
25✔
605
        const updatedField = systemScope + "-" + model.AttrNameUpdated
25✔
606
        const createdField = systemScope + "-" + model.AttrNameCreated
25✔
607
        const etagField = model.AttrNameTagsEtag
25✔
608
        var (
25✔
609
                err error
25✔
610
        )
25✔
611

25✔
612
        c := db.client.
25✔
613
                Database(mstore.DbFromContext(ctx, DbName)).
25✔
614
                Collection(DbDevicesColl)
25✔
615

25✔
616
        update, err := makeAttrUpsert(updateAttrs)
25✔
617
        if err != nil {
26✔
618
                return nil, err
1✔
619
        }
1✔
620
        remove, err := makeAttrRemove(removeAttrs)
24✔
621
        if err != nil {
24✔
622
                return nil, err
×
623
        }
×
624
        filter := bson.M{"_id": id}
24✔
625
        if etag != "" {
27✔
626
                filter[etagField] = bson.M{"$eq": etag}
3✔
627
        }
3✔
628

629
        updateOpts := mopts.FindOneAndUpdate().
24✔
630
                SetUpsert(true).
24✔
631
                SetReturnDocument(mopts.After)
24✔
632
        if scope == model.AttrScopeTags {
34✔
633
                update[etagField] = uuid.New().String()
10✔
634
                updateOpts = updateOpts.SetUpsert(false)
10✔
635
        }
10✔
636
        now := time.Now()
24✔
637
        if scope != model.AttrScopeTags {
38✔
638
                update[updatedField] = model.DeviceAttribute{
14✔
639
                        Scope: model.AttrScopeSystem,
14✔
640
                        Name:  model.AttrNameUpdated,
14✔
641
                        Value: now,
14✔
642
                }
14✔
643
        }
14✔
644
        update = bson.M{
24✔
645
                "$set": update,
24✔
646
                "$setOnInsert": bson.M{
24✔
647
                        createdField: model.DeviceAttribute{
24✔
648
                                Scope: model.AttrScopeSystem,
24✔
649
                                Name:  model.AttrNameCreated,
24✔
650
                                Value: now,
24✔
651
                        },
24✔
652
                },
24✔
653
        }
24✔
654
        if len(remove) > 0 {
25✔
655
                update["$unset"] = remove
1✔
656
        }
1✔
657

658
        device := &model.Device{}
24✔
659
        res := c.FindOneAndUpdate(ctx, filter, update, updateOpts)
24✔
660
        err = res.Decode(device)
24✔
661
        if err == mongo.ErrNoDocuments {
25✔
662
                return &model.UpdateResult{
1✔
663
                        MatchedCount: 0,
1✔
664
                        CreatedCount: 0,
1✔
665
                        Devices:      []*model.Device{},
1✔
666
                }, nil
1✔
667
        } else if err == nil {
47✔
668
                return &model.UpdateResult{
23✔
669
                        MatchedCount: 1,
23✔
670
                        CreatedCount: 0,
23✔
671
                        Devices:      []*model.Device{device},
23✔
672
                }, nil
23✔
673
        }
23✔
674
        return nil, err
×
675
}
676

677
func (db *DataStoreMongo) UpdateDevicesGroup(
678
        ctx context.Context,
679
        devIDs []model.DeviceID,
680
        group model.GroupName,
681
) (*model.UpdateResult, error) {
61✔
682
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
61✔
683
        collDevs := database.Collection(DbDevicesColl)
61✔
684

61✔
685
        var filter = bson.M{}
61✔
686
        switch len(devIDs) {
61✔
687
        case 0:
3✔
688
                return &model.UpdateResult{}, nil
3✔
689
        case 1:
54✔
690
                filter[DbDevId] = devIDs[0]
54✔
691
        default:
4✔
692
                filter[DbDevId] = bson.M{"$in": devIDs}
4✔
693
        }
694
        update := bson.M{
58✔
695
                "$set": bson.M{
58✔
696
                        DbDevAttributesGroup: model.DeviceAttribute{
58✔
697
                                Scope: model.AttrScopeSystem,
58✔
698
                                Name:  DbDevGroup,
58✔
699
                                Value: group,
58✔
700
                        },
58✔
701
                },
58✔
702
        }
58✔
703
        res, err := collDevs.UpdateMany(ctx, filter, update)
58✔
704
        if err != nil {
58✔
705
                return nil, err
×
706
        }
×
707
        return &model.UpdateResult{
58✔
708
                MatchedCount: res.MatchedCount,
58✔
709
                UpdatedCount: res.ModifiedCount,
58✔
710
        }, nil
58✔
711
}
712

713
// UpdateDeviceText updates the device text field
714
func (db *DataStoreMongo) UpdateDeviceText(
715
        ctx context.Context,
716
        deviceID model.DeviceID,
717
        text string,
718
) error {
22✔
719
        filter := bson.M{
22✔
720
                DbDevId: deviceID.String(),
22✔
721
        }
22✔
722

22✔
723
        update := bson.M{
22✔
724
                "$set": bson.M{
22✔
725
                        DbDevAttributesText: text,
22✔
726
                },
22✔
727
        }
22✔
728

22✔
729
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
22✔
730
        collDevs := database.Collection(DbDevicesColl)
22✔
731

22✔
732
        _, err := collDevs.UpdateOne(ctx, filter, update)
22✔
733
        return err
22✔
734
}
22✔
735

736
func (db *DataStoreMongo) GetFiltersAttributes(
737
        ctx context.Context,
738
) ([]model.FilterAttribute, error) {
4✔
739
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
4✔
740
        collDevs := database.Collection(DbDevicesColl)
4✔
741

4✔
742
        const DbCount = "count"
4✔
743

4✔
744
        cur, err := collDevs.Aggregate(ctx, []bson.M{
4✔
745
                {
4✔
746
                        "$project": bson.M{
4✔
747
                                "attributes": bson.M{
4✔
748
                                        "$objectToArray": "$" + DbDevAttributes,
4✔
749
                                },
4✔
750
                        },
4✔
751
                },
4✔
752
                {
4✔
753
                        "$unwind": "$" + DbDevAttributes,
4✔
754
                },
4✔
755
                {
4✔
756
                        "$project": bson.M{
4✔
757
                                DbDevAttributesName:  "$" + DbDevAttributes + ".v." + DbDevAttributesName,
4✔
758
                                DbDevAttributesScope: "$" + DbDevAttributes + ".v." + DbDevAttributesScope,
4✔
759
                        },
4✔
760
                },
4✔
761
                {
4✔
762
                        "$group": bson.M{
4✔
763
                                DbDevId: bson.M{
4✔
764
                                        DbDevAttributesName:  "$" + DbDevAttributesName,
4✔
765
                                        DbDevAttributesScope: "$" + DbDevAttributesScope,
4✔
766
                                },
4✔
767
                                DbCount: bson.M{
4✔
768
                                        "$sum": 1,
4✔
769
                                },
4✔
770
                        },
4✔
771
                },
4✔
772
                {
4✔
773
                        "$project": bson.M{
4✔
774
                                DbDevId:              0,
4✔
775
                                DbDevAttributesName:  "$" + DbDevId + "." + DbDevAttributesName,
4✔
776
                                DbDevAttributesScope: "$" + DbDevId + "." + DbDevAttributesScope,
4✔
777
                                DbCount:              "$" + DbCount,
4✔
778
                        },
4✔
779
                },
4✔
780
                {
4✔
781
                        "$sort": bson.D{
4✔
782
                                {Key: DbCount, Value: -1},
4✔
783
                                {Key: DbDevAttributesScope, Value: 1},
4✔
784
                                {Key: DbDevAttributesName, Value: 1},
4✔
785
                        },
4✔
786
                },
4✔
787
                {
4✔
788
                        "$limit": FiltersAttributesLimit,
4✔
789
                },
4✔
790
        })
4✔
791
        if err != nil {
4✔
792
                return nil, err
×
793
        }
×
794
        defer cur.Close(ctx)
4✔
795

4✔
796
        var attributes []model.FilterAttribute
4✔
797
        err = cur.All(ctx, &attributes)
4✔
798
        if err != nil {
4✔
799
                return nil, err
×
800
        }
×
801

802
        return attributes, nil
4✔
803
}
804

805
func (db *DataStoreMongo) DeleteGroup(
806
        ctx context.Context,
807
        group model.GroupName,
808
) (chan model.DeviceID, error) {
1✔
809
        deviceIDs := make(chan model.DeviceID)
1✔
810

1✔
811
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
1✔
812
        collDevs := database.Collection(DbDevicesColl)
1✔
813

1✔
814
        filter := bson.M{DbDevAttributesGroupValue: group}
1✔
815

1✔
816
        const batchMaxSize = 100
1✔
817
        batchSize := int32(batchMaxSize)
1✔
818
        findOptions := &mopts.FindOptions{
1✔
819
                Projection: bson.M{DbDevId: 1},
1✔
820
                BatchSize:  &batchSize,
1✔
821
        }
1✔
822
        cursor, err := collDevs.Find(ctx, filter, findOptions)
1✔
823
        if err != nil {
1✔
824
                return nil, err
×
825
        }
×
826

827
        go func() {
2✔
828
                defer cursor.Close(ctx)
1✔
829
                batch := make([]model.DeviceID, batchMaxSize)
1✔
830
                batchSize := 0
1✔
831

1✔
832
                update := bson.M{"$unset": bson.M{DbDevAttributesGroup: 1}}
1✔
833
                device := &model.Device{}
1✔
834
                defer close(deviceIDs)
1✔
835

1✔
836
        next:
1✔
837
                for {
5✔
838
                        hasNext := cursor.Next(ctx)
4✔
839
                        if !hasNext {
6✔
840
                                if batchSize > 0 {
3✔
841
                                        break
1✔
842
                                }
843
                                return
1✔
844
                        }
845
                        if err = cursor.Decode(&device); err == nil {
4✔
846
                                batch[batchSize] = device.ID
2✔
847
                                batchSize++
2✔
848
                                if len(batch) == batchSize {
2✔
849
                                        break
×
850
                                }
851
                        }
852
                }
853

854
                _, _ = collDevs.UpdateMany(ctx, bson.M{DbDevId: bson.M{"$in": batch[:batchSize]}}, update)
1✔
855
                for _, item := range batch[:batchSize] {
3✔
856
                        deviceIDs <- item
2✔
857
                }
2✔
858
                batchSize = 0
1✔
859
                goto next
1✔
860
        }()
861

862
        return deviceIDs, nil
1✔
863
}
864

865
func (db *DataStoreMongo) UnsetDevicesGroup(
866
        ctx context.Context,
867
        deviceIDs []model.DeviceID,
868
        group model.GroupName,
869
) (*model.UpdateResult, error) {
14✔
870
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
14✔
871
        collDevs := database.Collection(DbDevicesColl)
14✔
872

14✔
873
        var filter bson.D
14✔
874
        // Add filter on device id (either $in or direct indexing)
14✔
875
        switch len(deviceIDs) {
14✔
876
        case 0:
1✔
877
                return &model.UpdateResult{}, nil
1✔
878
        case 1:
10✔
879
                filter = bson.D{{Key: DbDevId, Value: deviceIDs[0]}}
10✔
880
        default:
3✔
881
                filter = bson.D{{Key: DbDevId, Value: bson.M{"$in": deviceIDs}}}
3✔
882
        }
883
        // Append filter on group
884
        filter = append(
13✔
885
                filter,
13✔
886
                bson.E{Key: DbDevAttributesGroupValue, Value: group},
13✔
887
        )
13✔
888
        // Create unset operation on group attribute
13✔
889
        update := bson.M{
13✔
890
                "$unset": bson.M{
13✔
891
                        DbDevAttributesGroup: "",
13✔
892
                },
13✔
893
        }
13✔
894
        res, err := collDevs.UpdateMany(ctx, filter, update)
13✔
895
        if err != nil {
13✔
896
                return nil, err
×
897
        }
×
898
        return &model.UpdateResult{
13✔
899
                MatchedCount: res.MatchedCount,
13✔
900
                UpdatedCount: res.ModifiedCount,
13✔
901
        }, nil
13✔
902
}
903

904
func predicateToQuery(pred model.FilterPredicate) (bson.D, error) {
2✔
905
        if err := pred.Validate(); err != nil {
3✔
906
                return nil, err
1✔
907
        }
1✔
908
        name := fmt.Sprintf(
1✔
909
                "%s.%s-%s.value",
1✔
910
                DbDevAttributes,
1✔
911
                pred.Scope,
1✔
912
                model.GetDeviceAttributeNameReplacer().Replace(pred.Attribute),
1✔
913
        )
1✔
914
        return bson.D{{
1✔
915
                Key: name, Value: bson.D{{Key: pred.Type, Value: pred.Value}},
1✔
916
        }}, nil
1✔
917
}
918

919
func (db *DataStoreMongo) ListGroups(
920
        ctx context.Context,
921
        filters []model.FilterPredicate,
922
) ([]model.GroupName, error) {
12✔
923
        c := db.client.
12✔
924
                Database(mstore.DbFromContext(ctx, DbName)).
12✔
925
                Collection(DbDevicesColl)
12✔
926

12✔
927
        fltr := bson.D{{
12✔
928
                Key: DbDevAttributesGroupValue, Value: bson.M{"$exists": true},
12✔
929
        }}
12✔
930
        if len(fltr) > 0 {
24✔
931
                for _, p := range filters {
14✔
932
                        q, err := predicateToQuery(p)
2✔
933
                        if err != nil {
3✔
934
                                return nil, errors.Wrap(
1✔
935
                                        err, "store: bad filter predicate",
1✔
936
                                )
1✔
937
                        }
1✔
938
                        fltr = append(fltr, q...)
1✔
939
                }
940
        }
941
        results, err := c.Distinct(
11✔
942
                ctx, DbDevAttributesGroupValue, fltr,
11✔
943
        )
11✔
944
        if err != nil {
11✔
945
                return nil, err
×
946
        }
×
947

948
        groups := make([]model.GroupName, len(results))
11✔
949
        for i, d := range results {
47✔
950
                groups[i] = model.GroupName(d.(string))
36✔
951
        }
36✔
952
        return groups, nil
11✔
953
}
954

955
func (db *DataStoreMongo) GetDevicesByGroup(
956
        ctx context.Context,
957
        group model.GroupName,
958
        skip,
959
        limit int,
960
) ([]model.DeviceID, int, error) {
37✔
961
        c := db.client.
37✔
962
                Database(mstore.DbFromContext(ctx, DbName)).
37✔
963
                Collection(DbDevicesColl)
37✔
964

37✔
965
        filter := bson.M{DbDevAttributesGroupValue: group}
37✔
966
        result := c.FindOne(ctx, filter)
37✔
967
        if result == nil {
37✔
968
                return nil, -1, store.ErrGroupNotFound
×
969
        }
×
970

971
        var dev model.Device
37✔
972
        err := result.Decode(&dev)
37✔
973
        if err != nil {
43✔
974
                return nil, -1, store.ErrGroupNotFound
6✔
975
        }
6✔
976

977
        hasGroup := group != ""
31✔
978
        devices, totalDevices, e := db.GetDevices(ctx,
31✔
979
                store.ListQuery{
31✔
980
                        Skip:      skip,
31✔
981
                        Limit:     limit,
31✔
982
                        Filters:   nil,
31✔
983
                        Sort:      nil,
31✔
984
                        HasGroup:  &hasGroup,
31✔
985
                        GroupName: string(group)})
31✔
986
        if e != nil {
31✔
987
                return nil, -1, errors.Wrap(e, "failed to get device list for group")
×
988
        }
×
989

990
        resIds := make([]model.DeviceID, len(devices))
31✔
991
        for i, d := range devices {
84✔
992
                resIds[i] = d.ID
53✔
993
        }
53✔
994
        return resIds, totalDevices, nil
31✔
995
}
996

997
func (db *DataStoreMongo) GetDeviceGroup(
998
        ctx context.Context,
999
        id model.DeviceID,
1000
) (model.GroupName, error) {
6✔
1001
        dev, err := db.GetDevice(ctx, id)
6✔
1002
        if err != nil || dev == nil {
8✔
1003
                return "", store.ErrDevNotFound
2✔
1004
        }
2✔
1005

1006
        return dev.Group, nil
4✔
1007
}
1008

1009
func (db *DataStoreMongo) DeleteDevices(
1010
        ctx context.Context, ids []model.DeviceID,
1011
) (*model.UpdateResult, error) {
3✔
1012
        var filter = bson.M{}
3✔
1013
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
3✔
1014
        collDevs := database.Collection(DbDevicesColl)
3✔
1015

3✔
1016
        switch len(ids) {
3✔
1017
        case 0:
×
1018
                // This is a no-op, don't bother requesting mongo.
×
1019
                return &model.UpdateResult{DeletedCount: 0}, nil
×
1020
        case 1:
2✔
1021
                filter[DbDevId] = ids[0]
2✔
1022
        default:
1✔
1023
                filter[DbDevId] = bson.M{"$in": ids}
1✔
1024
        }
1025
        res, err := collDevs.DeleteMany(ctx, filter)
3✔
1026
        if err != nil {
3✔
1027
                return nil, err
×
1028
        }
×
1029
        return &model.UpdateResult{
3✔
1030
                DeletedCount: res.DeletedCount,
3✔
1031
        }, nil
3✔
1032
}
1033

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

31✔
1037
        project := bson.M{
31✔
1038
                "$project": bson.M{
31✔
1039
                        "arrayofkeyvalue": bson.M{
31✔
1040
                                "$objectToArray": "$$ROOT.attributes",
31✔
1041
                        },
31✔
1042
                },
31✔
1043
        }
31✔
1044

31✔
1045
        unwind := bson.M{
31✔
1046
                "$unwind": "$arrayofkeyvalue",
31✔
1047
        }
31✔
1048

31✔
1049
        group := bson.M{
31✔
1050
                "$group": bson.M{
31✔
1051
                        "_id": nil,
31✔
1052
                        "allkeys": bson.M{
31✔
1053
                                "$addToSet": "$arrayofkeyvalue.v.name",
31✔
1054
                        },
31✔
1055
                },
31✔
1056
        }
31✔
1057

31✔
1058
        l := log.FromContext(ctx)
31✔
1059
        cursor, err := c.Aggregate(ctx, []bson.M{
31✔
1060
                project,
31✔
1061
                unwind,
31✔
1062
                group,
31✔
1063
        })
31✔
1064
        if err != nil {
31✔
1065
                return nil, err
×
1066
        }
×
1067
        defer cursor.Close(ctx)
31✔
1068

31✔
1069
        cursor.Next(ctx)
31✔
1070
        elem := &bson.D{}
31✔
1071
        err = cursor.Decode(elem)
31✔
1072
        if err != nil {
45✔
1073
                if err != io.EOF {
14✔
1074
                        return nil, errors.Wrap(err, "failed to get attributes")
×
1075
                } else {
14✔
1076
                        return make([]string, 0), nil
14✔
1077
                }
14✔
1078
        }
1079
        m := elem.Map()
17✔
1080
        results := m["allkeys"].(primitive.A)
17✔
1081
        attributeNames := make([]string, len(results))
17✔
1082
        for i, d := range results {
76✔
1083
                attributeNames[i] = d.(string)
59✔
1084
                l.Debugf("GetAllAttributeNames got: '%v'", d)
59✔
1085
        }
59✔
1086

1087
        return attributeNames, nil
17✔
1088
}
1089

1090
func (db *DataStoreMongo) SearchDevices(
1091
        ctx context.Context,
1092
        searchParams model.SearchParams,
1093
) ([]model.Device, int, error) {
15✔
1094
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
15✔
1095

15✔
1096
        queryFilters := make([]bson.M, 0)
15✔
1097
        for _, filter := range searchParams.Filters {
29✔
1098
                op := filter.Type
14✔
1099
                var field string
14✔
1100
                if filter.Scope == model.AttrScopeIdentity && filter.Attribute == model.AttrNameID {
16✔
1101
                        field = DbDevId
2✔
1102
                } else {
14✔
1103
                        name := fmt.Sprintf(
12✔
1104
                                "%s-%s",
12✔
1105
                                filter.Scope,
12✔
1106
                                model.GetDeviceAttributeNameReplacer().Replace(filter.Attribute),
12✔
1107
                        )
12✔
1108
                        field = fmt.Sprintf("%s.%s.%s", DbDevAttributes, name, DbDevAttributesValue)
12✔
1109
                }
12✔
1110
                queryFilters = append(queryFilters, bson.M{field: bson.M{op: filter.Value}})
14✔
1111
        }
1112

1113
        // FIXME: remove after migrating ids to attributes
1114
        if len(searchParams.DeviceIDs) > 0 {
16✔
1115
                queryFilters = append(queryFilters, bson.M{"_id": bson.M{"$in": searchParams.DeviceIDs}})
1✔
1116
        }
1✔
1117

1118
        if searchParams.Text != "" {
16✔
1119
                queryFilters = append(queryFilters, bson.M{
1✔
1120
                        "$text": bson.M{
1✔
1121
                                "$search": utils.TextToKeywords(searchParams.Text),
1✔
1122
                        },
1✔
1123
                })
1✔
1124
        }
1✔
1125

1126
        findQuery := bson.M{}
15✔
1127
        if len(queryFilters) > 0 {
28✔
1128
                findQuery["$and"] = queryFilters
13✔
1129
        }
13✔
1130

1131
        findOptions := mopts.Find()
15✔
1132
        findOptions.SetSkip(int64((searchParams.Page - 1) * searchParams.PerPage))
15✔
1133
        findOptions.SetLimit(int64(searchParams.PerPage))
15✔
1134

15✔
1135
        if len(searchParams.Attributes) > 0 {
17✔
1136
                name := fmt.Sprintf(
2✔
1137
                        "%s-%s",
2✔
1138
                        model.AttrScopeSystem,
2✔
1139
                        model.GetDeviceAttributeNameReplacer().Replace(DbDevUpdatedTs),
2✔
1140
                )
2✔
1141
                field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
2✔
1142
                projection := bson.M{field: 1}
2✔
1143
                for _, attribute := range searchParams.Attributes {
5✔
1144
                        name := fmt.Sprintf(
3✔
1145
                                "%s-%s",
3✔
1146
                                attribute.Scope,
3✔
1147
                                model.GetDeviceAttributeNameReplacer().Replace(attribute.Attribute),
3✔
1148
                        )
3✔
1149
                        field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
3✔
1150
                        projection[field] = 1
3✔
1151
                }
3✔
1152
                findOptions.SetProjection(projection)
2✔
1153
        }
1154

1155
        if searchParams.Text != "" {
16✔
1156
                findOptions.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
1✔
1157
        } else if len(searchParams.Sort) > 0 {
19✔
1158
                sortField := make(bson.D, len(searchParams.Sort))
4✔
1159
                for i, sortQ := range searchParams.Sort {
9✔
1160
                        var field string
5✔
1161
                        if sortQ.Scope == model.AttrScopeIdentity && sortQ.Attribute == model.AttrNameID {
6✔
1162
                                field = DbDevId
1✔
1163
                        } else {
5✔
1164
                                name := fmt.Sprintf(
4✔
1165
                                        "%s-%s",
4✔
1166
                                        sortQ.Scope,
4✔
1167
                                        model.GetDeviceAttributeNameReplacer().Replace(sortQ.Attribute),
4✔
1168
                                )
4✔
1169
                                field = fmt.Sprintf("%s.%s", DbDevAttributes, name)
4✔
1170
                        }
4✔
1171
                        sortField[i] = bson.E{Key: field, Value: 1}
5✔
1172
                        if sortQ.Order == "desc" {
8✔
1173
                                sortField[i].Value = -1
3✔
1174
                        }
3✔
1175
                }
1176
                findOptions.SetSort(sortField)
4✔
1177
        }
1178

1179
        cursor, err := c.Find(ctx, findQuery, findOptions)
15✔
1180
        if err != nil {
16✔
1181
                return nil, -1, errors.Wrap(err, "failed to search devices")
1✔
1182
        }
1✔
1183
        defer cursor.Close(ctx)
14✔
1184

14✔
1185
        devices := []model.Device{}
14✔
1186

14✔
1187
        if err = cursor.All(ctx, &devices); err != nil {
14✔
1188
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1189
        }
×
1190

1191
        count, err := c.CountDocuments(ctx, findQuery)
14✔
1192
        if err != nil {
14✔
1193
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1194
        }
×
1195

1196
        return devices, int(count), nil
14✔
1197
}
1198

1199
func indexAttr(s *mongo.Client, ctx context.Context, attr string) error {
68✔
1200
        l := log.FromContext(ctx)
68✔
1201
        c := s.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
68✔
1202

68✔
1203
        indexView := c.Indexes()
68✔
1204
        keys := bson.D{
68✔
1205
                {Key: indexAttrName(attrIdentityStatus), Value: 1},
68✔
1206
                {Key: indexAttrName(attr), Value: 1},
68✔
1207
        }
68✔
1208
        _, err := indexView.CreateOne(ctx, mongo.IndexModel{Keys: keys, Options: &mopts.IndexOptions{
68✔
1209
                Name: &attr,
68✔
1210
        }})
68✔
1211

68✔
1212
        if err != nil {
68✔
1213
                if isTooManyIndexes(err) {
×
1214
                        l.Warnf(
×
1215
                                "failed to index attr %s in db %s: too many indexes",
×
1216
                                attr,
×
1217
                                mstore.DbFromContext(ctx, DbName),
×
1218
                        )
×
1219
                } else {
×
1220
                        return errors.Wrapf(
×
1221
                                err,
×
1222
                                "failed to index attr %s in db %s",
×
1223
                                attr,
×
1224
                                mstore.DbFromContext(ctx, DbName),
×
1225
                        )
×
1226
                }
×
1227
        }
1228

1229
        return nil
68✔
1230
}
1231

1232
func indexAttrName(attr string) string {
152✔
1233
        return fmt.Sprintf("attributes.%s.value", attr)
152✔
1234
}
152✔
1235

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