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