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

mendersoftware / reporting / 820253733

pending completion
820253733

Pull #125

gitlab-ci

GitHub
Merge pull request #124 from kjaskiewiczz/men-6405
Pull Request #125: align staging with master

11 of 20 new or added lines in 4 files covered. (55.0%)

5 existing lines in 3 files now uncovered.

2815 of 3311 relevant lines covered (85.02%)

17.51 hits per line

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

77.81
/app/reporting/reporting.go
1
// Copyright 2022 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 reporting
16

17
import (
18
        "context"
19
        "errors"
20
        "sort"
21
        "time"
22

23
        "github.com/mendersoftware/go-lib-micro/log"
24

25
        "github.com/mendersoftware/reporting/client/inventory"
26
        "github.com/mendersoftware/reporting/mapping"
27
        "github.com/mendersoftware/reporting/model"
28
        "github.com/mendersoftware/reporting/store"
29
)
30

31
//go:generate ../../x/mockgen.sh
32
type App interface {
33
        HealthCheck(ctx context.Context) error
34
        GetMapping(ctx context.Context, tid string) (*model.Mapping, error)
35
        GetSearchableInvAttrs(ctx context.Context, tid string) ([]model.FilterAttribute, error)
36
        AggregateDevices(ctx context.Context, aggregateParams *model.AggregateParams) (
37
                []model.DeviceAggregation, error)
38
        SearchDevices(ctx context.Context, searchParams *model.SearchParams) (
39
                []inventory.Device, int, error)
40
        AggregateDeployments(ctx context.Context, aggregateParams *model.AggregateDeploymentsParams) (
41
                []model.DeviceAggregation, error)
42
        SearchDeployments(ctx context.Context, searchParams *model.DeploymentsSearchParams) (
43
                []model.Deployment, int, error)
44
}
45

46
type app struct {
47
        store  store.Store
48
        mapper mapping.Mapper
49
        ds     store.DataStore
50
}
51

52
func NewApp(store store.Store, ds store.DataStore) App {
1✔
53
        mapper := mapping.NewMapper(ds)
1✔
54
        return &app{
1✔
55
                store:  store,
1✔
56
                mapper: mapper,
1✔
57
                ds:     ds,
1✔
58
        }
1✔
59
}
1✔
60

61
// HealthCheck performs a health check and returns an error if it fails
62
func (a *app) HealthCheck(ctx context.Context) error {
63
        err := a.ds.Ping(ctx)
64
        if err == nil {
65
                err = a.store.Ping(ctx)
66
        }
67
        return err
68
}
69

70
// GetMapping returns the mapping for the specified tenant
71
func (app *app) GetMapping(ctx context.Context, tid string) (*model.Mapping, error) {
72
        return app.ds.GetMapping(ctx, tid)
73
}
74

75
// AggregateDevices aggregates device data
76
func (app *app) AggregateDevices(
77
        ctx context.Context,
78
        aggregateParams *model.AggregateParams,
79
) ([]model.DeviceAggregation, error) {
2✔
80
        searchParams := &model.SearchParams{
2✔
81
                Filters:  aggregateParams.Filters,
2✔
82
                Groups:   aggregateParams.Groups,
2✔
83
                TenantID: aggregateParams.TenantID,
2✔
84
        }
2✔
85
        if err := app.mapSearchParams(ctx, searchParams); err != nil {
2✔
86
                return nil, err
87
        }
88
        query, err := model.BuildQuery(*searchParams)
2✔
89
        if err != nil {
2✔
90
                return nil, err
91
        }
92
        if searchParams.TenantID != "" {
4✔
93
                query = query.Must(model.M{
2✔
94
                        "term": model.M{
2✔
95
                                model.FieldNameTenantID: searchParams.TenantID,
2✔
96
                        },
2✔
97
                })
2✔
98
        }
2✔
99

100
        if err := app.mapAggregations(ctx, searchParams.TenantID,
2✔
101
                aggregateParams.Aggregations); err != nil {
2✔
102
                return nil, err
103
        }
104
        aggregations, err := model.BuildAggregations(aggregateParams.Aggregations)
2✔
105
        if err != nil {
2✔
106
                return nil, err
107
        }
108

109
        query = query.WithSize(0).With(map[string]interface{}{
2✔
110
                "aggs": aggregations,
2✔
111
        })
2✔
112
        esRes, err := app.store.AggregateDevices(ctx, query)
2✔
113
        if err != nil {
2✔
114
                return nil, err
115
        }
116

117
        aggregationsS, ok := esRes["aggregations"].(map[string]interface{})
2✔
118
        if !ok {
2✔
119
                return nil, errors.New("can't process store aggregations slice")
120
        }
121
        res, err := app.storeToDeviceAggregations(ctx, searchParams.TenantID, aggregationsS)
2✔
122
        if err != nil {
2✔
123
                return nil, err
124
        }
125

126
        return res, nil
2✔
127
}
128

