package swapcfg import ( "bytes" "context" "errors" "os" "path/filepath" "gopkg.in/yaml.v2" "edge-infra.dev/pkg/k8s/runtime/controller/reconcile" v1ien "edge-infra.dev/pkg/sds/ien/k8s/apis/v1" "edge-infra.dev/pkg/sds/ien/k8s/controllers/nodeagent/config" ) const ( swapConfigFilePath = "/zynstra/config/swapcfg.yaml" filePerms os.FileMode = 0644 ) type Plugin struct{} var ( ErrSwapFieldNotFound = errors.New("swap enabled field not found") ) type swapConfig struct { Swap Swap `yaml:"swap"` } type Swap struct { Enabled bool `yaml:"enabled"` } // Updates the swap configuration file on the node func (swapCfgPlugin Plugin) Reconcile(_ context.Context, ienode *v1ien.IENode, conf config.Config) (reconcile.Result, error) { if ienode.Spec.SwapEnabled == nil { return reconcile.ResultEmpty, nil } if err := modifySwapConfig(ienode, filepath.Join(conf.GetNodeRootPath(), swapConfigFilePath)); err != nil { return reconcile.ResultRequeue, err } return reconcile.ResultSuccess, nil } func modifySwapConfig(ien *v1ien.IENode, configPath string) error { currentSwapBytes, err := readConfig(configPath) if err != nil { return err } targetSwapBytes, err := generateSwapConfig(ien) if err != nil { return err } if bytes.Equal(currentSwapBytes, targetSwapBytes) { return nil } return os.WriteFile(configPath, targetSwapBytes, filePerms) } func readConfig(configPath string) ([]byte, error) { if _, err := os.Stat(configPath); err != nil && !os.IsNotExist(err) { return nil, err } else if !os.IsNotExist(err) { return os.ReadFile(configPath) } return nil, nil } func generateSwapConfig(ien *v1ien.IENode) ([]byte, error) { targetSwapCfg := &swapConfig{ Swap: Swap{ Enabled: *ien.Spec.SwapEnabled, }, } return yaml.Marshal(&targetSwapCfg) }