github.com/pluralsh/plural-cli@v0.9.5/pkg/utils/backup/capi.go (about)

     1  package backup
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	apiclient "sigs.k8s.io/cluster-api/cmd/clusterctl/client"
     9  
    10  	"github.com/pluralsh/plural-cli/pkg/config"
    11  )
    12  
    13  type CAPIBackup struct {
    14  	dirPath string
    15  }
    16  
    17  func (this CAPIBackup) createDir() {
    18  	if this.Exists() {
    19  		return
    20  	}
    21  
    22  	_ = os.MkdirAll(this.dirPath, os.ModePerm)
    23  }
    24  
    25  func (this CAPIBackup) Exists() bool {
    26  	_, err := os.Stat(this.dirPath)
    27  	return !os.IsNotExist(err)
    28  }
    29  
    30  func (this CAPIBackup) Save(options apiclient.MoveOptions) error {
    31  	client, err := apiclient.New("")
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	this.createDir()
    37  	if len(options.FromKubeconfig.Context) == 0 || len(options.FromKubeconfig.Path) == 0 {
    38  		return fmt.Errorf("both FromKubeconfig context and path have to be configured\n")
    39  	}
    40  
    41  	options.ToDirectory = this.dirPath
    42  	options.Namespace = "bootstrap"
    43  
    44  	return client.Move(options)
    45  }
    46  
    47  func (this CAPIBackup) Restore(options apiclient.MoveOptions) error {
    48  	client, err := apiclient.New("")
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	if len(options.ToKubeconfig.Context) == 0 || len(options.ToKubeconfig.Path) == 0 {
    54  		return fmt.Errorf("both ToKubeconfig context and path have to be configured\n")
    55  	}
    56  
    57  	if !this.Exists() {
    58  		return fmt.Errorf("could not find move backup to restore from")
    59  	}
    60  
    61  	options.FromDirectory = this.dirPath
    62  	options.Namespace = "bootstrap"
    63  
    64  	return client.Move(options)
    65  }
    66  
    67  func (this CAPIBackup) Remove() error {
    68  	if !this.Exists() {
    69  		return nil
    70  	}
    71  
    72  	return os.RemoveAll(this.dirPath)
    73  }
    74  
    75  func NewCAPIBackup(cluster string) Backup[apiclient.MoveOptions] {
    76  	path, _ := config.PluralDir()
    77  
    78  	return CAPIBackup{
    79  		dirPath: filepath.Join(path, backupsDir, cluster),
    80  	}
    81  }