github.com/sagernet/sing-box@v1.9.0-rc.20/common/conntrack/killer.go (about)

     1  package conntrack
     2  
     3  import (
     4  	runtimeDebug "runtime/debug"
     5  	"time"
     6  
     7  	E "github.com/sagernet/sing/common/exceptions"
     8  	"github.com/sagernet/sing/common/memory"
     9  )
    10  
    11  var (
    12  	KillerEnabled   bool
    13  	MemoryLimit     uint64
    14  	killerLastCheck time.Time
    15  )
    16  
    17  func KillerCheck() error {
    18  	if !KillerEnabled {
    19  		return nil
    20  	}
    21  	nowTime := time.Now()
    22  	if nowTime.Sub(killerLastCheck) < 3*time.Second {
    23  		return nil
    24  	}
    25  	killerLastCheck = nowTime
    26  	if memory.Total() > MemoryLimit {
    27  		Close()
    28  		go func() {
    29  			time.Sleep(time.Second)
    30  			runtimeDebug.FreeOSMemory()
    31  		}()
    32  		return E.New("out of memory")
    33  	}
    34  	return nil
    35  }