129
// storeToDeviceAggregations translates ES results directly to device aggregations
130
func (a *app) storeToDeviceAggregations(
131
        ctx context.Context, tenantID string, aggregationsS map[string]interface{},
132
) ([]model.DeviceAggregation, error) {
8✔
133
        aggs := []model.DeviceAggregation{}
8✔
134
        for name, aggregationS := range aggregationsS {
20✔
135
                if _, ok := aggregationS.(map[string]interface{}); !ok {
20✔
136
                        continue
8✔
137
                }
138
                bucketsS, ok := aggregationS.(map[string]interface{})["buckets"].([]interface{})
4✔
139
                if !ok {
4✔
140
                        continue
141
                }
142
                items := make([]model.DeviceAggregationItem, 0, len(bucketsS))
4✔
143
                for _, bucket := range bucketsS {
8✔
144
                        bucketMap, ok := bucket.(map[string]interface{})
4✔
145
                        if !ok {
4✔
146
                                return nil, errors.New("can't process store bucket item")
147
                        }
148
                        key, ok := bucketMap["key"].(string)
4✔
149
                        if !ok {
4✔
150
                                return nil, errors.New("can't process store key attribute")
151
                        }
152
                        count, ok := bucketMap["doc_count"].(float64)
4✔
153
                        if !ok {
4✔
154
                                return nil, errors.New("can't process store doc_count attribute")
155
                        }
156
                        item := model.DeviceAggregationItem{
4✔
157
                                Key:   key,
4✔
158
                                Count: int(count),
4✔
159
                        }
4✔
160
                        subaggs, err := a.storeToDeviceAggregations(ctx, tenantID, bucketMap)
4✔
161
                        if err == nil && len(subaggs) > 0 {
4✔
162
                                item.Aggregations = subaggs
163
                        }
164
                        items = append(items, item)
4✔
165
                }
166

167
                otherCount := 0
4✔
168
                if count, ok := aggregationS.(map[string]interface{})["sum_other_doc_count"].(float64); ok {
8✔
169
                        otherCount = int(count)
4✔
170
                }
4✔
171

172
                aggs = append(aggs, model.DeviceAggregation{
4✔
173
                        Name:       name,
4✔
174
                        Items:      items,
4✔
175
                        OtherCount: otherCount,
4✔
176
                })
4✔
177
        }
178
        return aggs, nil
8✔
179
}
180

181
// SearchDevices searches device data
182
func (app *app) SearchDevices(
183
        ctx context.Context,
184
        searchParams *model.SearchParams,
185
) ([]inventory.Device, int, error) {
17✔
186
        if err := app.mapSearchParams(ctx, searchParams); err != nil {
17✔
187
                return nil, 0, err
188
        }
189
        query, err := model.BuildQuery(*searchParams)
17✔
190
        if err != nil {
17✔
191
                return nil, 0, err
192
        }
193

194
        if searchParams.TenantID != "" {
34✔
195
                query = query.Must(model.M{
17✔
196
                        "term": model.M{
17✔
197
                                model.FieldNameTenantID: searchParams.TenantID,
17✔
198
                        },
17✔
199
                })
17✔
200
        }
17✔
201

202
        if len(searchParams.DeviceIDs) > 0 {
17✔
203
                query = query.Must(model.M{
204
                        "terms": model.M{
205
                                model.FieldNameID: searchParams.DeviceIDs,
206
                        },
207
                })
208
        }
209

210
        esRes, err := app.store.SearchDevices(ctx, query)
17✔
211
        if err != nil {
17✔
212
                return nil, 0, err
213
        }
214

215
        res, total, err := app.storeToInventoryDevs(ctx, searchParams.TenantID, esRes)
17✔
216
        if err != nil {
17✔
217
                return nil, 0, err
218
        }
219

220
        return res, total, err
17✔
221
}
222

