package spec

import (
	"fmt"

	"k8s.io/apimachinery/pkg/api/resource"
)

const (
	// ref to: https://tip.golang.org/doc/gc-guide
	// In this case, a good rule of thumb is to leave an additional 5-10% of headroom to account for
	// memory sources the Go runtime is unaware of.
	DefaultGoMemLimitRatio = 0.9

	// we get the following estimated extra pods memory cost from our normal running node(2Gi total)
	// extra memory cost is approximately 600Mi(2Gi-197472Ki-1249808Ki)
	//
	// PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
	// 9295 root      20   0  959220 197472  65172 S  19.9  9.9   0:30.22 tiflow
	// [root@ip-10-250-24-180 bin]# free -k
	//          total        used        free      shared  buff/cache   available
	// Mem:   1997892      592236      775640        5544      630016     1249808
	//
	defaultExtraPodsMemoryCost int64 = 600 * 1024 * 1024
)

func GetGoMemLimit(memory resource.Quantity, ratio float64) string {
	remainMax := int64(float64(memory.Value()) * ratio)
	remain := (memory.Value() - defaultExtraPodsMemoryCost)
	if remainMax > remain && remain > 0 {
		remainMax = remain
	}

	// GOMEMLIMIT support suffix: B/KiB/MiB/GiB/TiB
	return fmt.Sprintf("%vMiB", remainMax/1024/1024)
}
