/
inventory.go
72 lines (58 loc) · 1.46 KB
/
inventory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package inventory
import (
"encoding/json"
"fmt"
"sync"
)
// Limits
const (
MaxKeyLen = 375
)
// Items ...
type Items map[string]Item
// Item ...
type Item map[string]interface{}
// Inventory is the data type for inventory data produced by an integration data
// source and emitted to the agent's inventory data store.
type Inventory struct {
items Items
lock sync.Mutex
}
// MarshalJSON Marshals the items map into a JSON
func (i *Inventory) MarshalJSON() ([]byte, error) {
return json.Marshal(i.items)
}
// SetItem stores a value into the inventory, updating if already exists an item with the same key
// key is limited to 375 characters.
func (i *Inventory) SetItem(key string, field string, value interface{}) error {
if len(key) > MaxKeyLen {
return fmt.Errorf("maximum inventory key length is %d, current key %s has %d characters", MaxKeyLen, key, len(key))
}
i.lock.Lock()
defer i.lock.Unlock()
if _, ok := i.items[key]; ok {
i.items[key][field] = value
} else {
i.items[key] = Item{field: value}
}
return nil
}
// Item returns stored item
func (i *Inventory) Item(key string) (item Item, exists bool) {
item, exists = i.items[key]
return
}
// Items returns all stored items
func (i *Inventory) Items() Items {
return i.items
}
// Len returns the number of elements stored in Inventory.
func (i *Inventory) Len() int {
return len(i.items)
}
// New creates new inventory.
func New() *Inventory {
return &Inventory{
items: make(Items),
}
}