forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
policy_resolver.go
191 lines (174 loc) · 6.46 KB
/
policy_resolver.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
// Copyright (c) 2016-2017 Tigera, Inc. All rights reserved.
//
// 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 calc
import (
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/felix/dispatcher"
"github.com/projectcalico/felix/multidict"
"github.com/projectcalico/libcalico-go/lib/backend/api"
"github.com/projectcalico/libcalico-go/lib/backend/model"
"github.com/projectcalico/libcalico-go/lib/set"
)
var (
gaugeNumActiveEndpoints = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "felix_active_local_endpoints",
Help: "Number of active endpoints on this host.",
})
gaugeNumActivePolicies = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "felix_active_local_policies",
Help: "Number of active policies on this host.",
})
)
func init() {
prometheus.MustRegister(gaugeNumActiveEndpoints)
prometheus.MustRegister(gaugeNumActivePolicies)
}
// PolicyResolver marries up the active policies with local endpoints and
// calculates the complete, ordered set of policies that apply to each endpoint.
// As policies and endpoints are added/removed/updated, it emits events
// via the PolicyResolverCallbacks with the updated set of matching policies.
//
// The PolicyResolver doesn't figure out which policies are currently active, it
// expects to be told via its OnPolicyMatch(Stopped) methods which policies match
// which endpoints. The ActiveRulesCalculator does that calculation.
type PolicyResolver struct {
policyIDToEndpointIDs multidict.IfaceToIface
endpointIDToPolicyIDs multidict.IfaceToIface
sortedTierData *tierInfo
endpoints map[model.Key]interface{}
dirtyEndpoints set.Set
sortRequired bool
policySorter *PolicySorter
Callbacks PolicyResolverCallbacks
InSync bool
}
type PolicyResolverCallbacks interface {
OnEndpointTierUpdate(endpointKey model.Key, endpoint interface{}, filteredTiers []tierInfo)
}
func NewPolicyResolver() *PolicyResolver {
return &PolicyResolver{
policyIDToEndpointIDs: multidict.NewIfaceToIface(),
endpointIDToPolicyIDs: multidict.NewIfaceToIface(),
sortedTierData: NewTierInfo("default"),
endpoints: make(map[model.Key]interface{}),
dirtyEndpoints: set.New(),
policySorter: NewPolicySorter(),
}
}
func (pr *PolicyResolver) RegisterWith(allUpdDispatcher, localEndpointDispatcher *dispatcher.Dispatcher) {
allUpdDispatcher.Register(model.PolicyKey{}, pr.OnUpdate)
localEndpointDispatcher.Register(model.WorkloadEndpointKey{}, pr.OnUpdate)
localEndpointDispatcher.Register(model.HostEndpointKey{}, pr.OnUpdate)
localEndpointDispatcher.RegisterStatusHandler(pr.OnDatamodelStatus)
}
func (pr *PolicyResolver) OnUpdate(update api.Update) (filterOut bool) {
policiesDirty := false
switch key := update.Key.(type) {
case model.WorkloadEndpointKey, model.HostEndpointKey:
if update.Value != nil {
pr.endpoints[key] = update.Value
} else {
delete(pr.endpoints, key)
}
pr.dirtyEndpoints.Add(key)
gaugeNumActiveEndpoints.Set(float64(len(pr.endpoints)))
case model.PolicyKey:
log.Debugf("Policy update: %v", key)
policiesDirty = pr.policySorter.OnUpdate(update)
if policiesDirty {
pr.markEndpointsMatchingPolicyDirty(key)
}
}
pr.sortRequired = pr.sortRequired || policiesDirty
pr.maybeFlush()
gaugeNumActivePolicies.Set(float64(pr.policyIDToEndpointIDs.Len()))
return
}
func (pr *PolicyResolver) OnDatamodelStatus(status api.SyncStatus) {
if status == api.InSync {
pr.InSync = true
pr.maybeFlush()
}
}
func (pr *PolicyResolver) refreshSortOrder() {
pr.sortedTierData = pr.policySorter.Sorted()
pr.sortRequired = false
log.Debugf("New sort order: %v", pr.sortedTierData)
}
func (pr *PolicyResolver) markEndpointsMatchingPolicyDirty(polKey model.PolicyKey) {
log.Debugf("Marking all endpoints matching %v dirty", polKey)
pr.policyIDToEndpointIDs.Iter(polKey, func(epID interface{}) {
pr.dirtyEndpoints.Add(epID)
})
}
func (pr *PolicyResolver) OnPolicyMatch(policyKey model.PolicyKey, endpointKey interface{}) {
log.Debugf("Storing policy match %v -> %v", policyKey, endpointKey)
pr.policyIDToEndpointIDs.Put(policyKey, endpointKey)
pr.endpointIDToPolicyIDs.Put(endpointKey, policyKey)
pr.dirtyEndpoints.Add(endpointKey)
pr.maybeFlush()
}
func (pr *PolicyResolver) OnPolicyMatchStopped(policyKey model.PolicyKey, endpointKey interface{}) {
log.Debugf("Deleting policy match %v -> %v", policyKey, endpointKey)
pr.policyIDToEndpointIDs.Discard(policyKey, endpointKey)
pr.endpointIDToPolicyIDs.Discard(endpointKey, policyKey)
pr.dirtyEndpoints.Add(endpointKey)
pr.maybeFlush()
}
func (pr *PolicyResolver) maybeFlush() {
if !pr.InSync {
log.Debugf("Not in sync, skipping flush")
return
}
if pr.sortRequired {
pr.refreshSortOrder()
}
pr.dirtyEndpoints.Iter(pr.sendEndpointUpdate)
pr.dirtyEndpoints = set.New()
}
func (pr *PolicyResolver) sendEndpointUpdate(endpointID interface{}) error {
log.Debugf("Sending tier update for endpoint %v", endpointID)
endpoint, ok := pr.endpoints[endpointID.(model.Key)]
if !ok {
log.Debugf("Endpoint is unknown, sending nil update")
pr.Callbacks.OnEndpointTierUpdate(endpointID.(model.Key),
nil, []tierInfo{})
return nil
}
applicableTiers := []tierInfo{}
tier := pr.sortedTierData
tierMatches := false
filteredTier := tierInfo{
Name: tier.Name,
Order: tier.Order,
}
for _, polKV := range tier.OrderedPolicies {
log.Debugf("Checking if policy %v matches %v", polKV.Key, endpointID)
if pr.endpointIDToPolicyIDs.Contains(endpointID, polKV.Key) {
log.Debugf("Policy %v matches %v", polKV.Key, endpointID)
tierMatches = true
filteredTier.OrderedPolicies = append(filteredTier.OrderedPolicies,
polKV)
}
}
if tierMatches {
log.Debugf("Tier %v matches %v", tier.Name, endpointID)
applicableTiers = append(applicableTiers, filteredTier)
}
log.Debugf("Endpoint tier update: %v -> %v", endpointID, applicableTiers)
pr.Callbacks.OnEndpointTierUpdate(endpointID.(model.Key),
endpoint, applicableTiers)
return nil
}