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

mendersoftware / reporting / 850601221

pending completion
850601221

Pull #138

gitlab-ci

GitHub
Merge pull request #130 from kjaskiewiczz/men-5912
Pull Request #138: Align staging with master

139 of 151 new or added lines in 5 files covered. (92.05%)

2 existing lines in 1 file now uncovered.

2964 of 3474 relevant lines covered (85.32%)

17.74 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 {
49✔
53
        mapper := mapping.NewMapper(ds)
49✔
54
        return &app{
49✔
55
                store:  store,
49✔
56
                mapper: mapper,
49✔
57
                ds:     ds,
49✔
58
        }
49✔
59
}
49✔
60

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

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

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

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

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

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

126
        return res, nil
6✔
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) {
40✔
133
        aggs := []model.DeviceAggregation{}
40✔
134
        for name, aggregationS := range aggregationsS {
116✔
135
                if _, ok := aggregationS.(map[string]interface{}); !ok {
132✔
136
                        continue
56✔
137
                }
138
                bucketsS, ok := aggregationS.(map[string]interface{})["buckets"].([]interface{})
20✔
139
                if !ok {
20✔
140
                        continue
×
141
                }
142
                items := make([]model.DeviceAggregationItem, 0, len(bucketsS))
20✔
143
                for _, bucket := range bucketsS {
48✔
144
                        bucketMap, ok := bucket.(map[string]interface{})
28✔
145
                        if !ok {
28✔
146
                                return nil, errors.New("can't process store bucket item")
×
147
                        }
×
148
                        key, ok := bucketMap["key"].(string)
28✔
149
                        if !ok {
28✔
150
                                return nil, errors.New("can't process store key attribute")
×
151
                        }
×
152
                        count, ok := bucketMap["doc_count"].(float64)
28✔
153
                        if !ok {
28✔
154
                                return nil, errors.New("can't process store doc_count attribute")
×
155
                        }
×
156
                        item := model.DeviceAggregationItem{
28✔
157
                                Key:   key,
28✔
158
                                Count: int(count),
28✔
159
                        }
28✔
160
                        subaggs, err := a.storeToDeviceAggregations(ctx, tenantID, bucketMap)
28✔
161
                        if err == nil && len(subaggs) > 0 {
36✔
162
                                item.Aggregations = subaggs
8✔
163
                        }
8✔
164
                        items = append(items, item)
28✔
165
                }
166

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

172
                aggs = append(aggs, model.DeviceAggregation{
20✔
173
                        Name:       name,
20✔
174
                        Items:      items,
20✔
175
                        OtherCount: otherCount,
20✔
176
                })
20✔
177
        }
178
        return aggs, nil
40✔
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) {
33✔
186
        if err := app.mapSearchParams(ctx, searchParams); err != nil {
33✔
187
                return nil, 0, err
×
188
        }
×
189
        query, err := model.BuildQuery(*searchParams)
33✔
190
        if err != nil {
35✔
191
                return nil, 0, err
2✔
192
        }
2✔
193

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

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

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

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

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

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

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

320
        return nil
39✔
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) {
29✔
327
        devs := []inventory.Device{}
29✔
328

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

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

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

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

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

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

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

361
func (a *app) storeToInventoryDev(ctx context.Context, tenantID string,
362
        storeRes interface{}) (*inventory.Device, error) {
35✔
363
        resM, ok := storeRes.(map[string]interface{})
35✔
364
        if !ok {
35✔
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{})
35✔
370
        if !ok {
37✔
371
                sourceM, ok = resM["fields"].(map[string]interface{})
2✔
372
                if !ok {
2✔
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)
35✔
379
        if !ok {
35✔
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{
35✔
396
                ID: inventory.DeviceID(id),
35✔
397
        }
35✔
398

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

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

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

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

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

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

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

35✔
436
        return ret, nil
35✔
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) {
4✔
451
        l := log.FromContext(ctx)
4✔
452

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

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

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

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

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

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

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

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

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

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

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

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

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

2✔
515
        return ret, nil
2✔
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