Debian Codegraph @

plugins/meta/bandwidth/main.go

raw symbols SCIP
1 // Copyright 2018 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package main
16
17 import (
18 "encoding/json"
19 "fmt"
20 "math"
21
22 "github.com/vishvananda/netlink"
23
24 "github.com/containernetworking/cni/pkg/skel"
25 "github.com/containernetworking/cni/pkg/types"
26 current "github.com/containernetworking/cni/pkg/types/100"
27 "github.com/containernetworking/cni/pkg/version"
28 "github.com/containernetworking/plugins/pkg/ip"
29 "github.com/containernetworking/plugins/pkg/netlinksafe"
30 "github.com/containernetworking/plugins/pkg/ns"
31 "github.com/containernetworking/plugins/pkg/utils"
32 bv "github.com/containernetworking/plugins/pkg/utils/buildversion"
33 )
34
35 const (
36 maxIfbDeviceLength = 15
37 ifbDevicePrefix = "bwp"
38 )
39
40 // BandwidthEntry corresponds to a single entry in the bandwidth argument,
41 // see CONVENTIONS.md
42 type BandwidthEntry struct {
43 IngressRate uint64 `json:"ingressRate"` // Bandwidth rate in bps for traffic through container. 0 for no limit. If ingressRate is set, ingressBurst must also be set
44 IngressBurst uint64 `json:"ingressBurst"` // Bandwidth burst in bits for traffic through container. 0 for no limit. If ingressBurst is set, ingressRate must also be set
45
46 EgressRate uint64 `json:"egressRate"` // Bandwidth rate in bps for traffic through container. 0 for no limit. If egressRate is set, egressBurst must also be set
47 EgressBurst uint64 `json:"egressBurst"` // Bandwidth burst in bits for traffic through container. 0 for no limit. If egressBurst is set, egressRate must also be set
48 }
49
50 func (bw *BandwidthEntry) isZero() bool {
51 return bw.IngressBurst == 0 && bw.IngressRate == 0 && bw.EgressBurst == 0 && bw.EgressRate == 0
52 }
53
54 type PluginConf struct {
55 types.NetConf
56
57 RuntimeConfig struct {
58 Bandwidth *BandwidthEntry `json:"bandwidth,omitempty"`
59 } `json:"runtimeConfig,omitempty"`
60
61 *BandwidthEntry
62 }
63
64 // parseConfig parses the supplied configuration (and prevResult) from stdin.
65 func parseConfig(stdin []byte) (*PluginConf, error) {
66 conf := PluginConf{}
67
68 if err := json.Unmarshal(stdin, &conf); err != nil {
69 return nil, fmt.Errorf("failed to parse network configuration: %v", err)
70 }
71
72 bandwidth := getBandwidth(&conf)
73 if bandwidth != nil {
74 err := validateRateAndBurst(bandwidth.IngressRate, bandwidth.IngressBurst)
75 if err != nil {
76 return nil, err
77 }
78 err = validateRateAndBurst(bandwidth.EgressRate, bandwidth.EgressBurst)
79 if err != nil {
80 return nil, err
81 }
82 }
83
84 if conf.RawPrevResult != nil {
85 var err error
86 if err = version.ParsePrevResult(&conf.NetConf); err != nil {
87 return nil, fmt.Errorf("could not parse prevResult: %v", err)
88 }
89
90 _, err = current.NewResultFromResult(conf.PrevResult)
91 if err != nil {
92 return nil, fmt.Errorf("could not convert result to current version: %v", err)
93 }
94 }
95
96 return &conf, nil
97 }
98
99 func getBandwidth(conf *PluginConf) *BandwidthEntry {
100 if conf.BandwidthEntry == nil && conf.RuntimeConfig.Bandwidth != nil {
101 return conf.RuntimeConfig.Bandwidth
102 }
103 return conf.BandwidthEntry
104 }
105
106 func validateRateAndBurst(rate, burst uint64) error {
107 switch {
108 case burst == 0 && rate != 0:
109 return fmt.Errorf("if rate is set, burst must also be set")
110 case rate == 0 && burst != 0:
111 return fmt.Errorf("if burst is set, rate must also be set")
112 case burst/8 >= math.MaxUint32:
113 return fmt.Errorf("burst cannot be more than 4GB")
114 }
115
116 return nil
117 }
118
119 func getIfbDeviceName(networkName string, containerID string) string {
120 return utils.MustFormatHashWithPrefix(maxIfbDeviceLength, ifbDevicePrefix, networkName+containerID)
121 }
122
123 func getMTU(deviceName string) (int, error) {
124 link, err := netlinksafe.LinkByName(deviceName)
125 if err != nil {
126 return -1, err
127 }
128
129 return link.Attrs().MTU, nil
130 }
131
132 // get the veth peer of container interface in host namespace
133 func getHostInterface(interfaces []*current.Interface, containerIfName string, netns ns.NetNS) (*current.Interface, error) {
134 if len(interfaces) == 0 {
135 return nil, fmt.Errorf("no interfaces provided")
136 }
137
138 // get veth peer index of container interface
139 var peerIndex int
140 var err error
141 _ = netns.Do(func(_ ns.NetNS) error {
142 _, peerIndex, err = ip.GetVethPeerIfindex(containerIfName)
143 return nil
144 })
145 if peerIndex <= 0 {
146 return nil, fmt.Errorf("container interface %s has no veth peer: %v", containerIfName, err)
147 }
148
149 // find host interface by index
150 link, err := netlink.LinkByIndex(peerIndex)
151 if err != nil {
152 return nil, fmt.Errorf("veth peer with index %d is not in host ns", peerIndex)
153 }
154 for _, iface := range interfaces {
155 if iface.Sandbox == "" && iface.Name == link.Attrs().Name {
156 return iface, nil
157 }
158 }
159
160 return nil, fmt.Errorf("no veth peer of container interface found in host ns")
161 }
162
163 func cmdAdd(args *skel.CmdArgs) error {
164 conf, err := parseConfig(args.StdinData)
165 if err != nil {
166 return err
167 }
168
169 bandwidth := getBandwidth(conf)
170 if bandwidth == nil || bandwidth.isZero() {
171 return types.PrintResult(conf.PrevResult, conf.CNIVersion)
172 }
173
174 if conf.PrevResult == nil {
175 return fmt.Errorf("must be called as chained plugin")
176 }
177
178 result, err := current.NewResultFromResult(conf.PrevResult)
179 if err != nil {
180 return fmt.Errorf("could not convert result to current version: %v", err)
181 }
182
183 netns, err := ns.GetNS(args.Netns)
184 if err != nil {
185 return fmt.Errorf("failed to open netns %q: %v", netns, err)
186 }
187 defer netns.Close()
188
189 hostInterface, err := getHostInterface(result.Interfaces, args.IfName, netns)
190 if err != nil {
191 return err
192 }
193
194 if bandwidth.IngressRate > 0 && bandwidth.IngressBurst > 0 {
195 err = CreateIngressQdisc(bandwidth.IngressRate, bandwidth.IngressBurst, hostInterface.Name)
196 if err != nil {
197 return err
198 }
199 }
200
201 if bandwidth.EgressRate > 0 && bandwidth.EgressBurst > 0 {
202 mtu, err := getMTU(hostInterface.Name)
203 if err != nil {
204 return err
205 }
206
207 ifbDeviceName := getIfbDeviceName(conf.Name, args.ContainerID)
208
209 err = CreateIfb(ifbDeviceName, mtu)
210 if err != nil {
211 return err
212 }
213
214 ifbDevice, err := netlinksafe.LinkByName(ifbDeviceName)
215 if err != nil {
216 return err
217 }
218
219 result.Interfaces = append(result.Interfaces, &current.Interface{
220 Name: ifbDeviceName,
221 Mac: ifbDevice.Attrs().HardwareAddr.String(),
222 })
223 err = CreateEgressQdisc(bandwidth.EgressRate, bandwidth.EgressBurst, hostInterface.Name, ifbDeviceName)
224 if err != nil {
225 return err
226 }
227 }
228
229 return types.PrintResult(result, conf.CNIVersion)
230 }
231
232 func cmdDel(args *skel.CmdArgs) error {
233 conf, err := parseConfig(args.StdinData)
234 if err != nil {
235 return err
236 }
237
238 ifbDeviceName := getIfbDeviceName(conf.Name, args.ContainerID)
239
240 return TeardownIfb(ifbDeviceName)
241 }
242
243 func main() {
244 skel.PluginMainFuncs(skel.CNIFuncs{
245 Add: cmdAdd,
246 Check: cmdCheck,
247 Del: cmdDel,
248 /* FIXME GC */
249 /* FIXME Status */
250 }, version.VersionsStartingFrom("0.3.0"), bv.BuildString("bandwidth"))
251 }
252
253 func SafeQdiscList(link netlink.Link) ([]netlink.Qdisc, error) {
254 qdiscs, err := netlinksafe.QdiscList(link)
255 if err != nil {
256 return nil, err
257 }
258 result := []netlink.Qdisc{}
259 for _, qdisc := range qdiscs {
260 // filter out pfifo_fast qdiscs because
261 // older kernels don't return them
262 _, pfifo := qdisc.(*netlink.PfifoFast)
263 if !pfifo {
264 result = append(result, qdisc)
265 }
266 }
267 return result, nil
268 }
269
270 func cmdCheck(args *skel.CmdArgs) error {
271 bwConf, err := parseConfig(args.StdinData)
272 if err != nil {
273 return err
274 }
275
276 if bwConf.PrevResult == nil {
277 return fmt.Errorf("must be called as a chained plugin")
278 }
279
280 result, err := current.NewResultFromResult(bwConf.PrevResult)
281 if err != nil {
282 return fmt.Errorf("could not convert result to current version: %v", err)
283 }
284
285 netns, err := ns.GetNS(args.Netns)
286 if err != nil {
287 return fmt.Errorf("failed to open netns %q: %v", netns, err)
288 }
289 defer netns.Close()
290
291 hostInterface, err := getHostInterface(result.Interfaces, args.IfName, netns)
292 if err != nil {
293 return err
294 }
295 link, err := netlinksafe.LinkByName(hostInterface.Name)
296 if err != nil {
297 return err
298 }
299
300 bandwidth := getBandwidth(bwConf)
301
302 // No bandwidth config; nothing to do.
303 if bandwidth == nil || bandwidth.isZero() {
304 return nil
305 }
306
307 if bandwidth.IngressRate > 0 && bandwidth.IngressBurst > 0 {
308 rateInBytes := bandwidth.IngressRate / 8
309 burstInBytes := bandwidth.IngressBurst / 8
310 bufferInBytes := buffer(rateInBytes, uint32(burstInBytes))
311 latency := latencyInUsec(latencyInMillis)
312 limitInBytes := limit(rateInBytes, latency, uint32(burstInBytes))
313
314 qdiscs, err := SafeQdiscList(link)
315 if err != nil {
316 return err
317 }
318 if len(qdiscs) == 0 {
319 return fmt.Errorf("Failed to find qdisc")
320 }
321
322 for _, qdisc := range qdiscs {
323 tbf, isTbf := qdisc.(*netlink.Tbf)
324 if !isTbf {
325 break
326 }
327 if tbf.Rate != rateInBytes {
328 return fmt.Errorf("Rate doesn't match")
329 }
330 if tbf.Limit != limitInBytes {
331 return fmt.Errorf("Limit doesn't match")
332 }
333 if tbf.Buffer != bufferInBytes {
334 return fmt.Errorf("Buffer doesn't match")
335 }
336 }
337 }
338
339 if bandwidth.EgressRate > 0 && bandwidth.EgressBurst > 0 {
340 rateInBytes := bandwidth.EgressRate / 8
341 burstInBytes := bandwidth.EgressBurst / 8
342 bufferInBytes := buffer(rateInBytes, uint32(burstInBytes))
343 latency := latencyInUsec(latencyInMillis)
344 limitInBytes := limit(rateInBytes, latency, uint32(burstInBytes))
345
346 ifbDeviceName := getIfbDeviceName(bwConf.Name, args.ContainerID)
347
348 ifbDevice, err := netlinksafe.LinkByName(ifbDeviceName)
349 if err != nil {
350 return fmt.Errorf("get ifb device: %s", err)
351 }
352
353 qdiscs, err := SafeQdiscList(ifbDevice)
354 if err != nil {
355 return err
356 }
357 if len(qdiscs) == 0 {
358 return fmt.Errorf("Failed to find qdisc")
359 }
360
361 for _, qdisc := range qdiscs {
362 tbf, isTbf := qdisc.(*netlink.Tbf)
363 if !isTbf {
364 break
365 }
366 if tbf.Rate != rateInBytes {
367 return fmt.Errorf("Rate doesn't match")
368 }
369 if tbf.Limit != limitInBytes {
370 return fmt.Errorf("Limit doesn't match")
371 }
372 if tbf.Buffer != bufferInBytes {
373 return fmt.Errorf("Buffer doesn't match")
374 }
375 }
376 }
377
378 return nil
379 }