github.com/cloud-foundations/dominator@v0.0.0-20221004181915-6e4fee580046/cmd/subd/vCpu.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"runtime"
     8  	"strings"
     9  
    10  	"github.com/Cloud-Foundations/Dominator/lib/log"
    11  )
    12  
    13  var metadataServer = "http://169.254.169.254/"
    14  var awsInstanceTypePath = "latest/meta-data/instance-type"
    15  
    16  func getAwsInstanceType() (string, error) {
    17  	resp, err := http.Get(metadataServer + awsInstanceTypePath)
    18  	if err != nil {
    19  		return "", err
    20  	}
    21  	defer resp.Body.Close()
    22  	if resp.StatusCode != 200 {
    23  		return "", errors.New(resp.Status)
    24  	}
    25  	if body, err := ioutil.ReadAll(resp.Body); err != nil {
    26  		return "", err
    27  	} else {
    28  		value := strings.TrimSpace(string(body))
    29  		if value == "" {
    30  			return "", errors.New("empty body")
    31  		} else {
    32  			return value, nil
    33  		}
    34  	}
    35  }
    36  
    37  func getAwsVcpuCreditRate() (uint, error) {
    38  	iType, err := getAwsInstanceType()
    39  	if err != nil {
    40  		return 0, err
    41  	}
    42  	switch iType {
    43  	case "t2.nano":
    44  		return 3, nil
    45  	case "t2.micro":
    46  		return 6, nil
    47  	case "t2.small":
    48  		return 12, nil
    49  	case "t2.medium":
    50  		return 24, nil
    51  	case "t2.large":
    52  		return 36, nil
    53  	case "t2.xlarge":
    54  		return 54, nil
    55  	case "t2.2xlarge":
    56  		return 81, nil
    57  	default:
    58  		return 0, nil
    59  	}
    60  }
    61  
    62  func adjustVcpuLimit(limit *uint, logger log.Logger) {
    63  	initialLimit := *limit
    64  	vCpuCreditRate, err := getAwsVcpuCreditRate()
    65  	if err == nil && vCpuCreditRate > 0 {
    66  		newLimit := initialLimit * vCpuCreditRate / 60 / uint(runtime.NumCPU())
    67  		logger.Printf("Adjusting default CPU limit to: %d%%\n", newLimit)
    68  		*limit = newLimit
    69  	}
    70  }