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

mendersoftware / inventory / 1401701972

05 Aug 2024 08:32PM UTC coverage: 91.217%. Remained the same
1401701972

push

gitlab-ci

web-flow
Merge pull request #460 from mendersoftware/dependabot/docker/docker-dependencies-03b04ac819

chore: bump golang from 1.22.4-alpine3.19 to 1.22.5-alpine3.19 in the docker-dependencies group

3095 of 3393 relevant lines covered (91.22%)

148.68 hits per line

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

90.37
/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
        FiltersAttributesMaxDevices = 5000
67
        FiltersAttributesLimit      = 500
68

69
        attrIdentityStatus = "identity-status"
70
)
71

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

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

79
        ErrNotFound = errors.New("mongo: no documents in result")
80
)
81

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

380✔
360
        c := db.client.
380✔
361
                Database(mstore.DbFromContext(ctx, DbName)).
380✔
362
                Collection(DbDevicesColl)
380✔
363

380✔
364
        update, err := makeAttrUpsert(attrs)
380✔
365
        if err != nil {
382✔
366
                return nil, err
2✔
367
        }
2✔
368

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

381
        const updatedField = systemScope + "-" + model.AttrNameUpdated
378✔
382
        if withUpdated {
391✔
383
                update[updatedField] = model.DeviceAttribute{
13✔
384
                        Scope: model.AttrScopeSystem,
13✔
385
                        Name:  model.AttrNameUpdated,
13✔
386
                        Value: now,
13✔
387
                }
13✔
388
        }
13✔
389

