-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
cache.go
347 lines (306 loc) · 10.3 KB
/
cache.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright 2019 Authors of Cilium
//
// 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 loader
import (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/cilium/cilium/common"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/datapath"
"github.com/cilium/cilium/pkg/defaults"
"github.com/cilium/cilium/pkg/elf"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/serializer"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
var (
once sync.Once
// templateCache is the cache of pre-compiled datapaths.
templateCache *objectCache
templateWatcherQueueSize = 10
ignoredELFPrefixes = []string{
"2/", // Calls within the endpoint
"HOST_IP", // Global
"ROUTER_IP", // Global
"cilium_ct", // All CT maps, including local
"cilium_events", // Global
"cilium_ipcache", // Global
"cilium_lb", // Global
"cilium_lxc", // Global
"cilium_metrics", // Global
"cilium_proxy", // Global
"cilium_tunnel", // Global
"cilium_policy", // Global
"from-container", // Prog name
}
)
// Init initializes the datapath cache with base program hashes derived from
// the LocalNodeConfiguration.
func Init(dp datapath.Datapath, nodeCfg *datapath.LocalNodeConfiguration) {
once.Do(func() {
templateCache = NewObjectCache(dp, nodeCfg)
ignorePrefixes := ignoredELFPrefixes
if !option.Config.EnableIPv4 {
ignorePrefixes = append(ignorePrefixes, "LXC_IPV4")
}
if !option.Config.EnableIPv6 {
ignorePrefixes = append(ignorePrefixes, "LXC_IP_")
}
elf.IgnoreSymbolPrefixes(ignorePrefixes)
})
templateCache.Update(nodeCfg)
}
// RestoreTemplates populates the object cache from templates on the filesystem
// at the specified path.
func RestoreTemplates(stateDir string) error {
// Simplest implementation: Just garbage-collect everything.
// In future we should make this smarter.
path := filepath.Join(stateDir, defaults.TemplatesDir)
err := os.RemoveAll(path)
if err == nil || os.IsNotExist(err) {
return nil
}
return &os.PathError{
Op: "failed to remove old BPF templates",
Path: path,
Err: err,
}
}
// objectCache is a map from a hash of the datapath to the path on the
// filesystem where its corresponding BPF object file exists.
type objectCache struct {
lock.Mutex
datapath.Datapath
workingDirectory string
baseHash *datapathHash
// newTemplates is notified whenever template is added to the objectCache.
newTemplates chan string
templateWatcherDone chan struct{}
// toPath maps a hash to the filesystem path of the corresponding object.
toPath map[string]string
// compileQueue maps a hash to a queue which ensures that only one
// attempt is made concurrently to compile the corresponding template.
compileQueue map[string]*serializer.FunctionQueue
}
func newObjectCache(dp datapath.Datapath, nodeCfg *datapath.LocalNodeConfiguration, workingDir string) *objectCache {
oc := &objectCache{
Datapath: dp,
workingDirectory: workingDir,
newTemplates: make(chan string, templateWatcherQueueSize),
templateWatcherDone: make(chan struct{}),
toPath: make(map[string]string),
compileQueue: make(map[string]*serializer.FunctionQueue),
}
oc.Update(nodeCfg)
controller.NewManager().UpdateController("template-dir-watcher",
controller.ControllerParams{
DoFunc: oc.watchTemplatesDirectory,
// No run interval but needs to re-run on errors.
})
return oc
}
// NewObjectCache creates a new cache for datapath objects, basing the hash
// upon the configuration of the datapath and the specified node configuration.
func NewObjectCache(dp datapath.Datapath, nodeCfg *datapath.LocalNodeConfiguration) *objectCache {
return newObjectCache(dp, nodeCfg, option.Config.StateDir)
}
// Update may be called to update the base hash for configuration of datapath
// configuration that applies across the node.
func (o *objectCache) Update(nodeCfg *datapath.LocalNodeConfiguration) {
newHash := hashDatapath(o.Datapath, nodeCfg, nil, nil)
o.Lock()
defer o.Unlock()
o.baseHash = newHash
}
// serialize finds the channel that serializes builds against the same hash.
// Returns the channel and whether or not the caller needs to compile the
// datapath for this hash.
func (o *objectCache) serialize(hash string) (fq *serializer.FunctionQueue, found bool) {
o.Lock()
defer o.Unlock()
fq, compiled := o.compileQueue[hash]
if !compiled {
fq = serializer.NewFunctionQueue(1)
o.compileQueue[hash] = fq
}
return fq, compiled
}
func (o *objectCache) lookup(hash string) (string, bool) {
o.Lock()
defer o.Unlock()
path, exists := o.toPath[hash]
return path, exists
}
func (o *objectCache) insert(hash, objectPath string) error {
o.Lock()
defer o.Unlock()
o.toPath[hash] = objectPath
scopedLog := log.WithField(logfields.Path, objectPath)
select {
case o.newTemplates <- objectPath:
case <-o.templateWatcherDone:
// This means that the controller was stopped and Cilium is
// shutting down; don't bother complaining too loudly.
scopedLog.Debug("Failed to watch for template filesystem changes")
default:
// Unusual case; send on channel was blocked.
scopedLog.Warn("Failed to watch for template filesystem changes")
}
return nil
}
func (o *objectCache) delete(hash string) {
o.Lock()
defer o.Unlock()
delete(o.toPath, hash)
delete(o.compileQueue, hash)
}
// build attempts to compile and cache a datapath template object file
// corresponding to the specified endpoint configuration.
func (o *objectCache) build(ctx context.Context, cfg *templateCfg, hash string) error {
templatePath := filepath.Join(o.workingDirectory, defaults.TemplatesDir, hash)
headerPath := filepath.Join(templatePath, common.CHeaderFileName)
objectPath := filepath.Join(templatePath, endpointObj)
if err := os.MkdirAll(templatePath, defaults.StateDirRights); err != nil {
return &os.PathError{
Op: "failed to create template directory",
Path: templatePath,
Err: err,
}
}
f, err := os.Create(headerPath)
if err != nil {
return &os.PathError{
Op: "failed to open template header for writing",
Path: headerPath,
Err: err,
}
}
if err = o.Datapath.WriteEndpointConfig(f, cfg); err != nil {
return &os.PathError{
Op: "failed to write template header",
Path: headerPath,
Err: err,
}
}
cfg.stats.bpfCompilation.Start()
err = compileTemplate(ctx, templatePath)
cfg.stats.bpfCompilation.End(err == nil)
if err != nil {
return &os.PathError{
Op: "failed to compile template program",
Path: templatePath,
Err: err,
}
}
log.WithFields(logrus.Fields{
logfields.Path: objectPath,
logfields.BPFCompilationTime: cfg.stats.bpfCompilation.Total(),
}).Info("Compiled new BPF template")
o.insert(hash, objectPath)
return nil
}
// fetchOrCompile attempts to fetch the path to the datapath object
// corresponding to the provided endpoint configuration, or if this
// configuration is not yet compiled, compiles it. It will block if multiple
// threads attempt to concurrently fetchOrCompile a template binary for the
// same set of EndpointConfiguration.
//
// Returns the path to the compiled template datapath object and whether the
// object was compiled, or an error.
func (o *objectCache) fetchOrCompile(ctx context.Context, cfg datapath.EndpointConfiguration, stats *SpanStat) (path string, compiled bool, err error) {
var hash string
hash, err = o.baseHash.sumEndpoint(o, cfg, false)
if err != nil {
return "", false, err
}
// Capture the time spent waiting for the template to compile.
if stats != nil {
stats.bpfWaitForELF.Start()
defer func() {
// Wrap to ensure that "err" is compared upon return.
stats.bpfWaitForELF.End(err == nil)
}()
}
// Serializes attempts to compile this cfg.
fq, compiled := o.serialize(hash)
if !compiled {
fq.Enqueue(func() error {
defer fq.Stop()
templateCfg := wrap(cfg, stats)
return o.build(ctx, templateCfg, hash)
}, serializer.NoRetry)
}
// Wait until the build completes.
if err = fq.Wait(ctx); err != nil {
return "", false, fmt.Errorf("BPF template compilation failed: %s", err)
}
// Fetch the result of the compilation.
path, ok := o.lookup(hash)
if !ok {
return "", false, fmt.Errorf("BPF template compilation unsuccessful")
}
return path, !compiled, nil
}
func (o *objectCache) watchTemplatesDirectory(ctx context.Context) error {
templateWatcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
close(o.templateWatcherDone)
templateWatcher.Close()
}()
for {
select {
// Watch for new templates being compiled and add to the filesystem watcher
case templatePath := <-o.newTemplates:
if err = templateWatcher.Add(templatePath); err != nil {
log.WithFields(logrus.Fields{
logfields.Path: templatePath,
}).WithError(err).Warning("Failed to watch templates directory")
} else {
log.WithFields(logrus.Fields{
logfields.Path: templatePath,
}).Debug("Watching template path")
}
// Handle filesystem deletes for current templates
case event, open := <-templateWatcher.Events:
if !open {
break
}
if event.Op&fsnotify.Remove != 0 {
log.WithField(logfields.Path, event.Name).Debug("Detected template removal")
templateHash := filepath.Base(filepath.Dir(event.Name))
o.delete(templateHash)
} else {
log.WithField("event", event).Debug("Ignoring template FS event")
}
case err, _ = <-templateWatcher.Errors:
return err
case <-ctx.Done():
return ctx.Err()
}
}
}
// EndpointHash hashes the specified endpoint configuration with the current
// datapath hash cache and returns the hash as string.
func EndpointHash(cfg datapath.EndpointConfiguration) (string, error) {
return templateCache.baseHash.sumEndpoint(templateCache, cfg, true)
}