...

Source file src/edge-infra.dev/pkg/sds/ien/k8s/controllers/nodeagent/plugins/swapcfg/swapcfg.go

Documentation: edge-infra.dev/pkg/sds/ien/k8s/controllers/nodeagent/plugins/swapcfg

     1  package swapcfg
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"errors"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"gopkg.in/yaml.v2"
    11  
    12  	"edge-infra.dev/pkg/k8s/runtime/controller/reconcile"
    13  	v1ien "edge-infra.dev/pkg/sds/ien/k8s/apis/v1"
    14  	"edge-infra.dev/pkg/sds/ien/k8s/controllers/nodeagent/config"
    15  )
    16  
    17  const (
    18  	swapConfigFilePath             = "/zynstra/config/swapcfg.yaml"
    19  	filePerms          os.FileMode = 0644
    20  )
    21  
    22  type Plugin struct{}
    23  
    24  var (
    25  	ErrSwapFieldNotFound = errors.New("swap enabled field not found")
    26  )
    27  
    28  type swapConfig struct {
    29  	Swap Swap `yaml:"swap"`
    30  }
    31  
    32  type Swap struct {
    33  	Enabled bool `yaml:"enabled"`
    34  }
    35  
    36  // Updates the swap configuration file on the node
    37  func (swapCfgPlugin Plugin) Reconcile(_ context.Context, ienode *v1ien.IENode, conf config.Config) (reconcile.Result, error) {
    38  	if ienode.Spec.SwapEnabled == nil {
    39  		return reconcile.ResultEmpty, nil
    40  	}
    41  	if err := modifySwapConfig(ienode, filepath.Join(conf.GetNodeRootPath(), swapConfigFilePath)); err != nil {
    42  		return reconcile.ResultRequeue, err
    43  	}
    44  	return reconcile.ResultSuccess, nil
    45  }
    46  
    47  func modifySwapConfig(ien *v1ien.IENode, configPath string) error {
    48  	currentSwapBytes, err := readConfig(configPath)
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	targetSwapBytes, err := generateSwapConfig(ien)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	if bytes.Equal(currentSwapBytes, targetSwapBytes) {
    59  		return nil
    60  	}
    61  	return os.WriteFile(configPath, targetSwapBytes, filePerms)
    62  }
    63  
    64  func readConfig(configPath string) ([]byte, error) {
    65  	if _, err := os.Stat(configPath); err != nil && !os.IsNotExist(err) {
    66  		return nil, err
    67  	} else if !os.IsNotExist(err) {
    68  		return os.ReadFile(configPath)
    69  	}
    70  	return nil, nil
    71  }
    72  
    73  func generateSwapConfig(ien *v1ien.IENode) ([]byte, error) {
    74  	targetSwapCfg := &swapConfig{
    75  		Swap: Swap{
    76  			Enabled: *ien.Spec.SwapEnabled,
    77  		},
    78  	}
    79  	return yaml.Marshal(&targetSwapCfg)
    80  }
    81  

View as plain text