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

mendersoftware / reporting / 844901443

pending completion
844901443

Pull #134

gitlab-ci

Krzysztof Jaskiewicz
feat: index last device deployment status
Pull Request #134: feat: index last device deployment status

37 of 42 new or added lines in 2 files covered. (88.1%)

4 existing lines in 2 files now uncovered.

2830 of 3328 relevant lines covered (85.04%)

16.82 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 {
48✔
53
        mapper := mapping.NewMapper(ds)
48✔
54
        return &app{
48✔
55
                store:  store,
48✔
56
                mapper: mapper,
48✔
57
                ds:     ds,
48✔
58
        }
48✔
59
}
48✔
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) {
4✔
80
        searchParams := &model.SearchParams{
4✔
81
                Filters:  aggregateParams.Filters,
4✔
82
                Groups:   aggregateParams.Groups,
4✔
83
                TenantID: aggregateParams.TenantID,
4✔
84
        }
4✔
85
        if err := app.mapSearchParams(ctx, searchParams); err != nil {
4✔
86
                return nil, err
87
        }
88
        query, err := model.BuildQuery(*searchParams)
4✔
89
        if err != nil {
4✔
90
                return nil, err
91
        }
92
        if searchParams.TenantID != "" {
8✔
93
                query = query.Must(model.M{
4✔
94
                        "term": model.M{
4✔
95
                                model.FieldNameTenantID: searchParams.TenantID,
4✔
96
                        },
4✔
97
                })
4✔
98
        }
4✔
99

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

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

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

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

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

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

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

202
        if len(searchParams.DeviceIDs) > 0 {
14✔
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)
10✔
211
        if err != nil {
12✔
212
                return nil, 0, err
2✔
213
        }
2✔
214

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

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

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

249
func (app *app) mapSearchParams(ctx context.Context, searchParams *model.SearchParams) error {
16✔
250
        if len(searchParams.Filters) > 0 {
26✔
251
                attributes := make(inventory.DeviceAttributes, 0, len(searchParams.Attributes))
10✔
252
                for i := 0; i < len(searchParams.Filters); i++ {
20✔
253
                        attributes = append(attributes, inventory.DeviceAttribute{
10✔
254
                                Name:        searchParams.Filters[i].Attribute,
10✔
255
                                Scope:       searchParams.Filters[i].Scope,
10✔
256
                                Value:       searchParams.Filters[i].Value,
10✔
257
                                Description: &searchParams.Filters[i].Type,
10✔
258
                        })
10✔
259
                }
10✔
260
                attributes, err := app.mapper.MapInventoryAttributes(ctx, searchParams.TenantID,
10✔
261
                        attributes, false, true)
10✔
262
                if err != nil {
10✔
263
                        return err
264
                }
265
                searchParams.Filters = make([]model.FilterPredicate, 0, len(searchParams.Filters))
10✔
266
                for _, attribute := range attributes {
20✔
267
                        searchParams.Filters = append(searchParams.Filters, model.FilterPredicate{
10✔
268
                                Attribute: attribute.Name,
10✔
269
                                Scope:     attribute.Scope,
10✔
270
                                Value:     attribute.Value,
10✔
271
                                Type:      *attribute.Description,
10✔
272
                        })
10✔
273
                }
10✔
274
        }
275
        if len(searchParams.Attributes) > 0 {
18✔
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 {
20✔
297
                attributes := make(inventory.DeviceAttributes, 0, len(searchParams.Sort))
4✔
298
                for i := 0; i < len(searchParams.Sort); i++ {
8✔
299
                        attributes = append(attributes, inventory.DeviceAttribute{
4✔
300
                                Name:        searchParams.Sort[i].Attribute,
4✔
301
                                Scope:       searchParams.Sort[i].Scope,
4✔
302
                                Description: &searchParams.Sort[i].Order,
4✔
303
                        })
4✔
304
                }
4✔
305
                attributes, err := app.mapper.MapInventoryAttributes(ctx, searchParams.TenantID,
4✔
306
                        attributes, false, false)
4✔
307
                if err != nil {
4✔
308
                        return err
309
                }
310
                searchParams.Sort = make([]model.SortCriteria, 0, len(searchParams.Attributes))
4✔
311
                for _, attribute := range attributes {
8✔
312
                        searchParams.Sort = append(searchParams.Sort, model.SortCriteria{
4✔
313
                                Attribute: attribute.Name,
4✔
314
                                Scope:     attribute.Scope,
4✔
315
                                Order:     *attribute.Description,
4✔
316
                        })
4✔
317
                }
4✔
318
        }
319

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4✔
436
        return ret, nil
4✔
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