forked from intelsdi-x/snap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
269 lines (239 loc) · 6.23 KB
/
node.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cpolicy
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"sync"
"github.com/intelsdi-x/snap/core/ctypes"
"github.com/intelsdi-x/snap/pkg/ctree"
)
type ProcessingErrors struct {
errors []error
mutex *sync.Mutex
}
func NewProcessingErrors() *ProcessingErrors {
return &ProcessingErrors{
errors: []error{},
mutex: &sync.Mutex{},
}
}
func (p *ProcessingErrors) Errors() []error {
p.mutex.Lock()
defer p.mutex.Unlock()
return p.errors
}
func (p *ProcessingErrors) HasErrors() bool {
return len(p.errors) > 0
}
func (p *ProcessingErrors) AddError(e error) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.errors = append(p.errors, e)
}
type ConfigPolicyNode struct {
rules map[string]Rule
mutex *sync.Mutex
}
func NewPolicyNode() *ConfigPolicyNode {
return &ConfigPolicyNode{
rules: make(map[string]Rule),
mutex: &sync.Mutex{},
}
}
// UnmarshalJSON unmarshals JSON into a ConfigPolicyNode
func (c *ConfigPolicyNode) UnmarshalJSON(data []byte) error {
m := map[string]interface{}{}
decoder := json.NewDecoder(bytes.NewReader(data))
if err := decoder.Decode(&m); err != nil {
return err
}
if n, ok := m["PolicyNode"]; ok {
if pn, ok := n.(map[string]interface{}); ok {
if rs, ok := pn["rules"]; ok {
if rules, ok := rs.(map[string]interface{}); ok {
addRulesToConfigPolicyNode(rules, c)
}
}
}
}
return nil
}
func (c *ConfigPolicyNode) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Rules map[string]Rule `json:"rules"`
}{
Rules: c.rules,
})
}
func (c *ConfigPolicyNode) GobEncode() ([]byte, error) {
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
if err := encoder.Encode(&c.rules); err != nil {
return nil, err
}
return w.Bytes(), nil
}
func (c *ConfigPolicyNode) GobDecode(buf []byte) error {
c.mutex = &sync.Mutex{}
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
return decoder.Decode(&c.rules)
}
// Adds a rule to this policy node
func (p *ConfigPolicyNode) Add(rules ...Rule) {
p.mutex.Lock()
defer p.mutex.Unlock()
for _, r := range rules {
p.rules[r.Key()] = r
}
}
type RuleTable struct {
Name string
Type string
Default interface{}
Required bool
Minimum interface{}
Maximum interface{}
}
func (p *ConfigPolicyNode) RulesAsTable() []RuleTable {
p.mutex.Lock()
defer p.mutex.Unlock()
rt := make([]RuleTable, 0, len(p.rules))
for _, r := range p.rules {
rt = append(rt, RuleTable{
Name: r.Key(),
Type: r.Type(),
Default: r.Default(),
Required: r.Required(),
Minimum: r.Minimum(),
Maximum: r.Maximum(),
})
}
return rt
}
func (c *ConfigPolicyNode) HasRules() bool {
if len(c.rules) > 0 {
return true
}
return false
}
// Validates and returns a processed policy node or nil and error if validation has failed
func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) {
c.mutex.Lock()
defer c.mutex.Unlock()
pErrors := NewProcessingErrors()
// Loop through each rule and process
for key, rule := range c.rules {
// items exists for rule
if cv, ok := m[key]; ok {
// Validate versus matching data
e := rule.Validate(cv)
if e != nil {
pErrors.AddError(e)
}
} else {
// If it was required add error
if rule.Required() {
e := errors.New(fmt.Sprintf("required key missing (%s)", key))
pErrors.AddError(e)
} else {
// If default returns we should add it
cv := rule.Default()
if cv != nil {
m[key] = cv
}
}
}
}
if pErrors.HasErrors() {
return nil, pErrors
}
return &m, pErrors
}
// Merges a ConfigPolicyNode on top of this one (overwriting items where it occurs).
func (c ConfigPolicyNode) Merge(n ctree.Node) ctree.Node {
// Because Add only allows the ConfigPolicyNode type we
// are safe to convert ctree.Node interface to ConfigPolicyNode
cd := n.(*ConfigPolicyNode)
// For the rules in the passed ConfigPolicyNode(converted) add each rule to
// this ConfigPolicyNode overwriting where needed.
for _, r := range cd.rules {
c.Add(r)
}
// Return modified version of ConfigPolicyNode(as ctree.Node)
return c
}
// addRulesToConfigPolicyNode accepts a map of empty interfaces that will be
// marshalled into rules which will be added to the ConfigPolicyNode provided
// as the second argument. This function is called used by the UnmarshalJSON
// for ConfigPolicy and ConfigPolicyNode.
func addRulesToConfigPolicyNode(rules map[string]interface{}, cpn *ConfigPolicyNode) error {
for k, rule := range rules {
if rule, ok := rule.(map[string]interface{}); ok {
req, _ := rule["required"].(bool)
switch rule["type"] {
case "integer":
r, _ := NewIntegerRule(k, req)
if d, ok := rule["default"]; ok {
// json encoding an int results in a float when decoding
def_, _ := d.(float64)
def := int(def_)
r.default_ = &def
}
if m, ok := rule["minimum"]; ok {
min_, _ := m.(float64)
min := int(min_)
r.minimum = &min
}
if m, ok := rule["maximum"]; ok {
max_, _ := m.(float64)
max := int(max_)
r.maximum = &max
}
cpn.Add(r)
case "string":
r, _ := NewStringRule(k, req)
if d, ok := rule["default"]; ok {
def, _ := d.(string)
if def != "" {
r.default_ = &def
}
}
cpn.Add(r)
case "float":
r, _ := NewFloatRule(k, req)
if d, ok := rule["default"]; ok {
def, _ := d.(float64)
r.default_ = &def
}
if m, ok := rule["minimum"]; ok {
min, _ := m.(float64)
r.minimum = &min
}
if m, ok := rule["maximum"]; ok {
max, _ := m.(float64)
r.maximum = &max
}
cpn.Add(r)
default:
return errors.New("unknown type")
}
}
}
return nil
}