sing-box/common/conntrack/killer.go

36 lines
595 B
Go
Raw Permalink Normal View History

2023-03-16 02:55:06 +00:00
package conntrack
import (
runtimeDebug "runtime/debug"
"time"
E "github.com/sagernet/sing/common/exceptions"
2023-09-20 06:12:08 +00:00
"github.com/sagernet/sing/common/memory"
2023-03-16 02:55:06 +00:00
)
var (
KillerEnabled bool
2023-09-20 06:12:08 +00:00
MemoryLimit uint64
2023-03-16 02:55:06 +00:00
killerLastCheck time.Time
)
2023-09-20 06:12:08 +00:00
func KillerCheck() error {
2023-03-16 02:55:06 +00:00
if !KillerEnabled {
return nil
}
nowTime := time.Now()
if nowTime.Sub(killerLastCheck) < 3*time.Second {
return nil
}
killerLastCheck = nowTime
2023-09-20 06:12:08 +00:00
if memory.Total() > MemoryLimit {
2023-03-16 02:55:06 +00:00
Close()
go func() {
time.Sleep(time.Second)
runtimeDebug.FreeOSMemory()
}()
return E.New("out of memory")
}
return nil
}