-
Notifications
You must be signed in to change notification settings - Fork 72
/
api_policy_mapper.go
101 lines (90 loc) · 2.43 KB
/
api_policy_mapper.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
package api_v0
import (
"fmt"
"policy-server/api"
"policy-server/store"
"code.cloudfoundry.org/cf-networking-helpers/marshal"
)
type policyMapper struct {
Unmarshaler marshal.Unmarshaler
Marshaler marshal.Marshaler
Validator validator
}
func NewMapper(unmarshaler marshal.Unmarshaler, marshaler marshal.Marshaler, validator validator) api.PolicyMapper {
return &policyMapper{
Unmarshaler: unmarshaler,
Marshaler: marshaler,
Validator: validator,
}
}
func (p *policyMapper) AsStorePolicy(bytes []byte) ([]store.Policy, error) {
payload := &Policies{}
err := p.Unmarshaler.Unmarshal(bytes, payload)
if err != nil {
return nil, fmt.Errorf("unmarshal json: %s", err)
}
err = p.Validator.ValidatePolicies(payload.Policies)
if err != nil {
return nil, fmt.Errorf("validate policies: %s", err)
}
storePolicies := []store.Policy{}
for _, policy := range payload.Policies {
storePolicies = append(storePolicies, policy.asStorePolicy())
}
return storePolicies, nil
}
func (p *policyMapper) AsBytes(storePolicies []store.Policy) ([]byte, error) {
// convert store.Policy to api_v0.Policy
apiPolicies := []Policy{}
for _, policy := range storePolicies {
policyToAdd, canMap := mapStorePolicy(policy)
if canMap {
apiPolicies = append(apiPolicies, policyToAdd)
}
}
// convert api_v0.Policy payload to bytes
payload := &Policies{
TotalPolicies: len(apiPolicies),
Policies: apiPolicies,
}
bytes, err := p.Marshaler.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshal json: %s", err)
}
return bytes, nil
}
func (p *Policy) asStorePolicy() store.Policy {
return store.Policy{
Source: store.Source{
ID: p.Source.ID,
Tag: p.Source.Tag,
},
Destination: store.Destination{
ID: p.Destination.ID,
Tag: p.Destination.Tag,
Protocol: p.Destination.Protocol,
Port: p.Destination.Port,
Ports: store.Ports{
Start: p.Destination.Port,
End: p.Destination.Port,
},
},
}
}
func mapStorePolicy(storePolicy store.Policy) (Policy, bool) {
if storePolicy.Destination.Ports.Start != storePolicy.Destination.Ports.End {
return Policy{}, false
}
return Policy{
Source: Source{
ID: storePolicy.Source.ID,
Tag: storePolicy.Source.Tag,
},
Destination: Destination{
ID: storePolicy.Destination.ID,
Tag: storePolicy.Destination.Tag,
Protocol: storePolicy.Destination.Protocol,
Port: storePolicy.Destination.Ports.Start,
},
}, true
}