github.com/jayanthvn/pure-gobpf@v0.0.0-20230623131354-8d1d959d9e0b/pkg/ebpf_xdp/xdp_probes.go (about) 1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 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 ebpf_xdp 16 17 import ( 18 "fmt" 19 20 "github.com/jayanthvn/pure-gobpf/pkg/logger" 21 "github.com/vishvananda/netlink" 22 ) 23 24 const ( 25 XDP_ATTACH_MODE_NONE = 0 26 XDP_ATTACH_MODE_SKB = 1 27 XDP_ATTACH_MODE_DRV = 2 28 XDP_ATTACH_MODE_HW = 3 29 ) 30 31 var log = logger.Get() 32 33 func XDPAttach(interfaceName string, progFD int) error { 34 35 //var log = logger.Get() 36 link, err := netlink.LinkByName(interfaceName) 37 if err != nil { 38 log.Infof("Failed linkbyname") 39 return fmt.Errorf("Get LinkByName failed: %v", err) 40 } 41 42 log.Infof("Attaching xdp to interface %s and prog %d", interfaceName, progFD) 43 if err := netlink.LinkSetXdpFdWithFlags(link, progFD, int(XDP_ATTACH_MODE_SKB)); err != nil { 44 log.Infof("failed to setxdp: %v", err) 45 return fmt.Errorf("LinkSetXdpFd failed: %v", err) 46 } 47 log.Infof("Attached XDP to interface %s", interfaceName) 48 return nil 49 } 50 51 func XDPDetach(interfaceName string) error { 52 53 //var log = logger.Get() 54 link, err := netlink.LinkByName(interfaceName) 55 if err != nil { 56 log.Infof("Failed linkbyname") 57 return fmt.Errorf("Get LinkByName failed: %v", err) 58 } 59 60 if err := netlink.LinkSetXdpFdWithFlags(link, -1, int(XDP_ATTACH_MODE_SKB)); err != nil { 61 log.Infof("failed to setxdp") 62 return fmt.Errorf("LinkSetXdpFd() failed: %v", err) 63 } 64 return nil 65 }