223
func (app *app) mapAggregations(ctx context.Context, tenantID string,
224
        aggregations []model.AggregationTerm) error {
2✔
225
        attributes := make(inventory.DeviceAttributes, 0, len(aggregations))
2✔
226
        for i := range aggregations {
4✔
227
                attributes = append(attributes, inventory.DeviceAttribute{
2✔
228
                        Name:  aggregations[i].Attribute,
2✔
229
                        Scope: aggregations[i].Scope,
2✔
230
                })
2✔
231
        }
2✔
232
        attributes, err := app.mapper.MapInventoryAttributes(ctx, tenantID,
2✔
233
                attributes, false, true)
2✔
234
        if err == nil {
4✔
235
                for i, attr := range attributes {
4✔
236
                        aggregations[i].Attribute = attr.Name
2✔
237
                        aggregations[i].Scope = attr.Scope
2✔
238
                        if len(aggregations[i].Aggregations) > 0 {
2✔
239
                                err = app.mapAggregations(ctx, tenantID, aggregations[i].Aggregations)
240
                                if err != nil {
241
                                        break
242
                                }
243
                        }
244
                }
245
        }
246
        return err
2✔
247
}
248

249
func (app *app) mapSearchParams(ctx context.Context, searchParams *model.SearchParams) error {
19✔
250
        if len(searchParams.Filters) > 0 {
37✔
251
                attributes := make(inventory.DeviceAttributes, 0, len(searchParams.Attributes))
18✔
252
                for i := 0; i < len(searchParams.Filters); i++ {
36✔
253
                        attributes = append(attributes, inventory.DeviceAttribute{
18✔
254
                                Name:        searchParams.Filters[i].Attribute,
18✔
255
                                Scope:       searchParams.Filters[i].Scope,
18✔
256
                                Value:       searchParams.Filters[i].Value,
18✔
257
                                Description: &searchParams.Filters[i].Type,
18✔
258
                        })
18✔
259
                }
18✔
260
                attributes, err := app.mapper.MapInventoryAttributes(ctx, searchParams.TenantID,
18✔
261
                        attributes, false, true)
18✔
262
                if err != nil {
18✔
263
                        return err
264
                }
265
                searchParams.Filters = make([]model.FilterPredicate, 0, len(searchParams.Filters))
18✔
266
                for _, attribute := range attributes {
36✔
267
                        searchParams.Filters = append(searchParams.Filters, model.FilterPredicate{
18✔
268
                                Attribute: attribute.Name,
18✔
269
                                Scope:     attribute.Scope,
18✔
270
                                Value:     attribute.Value,
18✔
271
                                Type:      *attribute.Description,
18✔
272
                        })
18✔
273
                }
18✔
274
        }
275
        if len(searchParams.Attributes) > 0 {
19✔
276
                attributes := make(inventory.DeviceAttributes, 0, len(searchParams.Attributes))
277
                for i := 0; i < len(searchParams.Attributes); i++ {
278
                        attributes = append(attributes, inventory.DeviceAttribute{
279
                                Name:  searchParams.Attributes[i].Attribute,
280
                                Scope: searchParams.Attributes[i].Scope,
281
                        })
282
                }
283
                attributes, err := app.mapper.MapInventoryAttributes(ctx, searchParams.TenantID,
284
                        attributes, false, false)
285
                if err != nil {
286
                        return err
287
                }
288
                searchParams.Attributes = make([]model.SelectAttribute, 0, len(searchParams.Attributes))
289
                for _, attribute := range attributes {
290
                        searchParams.Attributes = append(searchParams.Attributes, model.SelectAttribute{
291
                                Attribute: attribute.Name,
292
                                Scope:     attribute.Scope,
293
                        })
294
                }
295
        }
296
        if len(searchParams.Sort) > 0 {
30✔
297
                attributes := make(inventory.DeviceAttributes, 0, len(searchParams.Sort))
11✔
298
                for i := 0; i < len(searchParams.Sort); i++ {
22✔
299
                        attributes = append(attributes, inventory.DeviceAttribute{
11✔
300
                                Name:        searchParams.Sort[i].Attribute,
11✔
301
                                Scope:       searchParams.Sort[i].Scope,
11✔
302
                                Description: &searchParams.Sort[i].Order,
11✔
303
                        })
11✔
304
                }
11✔
305
                attributes, err := app.mapper.MapInventoryAttributes(ctx, searchParams.TenantID,
11✔
306
                        attributes, false, false)
11✔
307
                if err != nil {
11✔
308
                        return err
309
                }
310
                searchParams.Sort = make([]model.SortCriteria, 0, len(searchParams.Attributes))
11✔
311
                for _, attribute := range attributes {
22✔
312
                        searchParams.Sort = append(searchParams.Sort, model.SortCriteria{
11✔
313
                                Attribute: attribute.Name,
11✔
314
                                Scope:     attribute.Scope,
11✔
315
                                Order:     *attribute.Description,
11✔
316
                        })
11✔
317
                }
11✔
318
        }
319

320
        return nil
19✔
321
}
322

