github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/common/dialer/conntrack/killer.go (about)

     1  package conntrack
     2  
     3  import (
     4  	"runtime"
     5  	runtimeDebug "runtime/debug"
     6  	"time"
     7  
     8  	E "github.com/sagernet/sing/common/exceptions"
     9  )
    10  
    11  var (
    12  	KillerEnabled   bool
    13  	MemoryLimit     int64
    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  	var memStats runtime.MemStats
    27  	runtime.ReadMemStats(&memStats)
    28  	inuseMemory := int64(memStats.StackInuse + memStats.HeapInuse + memStats.HeapIdle - memStats.HeapReleased)
    29  	if inuseMemory > MemoryLimit {
    30  		Close()
    31  		go func() {
    32  			time.Sleep(time.Second)
    33  			runtimeDebug.FreeOSMemory()
    34  		}()
    35  		return E.New("out of memory")
    36  	}
    37  	return nil
    38  }