github.com/caos/orbos@v1.5.14-0.20221103111702-e6cd0cea7ad4/internal/operator/nodeagent/dep/swap/dep.go (about) 1 package swap 2 3 import ( 4 "bytes" 5 6 "fmt" 7 "io" 8 "os/exec" 9 "strings" 10 11 "github.com/caos/orbos/internal/operator/common" 12 "github.com/caos/orbos/internal/operator/nodeagent" 13 "github.com/caos/orbos/internal/operator/nodeagent/dep" 14 "github.com/caos/orbos/internal/operator/nodeagent/dep/middleware" 15 ) 16 17 type Installer interface { 18 isSwap() 19 nodeagent.Installer 20 } 21 22 type swapDep struct { 23 fstabFilePath string 24 } 25 26 func New(fstabFilePath string) Installer { 27 return &swapDep{fstabFilePath: fstabFilePath} 28 } 29 30 func (swapDep) Is(other nodeagent.Installer) bool { 31 _, ok := middleware.Unwrap(other).(Installer) 32 return ok 33 } 34 35 func (swapDep) isSwap() {} 36 37 func (swapDep) String() string { return "Swap" } 38 39 func (*swapDep) Equals(other nodeagent.Installer) bool { 40 _, ok := other.(*swapDep) 41 return ok 42 } 43 44 func (*swapDep) InstalledFilter() []string { return nil } 45 46 func (s *swapDep) Current() (pkg common.Package, err error) { 47 48 buf := new(bytes.Buffer) 49 defer buf.Reset() 50 51 swapon := exec.Command("swapon", "--summary") 52 swapon.Stdout = buf 53 if err := swapon.Run(); err != nil { 54 return pkg, err 55 } 56 57 pkg.Version = "disabled" 58 var lines uint8 59 var line string 60 for { 61 if err != nil && err != io.EOF { 62 return pkg, err 63 } 64 line, err = buf.ReadString('\n') 65 if len(line) > 0 { 66 lines++ 67 } 68 if lines >= 2 { 69 pkg.Version = "enabled" 70 return 71 } 72 if err == io.EOF { 73 return pkg, nil 74 } 75 } 76 } 77 78 func (s *swapDep) Ensure(remove common.Package, ensure common.Package, _ bool) error { 79 buf := new(bytes.Buffer) 80 defer buf.Reset() 81 82 swapoff := exec.Command("swapoff", "--all") 83 swapoff.Stderr = buf 84 if err := swapoff.Run(); err != nil { 85 return fmt.Errorf("disabling swap failed with standard error: %s: %w", buf.String(), err) 86 } 87 88 return dep.ManipulateFile(s.fstabFilePath, nil, nil, func(line string) *string { 89 if !strings.Contains(line, "swap") { 90 return &line 91 } 92 switch { 93 case strings.HasPrefix(line, "#") && ensure.Version == "enabled" && remove.Version == "disabled": 94 line = strings.Replace(line, "#", "", 1) 95 case !strings.HasPrefix(line, "#") && ensure.Version == "disabled" && remove.Version == "enabled": 96 line = "#" + line 97 } 98 return &line 99 }) 100 }