github.com/TeaOSLab/EdgeNode@v1.3.8/internal/nodes/task_trim_disks.go (about)

     1  // Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package nodes
     4  
     5  import (
     6  	"fmt"
     7  	"github.com/TeaOSLab/EdgeNode/internal/remotelogs"
     8  	"github.com/TeaOSLab/EdgeNode/internal/trackers"
     9  	executils "github.com/TeaOSLab/EdgeNode/internal/utils/exec"
    10  	"github.com/TeaOSLab/EdgeNode/internal/utils/idles"
    11  	"runtime"
    12  	"time"
    13  )
    14  
    15  // TrimDisksTask trim ssd disks automatically
    16  type TrimDisksTask struct {
    17  }
    18  
    19  // NewTrimDisksTask create new task
    20  func NewTrimDisksTask() *TrimDisksTask {
    21  	return &TrimDisksTask{}
    22  }
    23  
    24  // Start the task
    25  func (this *TrimDisksTask) Start() {
    26  	// execute once
    27  	if idles.IsMinHour() {
    28  		err := this.loop()
    29  		if err != nil {
    30  			remotelogs.Warn("TRIM_DISKS", "trim disks failed: "+err.Error())
    31  		}
    32  	}
    33  
    34  	var ticker = time.NewTicker(2 * 24 * time.Hour) // every 2 days
    35  	idles.RunTicker(ticker, func() {
    36  		// run the task
    37  		err := this.loop()
    38  		if err != nil {
    39  			remotelogs.Warn("TRIM_DISKS", "trim disks failed: "+err.Error())
    40  		}
    41  	})
    42  }
    43  
    44  // run the task once
    45  func (this *TrimDisksTask) loop() error {
    46  	if runtime.GOOS != "linux" {
    47  		return nil
    48  	}
    49  
    50  	var nodeConfig = sharedNodeConfig
    51  	if nodeConfig == nil {
    52  		return nil
    53  	}
    54  	if !nodeConfig.AutoTrimDisks {
    55  		return nil
    56  	}
    57  
    58  	trimExe, err := executils.LookPath("fstrim")
    59  	if err != nil {
    60  		return fmt.Errorf("'fstrim' command not found: %w", err)
    61  	}
    62  
    63  	defer trackers.Begin("TRIM_DISKS").End()
    64  
    65  	var cmd = executils.NewCmd(trimExe, "-a").
    66  		WithStderr()
    67  	err = cmd.Run()
    68  	if err != nil {
    69  		return fmt.Errorf("'fstrim' execute failed: %s", cmd.Stderr())
    70  	}
    71  
    72  	return nil
    73  }