323
// storeToInventoryDevs translates ES results directly to inventory devices
324
func (a *app) storeToInventoryDevs(
325
        ctx context.Context, tenantID string, storeRes map[string]interface{},
326
) ([]inventory.Device, int, error) {
17✔
327
        devs := []inventory.Device{}
17✔
328

17✔
329
        hitsM, ok := storeRes["hits"].(map[string]interface{})
17✔
330
        if !ok {
17✔
331
                return nil, 0, errors.New("can't process store hits map")
332
        }
333

334
        hitsTotalM, ok := hitsM["total"].(map[string]interface{})
17✔
335
        if !ok {
17✔
336
                return nil, 0, errors.New("can't process total hits struct")
337
        }
338

339
        total, ok := hitsTotalM["value"].(float64)
17✔
340
        if !ok {
17✔
341
                return nil, 0, errors.New("can't process total hits value")
342
        }
343

344
        hitsS, ok := hitsM["hits"].([]interface{})
17✔
345
        if !ok {
17✔
346
                return nil, 0, errors.New("can't process store hits slice")
347
        }
348

349
        for _, v := range hitsS {
46✔
350
                res, err := a.storeToInventoryDev(ctx, tenantID, v)
29✔
351
                if err != nil {
29✔
352
                        return nil, 0, err
353
                }
354

355
                devs = append(devs, *res)
29✔
356
        }
357

358
        return devs, int(total), nil
17✔
359
}
360