390
        switch len(devices) {
378✔
391
        case 0:
2✔
392
                return &model.UpdateResult{}, nil
2✔
393
        case 1:
373✔
394
                filter := bson.M{
373✔
395
                        "_id": devices[0].Id,
373✔
396
                }
373✔
397
                updateOpts := mopts.FindOneAndUpdate().
373✔
398
                        SetUpsert(true).
373✔
399
                        SetReturnDocument(mopts.After)
373✔
400

373✔
401
                if withRevision {
375✔
402
                        filter[DbDevRevision] = bson.M{"$lt": devices[0].Revision}
2✔
403
                        update[DbDevRevision] = devices[0].Revision
2✔
404
                }
2✔
405
                if scope == model.AttrScopeTags {
379✔
406
                        update[etagField] = uuid.New().String()
6✔
407
                        updateOpts = mopts.FindOneAndUpdate().
6✔
408
                                SetUpsert(false).
6✔
409
                                SetReturnDocument(mopts.After)
6✔
410
                }
6✔
411
                if etag != "" {
374✔
412
                        filter[etagField] = bson.M{"$eq": etag}
1✔
413
                }
1✔
414

415
                update = bson.M{
373✔
416
                        "$set":         update,
373✔
417
                        "$setOnInsert": oninsert,
373✔
418
                }
373✔
419

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

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

488
// makeAttrField is a convenience function for composing attribute field names.
489
func makeAttrField(attrName, attrScope string, subFields ...string) string {
6,388✔
490
        field := fmt.Sprintf(
6,388✔
491
                "%s.%s-%s",
6,388✔
492
                DbDevAttributes,
6,388✔
493
                attrScope,
6,388✔
494
                model.GetDeviceAttributeNameReplacer().Replace(attrName),
6,388✔
495
        )
6,388✔
496
        if len(subFields) > 0 {
12,775✔
497
                field = strings.Join(
6,387✔
498
                        append([]string{field}, subFields...), ".",
6,387✔
499
                )
6,387✔
500
        }
6,387✔
501
        return field
6,388✔
502
}
503

504
// makeAttrUpsert creates a new upsert document for the given attributes.
505
func makeAttrUpsert(attrs model.DeviceAttributes) (bson.M, error) {
407✔
506
        var fieldName string
407✔
507
        upsert := make(bson.M)
407✔
508

407✔
509
        for i := range attrs {
2,276✔
510
                if attrs[i].Name == "" {
1,872✔
511
                        return nil, store.ErrNoAttrName
3✔
512
                }
3✔
513
                if attrs[i].Scope == "" {
1,872✔
514
                        // Default to inventory scope
6✔
515
                        attrs[i].Scope = model.AttrScopeInventory
6✔
516
                }
6✔
517

518
                fieldName = makeAttrField(
1,866✔
519
                        attrs[i].Name,
1,866✔
520
                        attrs[i].Scope,
1,866✔
521
                        DbDevAttributesScope,
1,866✔
522
                )
1,866✔
523
                upsert[fieldName] = attrs[i].Scope
1,866✔
524

1,866✔
525
                fieldName = makeAttrField(
1,866✔
526
                        attrs[i].Name,
1,866✔
527
                        attrs[i].Scope,
1,866✔
528
                        DbDevAttributesName,
1,866✔
529
                )
1,866✔
530
                upsert[fieldName] = attrs[i].Name
1,866✔
531

1,866✔
532
                if attrs[i].Value != nil {
3,727✔
533
                        fieldName = makeAttrField(
1,861✔
534
                                attrs[i].Name,
1,861✔
535
                                attrs[i].Scope,
1,861✔
536
                                DbDevAttributesValue,
1,861✔
537
                        )
1,861✔
538
                        upsert[fieldName] = attrs[i].Value
1,861✔
539
                }
1,861✔
540

541
                if attrs[i].Description != nil {
2,568✔
542
                        fieldName = makeAttrField(
702✔
543
                                attrs[i].Name,
702✔
544
                                attrs[i].Scope,
702✔
545
                                DbDevAttributesDesc,
702✔
546
                        )
702✔
547
                        upsert[fieldName] = attrs[i].Description
702✔
548
                }
702✔
549

550
                if attrs[i].Timestamp != nil {
1,958✔
551
                        fieldName = makeAttrField(
92✔
552
                                attrs[i].Name,
92✔
553
                                attrs[i].Scope,
92✔
554
                                DbDevAttributesTs,
92✔
555
                        )
92✔
556
                        upsert[fieldName] = attrs[i].Timestamp
92✔
557
                }
92✔
558
        }
559
        return upsert, nil
404✔
560
}
561

562
// makeAttrRemove creates a new unset document to remove attributes
563
func makeAttrRemove(attrs model.DeviceAttributes) (bson.M, error) {
26✔
564
        var fieldName string
26✔
565
        remove := make(bson.M)
26✔
566

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

584
func mongoOperator(co store.ComparisonOperator) string {
7✔
585
        switch co {
7✔
586
        case store.Eq:
7✔
587
                return "$eq"
7✔
588
        }
589
        return ""
×
590
}
591

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

27✔
608
        c := db.client.
27✔
609
                Database(mstore.DbFromContext(ctx, DbName)).
27✔
610
                Collection(DbDevicesColl)
27✔
611

27✔
612
        update, err := makeAttrUpsert(updateAttrs)
27✔
613
        if err != nil {
28✔
614
                return nil, err
1✔
615
        }
1✔
616
        remove, err := makeAttrRemove(removeAttrs)
26✔
617
        if err != nil {
26✔
618
                return nil, err
×
619
        }
×
620
        filter := bson.M{"_id": id}
26✔
621
        if etag != "" {
31✔
622
                filter[etagField] = bson.M{"$eq": etag}
5✔
623
        }
5✔
624

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

654
        device := &model.Device{}
26✔
655
        res := c.FindOneAndUpdate(ctx, filter, update, updateOpts)
26✔
656
        err = res.Decode(device)
26✔
657
        if err == mongo.ErrNoDocuments {
28✔
658
                return &model.UpdateResult{
2✔
659
                        MatchedCount: 0,
2✔
660
                        CreatedCount: 0,
2✔
661
                        Devices:      []*model.Device{},
2✔
662
                }, nil
2✔
663
        } else if err == nil {
50✔
664
                return &model.UpdateResult{
24✔
665
                        MatchedCount: 1,
24✔
666
                        CreatedCount: 0,
24✔
667
                        Devices:      []*model.Device{device},
24✔
668
                }, nil
24✔
669
        }
24✔
670
        return nil, err
×
671
}
672

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

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

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

22✔
719
        update := bson.M{
22✔
720
                "$set": bson.M{
22✔
721
                        DbDevAttributesText: text,
22✔
722
                },
22✔
723
        }
22✔
724

22✔
725
        database := db.client.Database(mstore.DbFromContext(ctx, DbName))
22✔
726
        collDevs := database.Collection(DbDevicesColl)
22✔
727

22✔
728
        _, err := collDevs.UpdateOne(ctx, filter, update)
22✔
729
        return err
22✔
730
}
22✔
731

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

