Cpu resources (#642)

* fn: cpu quota implementation
This commit is contained in:
Tolga Ceylan
2018-01-12 11:38:28 -08:00
committed by GitHub
parent fa59400a97
commit 39b2cb2d9b
29 changed files with 856 additions and 91 deletions

View File

@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type Config map[string]string
@@ -125,3 +126,67 @@ func (h *Headers) Scan(value interface{}) error {
// otherwise, return an error
return fmt.Errorf("headers invalid db format: %T %T value, err: %v", value, bv, err)
}
// MilliCPU units
type MilliCPUs uint64
const (
MinMilliCPUs = 0 // 0 is unlimited
MaxMilliCPUs = 1024000 // 1024 CPUs
)
// implements fmt.Stringer
func (c MilliCPUs) String() string {
if c == 0 {
return ""
}
return fmt.Sprintf("%dm", c)
}
// implements json.Unmarshaler
func (c *MilliCPUs) UnmarshalJSON(data []byte) error {
outer := bytes.TrimSpace(data)
if !bytes.HasSuffix(outer, []byte("\"")) || !bytes.HasPrefix(outer, []byte("\"")) {
return ErrInvalidJSON
}
outer = bytes.TrimPrefix(outer, []byte("\""))
outer = bytes.TrimSuffix(outer, []byte("\""))
outer = bytes.TrimSpace(outer)
if len(outer) == 0 {
*c = 0
return nil
}
if bytes.HasSuffix(outer, []byte("m")) {
// Support milli cores as "100m"
outer = bytes.TrimSuffix(outer, []byte("m"))
mCPU, err := strconv.ParseUint(string(outer), 10, 64)
if err != nil || mCPU > MaxMilliCPUs || mCPU < MinMilliCPUs {
return ErrInvalidCPUs
}
*c = MilliCPUs(mCPU)
} else {
// Support for floating point "0.1" style CPU units
fCPU, err := strconv.ParseFloat(string(outer), 64)
if err != nil || fCPU < MinMilliCPUs/1000 || fCPU > MaxMilliCPUs/1000 {
return ErrInvalidCPUs
}
*c = MilliCPUs(fCPU * 1000)
}
return nil
}
// implements json.Marshaler
func (c *MilliCPUs) MarshalJSON() ([]byte, error) {
if *c < MinMilliCPUs || *c > MaxMilliCPUs {
return nil, ErrInvalidCPUs
}
// always use milli cpus "1000m" format
return []byte(fmt.Sprintf("\"%s\"", c.String())), nil
}