Files
EdgeNode/internal/iplibrary/action_script.go

69 lines
1.7 KiB
Go
Raw Permalink Normal View History

2021-02-06 17:34:33 +08:00
package iplibrary
import (
"fmt"
2024-07-27 15:42:50 +08:00
"path/filepath"
"time"
2021-02-06 17:34:33 +08:00
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/firewallconfigs"
2022-09-15 11:14:33 +08:00
executils "github.com/TeaOSLab/EdgeNode/internal/utils/exec"
2021-02-06 17:34:33 +08:00
)
2021-11-14 20:46:08 +08:00
// ScriptAction 脚本命令动作
2021-02-06 17:34:33 +08:00
type ScriptAction struct {
BaseAction
config *firewallconfigs.FirewallActionScriptConfig
}
func NewScriptAction() *ScriptAction {
return &ScriptAction{}
}
func (this *ScriptAction) Init(config *firewallconfigs.FirewallActionConfig) error {
this.config = &firewallconfigs.FirewallActionScriptConfig{}
err := this.convertParams(config.Params, this.config)
if err != nil {
return err
}
if len(this.config.Path) == 0 {
return NewFataError("'path' should not be empty")
}
return nil
}
func (this *ScriptAction) AddItem(listType IPListType, item *pb.IPItem) error {
return this.runAction("addItem", listType, item)
}
func (this *ScriptAction) DeleteItem(listType IPListType, item *pb.IPItem) error {
return this.runAction("deleteItem", listType, item)
}
func (this *ScriptAction) runAction(action string, listType IPListType, item *pb.IPItem) error {
// TODO 智能支持 .sh 脚本文件
2022-09-15 11:14:33 +08:00
var cmd = executils.NewTimeoutCmd(30*time.Second, this.config.Path)
cmd.WithEnv([]string{
2021-02-06 17:34:33 +08:00
"ACTION=" + action,
"TYPE=" + item.Type,
"IP_FROM=" + item.IpFrom,
"IP_TO=" + item.IpTo,
"EXPIRED_AT=" + fmt.Sprintf("%d", item.ExpiredAt),
"LIST_TYPE=" + listType,
2022-09-15 11:14:33 +08:00
})
2021-02-06 17:34:33 +08:00
if len(this.config.Cwd) > 0 {
2022-09-15 11:14:33 +08:00
cmd.WithDir(this.config.Cwd)
2021-02-06 17:34:33 +08:00
} else {
2022-09-15 11:14:33 +08:00
cmd.WithDir(filepath.Dir(this.config.Path))
2021-02-06 17:34:33 +08:00
}
2022-09-15 11:14:33 +08:00
cmd.WithStderr()
2021-02-06 17:34:33 +08:00
err := cmd.Run()
if err != nil {
2023-08-11 14:51:23 +08:00
return fmt.Errorf("%w, output: %s", err, cmd.Stderr())
2021-02-06 17:34:33 +08:00
}
return nil
}