4✔
738
        const DbCount = "count"
4✔
739

4✔
740
        cur, err := collDevs.Aggregate(ctx, []bson.M{
4✔
741
                // Sample up to 5,000 devices to get a representative sample
4✔
742
                {
4✔
743
                        "$limit": FiltersAttributesMaxDevices,
4✔
744
                },
4✔
745
                {
4✔
746
                        "$project": bson.M{
4✔
747
                                "_id": 0,
4✔
748
                                "attributes": bson.M{
4✔
749
                                        "$objectToArray": "$" + DbDevAttributes,
4✔
750
                                },
4✔
751
                        },
4✔
752
                },
4✔
753
                {
4✔
754
                        "$unwind": "$" + DbDevAttributes,
4✔
755
                },
4✔
756
                {
4✔
757
                        "$group": bson.M{
4✔
758
                                DbDevId: bson.M{
4✔
759
                                        DbDevAttributesName:  "$" + DbDevAttributes + ".v." + DbDevAttributesName,
4✔
760
                                        DbDevAttributesScope: "$" + DbDevAttributes + ".v." + DbDevAttributesScope,
4✔
761
                                },
4✔
762
                                DbCount: bson.M{
4✔
763
                                        "$sum": 1,
4✔
764
                                },
4✔
765
                        },
4✔
766
                },
4✔
767
                {
4✔
768
                        "$limit": FiltersAttributesLimit,
4✔
769
                },
4✔
770
                {
4✔
771
                        "$sort": bson.D{
4✔
772
                                {Key: DbCount, Value: -1},
4✔
773
                                {Key: DbDevId + "." + DbDevAttributesScope, Value: 1},
4✔
774
                                {Key: DbDevId + "." + DbDevAttributesName, Value: 1},
4✔
775
                        },
4✔
776
                },
4✔
777
        })
4✔
778
        if err != nil {
4✔
779
                return nil, err
×
780
        }
×
781
        defer cur.Close(ctx)
4✔
782

4✔
783
        var attributes []model.FilterAttribute
4✔
784
        type Result struct {
4✔
785
                Group struct {
4✔
786
                        Name  string `bson:"name"`
4✔
787
                        Scope string `bson:"scope"`
4✔
788
                } `bson:"_id"`
4✔
789
                Count int32 `bson:"count"`
4✔
790
        }
4✔
791
        for cur.Next(ctx) {
12✔
792
                var elem Result
8✔
793
                err = cur.Decode(&elem)
8✔
794
                if err != nil {
8✔
795
                        break
×
796
                }
797
                attributes = append(attributes, model.FilterAttribute{
8✔
798
                        Name:  elem.Group.Name,
8✔
799
                        Scope: elem.Group.Scope,
8✔
800
                        Count: elem.Count,
8✔
801
                })
8✔
802
        }
803

804
        return attributes, nil
4✔
805
}
806

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

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

1✔
816
        filter := bson.M{DbDevAttributesGroupValue: group}
1✔
817

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

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

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

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

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

864
        return deviceIDs, nil
1✔
865
}
866

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

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

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

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

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

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

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

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

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

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

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

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

1008
        return dev.Group, nil
4✔
1009
}
1010

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

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

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

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

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

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

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

31✔
1071
        cursor.Next(ctx)
31✔
1072
        elem := &bson.D{}
31✔
1073
        err = cursor.Decode(elem)
