[FIX] wrong memory

This commit is contained in:
GLYASAI 2019-08-11 18:42:26 +08:00
parent d4b4b6d711
commit 92cc67a404
2 changed files with 61 additions and 8 deletions

View File

@ -239,15 +239,50 @@ func DetermineDeployType(imageName Image) string {
//10k 128 //10k 128
//10b 128 //10b 128
func readmemory(s string) int { func readmemory(s string) int {
q, err := resource.ParseQuantity(strings.ToUpper(s)) def := 512
s = strings.ToLower(s)
// <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
isValid := false
validUnits := map[string]string{
"gi": "Gi", "mi": "Mi", "ki": "Ki",
}
for k, v := range validUnits {
if strings.Contains(s, k) {
isValid = true
s = strings.Replace(s, k, v, 1)
break
}
}
if !isValid {
validUnits := map[string]string{
"g": "Gi", "m": "Mi", "k": "Ki",
}
for k, v := range validUnits {
if strings.Contains(s, k) {
isValid = true
s = strings.Replace(s, k, v, 1)
break
}
}
}
if !isValid {
logrus.Warningf("s: %s; invalid unit", s)
return def
}
q, err := resource.ParseQuantity(s)
if err != nil { if err != nil {
return 512 logrus.Warningf("s: %s; failed to parse quantity: %v", s, err)
return def
}
re, ok := q.AsInt64()
if !ok {
logrus.Warningf("failed to int64: %d", re)
return def
} }
re, _ := q.AsInt64()
if re != 0 { if re != 0 {
return int(re) / (1000 * 1000) return int(re) / (1024 * 1024)
} }
return 512 return def
} }
//ParseImageName parse image name //ParseImageName parse image name

View File

@ -50,7 +50,25 @@ func TestDetermineDeployType(t *testing.T) {
} }
func TestReadmemory(t *testing.T) { func TestReadmemory(t *testing.T) {
t.Log(readmemory("10G")) testcases := []struct {
t.Log(readmemory("300m")) mem string
t.Log(readmemory("300M")) exp int
}{
{mem: "", exp: 512},
{mem: "2Gi", exp: 2 * 1024},
{mem: "2G", exp: 2 * 1024},
{mem: "300Mi", exp: 300},
{mem: "300m", exp: 300},
{mem: "1024Ki", exp: 1024 / 1024},
{mem: "1024k", exp: 1024 / 1024},
{mem: "1024K", exp: 1024 / 1024},
{mem: "1048576Bi", exp: 512},
{mem: "abc", exp: 512},
}
for _, tc := range testcases {
mem := readmemory(tc.mem)
if mem != tc.exp {
t.Errorf("mem: %s; Expected %d, but returned %d", tc.mem, tc.exp, mem)
}
}
} }