forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attach.go
293 lines (245 loc) · 8.05 KB
/
attach.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
// Copyright (c) 2020-2022 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 xdp
import (
"fmt"
"os"
"path"
"strings"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"github.com/dtest11/calico/felix/bpf"
"github.com/dtest11/calico/felix/bpf/libbpf"
"github.com/dtest11/calico/felix/bpf/maps"
tcdefs "github.com/dtest11/calico/felix/bpf/tc/defs"
)
var JumpMapIndexes = map[string]map[int]string{
"IPv4": map[int]string{
tcdefs.ProgIndexPolicy: "calico_xdp_norm_pol_tail",
tcdefs.ProgIndexAllowed: "calico_xdp_accepted_entrypoint",
tcdefs.ProgIndexDrop: "calico_xdp_drop",
},
}
const DetachedID = 0
type AttachPoint struct {
Iface string
LogLevel string
Modes []bpf.XDPMode
}
func (ap *AttachPoint) IfaceName() string {
return ap.Iface
}
func (ap *AttachPoint) HookName() bpf.Hook {
return bpf.HookXDP
}
func (ap *AttachPoint) Config() string {
return fmt.Sprintf("%+v", ap)
}
func (ap *AttachPoint) JumpMapFDMapKey() string {
return bpf.HookXDP.String()
}
func (ap *AttachPoint) FileName() string {
logLevel := strings.ToLower(ap.LogLevel)
if logLevel == "off" {
logLevel = "no_log"
}
return "xdp_" + logLevel + ".o"
}
func (ap *AttachPoint) ProgramName() string {
return "xdp_calico_entry"
}
func (ap *AttachPoint) Log() *log.Entry {
return log.WithFields(log.Fields{
"iface": ap.Iface,
"modes": ap.Modes,
"logLevel": ap.LogLevel,
})
}
func (ap *AttachPoint) AlreadyAttached(object string) (int, bool) {
progID, err := ap.ProgramID()
if err != nil {
ap.Log().Debugf("Couldn't get the attached XDP program ID. err=%v", err)
return -1, false
}
somethingAttached, err := ap.IsAttached()
if err != nil {
ap.Log().Debugf("Failed to verify if any program is attached to interface. err=%v", err)
return -1, false
}
isAttached, err := bpf.AlreadyAttachedProg(ap, object, progID)
if err != nil {
ap.Log().Debugf("Failed to check if BPF program was already attached. err=%v", err)
return -1, false
}
if isAttached && somethingAttached {
return progID, true
}
return -1, false
}
func ConfigureProgram(m *libbpf.Map, iface string) error {
var globalData libbpf.XDPGlobalData
in := []byte("---------------")
copy(in, iface)
globalData.IfaceName = string(in)
if err := libbpf.XDPSetGlobals(m, &globalData); err != nil {
return fmt.Errorf("failed to configure xdp: %w", err)
}
return nil
}
func (ap *AttachPoint) AttachProgram() (int, error) {
tempDir, err := os.MkdirTemp("", "calico-xdp")
if err != nil {
return -1, fmt.Errorf("failed to create temporary directory: %w", err)
}
defer func() {
_ = os.RemoveAll(tempDir)
}()
filename := ap.FileName()
preCompiledBinary := path.Join(bpf.ObjectDir, filename)
obj, err := libbpf.OpenObject(preCompiledBinary)
if err != nil {
return -1, err
}
defer obj.Close()
for m, err := obj.FirstMap(); m != nil && err == nil; m, err = m.NextMap() {
if m.IsMapInternal() {
if err := ConfigureProgram(m, ap.Iface); err != nil {
return -1, err
}
continue
}
// TODO: We need to set map size here like tc.
pinDir := bpf.MapPinDir(m.Type(), m.Name(), ap.Iface, bpf.HookXDP)
if err := m.SetPinPath(path.Join(pinDir, m.Name())); err != nil {
return -1, fmt.Errorf("error pinning map %s: %w", m.Name(), err)
}
}
// Check if the bpf object is already attached, and we should skip re-attaching it
progID, isAttached := ap.AlreadyAttached(preCompiledBinary)
if isAttached {
ap.Log().Infof("Programs already attached, skip reattaching %s", filename)
return progID, nil
}
ap.Log().Infof("Continue with attaching BPF program %s", filename)
if err := obj.Load(); err != nil {
ap.Log().Warn("Failed to load program")
return -1, fmt.Errorf("error loading program: %w", err)
}
// TODO: Add support for IPv6
err = updateJumpMap(obj)
if err != nil {
ap.Log().Warn("Failed to update jump map")
return -1, fmt.Errorf("error updating jump map %v", err)
}
oldID, err := ap.ProgramID()
if err != nil {
return -1, fmt.Errorf("failed to get the attached XDP program ID: %w", err)
}
attachmentSucceeded := false
for _, mode := range ap.Modes {
ap.Log().Debugf("Trying to attach XDP program in mode %v - old id: %v", mode, oldID)
// Force attach the program. If there is already a program attached, the replacement only
// succeed in the same mode of the current program.
progID, err = obj.AttachXDP(ap.Iface, ap.ProgramName(), oldID, unix.XDP_FLAGS_REPLACE|uint(mode))
if err != nil || progID == DetachedID || progID == oldID {
ap.Log().WithError(err).Warnf("Failed to attach to XDP program %s mode %v", ap.ProgramName(), mode)
} else {
ap.Log().Debugf("Successfully attached XDP program in mode %v. ID: %v", mode, progID)
attachmentSucceeded = true
break
}
}
if !attachmentSucceeded {
return -1, fmt.Errorf("failed to attach XDP program with program name %v to interface %v",
ap.ProgramName(), ap.Iface)
}
// program is now attached. Now we should store its information to prevent unnecessary reloads in future
if err = bpf.RememberAttachedProg(ap, preCompiledBinary, progID); err != nil {
ap.Log().Errorf("Failed to record hash of BPF program on disk; Ignoring. err=%v", err)
}
return progID, nil
}
func (ap *AttachPoint) DetachProgram() error {
// Get the current XDP program ID, if any.
progID, err := ap.ProgramID()
if err != nil {
return fmt.Errorf("failed to get the attached XDP program ID: %w", err)
}
if progID == DetachedID {
ap.Log().Debugf("No XDP program attached.")
return nil
}
ourProg, err := bpf.AlreadyAttachedProg(ap, path.Join(bpf.ObjectDir, ap.FileName()), progID)
if err != nil || !ourProg {
return fmt.Errorf("XDP expected program ID does match with current one: %w", err)
}
// Try to remove our XDP program in all modes, until the program ID is 0
removalSucceeded := false
for _, mode := range ap.Modes {
err = libbpf.DetachXDP(ap.Iface, uint(mode))
ap.Log().Debugf("Trying to detach XDP program in mode %v.", mode)
if err != nil {
ap.Log().Debugf("Failed to detach XDP program in mode %v: %v.", mode, err)
continue
}
curProgId, err := ap.ProgramID()
if err != nil {
return fmt.Errorf("failed to get the attached XDP program ID: %w", err)
}
if curProgId == DetachedID {
removalSucceeded = true
ap.Log().Debugf("Successfully detached XDP program.")
break
}
}
if !removalSucceeded {
return fmt.Errorf("couldn't remove our XDP program. program ID: %v", progID)
}
ap.Log().Infof("XDP program detached. program ID: %v", progID)
// Program is detached, now remove the json file we saved for it
if err = bpf.ForgetAttachedProg(ap.IfaceName(), bpf.HookXDP); err != nil {
return fmt.Errorf("failed to delete hash of BPF program from disk: %w", err)
}
return nil
}
func (ap *AttachPoint) IsAttached() (bool, error) {
_, err := ap.ProgramID()
return err == nil, err
}
func (ap *AttachPoint) ProgramID() (int, error) {
progID, err := libbpf.GetXDPProgramID(ap.Iface)
if err != nil {
return -1, fmt.Errorf("Couldn't check for XDP program on iface %v: %w", ap.Iface, err)
}
return progID, nil
}
func updateJumpMap(obj *libbpf.Obj) error {
ipVersions := []string{"IPv4"}
for _, ipFamily := range ipVersions {
if err := UpdateJumpMap(obj, JumpMapIndexes[ipFamily]); err != nil {
return fmt.Errorf("proto %s: %w", ipFamily, err)
}
}
return nil
}
func UpdateJumpMap(obj *libbpf.Obj, progs map[int]string) error {
mapName := maps.JumpMapName()
for idx, name := range progs {
err := obj.UpdateJumpMap(mapName, name, idx)
if err != nil {
return fmt.Errorf("failed to update program '%s' at index %d: %w", name, idx, err)
}
}
return nil
}