31✔
1074
        if err != nil {
45✔
1075
                if err != io.EOF {
14✔
1076
                        return nil, errors.Wrap(err, "failed to get attributes")
×
1077
                } else {
14✔
1078
                        return make([]string, 0), nil
14✔
1079
                }
14✔
1080
        }
1081
        bsonValue, err := bson.Marshal(elem)
17✔
1082
        if err != nil {
17✔
1083
                return make([]string, 0), nil
×
1084
        }
×
1085
        var mapValue bson.M
17✔
1086
        err = bson.Unmarshal(bsonValue, &mapValue)
17✔
1087
        if err != nil {
17✔
1088
                return make([]string, 0), nil
×
1089
        }
×
1090
        results := mapValue["allkeys"].(primitive.A)
17✔
1091
        attributeNames := make([]string, len(results))
17✔
1092
        for i, d := range results {
71✔
1093
                attributeNames[i] = d.(string)
54✔
1094
                l.Debugf("GetAllAttributeNames got: '%v'", d)
54✔
1095
        }
54✔
1096

1097
        return attributeNames, nil
17✔
1098
}
1099

1100
func (db *DataStoreMongo) SearchDevices(
1101
        ctx context.Context,
1102
        searchParams model.SearchParams,
1103
) ([]model.Device, int, error) {
16✔
1104
        c := db.client.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
16✔
1105

16✔
1106
        queryFilters := make([]bson.M, 0)
16✔
1107
        for _, filter := range searchParams.Filters {
30✔
1108
                op := filter.Type
14✔
1109
                var field string
14✔
1110
                if filter.Scope == model.AttrScopeIdentity && filter.Attribute == model.AttrNameID {
16✔
1111
                        field = DbDevId
2✔
1112
                } else {
14✔
1113
                        name := fmt.Sprintf(
12✔
1114
                                "%s-%s",
12✔
1115
                                filter.Scope,
12✔
1116
                                model.GetDeviceAttributeNameReplacer().Replace(filter.Attribute),
12✔
1117
                        )
12✔
1118
                        field = fmt.Sprintf("%s.%s.%s", DbDevAttributes, name, DbDevAttributesValue)
12✔
1119
                }
12✔
1120
                queryFilters = append(queryFilters, bson.M{field: bson.M{op: filter.Value}})
14✔
1121
        }
1122

1123
        // FIXME: remove after migrating ids to attributes
1124
        if len(searchParams.DeviceIDs) > 0 {
17✔
1125
                queryFilters = append(queryFilters, bson.M{"_id": bson.M{"$in": searchParams.DeviceIDs}})
1✔
1126
        }
1✔
1127

1128
        if searchParams.Text != "" {
17✔
1129
                queryFilters = append(queryFilters, bson.M{
1✔
1130
                        "$text": bson.M{
1✔
1131
                                "$search": utils.TextToKeywords(searchParams.Text),
1✔
1132
                        },
1✔
1133
                })
1✔
1134
        }
1✔
1135

1136
        findQuery := bson.M{}
16✔
1137
        if len(queryFilters) > 0 {
29✔
1138
                findQuery["$and"] = queryFilters
13✔
1139
        }
13✔
1140

1141
        findOptions := mopts.Find()
16✔
1142
        findOptions.SetSkip(int64((searchParams.Page - 1) * searchParams.PerPage))
16✔
1143
        findOptions.SetLimit(int64(searchParams.PerPage))
16✔
1144

16✔
1145
        if len(searchParams.Attributes) > 0 {
18✔
1146
                name := fmt.Sprintf(
2✔
1147
                        "%s-%s",
2✔
1148
                        model.AttrScopeSystem,
2✔
1149
                        model.GetDeviceAttributeNameReplacer().Replace(DbDevUpdatedTs),
2✔
1150
                )
2✔
1151
                field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
2✔
1152
                projection := bson.M{field: 1}
2✔
1153
                for _, attribute := range searchParams.Attributes {
5✔
1154
                        name := fmt.Sprintf(
3✔
1155
                                "%s-%s",
3✔
1156
                                attribute.Scope,
3✔
1157
                                model.GetDeviceAttributeNameReplacer().Replace(attribute.Attribute),
3✔
1158
                        )
3✔
1159
                        field := fmt.Sprintf("%s.%s", DbDevAttributes, name)
3✔
1160
                        projection[field] = 1
3✔
1161
                }
3✔
1162
                findOptions.SetProjection(projection)
2✔
1163
        }
1164

1165
        if searchParams.Text != "" {
17✔
1166
                findOptions.SetSort(bson.M{"score": bson.M{"$meta": "textScore"}})
1✔
1167
        } else if len(searchParams.Sort) > 0 {
21✔
1168
                sortField := make(bson.D, len(searchParams.Sort))
5✔
1169
                for i, sortQ := range searchParams.Sort {
11✔
1170
                        var field string
6✔
1171
                        if sortQ.Scope == model.AttrScopeIdentity && sortQ.Attribute == model.AttrNameID {
7✔
1172
                                field = DbDevId
1✔
1173
                        } else {
6✔
1174
                                name := fmt.Sprintf(
5✔
1175
                                        "%s-%s",
5✔
1176
                                        sortQ.Scope,
5✔
1177
                                        model.GetDeviceAttributeNameReplacer().Replace(sortQ.Attribute),
5✔
1178
                                )
5✔
1179
                                field = fmt.Sprintf("%s.%s.value", DbDevAttributes, name)
5✔
1180
                        }
5✔
1181
                        sortField[i] = bson.E{Key: field, Value: 1}
6✔
1182
                        if sortQ.Order == "desc" {
10✔
1183
                                sortField[i].Value = -1
4✔
1184
                        }
4✔
1185
                }
1186
                findOptions.SetSort(sortField)
5✔
1187
        }
1188

1189
        cursor, err := c.Find(ctx, findQuery, findOptions)
16✔
1190
        if err != nil {
17✔
1191
                return nil, -1, errors.Wrap(err, "failed to search devices")
1✔
1192
        }
1✔
1193
        defer cursor.Close(ctx)
15✔
1194

15✔
1195
        devices := []model.Device{}
15✔
1196

15✔
1197
        if err = cursor.All(ctx, &devices); err != nil {
15✔
1198
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1199
        }
×
1200

1201
        count, err := c.CountDocuments(ctx, findQuery)
15✔
1202
        if err != nil {
15✔
1203
                return nil, -1, errors.Wrap(err, "failed to search devices")
×
1204
        }
×
1205

1206
        return devices, int(count), nil
15✔
1207
}
1208