361
func (a *app) storeToInventoryDev(ctx context.Context, tenantID string,
362
        storeRes interface{}) (*inventory.Device, error) {
29✔
363
        resM, ok := storeRes.(map[string]interface{})
29✔
364
        if !ok {
29✔
365
                return nil, errors.New("can't process individual hit")
366
        }
367

368
        // if query has a 'fields' clause, use 'fields' instead of '_source'
369
        sourceM, ok := resM["_source"].(map[string]interface{})
29✔
370
        if !ok {
29✔
371
                sourceM, ok = resM["fields"].(map[string]interface{})
372
                if !ok {
373
                        return nil, errors.New("can't process hit's '_source' nor 'fields'")
374
                }
375
        }
376

377
        // if query has a 'fields' clause, all results will be arrays incl. device id, so extract it
378
        id, ok := sourceM["id"].(string)
29✔
379
        if !ok {
29✔
380
                idarr, ok := sourceM["id"].([]interface{})
381
                if !ok {
382
                        return nil, errors.New(
383
                                "can't parse device id as neither single value nor array",
384
                        )
385
                }
386

387
                id, ok = idarr[0].(string)
388
                if !ok {
389
                        return nil, errors.New(
390
                                "can't parse device id as neither single value nor array",
391
                        )
392
                }
393
        }
394

395
        ret := &inventory.Device{
29✔
396
                ID: inventory.DeviceID(id),
29✔
397
        }
29✔
398

29✔
399
        attrs := []inventory.DeviceAttribute{}
29✔
400

29✔
401
        for k, v := range sourceM {
197✔
402
                s, n, err := model.MaybeParseAttr(k)
168✔
403
                if err != nil {
168✔
404
                        return nil, err
405
                }
406

407
                if vArray, ok := v.([]interface{}); ok && len(vArray) == 1 {
278✔
408
                        v = vArray[0]
110✔
409
                }
110✔
410

411
                if n != "" {
278✔
412
                        a := inventory.DeviceAttribute{
110✔
413
                                Name:  model.Redot(n),
110✔
414
                                Scope: s,
110✔
415
                                Value: v,
110✔
416
                        }
110✔
417

110✔
418
                        if a.Scope == model.ScopeSystem &&
110✔
419
                                a.Name == model.AttrNameUpdatedAt {
110✔
420
                                ret.UpdatedTs = parseTime(v)
421
                        } else if a.Scope == model.ScopeSystem &&
110✔
422
                                a.Name == model.AttrNameCreatedAt {
110✔
423
                                ret.CreatedTs = parseTime(v)
424
                        }
425

426
                        attrs = append(attrs, a)
110✔
427
                }
428
        }
429

430
        attributes, err := a.mapper.ReverseInventoryAttributes(ctx, tenantID, attrs)
29✔
431
        if err != nil {
29✔
432
                return nil, err
433
        }
434
        ret.Attributes = attributes
29✔
435

29✔
436
        return ret, nil
29✔
437
}
438

439
func parseTime(v interface{}) time.Time {
440
        val, _ := v.(string)
441
        if t, err := time.Parse(time.RFC3339, val); err == nil {
442
                return t
443
        }
444
        return time.Time{}
445
}
446

447
func (app *app) GetSearchableInvAttrs(
448
        ctx context.Context,
449
        tid string,
450
) ([]model.FilterAttribute, error) {
451
        l := log.FromContext(ctx)
452

453
        index, err := app.store.GetDevicesIndexMapping(ctx, tid)
454
        if err != nil {
455
                return nil, err
456
        }
457

458
        // inventory attributes are under 'mappings.properties'
459
        mappings, ok := index["mappings"]
460
        if !ok {
461
                return nil, errors.New("can't parse index mappings")
462
        }
463

464
        mappingsM, ok := mappings.(map[string]interface{})
465
        if !ok {
466
                return nil, errors.New("can't parse index mappings")
467
        }
468

469
        props, ok := mappingsM["properties"]
470
        if !ok {
471
                return nil, errors.New("can't parse index properties")
472
        }
473

474
        propsM, ok := props.(map[string]interface{})
475
        if !ok {
476
                return nil, errors.New("can't parse index properties")
477
        }
478

479
        attrs := []inventory.DeviceAttribute{}
480
        for k := range propsM {
481
                s, n, err := model.MaybeParseAttr(k)
482

483
                if err != nil {
484
                        return nil, err
485
                }
486

487
                if n != "" {
488
                        attrs = append(attrs, inventory.DeviceAttribute{Name: n, Scope: s})
489
                }
490
        }
491
        attributes, err := app.mapper.ReverseInventoryAttributes(ctx, tid, attrs)
492
        if err != nil {
493
                return nil, err
494
        }
495

496
        ret := []model.FilterAttribute{}
497
        for _, attr := range attributes {
498
                ret = append(ret, model.FilterAttribute{Name: attr.Name, Scope: attr.Scope, Count: 1})
499
        }
500

501
        sort.Slice(ret, func(i, j int) bool {
502
                if ret[j].Scope > ret[i].Scope {
UNCOV
503
                        return true
UNCOV
504
                }
505

506
                if ret[j].Scope < ret[i].Scope {
507
                        return false
508
                }
509

510
                return ret[j].Name > ret[i].Name
511
        })
512

513
        l.Debugf("parsed searchable attributes %v\n", ret)
514

515
        return ret, nil
516
}
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