| 1 |
|
| 2 |
|
| 3 |
package sys |
| 4 |
|
| 5 |
import ( |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"os" |
| 9 |
"path/filepath" |
| 10 |
"runtime" |
| 11 |
|
| 12 |
"github.com/cilium/ebpf/internal/linux" |
| 13 |
"github.com/cilium/ebpf/internal/unix" |
| 14 |
) |
| 15 |
|
| 16 |
func Pin(currentPath, newPath string, fd *FD) error { |
| 17 |
if newPath == "" { |
| 18 |
return errors.New("given pinning path cannot be empty") |
| 19 |
} |
| 20 |
if currentPath == newPath { |
| 21 |
return nil |
| 22 |
} |
| 23 |
|
| 24 |
fsType, err := linux.FSType(filepath.Dir(newPath)) |
| 25 |
if err != nil { |
| 26 |
return err |
| 27 |
} |
| 28 |
if fsType != unix.BPF_FS_MAGIC { |
| 29 |
return fmt.Errorf("%s is not on a bpf filesystem", newPath) |
| 30 |
} |
| 31 |
|
| 32 |
defer runtime.KeepAlive(fd) |
| 33 |
|
| 34 |
if currentPath == "" { |
| 35 |
return ObjPin(&ObjPinAttr{ |
| 36 |
Pathname: NewStringPointer(newPath), |
| 37 |
BpfFd: fd.Uint(), |
| 38 |
}) |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
err = unix.Renameat2(unix.AT_FDCWD, currentPath, unix.AT_FDCWD, newPath, unix.RENAME_NOREPLACE) |
| 44 |
if err == nil { |
| 45 |
|
| 46 |
return nil |
| 47 |
} |
| 48 |
if !os.IsNotExist(err) { |
| 49 |
return fmt.Errorf("unable to move pinned object to new path %v: %w", newPath, err) |
| 50 |
} |
| 51 |
|
| 52 |
return ObjPin(&ObjPinAttr{ |
| 53 |
Pathname: NewStringPointer(newPath), |
| 54 |
BpfFd: fd.Uint(), |
| 55 |
}) |
| 56 |
} |
| 57 |
|
| 58 |
func Unpin(pinnedPath string) error { |
| 59 |
if pinnedPath == "" { |
| 60 |
return nil |
| 61 |
} |
| 62 |
err := os.Remove(pinnedPath) |
| 63 |
if err == nil || os.IsNotExist(err) { |
| 64 |
return nil |
| 65 |
} |
| 66 |
return err |
| 67 |
} |