forked from projectcalico/calico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connecttime.go
240 lines (200 loc) · 6.75 KB
/
connecttime.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
// Copyright (c) 2020-2021 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 nat
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/dtest11/calico/felix/bpf"
"github.com/dtest11/calico/felix/bpf/bpfdefs"
"github.com/dtest11/calico/felix/bpf/bpfutils"
"github.com/dtest11/calico/felix/bpf/libbpf"
"github.com/dtest11/calico/felix/bpf/maps"
"github.com/dtest11/calico/felix/bpf/utils"
)
type cgroupProgs struct {
ID int `json:"id"`
AttachType string `json:"attach_type"`
AttachFlags string `json:"attach_flags"`
Name string `json:"name"`
}
func RemoveConnectTimeLoadBalancer(cgroupv2 string) error {
if os.Getenv("FELIX_DebugSkipCTLBCleanup") == "true" {
log.Info("FV special case: skipping CTLB cleanup")
return nil
}
cgroupPath, err := ensureCgroupPath(cgroupv2)
if err != nil {
return errors.Wrap(err, "failed to set-up cgroupv2")
}
cmd := exec.Command("bpftool", "-j", "-p", "cgroup", "show", cgroupPath)
log.WithField("args", cmd.Args).Info("Running bpftool to look up programs attached to cgroup")
out, err := cmd.Output()
if err != nil || strings.TrimSpace(string(out)) == "" {
log.WithError(err).WithField("output", string(out)).Info(
"Failed to list BPF programs. Assuming not supported/nothing to clean up.")
return err
}
var progs []cgroupProgs
err = json.Unmarshal(out, &progs)
if err != nil {
log.WithError(err).WithField("output", string(out)).Error("BPF program list not json.")
return err
}
for _, p := range progs {
if !strings.HasPrefix(p.Name, "cali_") {
continue
}
cmd = exec.Command("bpftool", "cgroup", "detach", cgroupPath, p.AttachType, "id", strconv.Itoa(p.ID))
log.WithField("args", cmd.Args).Info("Running bpftool to detach program")
out, err = cmd.CombinedOutput()
if err != nil {
log.WithError(err).WithField("output", string(out)).Error(
"Failed to detach connect-time load balancing program.")
return err
}
}
bpf.CleanUpCalicoPins("/sys/fs/bpf/calico_connect4")
return nil
}
func installProgram(name, ipver, bpfMount, cgroupPath, logLevel string, udpNotSeen time.Duration, excludeUDP bool) error {
progPinDir := path.Join(bpfMount, "calico_connect4")
_ = os.RemoveAll(progPinDir)
var filename string
if ipver == "6" {
filename = path.Join(bpf.ObjectDir, ProgFileName(logLevel, 6))
} else {
filename = path.Join(bpf.ObjectDir, ProgFileName(logLevel, 4))
}
progName := "calico_" + name + "_v" + ipver
log.WithField("filename", filename).Debug("Loading object file")
obj, err := libbpf.OpenObject(filename)
if err != nil {
return fmt.Errorf("failed to load program %s from %s: %w", progName, filename, err)
}
defer obj.Close()
for m, err := obj.FirstMap(); m != nil && err == nil; m, err = m.NextMap() {
// In case of global variables, libbpf creates an internal map <prog_name>.rodata
// The values are read only for the BPF programs, but can be set to a value from
// userspace before the program is loaded.
if m.IsMapInternal() {
if err := libbpf.CTLBSetGlobals(m, udpNotSeen, excludeUDP); err != nil {
return fmt.Errorf("error setting globals: %w", err)
}
continue
}
if size := maps.Size(m.Name()); size != 0 {
err := m.SetSize(size)
if err != nil {
return fmt.Errorf("error set map size %s: %w", m.Name(), err)
}
}
if err := m.SetPinPath(path.Join(bpfdefs.GlobalPinDir, m.Name())); err != nil {
return fmt.Errorf("error pinning map %s: %w", m.Name(), err)
}
log.WithFields(log.Fields{"program": progName, "map": m.Name()}).Debug("Pinned map")
}
if err := obj.Load(); err != nil {
return fmt.Errorf("error loading program %s: %w", progName, err)
}
// N.B. no need to remember the link since we are never going to detach
// these programs unless Felix restarts.
if _, err := obj.AttachCGroup(cgroupPath, progName); err != nil {
return fmt.Errorf("failed to attach program %s: %w", progName, err)
}
log.WithFields(log.Fields{"program": progName, "cgroup": cgroupPath}).Info("Loaded cgroup program")
return nil
}
func InstallConnectTimeLoadBalancer(cgroupv2 string, logLevel string, udpNotSeen time.Duration, excludeUDP bool) error {
bpfMount, err := utils.MaybeMountBPFfs()
if err != nil {
log.WithError(err).Error("Failed to mount bpffs, unable to do connect-time load balancing")
return err
}
cgroupPath, err := ensureCgroupPath(cgroupv2)
if err != nil {
return errors.Wrap(err, "failed to set-up cgroupv2")
}
err = installProgram("connect", "4", bpfMount, cgroupPath, logLevel, udpNotSeen, excludeUDP)
if err != nil {
return err
}
err = installProgram("connect", "6", bpfMount, cgroupPath, logLevel, udpNotSeen, excludeUDP)
if err != nil {
return err
}
if !excludeUDP {
err = installProgram("sendmsg", "4", bpfMount, cgroupPath, logLevel, udpNotSeen, false)
if err != nil {
return err
}
err = installProgram("recvmsg", "4", bpfMount, cgroupPath, logLevel, udpNotSeen, false)
if err != nil {
return err
}
err = installProgram("sendmsg", "6", bpfMount, cgroupPath, logLevel, udpNotSeen, false)
if err != nil {
return err
}
err = installProgram("recvmsg", "6", bpfMount, cgroupPath, logLevel, udpNotSeen, false)
if err != nil {
return err
}
}
return nil
}
func ProgFileName(logLevel string, ipver int) string {
logLevel = strings.ToLower(logLevel)
if logLevel == "off" {
logLevel = "no_log"
}
btf := ""
if bpfutils.BTFEnabled {
btf = "_co-re"
}
switch ipver {
case 4:
return fmt.Sprintf("connect_time_%s_v4%s.o", logLevel, btf)
case 6:
return fmt.Sprintf("connect_time_%s_v6%s.o", logLevel, btf)
}
log.WithField("ipver", ipver).Fatal("Invalid IP version")
return ""
}
func ensureCgroupPath(cgroupv2 string) (string, error) {
cgroupRoot, err := utils.MaybeMountCgroupV2()
if err != nil {
return "", err
}
cgroupPath := cgroupRoot
if cgroupv2 != "" {
cgroupPath = path.Clean(path.Join(cgroupRoot, cgroupv2))
if !strings.HasPrefix(cgroupPath, path.Clean(cgroupRoot)) {
log.Panic("Invalid cgroup path outside the root")
}
err = os.MkdirAll(cgroupPath, 0766)
if err != nil {
log.WithError(err).Error("Failed to make cgroup")
return "", errors.Wrap(err, "failed to create cgroup")
}
}
return cgroupPath, nil
}