github.com/TeaOSLab/EdgeNode@v1.3.8/internal/iplibrary/action_script.go (about)

     1  package iplibrary
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
     6  	"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
     7  	executils "github.com/TeaOSLab/EdgeNode/internal/utils/exec"
     8  	"path/filepath"
     9  	"time"
    10  )
    11  
    12  // ScriptAction 脚本命令动作
    13  type ScriptAction struct {
    14  	BaseAction
    15  
    16  	config *firewallconfigs.FirewallActionScriptConfig
    17  }
    18  
    19  func NewScriptAction() *ScriptAction {
    20  	return &ScriptAction{}
    21  }
    22  
    23  func (this *ScriptAction) Init(config *firewallconfigs.FirewallActionConfig) error {
    24  	this.config = &firewallconfigs.FirewallActionScriptConfig{}
    25  	err := this.convertParams(config.Params, this.config)
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	if len(this.config.Path) == 0 {
    31  		return NewFataError("'path' should not be empty")
    32  	}
    33  
    34  	return nil
    35  }
    36  
    37  func (this *ScriptAction) AddItem(listType IPListType, item *pb.IPItem) error {
    38  	return this.runAction("addItem", listType, item)
    39  }
    40  
    41  func (this *ScriptAction) DeleteItem(listType IPListType, item *pb.IPItem) error {
    42  	return this.runAction("deleteItem", listType, item)
    43  }
    44  
    45  func (this *ScriptAction) runAction(action string, listType IPListType, item *pb.IPItem) error {
    46  	// TODO 智能支持 .sh 脚本文件
    47  	var cmd = executils.NewTimeoutCmd(30*time.Second, this.config.Path)
    48  	cmd.WithEnv([]string{
    49  		"ACTION=" + action,
    50  		"TYPE=" + item.Type,
    51  		"IP_FROM=" + item.IpFrom,
    52  		"IP_TO=" + item.IpTo,
    53  		"EXPIRED_AT=" + fmt.Sprintf("%d", item.ExpiredAt),
    54  		"LIST_TYPE=" + listType,
    55  	})
    56  	if len(this.config.Cwd) > 0 {
    57  		cmd.WithDir(this.config.Cwd)
    58  	} else {
    59  		cmd.WithDir(filepath.Dir(this.config.Path))
    60  	}
    61  	cmd.WithStderr()
    62  	err := cmd.Run()
    63  	if err != nil {
    64  		return fmt.Errorf("%w, output: %s", err, cmd.Stderr())
    65  	}
    66  	return nil
    67  }