1209
func indexAttr(s *mongo.Client, ctx context.Context, attr string) error {
68✔
1210
        l := log.FromContext(ctx)
68✔
1211
        c := s.Database(mstore.DbFromContext(ctx, DbName)).Collection(DbDevicesColl)
68✔
1212

68✔
1213
        indexView := c.Indexes()
68✔
1214
        keys := bson.D{
68✔
1215
                {Key: indexAttrName(attrIdentityStatus), Value: 1},
68✔
1216
                {Key: indexAttrName(attr), Value: 1},
68✔
1217
        }
68✔
1218
        _, err := indexView.CreateOne(ctx, mongo.IndexModel{Keys: keys, Options: &mopts.IndexOptions{
68✔
1219
                Name: &attr,
68✔
1220
        }})
68✔
1221

68✔
1222
        if err != nil {
68✔
1223
                if isTooManyIndexes(err) {
×
1224
                        l.Warnf(
×
1225
                                "failed to index attr %s in db %s: too many indexes",
×
1226
                                attr,
×
1227
                                mstore.DbFromContext(ctx, DbName),
×
1228
                        )
×
1229
                } else {
×
1230
                        return errors.Wrapf(
×
1231
                                err,
×
1232
                                "failed to index attr %s in db %s",
×
1233
                                attr,
×
1234
                                mstore.DbFromContext(ctx, DbName),
×
1235
                        )
×
1236
                }
×
1237
        }
1238

1239
        return nil
68✔
1240
}
1241

1242
func indexAttrName(attr string) string {
152✔
1243
        return fmt.Sprintf("attributes.%s.value", attr)
152✔
1244
}
152✔
1245

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