-
Notifications
You must be signed in to change notification settings - Fork 51
/
supervisor.go
252 lines (203 loc) · 7.22 KB
/
supervisor.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
package supervisor
import (
"context"
"errors"
"fmt"
"sync"
"go.aporeto.io/trireme-lib/collector"
"go.aporeto.io/trireme-lib/common"
"go.aporeto.io/trireme-lib/controller/constants"
"go.aporeto.io/trireme-lib/controller/internal/enforcer"
"go.aporeto.io/trireme-lib/controller/internal/supervisor/iptablesctrl"
provider "go.aporeto.io/trireme-lib/controller/pkg/aclprovider"
"go.aporeto.io/trireme-lib/controller/pkg/fqconfig"
"go.aporeto.io/trireme-lib/controller/pkg/packetprocessor"
"go.aporeto.io/trireme-lib/monitor/extractors"
"go.aporeto.io/trireme-lib/policy"
"go.aporeto.io/trireme-lib/utils/cache"
"go.uber.org/zap"
)
type cacheData struct {
version int
ips policy.ExtendedMap
mark string
tcpPorts string
udpPorts string
username string
containerInfo *policy.PUInfo
}
// Config is the structure holding all information about the supervisor
type Config struct {
// mode is LocalServer or RemoteContainer
mode constants.ModeType
// versionTracker tracks the current version of the ACLs
versionTracker cache.DataStore
// impl is the packet filter implementation
impl Implementor
// collector is the stats collector implementation
collector collector.EventCollector
// filterQueue is the filterqueue parameters
filterQueue *fqconfig.FilterQueue
// excludeIPs are the IPs that must be always excluded
excludedIPs []string
// triremeNetworks are the target networks where Trireme is implemented
triremeNetworks []string
// service is an external packet service
service packetprocessor.PacketProcessor
sync.Mutex
}
// NewSupervisor will create a new connection supervisor that uses IPTables
// to redirect specific packets to userspace. It instantiates multiple data stores
// to maintain efficient mappings between contextID, policy and IP addresses. This
// simplifies the lookup operations at the expense of memory.
func NewSupervisor(collector collector.EventCollector, enforcerInstance enforcer.Enforcer, mode constants.ModeType, networks []string, p packetprocessor.PacketProcessor) (*Config, error) {
if collector == nil || enforcerInstance == nil {
return nil, errors.New("Invalid parameters")
}
filterQueue := enforcerInstance.GetFilterQueue()
if filterQueue == nil {
return nil, errors.New("enforcer filter queues cannot be nil")
}
impl, err := iptablesctrl.NewInstance(filterQueue, mode)
if err != nil {
return nil, fmt.Errorf("unable to initialize supervisor controllers: %s", err)
}
if len(networks) == 0 {
networks = []string{"0.0.0.0/1", "128.0.0.0/1"}
}
return &Config{
mode: mode,
impl: impl,
versionTracker: cache.NewCache("SupVersionTracker"),
collector: collector,
filterQueue: filterQueue,
excludedIPs: []string{},
triremeNetworks: networks,
service: p,
}, nil
}
// Supervise creates a mapping between an IP address and the corresponding labels.
// it invokes the various handlers that process the parameter policy.
func (s *Config) Supervise(contextID string, pu *policy.PUInfo) error {
if pu == nil || pu.Policy == nil || pu.Runtime == nil {
return errors.New("Invalid PU or policy info")
}
_, err := s.versionTracker.Get(contextID)
if err != nil {
// ContextID is not found in Cache, New PU: Do create.
return s.doCreatePU(contextID, pu)
}
// Context already in the cache. Just run update
return s.doUpdatePU(contextID, pu)
}
// Unsupervise removes the mapping from cache and cleans up the iptable rules. ALL
// remove operations will print errors by they don't return error. We want to force
// as much cleanup as possible to avoid stale state
func (s *Config) Unsupervise(contextID string) error {
s.Lock()
defer s.Unlock()
data, err := s.versionTracker.Get(contextID)
if err != nil {
return fmt.Errorf("cannot find policy version: %s", err)
}
cfg := data.(*cacheData)
port := cfg.containerInfo.Policy.ServicesListeningPort()
// If local server, delete pu specific chains in Trireme/NetworkSvc/Hostmode chains.
puType := extractors.GetPuType(cfg.containerInfo.Runtime)
if err := s.impl.DeleteRules(cfg.version, contextID, cfg.tcpPorts, cfg.udpPorts, cfg.mark, cfg.username, port, puType, cfg.containerInfo.Policy.ExcludedNetworks()); err != nil {
zap.L().Warn("Some rules were not deleted during unsupervise", zap.Error(err))
}
if err := s.versionTracker.Remove(contextID); err != nil {
zap.L().Warn("Failed to clean the rule version cache", zap.Error(err))
}
return nil
}
// Run starts the supervisor
func (s *Config) Run(ctx context.Context) error {
s.Lock()
defer s.Unlock()
if err := s.impl.Run(ctx); err != nil {
return fmt.Errorf("unable to start the implementer: %s", err)
}
if err := s.impl.SetTargetNetworks([]string{}, s.triremeNetworks); err != nil {
return err
}
if s.service != nil {
s.service.Initialize(s.filterQueue, s.impl.ACLProvider())
}
return nil
}
// CleanUp implements the cleanup interface
func (s *Config) CleanUp() error {
s.Lock()
defer s.Unlock()
return s.impl.CleanUp()
}
// SetTargetNetworks sets the target networks of the supervisor
func (s *Config) SetTargetNetworks(networks []string) error {
s.Lock()
defer s.Unlock()
// If there are no target networks, capture all traffic
if len(networks) == 0 {
networks = []string{"0.0.0.0/1", "128.0.0.0/1"}
}
if err := s.impl.SetTargetNetworks(s.triremeNetworks, networks); err != nil {
return err
}
s.triremeNetworks = networks
return nil
}
// ACLProvider returns the ACL provider used by the supervisor that can be
// shared with other entities.
func (s *Config) ACLProvider() provider.IptablesProvider {
return s.impl.ACLProvider()
}
func (s *Config) doCreatePU(contextID string, pu *policy.PUInfo) error {
s.Lock()
tcpPorts, udpPorts := common.ConvertServicesToProtocolPortList(pu.Runtime.Options().Services)
c := &cacheData{
version: 0,
ips: pu.Policy.IPAddresses(),
mark: pu.Runtime.Options().CgroupMark,
tcpPorts: tcpPorts,
udpPorts: udpPorts,
username: pu.Runtime.Options().UserID,
containerInfo: pu,
}
// Version the policy so that we can do hitless policy changes
s.versionTracker.AddOrUpdate(contextID, c)
// Configure the rules
if err := s.impl.ConfigureRules(c.version, contextID, pu); err != nil {
// Revert what you can since we have an error - it will fail most likely
s.Unlock()
s.Unsupervise(contextID) // nolint
return err
}
s.Unlock()
return nil
}
// UpdatePU creates a mapping between an IP address and the corresponding labels
//and the invokes the various handlers that process all policies.
func (s *Config) doUpdatePU(contextID string, pu *policy.PUInfo) error {
s.Lock()
data, err := s.versionTracker.LockedModify(contextID, revert, 1)
if err != nil {
return fmt.Errorf("unable to find pu %s in cache: %s", contextID, err)
}
c := data.(*cacheData)
if err := s.impl.UpdateRules(c.version, contextID, pu, c.containerInfo); err != nil {
// Try to clean up, even though this is fatal and it will most likely fail
s.Unlock()
s.Unsupervise(contextID) // nolint
return err
}
// Updated the policy in the cached processing unit.
c.containerInfo.Policy = pu.Policy
s.Unlock()
return nil
}
func revert(a, b interface{}) interface{} {
entry := a.(*cacheData)
entry.version = entry.version ^ 1
return entry
}