repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type options struct {
sourceOutput string
urlInput string
}
func main() {
opts := options{}
flag.StringVar(&opts.urlInput, "url", "https://raw.githubusercontent.com/aws/amazon-vpc-resource-controller-k8s/master/pkg/aws/vpc/limits.go",
"url of the raw vpc/limits.go file in the github.com/aws/amazon-vpc-resource-controller-k8s repo")
flag.StringVar(&opts.sourceOutput, "output", "pkg/providers/instancetype/zz_generated.vpclimits.go", "output location for the generated go source file")
flag.Parse()
limitsURL, err := url.Parse(opts.urlInput)
if err != nil {
log.Fatal(err)
}
out, err := os.Create(opts.sourceOutput)
if err != nil {
log.Fatal(err)
}
client := http.Client{Timeout: time.Second * 10}
resp, err := client.Get(limitsURL.String())
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
respData, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
newRespData := strings.Replace(string(respData), "package vpc", "package instancetype", 1)
out.WriteString(newRespData)
defer out.Close()
fmt.Printf("Downloaded vpc/limits.go from \"%s\" to file \"%s\"\n", limitsURL.String(), out.Name)
}
| 67 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
"github.com/aws/karpenter-core/pkg/operator/options"
)
func main() {
if len(os.Args) != 2 {
log.Fatalf("Usage: %s path/to/markdown.md", os.Args[0])
}
outputFileName := os.Args[1]
mdFile, err := os.ReadFile(outputFileName)
if err != nil {
log.Printf("Can't read %s file: %v", os.Args[1], err)
os.Exit(2)
}
genStart := "[comment]: <> (the content below is generated from hack/docs/configuration_gen_docs.go)"
genEnd := "[comment]: <> (end docs generated content from hack/docs/configuration_gen_docs.go)"
startDocSections := strings.Split(string(mdFile), genStart)
if len(startDocSections) != 2 {
log.Fatalf("expected one generated comment block start but got %d", len(startDocSections)-1)
}
endDocSections := strings.Split(string(mdFile), genEnd)
if len(endDocSections) != 2 {
log.Fatalf("expected one generated comment block end but got %d", len(endDocSections)-1)
}
topDoc := fmt.Sprintf("%s%s\n\n", startDocSections[0], genStart)
bottomDoc := fmt.Sprintf("\n%s%s", genEnd, endDocSections[1])
opts := options.New()
envVarsBlock := "| Environment Variable | CLI Flag | Description |\n"
envVarsBlock += "|--|--|--|\n"
opts.VisitAll(func(f *flag.Flag) {
if f.DefValue == "" {
envVarsBlock += fmt.Sprintf("| %s | %s | %s|\n", strings.ReplaceAll(strings.ToUpper(f.Name), "-", "_"), "\\-\\-"+f.Name, f.Usage)
} else {
envVarsBlock += fmt.Sprintf("| %s | %s | %s (default = %s)|\n", strings.ReplaceAll(strings.ToUpper(f.Name), "-", "_"), "\\-\\-"+f.Name, f.Usage, f.DefValue)
}
})
log.Println("writing output to", outputFileName)
f, err := os.Create(outputFileName)
if err != nil {
log.Fatalf("unable to open %s to write generated output: %v", outputFileName, err)
}
f.WriteString(topDoc + envVarsBlock + bottomDoc)
}
| 71 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"sort"
"strings"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/manager"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
coreoperator "github.com/aws/karpenter-core/pkg/operator"
coretest "github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
awscloudprovider "github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/operator"
"github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
// FakeManager is a manager that takes all the utilized calls from the operator setup
type FakeManager struct {
manager.Manager
}
func (m *FakeManager) GetClient() client.Client {
return fake.NewClientBuilder().Build()
}
func (m *FakeManager) GetConfig() *rest.Config {
return &rest.Config{}
}
func (m *FakeManager) Elected() <-chan struct{} {
return make(chan struct{}, 1)
}
func main() {
flag.Parse()
if flag.NArg() != 1 {
log.Fatalf("Usage: %s path/to/markdown.md", os.Args[0])
}
lo.Must0(os.Setenv("SYSTEM_NAMESPACE", "karpenter"))
lo.Must0(os.Setenv("AWS_SDK_LOAD_CONFIG", "true"))
lo.Must0(os.Setenv("AWS_REGION", "us-east-1"))
ctx := coresettings.ToContext(context.Background(), coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ClusterName: lo.ToPtr("docs-gen"),
ClusterEndpoint: lo.ToPtr("https://docs-gen.aws"),
IsolatedVPC: lo.ToPtr(true), // disable pricing lookup
}))
ctx, op := operator.NewOperator(ctx, &coreoperator.Operator{
Manager: &FakeManager{},
KubernetesInterface: kubernetes.NewForConfigOrDie(&rest.Config{}),
})
cp := awscloudprovider.New(op.InstanceTypesProvider, op.InstanceProvider, op.GetClient(), op.AMIProvider, op.SecurityGroupProvider, op.SubnetProvider)
provider := v1alpha1.AWS{SubnetSelector: map[string]string{
"*": "*",
}}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(provider); err != nil {
log.Fatalf("encoding provider, %s", err)
}
prov := &v1alpha5.Provisioner{
Spec: v1alpha5.ProvisionerSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpExists,
},
},
Provider: &v1alpha5.Provider{
Raw: buf.Bytes(),
},
},
}
instanceTypes, err := cp.GetInstanceTypes(ctx, prov)
if err != nil {
log.Fatalf("listing instance types, %s", err)
}
outputFileName := flag.Arg(0)
f, err := os.Create(outputFileName)
if err != nil {
log.Fatalf("error creating output file %s, %s", outputFileName, err)
}
log.Println("writing output to", outputFileName)
fmt.Fprintf(f, `---
title: "Instance Types"
linkTitle: "Instance Types"
weight: 100
description: >
Evaluate Instance Type Resources
---
`)
fmt.Fprintln(f, "<!-- this document is generated from hack/docs/instancetypes_gen_docs.go -->")
fmt.Fprintln(f, `AWS instance types offer varying resources and can be selected by labels. The values provided
below are the resources available with some assumptions and after the instance overhead has been subtracted:
- `+"`blockDeviceMappings` are not configured"+`
- `+"`aws-eni-limited-pod-density` is assumed to be `true`"+`
- `+"`amiFamily` is set to the default of `AL2`")
// generate a map of family -> instance types along with some other sorted lists. The sorted lists ensure we
// generate consistent docs every run.
families := map[string][]*cloudprovider.InstanceType{}
labelNameMap := sets.String{}
resourceNameMap := sets.String{}
for _, it := range instanceTypes {
familyName := strings.Split(it.Name, ".")[0]
families[familyName] = append(families[familyName], it)
for labelName := range it.Requirements {
labelNameMap.Insert(labelName)
}
for resourceName := range it.Capacity {
resourceNameMap.Insert(string(resourceName))
}
}
familyNames := lo.Keys(families)
sort.Strings(familyNames)
// we don't want to show a few labels that will vary amongst regions
delete(labelNameMap, v1.LabelTopologyZone)
delete(labelNameMap, v1alpha5.LabelCapacityType)
labelNames := lo.Keys(labelNameMap)
sort.Strings(labelNames)
resourceNames := lo.Keys(resourceNameMap)
sort.Strings(resourceNames)
for _, familyName := range familyNames {
fmt.Fprintf(f, "## %s Family\n", familyName)
// sort the instance types within the family, we sort by CPU and memory which should be a pretty good ordering
sort.Slice(families[familyName], func(a, b int) bool {
lhs := families[familyName][a]
rhs := families[familyName][b]
lhsResources := lhs.Capacity
rhsResources := rhs.Capacity
if cpuCmp := resources.Cmp(*lhsResources.Cpu(), *rhsResources.Cpu()); cpuCmp != 0 {
return cpuCmp < 0
}
if memCmp := resources.Cmp(*lhsResources.Memory(), *rhsResources.Memory()); memCmp != 0 {
return memCmp < 0
}
return lhs.Name < rhs.Name
})
for _, it := range families[familyName] {
fmt.Fprintf(f, "### `%s`\n", it.Name)
minusOverhead := resources.Subtract(it.Capacity, it.Overhead.Total())
fmt.Fprintln(f, "#### Labels")
fmt.Fprintln(f, " | Label | Value |")
fmt.Fprintln(f, " |--|--|")
for _, label := range labelNames {
req, ok := it.Requirements[label]
if !ok {
continue
}
if req.Key == v1.LabelTopologyRegion {
continue
}
if len(req.Values()) == 1 {
fmt.Fprintf(f, " |%s|%s|\n", label, req.Values()[0])
}
}
fmt.Fprintln(f, "#### Resources")
fmt.Fprintln(f, " | Resource | Quantity |")
fmt.Fprintln(f, " |--|--|")
for _, resourceName := range resourceNames {
quantity := minusOverhead[v1.ResourceName(resourceName)]
if quantity.IsZero() {
continue
}
if v1.ResourceName(resourceName) == v1.ResourceEphemeralStorage {
i64, _ := quantity.AsInt64()
quantity = *resource.NewQuantity(i64, resource.BinarySI)
}
fmt.Fprintf(f, " |%s|%s|\n", resourceName, quantity.String())
}
}
}
}
| 222 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/metrics"
)
type metricInfo struct {
namespace string
subsystem string
name string
help string
}
func (i metricInfo) qualifiedName() string {
return strings.Join(lo.Compact([]string{i.namespace, i.subsystem, i.name}), "_")
}
// metrics_gen_docs is used to parse the source code for Prometheus metrics and automatically generate markdown documentation
// based on the naming and help provided in the source code.
func main() {
flag.Parse()
if flag.NArg() < 2 {
log.Fatalf("Usage: %s path/to/metrics/controller path/to/metrics/controller2 path/to/markdown.md", os.Args[0])
}
var allMetrics []metricInfo
for i := 0; i < flag.NArg()-1; i++ {
packages := getPackages(flag.Arg(i))
allMetrics = append(allMetrics, getMetricsFromPackages(packages...)...)
}
sort.Slice(allMetrics, bySubsystem(allMetrics))
outputFileName := flag.Arg(flag.NArg() - 1)
f, err := os.Create(outputFileName)
if err != nil {
log.Fatalf("error creating output file %s, %s", outputFileName, err)
}
log.Println("writing output to", outputFileName)
fmt.Fprintf(f, `---
title: "Metrics"
linkTitle: "Metrics"
weight: 7
description: >
Inspect Karpenter Metrics
---
`)
fmt.Fprintf(f, "<!-- this document is generated from hack/docs/metrics_gen_docs.go -->\n")
fmt.Fprintf(f, "Karpenter makes several metrics available in Prometheus format to allow monitoring cluster provisioning status. "+
"These metrics are available by default at `karpenter.karpenter.svc.cluster.local:8080/metrics` configurable via the `METRICS_PORT` environment variable documented [here](../settings)\n")
previousSubsystem := ""
for _, metric := range allMetrics {
// Controller Runtime naming is different in that they don't specify a namespace or subsystem
// Getting the metrics requires special parsing logic
if metric.subsystem == "" && strings.HasPrefix(metric.name, "controller_runtime_") {
metric.subsystem = "controller_runtime"
metric.name = strings.TrimPrefix(metric.name, "controller_runtime_")
}
if metric.subsystem != previousSubsystem {
subsystemTitle := strings.Join(lo.Map(strings.Split(metric.subsystem, "_"), func(s string, _ int) string {
return fmt.Sprintf("%s%s", strings.ToTitle(s[0:1]), s[1:])
}), " ")
fmt.Fprintf(f, "## %s Metrics\n", subsystemTitle)
previousSubsystem = metric.subsystem
fmt.Fprintln(f)
}
fmt.Fprintf(f, "### `%s`\n", metric.qualifiedName())
fmt.Fprintf(f, "%s\n", metric.help)
fmt.Fprintln(f)
}
}
func getPackages(root string) []*ast.Package {
var packages []*ast.Package
fset := token.NewFileSet()
// walk our metrics controller directory
log.Println("parsing code in", root)
filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if d == nil {
return nil
}
if !d.IsDir() {
return nil
}
// parse the packagers that we find
pkgs, err := parser.ParseDir(fset, path, func(info fs.FileInfo) bool {
return true
}, parser.AllErrors)
if err != nil {
log.Fatalf("error parsing, %s", err)
}
for _, pkg := range pkgs {
if strings.HasSuffix(pkg.Name, "_test") {
continue
}
packages = append(packages, pkg)
}
return nil
})
return packages
}
func getMetricsFromPackages(packages ...*ast.Package) []metricInfo {
// metrics are all package global variables
var allMetrics []metricInfo
for _, pkg := range packages {
for _, file := range pkg.Files {
for _, decl := range file.Decls {
switch v := decl.(type) {
case *ast.FuncDecl:
// ignore
case *ast.GenDecl:
if v.Tok == token.VAR {
allMetrics = append(allMetrics, handleVariableDeclaration(v)...)
}
default:
}
}
}
}
return allMetrics
}
func bySubsystem(metrics []metricInfo) func(i int, j int) bool {
subSystemSortOrder := map[string]int{}
subSystemSortOrder["provisioner"] = 1
subSystemSortOrder["nodes"] = 2
subSystemSortOrder["pods"] = 3
subSystemSortOrder["cloudprovider"] = 4
subSystemSortOrder["cloudprovider_batcher"] = 5
return func(i, j int) bool {
lhs := metrics[i]
rhs := metrics[j]
if subSystemSortOrder[lhs.subsystem] != subSystemSortOrder[rhs.subsystem] {
return subSystemSortOrder[lhs.subsystem] < subSystemSortOrder[rhs.subsystem]
}
return lhs.qualifiedName() < rhs.qualifiedName()
}
}
func handleVariableDeclaration(v *ast.GenDecl) []metricInfo {
var promMetrics []metricInfo
for _, spec := range v.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
for _, v := range vs.Values {
ce, ok := v.(*ast.CallExpr)
if !ok {
continue
}
funcPkg := getFuncPackage(ce.Fun)
if funcPkg != "prometheus" {
continue
}
if len(ce.Args) == 0 {
continue
}
arg := ce.Args[0].(*ast.CompositeLit)
keyValuePairs := map[string]string{}
for _, el := range arg.Elts {
kv := el.(*ast.KeyValueExpr)
key := fmt.Sprintf("%s", kv.Key)
switch key {
case "Namespace", "Subsystem", "Name", "Help":
default:
// skip any keys we don't care about
continue
}
value := ""
switch val := kv.Value.(type) {
case *ast.BasicLit:
value = val.Value
case *ast.SelectorExpr:
selector := fmt.Sprintf("%s.%s", val.X, val.Sel)
if v, err := getIdentMapping(selector); err != nil {
log.Fatalf("unsupported selector %s, %s", selector, err)
} else {
value = v
}
case *ast.Ident:
if v, err := getIdentMapping(val.String()); err != nil {
log.Fatal(err)
} else {
value = v
}
default:
log.Fatalf("unsupported value %T %v", kv.Value, kv.Value)
}
keyValuePairs[key] = strings.TrimFunc(value, func(r rune) bool {
return r == '"'
})
}
promMetrics = append(promMetrics, metricInfo{
namespace: keyValuePairs["Namespace"],
subsystem: keyValuePairs["Subsystem"],
name: keyValuePairs["Name"],
help: keyValuePairs["Help"],
})
}
}
return promMetrics
}
func getFuncPackage(fun ast.Expr) string {
if pexpr, ok := fun.(*ast.ParenExpr); ok {
return getFuncPackage(pexpr.X)
}
if sexpr, ok := fun.(*ast.StarExpr); ok {
return getFuncPackage(sexpr.X)
}
if sel, ok := fun.(*ast.SelectorExpr); ok {
return fmt.Sprintf("%s", sel.X)
}
if ident, ok := fun.(*ast.Ident); ok {
return ident.String()
}
if iexpr, ok := fun.(*ast.IndexExpr); ok {
return getFuncPackage(iexpr.X)
}
log.Fatalf("unsupported func expression %T, %v", fun, fun)
return ""
}
// we cannot get the value of an Identifier directly so we map it manually instead
func getIdentMapping(identName string) (string, error) {
identMapping := map[string]string{
"metrics.Namespace": metrics.Namespace,
"Namespace": metrics.Namespace,
"nodeSubsystem": "nodes",
"machineSubsystem": "machines",
"interruptionSubsystem": "interruption",
"nodeTemplateSubsystem": "nodetemplate",
"deprovisioningSubsystem": "deprovisioning",
"consistencySubsystem": "consistency",
"batcherSubsystem": "cloudprovider_batcher",
"cloudProviderSubsystem": "cloudprovider",
}
if v, ok := identMapping[identName]; ok {
return v, nil
}
return "", fmt.Errorf("no identifier mapping exists for %s", identName)
}
| 280 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package apis contains Kubernetes API groups.
package apis
import (
_ "embed"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/aws/karpenter-core/pkg/operator/scheme"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var (
// Builder includes all types within the apis package
Builder = runtime.NewSchemeBuilder(
v1alpha1.SchemeBuilder.AddToScheme,
)
// AddToScheme may be used to add all resources defined in the project to a Scheme
AddToScheme = Builder.AddToScheme
Settings = []coresettings.Injectable{&settings.Settings{}}
)
//go:generate controller-gen crd object:headerFile="../../hack/boilerplate.go.txt" paths="./..." output:crd:artifacts:config=crds
var (
//go:embed crds/karpenter.k8s.aws_awsnodetemplates.yaml
AWSNodeTemplateCRD []byte
CRDs = append(apis.CRDs, lo.Must(functional.Unmarshal[v1.CustomResourceDefinition](AWSNodeTemplateCRD)))
)
func init() {
lo.Must0(AddToScheme(scheme.Scheme))
}
| 55 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package settings
import (
"context"
"encoding/json"
"fmt"
"net/url"
"github.com/go-playground/validator/v10"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
"knative.dev/pkg/configmap"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
type settingsKeyType struct{}
var ContextKey = settingsKeyType{}
var defaultSettings = &Settings{
ClusterName: "",
ClusterEndpoint: "",
DefaultInstanceProfile: "",
EnablePodENI: false,
EnableENILimitedPodDensity: true,
IsolatedVPC: false,
VMMemoryOverheadPercent: 0.075,
InterruptionQueueName: "",
Tags: map[string]string{},
ReservedENIs: 0,
}
// +k8s:deepcopy-gen=true
type Settings struct {
ClusterName string `validate:"required"`
ClusterEndpoint string
DefaultInstanceProfile string
EnablePodENI bool
EnableENILimitedPodDensity bool
IsolatedVPC bool
VMMemoryOverheadPercent float64 `validate:"min=0"`
InterruptionQueueName string
Tags map[string]string
ReservedENIs int `validate:"min=0"`
}
func (*Settings) ConfigMap() string {
return "karpenter-global-settings"
}
// Inject creates a Settings from the supplied ConfigMap
func (*Settings) Inject(ctx context.Context, cm *v1.ConfigMap) (context.Context, error) {
s := defaultSettings.DeepCopy()
if err := configmap.Parse(cm.Data,
configmap.AsString("aws.clusterName", &s.ClusterName),
configmap.AsString("aws.clusterEndpoint", &s.ClusterEndpoint),
configmap.AsString("aws.defaultInstanceProfile", &s.DefaultInstanceProfile),
configmap.AsBool("aws.enablePodENI", &s.EnablePodENI),
configmap.AsBool("aws.enableENILimitedPodDensity", &s.EnableENILimitedPodDensity),
configmap.AsBool("aws.isolatedVPC", &s.IsolatedVPC),
configmap.AsFloat64("aws.vmMemoryOverheadPercent", &s.VMMemoryOverheadPercent),
configmap.AsString("aws.interruptionQueueName", &s.InterruptionQueueName),
AsStringMap("aws.tags", &s.Tags),
configmap.AsInt("aws.reservedENIs", &s.ReservedENIs),
); err != nil {
return ctx, fmt.Errorf("parsing settings, %w", err)
}
if err := s.Validate(); err != nil {
return ctx, fmt.Errorf("validating settings, %w", err)
}
return ToContext(ctx, s), nil
}
// Validate leverages struct tags with go-playground/validator so you can define a struct with custom
// validation on fields i.e.
//
// type ExampleStruct struct {
// Example metav1.Duration `json:"example" validate:"required,min=10m"`
// }
func (s Settings) Validate() error {
return multierr.Combine(
s.validateEndpoint(),
s.validateTags(),
validator.New().Struct(s),
)
}
func (s Settings) validateEndpoint() error {
if s.ClusterEndpoint == "" {
return nil
}
endpoint, err := url.Parse(s.ClusterEndpoint)
// url.Parse() will accept a lot of input without error; make
// sure it's a real URL
if err != nil || !endpoint.IsAbs() || endpoint.Hostname() == "" {
return fmt.Errorf("\"%s\" not a valid clusterEndpoint URL", s.ClusterEndpoint)
}
return nil
}
func (s Settings) validateTags() (err error) {
for k := range s.Tags {
for _, pattern := range v1alpha1.RestrictedTagPatterns {
if pattern.MatchString(k) {
err = multierr.Append(err, apis.ErrInvalidKeyName(k, "tags", fmt.Sprintf("tag contains a restricted tag %q", pattern.String())))
}
}
}
return err
}
func ToContext(ctx context.Context, s *Settings) context.Context {
return context.WithValue(ctx, ContextKey, s)
}
func FromContext(ctx context.Context) *Settings {
data := ctx.Value(ContextKey)
if data == nil {
// This is developer error if this happens, so we should panic
panic("settings doesn't exist in context")
}
return data.(*Settings)
}
// AsTypedString passes the value at key through into the target, if it exists.
func AsTypedString[T ~string](key string, target *T) configmap.ParseFunc {
return func(data map[string]string) error {
if raw, ok := data[key]; ok {
*target = T(raw)
}
return nil
}
}
// AsStringMap parses a value as a JSON map of map[string]string.
func AsStringMap(key string, target *map[string]string) configmap.ParseFunc {
return func(data map[string]string) error {
if raw, ok := data[key]; ok {
m := map[string]string{}
if err := json.Unmarshal([]byte(raw), &m); err != nil {
return err
}
*target = m
}
return nil
}
}
| 165 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package settings_test
import (
"context"
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
. "knative.dev/pkg/logging/testing"
"github.com/aws/karpenter/pkg/apis/settings"
)
var ctx context.Context
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Settings")
}
var _ = Describe("Validation", func() {
It("should succeed to set defaults", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.DefaultInstanceProfile).To(Equal(""))
Expect(s.EnablePodENI).To(BeFalse())
Expect(s.EnableENILimitedPodDensity).To(BeTrue())
Expect(s.IsolatedVPC).To(BeFalse())
Expect(s.VMMemoryOverheadPercent).To(Equal(0.075))
Expect(len(s.Tags)).To(BeZero())
Expect(s.ReservedENIs).To(Equal(0))
})
It("should succeed to set custom values", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.defaultInstanceProfile": "karpenter",
"aws.enablePodENI": "true",
"aws.enableENILimitedPodDensity": "false",
"aws.isolatedVPC": "true",
"aws.vmMemoryOverheadPercent": "0.1",
"aws.tags": `{"tag1": "value1", "tag2": "value2", "example.com/tag": "my-value"}`,
"aws.reservedENIs": "1",
},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.DefaultInstanceProfile).To(Equal("karpenter"))
Expect(s.EnablePodENI).To(BeTrue())
Expect(s.EnableENILimitedPodDensity).To(BeFalse())
Expect(s.IsolatedVPC).To(BeTrue())
Expect(s.VMMemoryOverheadPercent).To(Equal(0.1))
Expect(len(s.Tags)).To(Equal(3))
Expect(s.Tags).To(HaveKeyWithValue("tag1", "value1"))
Expect(s.Tags).To(HaveKeyWithValue("tag2", "value2"))
Expect(s.Tags).To(HaveKeyWithValue("example.com/tag", "my-value"))
Expect(s.ReservedENIs).To(Equal(1))
})
It("should succeed when setting values that no longer exist (backwards compatibility)", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.defaultInstanceProfile": "karpenter",
"aws.enablePodENI": "true",
"aws.enableENILimitedPodDensity": "false",
"aws.isolatedVPC": "true",
"aws.vmMemoryOverheadPercent": "0.1",
"aws.tags": `{"tag1": "value1", "tag2": "value2", "example.com/tag": "my-value"}`,
"aws.reservedENIs": "1",
"aws.nodeNameConvention": "resource-name",
},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.DefaultInstanceProfile).To(Equal("karpenter"))
Expect(s.EnablePodENI).To(BeTrue())
Expect(s.EnableENILimitedPodDensity).To(BeFalse())
Expect(s.IsolatedVPC).To(BeTrue())
Expect(s.VMMemoryOverheadPercent).To(Equal(0.1))
Expect(len(s.Tags)).To(Equal(3))
Expect(s.Tags).To(HaveKeyWithValue("tag1", "value1"))
Expect(s.Tags).To(HaveKeyWithValue("tag2", "value2"))
Expect(s.Tags).To(HaveKeyWithValue("example.com/tag", "my-value"))
Expect(s.ReservedENIs).To(Equal(1))
})
It("should succeed validation when tags contain parts of restricted domains", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.tags": `{"karpenter.sh/custom-key": "value1", "karpenter.sh/managed": "true", "kubernetes.io/role/key": "value2", "kubernetes.io/cluster/other-tag/hello": "value3"}`,
},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.Tags).To(HaveKeyWithValue("karpenter.sh/custom-key", "value1"))
Expect(s.Tags).To(HaveKeyWithValue("karpenter.sh/managed", "true"))
Expect(s.Tags).To(HaveKeyWithValue("kubernetes.io/role/key", "value2"))
Expect(s.Tags).To(HaveKeyWithValue("kubernetes.io/cluster/other-tag/hello", "value3"))
})
It("should fail validation with panic when clusterName not included", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when clusterEndpoint is invalid (not absolute)", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterName": "my-name",
"aws.clusterEndpoint": "00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation with panic when vmMemoryOverheadPercent is negative", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.vmMemoryOverheadPercent": "-0.01",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when tags have keys that are in the restricted set of keys", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.tags": `{"karpenter.sh/provisioner-name": "value1"}`,
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
cm = &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.tags": `{"value1", "karpenter.sh/managed-by": "value"}`,
},
}
_, err = (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
cm = &v1.ConfigMap{
Data: map[string]string{
"aws.clusterEndpoint": "https://00000000000000000000000.gr7.us-west-2.eks.amazonaws.com",
"aws.clusterName": "my-cluster",
"aws.tags": `{"kubernetes.io/cluster/my-cluster": "value2"}`,
},
}
_, err = (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation with reservedENIs is negative", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"aws.reservedENIs": "-1",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
})
| 200 |
karpenter | aws | Go | //go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
package settings
import ()
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Settings) DeepCopyInto(out *Settings) {
*out = *in
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Settings.
func (in *Settings) DeepCopy() *Settings {
if in == nil {
return nil
}
out := new(Settings)
in.DeepCopyInto(out)
return out
}
| 45 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// Subnet contains resolved Subnet selector values utilized for node launch
type Subnet struct {
// ID of the subnet
// +required
ID string `json:"id"`
// The associated availability zone
// +required
Zone string `json:"zone"`
}
// SecurityGroup contains resolved SecurityGroup selector values utilized for node launch
type SecurityGroup struct {
// ID of the security group
// +required
ID string `json:"id"`
// Name of the security group
// +optional
Name string `json:"name,omitempty"`
}
// AMI contains resolved AMI selector values utilized for node launch
type AMI struct {
// ID of the AMI
// +required
ID string `json:"id"`
// Name of the AMI
// +optional
Name string `json:"name,omitempty"`
// Requirements of the AMI to be utilized on an instance type
// +required
Requirements []v1.NodeSelectorRequirement `json:"requirements"`
}
// AWSNodeTemplateStatus contains the resolved state of the AWSNodeTemplate
type AWSNodeTemplateStatus struct {
// Subnets contains the current Subnet values that are available to the
// cluster under the subnet selectors.
// +optional
Subnets []Subnet `json:"subnets,omitempty"`
// SecurityGroups contains the current Security Groups values that are available to the
// cluster under the SecurityGroups selectors.
// +optional
SecurityGroups []SecurityGroup `json:"securityGroups,omitempty"`
// AMI contains the current AMI values that are available to the
// cluster under the AMI selectors.
// +optional
AMIs []AMI `json:"amis,omitempty"`
}
// AWSNodeTemplateSpec is the top level specification for the AWS Karpenter Provider.
// This will contain configuration necessary to launch instances in AWS.
type AWSNodeTemplateSpec struct {
// UserData to be applied to the provisioned nodes.
// It must be in the appropriate format based on the AMIFamily in use. Karpenter will merge certain fields into
// this UserData to ensure nodes are being provisioned with the correct configuration.
// +optional
UserData *string `json:"userData,omitempty"`
AWS `json:",inline"`
// AMISelector discovers AMIs to be used by Amazon EC2 tags.
// +optional
AMISelector map[string]string `json:"amiSelector,omitempty"`
// DetailedMonitoring controls if detailed monitoring is enabled for instances that are launched
// +optional
DetailedMonitoring *bool `json:"detailedMonitoring,omitempty"`
}
// AWSNodeTemplate is the Schema for the AWSNodeTemplate API
// +kubebuilder:object:root=true
// +kubebuilder:resource:path=awsnodetemplates,scope=Cluster,categories=karpenter
// +kubebuilder:subresource:status
type AWSNodeTemplate struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec AWSNodeTemplateSpec `json:"spec,omitempty"`
Status AWSNodeTemplateStatus `json:"status,omitempty"`
}
// AWSNodeTemplateList contains a list of AWSNodeTemplate
// +kubebuilder:object:root=true
type AWSNodeTemplateList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []AWSNodeTemplate `json:"items"`
}
| 107 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"context"
)
// SetDefaults for the AWSNodeTemplate
func (a *AWSNodeTemplate) SetDefaults(_ context.Context) {
}
| 24 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"context"
"fmt"
"regexp"
"github.com/samber/lo"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"knative.dev/pkg/apis"
"github.com/aws/karpenter-core/pkg/utils/functional"
)
const (
userDataPath = "userData"
amiSelectorPath = "amiSelector"
)
var (
amiRegex = regexp.MustCompile("ami-[0-9a-z]+")
)
func (a *AWSNodeTemplate) SupportedVerbs() []admissionregistrationv1.OperationType {
return []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
}
}
func (a *AWSNodeTemplate) Validate(ctx context.Context) (errs *apis.FieldError) {
return errs.Also(
apis.ValidateObjectMetadata(a).ViaField("metadata"),
a.Spec.validate(ctx).ViaField("spec"),
)
}
func (a *AWSNodeTemplateSpec) validate(_ context.Context) (errs *apis.FieldError) {
return errs.Also(
a.AWS.Validate(),
a.validateUserData(),
a.validateAMISelector(),
a.validateAMIFamily(),
a.validateTags(),
)
}
func (a *AWSNodeTemplateSpec) validateUserData() (errs *apis.FieldError) {
if a.UserData == nil {
return nil
}
if a.LaunchTemplateName != nil {
errs = errs.Also(apis.ErrMultipleOneOf(userDataPath, launchTemplatePath))
}
if lo.FromPtr(a.AMIFamily) == AMIFamilyWindows2019 || lo.FromPtr(a.AMIFamily) == AMIFamilyWindows2022 {
errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("%s AMIFamily is not currently supported with custom userData", lo.FromPtr(a.AMIFamily)), userDataPath))
}
return errs
}
func (a *AWSNodeTemplateSpec) validateAMIFamily() (errs *apis.FieldError) {
if a.AMIFamily == nil {
return nil
}
if *a.AMIFamily == AMIFamilyCustom && a.AMISelector == nil {
errs = errs.Also(apis.ErrMissingField(amiSelectorPath))
}
return errs
}
func (a *AWSNodeTemplateSpec) validateAMISelector() (errs *apis.FieldError) {
if a.AMISelector == nil {
return nil
}
if a.LaunchTemplateName != nil {
errs = errs.Also(apis.ErrMultipleOneOf(amiSelectorPath, launchTemplatePath))
}
for key, value := range a.AMISelector {
if key == "" || value == "" {
errs = errs.Also(apis.ErrInvalidValue("\"\"", fmt.Sprintf("%s['%s']", amiSelectorPath, key)))
}
if key == "aws-ids" {
for _, amiID := range functional.SplitCommaSeparatedString(value) {
if !amiRegex.MatchString(amiID) {
fieldValue := fmt.Sprintf("\"%s\"", amiID)
message := fmt.Sprintf("%s['%s'] must be a valid ami-id (regex: %s)", amiSelectorPath, key, amiRegex.String())
errs = errs.Also(apis.ErrInvalidValue(fieldValue, message))
}
}
}
}
return errs
}
func (a *AWSNodeTemplateSpec) validateTags() (errs *apis.FieldError) {
for k := range a.Tags {
for _, pattern := range RestrictedTagPatterns {
if pattern.MatchString(k) {
errs = errs.Also(apis.ErrInvalidKeyName(k, "tags", fmt.Sprintf("tag contains a restricted tag matching %q", pattern.String())))
}
}
}
return errs
}
| 119 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// +k8s:openapi-gen=true
// +k8s:deepcopy-gen=package,register
// +k8s:defaulter-gen=TypeMeta
// +groupName=karpenter.k8s.aws
package v1alpha1 // doc.go is discovered by codegen
| 20 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// AWS contains parameters specific to this cloud provider
// +kubebuilder:object:root=true
type AWS struct {
// TypeMeta includes version and kind of the extensions, inferred if not provided.
// +optional
metav1.TypeMeta `json:",inline"`
// AMIFamily is the AMI family that instances use.
// +optional
AMIFamily *string `json:"amiFamily,omitempty"`
// Context is a Reserved field in EC2 APIs
// https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateFleet.html
// +optional
Context *string `json:"context,omitempty"`
// InstanceProfile is the AWS identity that instances use.
// +optional
InstanceProfile *string `json:"instanceProfile,omitempty"`
// SubnetSelector discovers subnets by tags. A value of "" is a wildcard.
// +optional
SubnetSelector map[string]string `json:"subnetSelector,omitempty"`
// SecurityGroups specify the names of the security groups.
// +optional
SecurityGroupSelector map[string]string `json:"securityGroupSelector,omitempty"`
// Tags to be applied on ec2 resources like instances and launch templates.
// +optional
Tags map[string]string `json:"tags,omitempty"`
// LaunchTemplate parameters to use when generating an LT
LaunchTemplate `json:",inline,omitempty"`
}
type LaunchTemplate struct {
// LaunchTemplateName for the node. If not specified, a launch template will be generated.
// NOTE: This field is for specifying a custom launch template and is exposed in the Spec
// as `launchTemplate` for backwards compatibility.
// +optional
LaunchTemplateName *string `json:"launchTemplate,omitempty"`
// MetadataOptions for the generated launch template of provisioned nodes.
//
// This specifies the exposure of the Instance Metadata Service to
// provisioned EC2 nodes. For more information,
// see Instance Metadata and User Data
// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)
// in the Amazon Elastic Compute Cloud User Guide.
//
// Refer to recommended, security best practices
// (https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node)
// for limiting exposure of Instance Metadata and User Data to pods.
// If omitted, defaults to httpEndpoint enabled, with httpProtocolIPv6
// disabled, with httpPutResponseLimit of 2, and with httpTokens
// required.
// +optional
MetadataOptions *MetadataOptions `json:"metadataOptions,omitempty"`
// BlockDeviceMappings to be applied to provisioned nodes.
// +optionals
BlockDeviceMappings []*BlockDeviceMapping `json:"blockDeviceMappings,omitempty"`
}
// MetadataOptions contains parameters for specifying the exposure of the
// Instance Metadata Service to provisioned EC2 nodes.
type MetadataOptions struct {
// HTTPEndpoint enables or disables the HTTP metadata endpoint on provisioned
// nodes. If metadata options is non-nil, but this parameter is not specified,
// the default state is "enabled".
//
// If you specify a value of "disabled", instance metadata will not be accessible
// on the node.
// +optional
HTTPEndpoint *string `json:"httpEndpoint,omitempty"`
// HTTPProtocolIPv6 enables or disables the IPv6 endpoint for the instance metadata
// service on provisioned nodes. If metadata options is non-nil, but this parameter
// is not specified, the default state is "disabled".
// +optional
HTTPProtocolIPv6 *string `json:"httpProtocolIPv6,omitempty"`
// HTTPPutResponseHopLimit is the desired HTTP PUT response hop limit for
// instance metadata requests. The larger the number, the further instance
// metadata requests can travel. Possible values are integers from 1 to 64.
// If metadata options is non-nil, but this parameter is not specified, the
// default value is 1.
// +optional
HTTPPutResponseHopLimit *int64 `json:"httpPutResponseHopLimit,omitempty"`
// HTTPTokens determines the state of token usage for instance metadata
// requests. If metadata options is non-nil, but this parameter is not
// specified, the default state is "optional".
//
// If the state is optional, one can choose to retrieve instance metadata with
// or without a signed token header on the request. If one retrieves the IAM
// role credentials without a token, the version 1.0 role credentials are
// returned. If one retrieves the IAM role credentials using a valid signed
// token, the version 2.0 role credentials are returned.
//
// If the state is "required", one must send a signed token header with any
// instance metadata retrieval requests. In this state, retrieving the IAM
// role credentials always returns the version 2.0 credentials; the version
// 1.0 credentials are not available.
// +optional
HTTPTokens *string `json:"httpTokens,omitempty"`
}
type BlockDeviceMapping struct {
// The device name (for example, /dev/sdh or xvdh).
DeviceName *string `json:"deviceName,omitempty"`
// EBS contains parameters used to automatically set up EBS volumes when an instance is launched.
EBS *BlockDevice `json:"ebs,omitempty"`
}
type BlockDevice struct {
// DeleteOnTermination indicates whether the EBS volume is deleted on instance termination.
DeleteOnTermination *bool `json:"deleteOnTermination,omitempty"`
// Encrypted indicates whether the EBS volume is encrypted. Encrypted volumes can only
// be attached to instances that support Amazon EBS encryption. If you are creating
// a volume from a snapshot, you can't specify an encryption value.
Encrypted *bool `json:"encrypted,omitempty"`
// IOPS is the number of I/O operations per second (IOPS). For gp3, io1, and io2 volumes,
// this represents the number of IOPS that are provisioned for the volume. For
// gp2 volumes, this represents the baseline performance of the volume and the
// rate at which the volume accumulates I/O credits for bursting.
//
// The following are the supported values for each volume type:
//
// * gp3: 3,000-16,000 IOPS
//
// * io1: 100-64,000 IOPS
//
// * io2: 100-64,000 IOPS
//
// For io1 and io2 volumes, we guarantee 64,000 IOPS only for Instances built
// on the Nitro System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances).
// Other instance families guarantee performance up to 32,000 IOPS.
//
// This parameter is supported for io1, io2, and gp3 volumes only. This parameter
// is not supported for gp2, st1, sc1, or standard volumes.
IOPS *int64 `json:"iops,omitempty"`
// KMSKeyID (ARN) of the symmetric Key Management Service (KMS) CMK used for encryption.
KMSKeyID *string `json:"kmsKeyID,omitempty"`
// SnapshotID is the ID of an EBS snapshot
SnapshotID *string `json:"snapshotID,omitempty"`
// Throughput to provision for a gp3 volume, with a maximum of 1,000 MiB/s.
// Valid Range: Minimum value of 125. Maximum value of 1000.
Throughput *int64 `json:"throughput,omitempty"`
// VolumeSize in GiBs. You must specify either a snapshot ID or
// a volume size. The following are the supported volumes sizes for each volume
// type:
//
// * gp2 and gp3: 1-16,384
//
// * io1 and io2: 4-16,384
//
// * st1 and sc1: 125-16,384
//
// * standard: 1-1,024
VolumeSize *resource.Quantity `json:"volumeSize,omitempty" hash:"string"`
// VolumeType of the block device.
// For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html)
// in the Amazon Elastic Compute Cloud User Guide.
VolumeType *string `json:"volumeType,omitempty"`
}
func DeserializeProvider(raw []byte) (*AWS, error) {
a := &AWS{}
_, gvk, err := codec.UniversalDeserializer().Decode(raw, nil, a)
if err != nil {
return nil, err
}
if gvk != nil {
a.SetGroupVersionKind(*gvk)
}
return a, nil
}
| 199 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"fmt"
"regexp"
"strings"
"github.com/aws/aws-sdk-go/service/ec2"
"k8s.io/apimachinery/pkg/api/resource"
"knative.dev/pkg/apis"
"github.com/aws/karpenter-core/pkg/utils/functional"
)
const (
launchTemplatePath = "launchTemplate"
securityGroupSelectorPath = "securityGroupSelector"
fieldPathSubnetSelectorPath = "subnetSelector"
amiFamilyPath = "amiFamily"
metadataOptionsPath = "metadataOptions"
instanceProfilePath = "instanceProfile"
blockDeviceMappingsPath = "blockDeviceMappings"
)
var (
minVolumeSize = *resource.NewScaledQuantity(1, resource.Giga)
maxVolumeSize = *resource.NewScaledQuantity(64, resource.Tera)
subnetRegex = regexp.MustCompile("subnet-[0-9a-z]+")
securityGroupRegex = regexp.MustCompile("sg-[0-9a-z]+")
)
func (a *AWS) Validate() (errs *apis.FieldError) {
return errs.Also(
a.validate().ViaField("provider"),
)
}
func (a *AWS) validate() (errs *apis.FieldError) {
return errs.Also(
a.validateLaunchTemplate(),
a.validateSubnets(),
a.validateSecurityGroups(),
a.validateTags(),
a.validateMetadataOptions(),
a.validateAMIFamily(),
a.validateBlockDeviceMappings(),
)
}
func (a *AWS) validateLaunchTemplate() (errs *apis.FieldError) {
if a.LaunchTemplateName == nil {
return nil
}
if a.SecurityGroupSelector != nil {
errs = errs.Also(apis.ErrMultipleOneOf(launchTemplatePath, securityGroupSelectorPath))
}
if a.MetadataOptions != nil {
errs = errs.Also(apis.ErrMultipleOneOf(launchTemplatePath, metadataOptionsPath))
}
if a.AMIFamily != nil {
errs = errs.Also(apis.ErrMultipleOneOf(launchTemplatePath, amiFamilyPath))
}
if a.InstanceProfile != nil {
errs = errs.Also(apis.ErrMultipleOneOf(launchTemplatePath, instanceProfilePath))
}
if len(a.BlockDeviceMappings) != 0 {
errs = errs.Also(apis.ErrMultipleOneOf(launchTemplatePath, blockDeviceMappingsPath))
}
return errs
}
func (a *AWS) validateSubnets() (errs *apis.FieldError) {
if a.SubnetSelector == nil {
errs = errs.Also(apis.ErrMissingField(fieldPathSubnetSelectorPath))
}
for key, value := range a.SubnetSelector {
if key == "" || value == "" {
errs = errs.Also(apis.ErrInvalidValue("\"\"", fmt.Sprintf("%s['%s']", fieldPathSubnetSelectorPath, key)))
}
if key == "aws-ids" {
for _, subnetID := range functional.SplitCommaSeparatedString(value) {
if !subnetRegex.MatchString(subnetID) {
fieldValue := fmt.Sprintf("\"%s\"", subnetID)
message := fmt.Sprintf("%s['%s'] must be a valid subnet-id (regex: %s)", fieldPathSubnetSelectorPath, key, subnetRegex.String())
errs = errs.Also(apis.ErrInvalidValue(fieldValue, message))
}
}
}
}
return errs
}
func (a *AWS) validateSecurityGroups() (errs *apis.FieldError) {
if a.LaunchTemplateName != nil {
return nil
}
if a.SecurityGroupSelector == nil {
errs = errs.Also(apis.ErrMissingField(securityGroupSelectorPath))
}
for key, value := range a.SecurityGroupSelector {
if key == "" || value == "" {
errs = errs.Also(apis.ErrInvalidValue("\"\"", fmt.Sprintf("%s['%s']", securityGroupSelectorPath, key)))
}
if key == "aws-ids" {
for _, securityGroupID := range functional.SplitCommaSeparatedString(value) {
if !securityGroupRegex.MatchString(securityGroupID) {
fieldValue := fmt.Sprintf("\"%s\"", securityGroupID)
message := fmt.Sprintf("%s['%s'] must be a valid group-id (regex: %s)", securityGroupSelectorPath, key, securityGroupRegex.String())
errs = errs.Also(apis.ErrInvalidValue(fieldValue, message))
}
}
}
}
return errs
}
func (a *AWS) validateTags() (errs *apis.FieldError) {
// Avoiding a check on number of tags (hard limit of 50) since that limit is shared by user
// defined and Karpenter tags, and the latter could change over time.
for tagKey, tagValue := range a.Tags {
if tagKey == "" {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf(
"the tag with key : '' and value : '%s' is invalid because empty tag keys aren't supported", tagValue), "tags"))
}
}
return errs
}
func (a *AWS) validateMetadataOptions() (errs *apis.FieldError) {
if a.MetadataOptions == nil {
return nil
}
return errs.Also(
a.validateHTTPEndpoint(),
a.validateHTTPProtocolIpv6(),
a.validateHTTPPutResponseHopLimit(),
a.validateHTTPTokens(),
).ViaField(metadataOptionsPath)
}
func (a *AWS) validateHTTPEndpoint() *apis.FieldError {
if a.MetadataOptions.HTTPEndpoint == nil {
return nil
}
return a.validateStringEnum(*a.MetadataOptions.HTTPEndpoint, "httpEndpoint", ec2.LaunchTemplateInstanceMetadataEndpointState_Values())
}
func (a *AWS) validateHTTPProtocolIpv6() *apis.FieldError {
if a.MetadataOptions.HTTPProtocolIPv6 == nil {
return nil
}
return a.validateStringEnum(*a.MetadataOptions.HTTPProtocolIPv6, "httpProtocolIPv6", ec2.LaunchTemplateInstanceMetadataProtocolIpv6_Values())
}
func (a *AWS) validateHTTPPutResponseHopLimit() *apis.FieldError {
if a.MetadataOptions.HTTPPutResponseHopLimit == nil {
return nil
}
limit := *a.MetadataOptions.HTTPPutResponseHopLimit
if limit < 1 || limit > 64 {
return apis.ErrOutOfBoundsValue(limit, 1, 64, "httpPutResponseHopLimit")
}
return nil
}
func (a *AWS) validateHTTPTokens() *apis.FieldError {
if a.MetadataOptions.HTTPTokens == nil {
return nil
}
return a.validateStringEnum(*a.MetadataOptions.HTTPTokens, "httpTokens", ec2.LaunchTemplateHttpTokensState_Values())
}
func (a *AWS) validateAMIFamily() *apis.FieldError {
if a.AMIFamily == nil {
return nil
}
return a.validateStringEnum(*a.AMIFamily, amiFamilyPath, SupportedAMIFamilies)
}
func (a *AWS) validateStringEnum(value, field string, validValues []string) *apis.FieldError {
for _, validValue := range validValues {
if value == validValue {
return nil
}
}
return apis.ErrInvalidValue(fmt.Sprintf("%s not in %v", value, strings.Join(validValues, ", ")), field)
}
func (a *AWS) validateBlockDeviceMappings() (errs *apis.FieldError) {
for i, blockDeviceMapping := range a.BlockDeviceMappings {
if err := a.validateBlockDeviceMapping(blockDeviceMapping); err != nil {
errs = errs.Also(err.ViaFieldIndex(blockDeviceMappingsPath, i))
}
}
return errs
}
func (a *AWS) validateBlockDeviceMapping(blockDeviceMapping *BlockDeviceMapping) (errs *apis.FieldError) {
return errs.Also(a.validateDeviceName(blockDeviceMapping), a.validateEBS(blockDeviceMapping))
}
func (a *AWS) validateDeviceName(blockDeviceMapping *BlockDeviceMapping) *apis.FieldError {
if blockDeviceMapping.DeviceName == nil {
return apis.ErrMissingField("deviceName")
}
return nil
}
func (a *AWS) validateEBS(blockDeviceMapping *BlockDeviceMapping) (errs *apis.FieldError) {
if blockDeviceMapping.EBS == nil {
return apis.ErrMissingField("ebs")
}
for _, err := range []*apis.FieldError{
a.validateVolumeType(blockDeviceMapping),
a.validateVolumeSize(blockDeviceMapping),
} {
if err != nil {
errs = errs.Also(err.ViaField("ebs"))
}
}
return errs
}
func (a *AWS) validateVolumeType(blockDeviceMapping *BlockDeviceMapping) *apis.FieldError {
if blockDeviceMapping.EBS.VolumeType != nil {
return a.validateStringEnum(*blockDeviceMapping.EBS.VolumeType, "volumeType", ec2.VolumeType_Values())
}
return nil
}
func (a *AWS) validateVolumeSize(blockDeviceMapping *BlockDeviceMapping) *apis.FieldError {
// If an EBS mapping is present, one of volumeSize or snapshotID must be present
if blockDeviceMapping.EBS.SnapshotID != nil && blockDeviceMapping.EBS.VolumeSize == nil {
return nil
} else if blockDeviceMapping.EBS.VolumeSize == nil {
return apis.ErrMissingField("volumeSize")
} else if blockDeviceMapping.EBS.VolumeSize.Cmp(minVolumeSize) == -1 || blockDeviceMapping.EBS.VolumeSize.Cmp(maxVolumeSize) == 1 {
return apis.ErrOutOfBoundsValue(blockDeviceMapping.EBS.VolumeSize.String(), minVolumeSize.String(), maxVolumeSize.String(), "volumeSize")
}
return nil
}
| 256 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"fmt"
"regexp"
"github.com/aws/aws-sdk-go/service/ec2"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
)
var (
LabelDomain = "karpenter.k8s.aws"
CapacityTypeSpot = ec2.DefaultTargetCapacityTypeSpot
CapacityTypeOnDemand = ec2.DefaultTargetCapacityTypeOnDemand
AWSToKubeArchitectures = map[string]string{
"x86_64": v1alpha5.ArchitectureAmd64,
v1alpha5.ArchitectureArm64: v1alpha5.ArchitectureArm64,
}
WellKnownArchitectures = sets.NewString(
v1alpha5.ArchitectureAmd64,
v1alpha5.ArchitectureArm64,
)
RestrictedLabelDomains = []string{
LabelDomain,
}
RestrictedTagPatterns = []*regexp.Regexp{
// Adheres to cluster name pattern matching as specified in the API spec
// https://docs.aws.amazon.com/eks/latest/APIReference/API_CreateCluster.html
regexp.MustCompile(`^kubernetes\.io/cluster/[0-9A-Za-z][A-Za-z0-9\-_]*$`),
regexp.MustCompile(fmt.Sprintf("^%s$", regexp.QuoteMeta(v1alpha5.ProvisionerNameLabelKey))),
regexp.MustCompile(fmt.Sprintf("^%s$", regexp.QuoteMeta(v1alpha5.MachineManagedByAnnotationKey))),
}
AMIFamilyBottlerocket = "Bottlerocket"
AMIFamilyAL2 = "AL2"
AMIFamilyUbuntu = "Ubuntu"
AMIFamilyWindows2019 = "Windows2019"
AMIFamilyWindows2022 = "Windows2022"
AMIFamilyCustom = "Custom"
SupportedAMIFamilies = []string{
AMIFamilyBottlerocket,
AMIFamilyAL2,
AMIFamilyUbuntu,
AMIFamilyWindows2019,
AMIFamilyWindows2022,
AMIFamilyCustom,
}
SupportedContainerRuntimesByAMIFamily = map[string]sets.String{
AMIFamilyBottlerocket: sets.NewString("containerd"),
AMIFamilyAL2: sets.NewString("dockerd", "containerd"),
AMIFamilyUbuntu: sets.NewString("dockerd", "containerd"),
AMIFamilyWindows2019: sets.NewString("dockerd", "containerd"),
AMIFamilyWindows2022: sets.NewString("dockerd", "containerd"),
}
Windows2019 = "2019"
Windows2022 = "2022"
WindowsCore = "Core"
Windows2019Build = "10.0.17763"
Windows2022Build = "10.0.20348"
ResourceNVIDIAGPU v1.ResourceName = "nvidia.com/gpu"
ResourceAMDGPU v1.ResourceName = "amd.com/gpu"
ResourceAWSNeuron v1.ResourceName = "aws.amazon.com/neuron"
ResourceHabanaGaudi v1.ResourceName = "habana.ai/gaudi"
ResourceAWSPodENI v1.ResourceName = "vpc.amazonaws.com/pod-eni"
ResourcePrivateIPv4Address v1.ResourceName = "vpc.amazonaws.com/PrivateIPv4Address"
NVIDIAacceleratorManufacturer AcceleratorManufacturer = "nvidia"
AWSAcceleratorManufacturer AcceleratorManufacturer = "aws"
LabelInstanceHypervisor = LabelDomain + "/instance-hypervisor"
LabelInstanceEncryptionInTransitSupported = LabelDomain + "/instance-encryption-in-transit-supported"
LabelInstanceCategory = LabelDomain + "/instance-category"
LabelInstanceFamily = LabelDomain + "/instance-family"
LabelInstanceGeneration = LabelDomain + "/instance-generation"
LabelInstanceLocalNVME = LabelDomain + "/instance-local-nvme"
LabelInstanceSize = LabelDomain + "/instance-size"
LabelInstanceCPU = LabelDomain + "/instance-cpu"
LabelInstanceMemory = LabelDomain + "/instance-memory"
LabelInstanceNetworkBandwidth = LabelDomain + "/instance-network-bandwidth"
LabelInstancePods = LabelDomain + "/instance-pods"
LabelInstanceGPUName = LabelDomain + "/instance-gpu-name"
LabelInstanceGPUManufacturer = LabelDomain + "/instance-gpu-manufacturer"
LabelInstanceGPUCount = LabelDomain + "/instance-gpu-count"
LabelInstanceGPUMemory = LabelDomain + "/instance-gpu-memory"
LabelInstanceAMIID = LabelDomain + "/instance-ami-id"
LabelInstanceAcceleratorName = LabelDomain + "/instance-accelerator-name"
LabelInstanceAcceleratorManufacturer = LabelDomain + "/instance-accelerator-manufacturer"
LabelInstanceAcceleratorCount = LabelDomain + "/instance-accelerator-count"
)
var (
Scheme = runtime.NewScheme()
codec = serializer.NewCodecFactory(Scheme, serializer.EnableStrict)
Group = "karpenter.k8s.aws"
SchemeGroupVersion = schema.GroupVersion{Group: Group, Version: "v1alpha1"}
SchemeBuilder = runtime.NewSchemeBuilder(func(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&AWSNodeTemplate{},
&AWSNodeTemplateList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
})
)
func init() {
Scheme.AddKnownTypes(schema.GroupVersion{Group: v1alpha5.ExtensionsGroup, Version: "v1alpha1"}, &AWS{})
v1alpha5.RestrictedLabelDomains = v1alpha5.RestrictedLabelDomains.Insert(RestrictedLabelDomains...)
v1alpha5.WellKnownLabels = v1alpha5.WellKnownLabels.Insert(
LabelInstanceHypervisor,
LabelInstanceEncryptionInTransitSupported,
LabelInstanceCategory,
LabelInstanceFamily,
LabelInstanceGeneration,
LabelInstanceSize,
LabelInstanceLocalNVME,
LabelInstanceCPU,
LabelInstanceMemory,
LabelInstanceNetworkBandwidth,
LabelInstancePods,
LabelInstanceGPUName,
LabelInstanceGPUManufacturer,
LabelInstanceGPUCount,
LabelInstanceGPUMemory,
LabelInstanceAcceleratorName,
LabelInstanceAcceleratorManufacturer,
LabelInstanceAcceleratorCount,
v1.LabelWindowsBuild,
)
}
type AcceleratorManufacturer string
| 154 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1_test
import (
"context"
"strings"
"testing"
"github.com/Pallinder/go-randomdata"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "knative.dev/pkg/logging/testing"
"knative.dev/pkg/ptr"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var ctx context.Context
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Validation")
}
var _ = Describe("Validation", func() {
var ant *v1alpha1.AWSNodeTemplate
BeforeEach(func() {
ant = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{Name: strings.ToLower(randomdata.SillyName())},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SubnetSelector: map[string]string{"foo": "bar"},
SecurityGroupSelector: map[string]string{"foo": "bar"},
},
},
}
})
Context("UserData", func() {
It("should succeed if user data is empty", func() {
Expect(ant.Validate(ctx)).To(Succeed())
})
It("should fail if launch template is also specified", func() {
ant.Spec.LaunchTemplateName = ptr.String("someLaunchTemplate")
ant.Spec.UserData = ptr.String("someUserData")
Expect(ant.Validate(ctx)).To(Not(Succeed()))
})
It("should fail if Windows2019 AMIFamily is specified", func() {
ant.Spec.AMIFamily = &v1alpha1.AMIFamilyWindows2019
ant.Spec.UserData = ptr.String("someUserData")
Expect(ant.Validate(ctx)).To(Not(Succeed()))
})
It("should fail if Windows2022 AMIFamily is specified", func() {
ant.Spec.AMIFamily = &v1alpha1.AMIFamilyWindows2022
ant.Spec.UserData = ptr.String("someUserData")
Expect(ant.Validate(ctx)).To(Not(Succeed()))
})
})
Context("Tags", func() {
It("should succeed when tags are empty", func() {
ant.Spec.Tags = map[string]string{}
Expect(ant.Validate(ctx)).To(Succeed())
})
It("should succeed if tags aren't in restricted tag keys", func() {
ant.Spec.Tags = map[string]string{
"karpenter.sh/custom-key": "value",
"karpenter.sh/managed": "true",
"kubernetes.io/role/key": "value",
}
Expect(ant.Validate(ctx)).To(Succeed())
})
It("should succeed by validating that regex is properly escaped", func() {
ant.Spec.Tags = map[string]string{
"karpenterzsh/provisioner-name": "value",
}
Expect(ant.Validate(ctx)).To(Succeed())
ant.Spec.Tags = map[string]string{
"kubernetesbio/cluster/test": "value",
}
Expect(ant.Validate(ctx)).To(Succeed())
ant.Spec.Tags = map[string]string{
"karpenterzsh/managed-by": "test",
}
Expect(ant.Validate(ctx)).To(Succeed())
})
It("should fail if tags contain a restricted domain key", func() {
ant.Spec.Tags = map[string]string{
"karpenter.sh/provisioner-name": "value",
}
Expect(ant.Validate(ctx)).To(Not(Succeed()))
ant.Spec.Tags = map[string]string{
"kubernetes.io/cluster/test": "value",
}
Expect(ant.Validate(ctx)).To(Not(Succeed()))
ant.Spec.Tags = map[string]string{
"karpenter.sh/managed-by": "test",
}
Expect(ant.Validate(ctx)).To(Not(Succeed()))
})
})
})
| 119 |
karpenter | aws | Go | //go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha1
import (
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AMI) DeepCopyInto(out *AMI) {
*out = *in
if in.Requirements != nil {
in, out := &in.Requirements, &out.Requirements
*out = make([]v1.NodeSelectorRequirement, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AMI.
func (in *AMI) DeepCopy() *AMI {
if in == nil {
return nil
}
out := new(AMI)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AWS) DeepCopyInto(out *AWS) {
*out = *in
out.TypeMeta = in.TypeMeta
if in.AMIFamily != nil {
in, out := &in.AMIFamily, &out.AMIFamily
*out = new(string)
**out = **in
}
if in.Context != nil {
in, out := &in.Context, &out.Context
*out = new(string)
**out = **in
}
if in.InstanceProfile != nil {
in, out := &in.InstanceProfile, &out.InstanceProfile
*out = new(string)
**out = **in
}
if in.SubnetSelector != nil {
in, out := &in.SubnetSelector, &out.SubnetSelector
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.SecurityGroupSelector != nil {
in, out := &in.SecurityGroupSelector, &out.SecurityGroupSelector
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
in.LaunchTemplate.DeepCopyInto(&out.LaunchTemplate)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWS.
func (in *AWS) DeepCopy() *AWS {
if in == nil {
return nil
}
out := new(AWS)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *AWS) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AWSNodeTemplate) DeepCopyInto(out *AWSNodeTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSNodeTemplate.
func (in *AWSNodeTemplate) DeepCopy() *AWSNodeTemplate {
if in == nil {
return nil
}
out := new(AWSNodeTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *AWSNodeTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AWSNodeTemplateList) DeepCopyInto(out *AWSNodeTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]AWSNodeTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSNodeTemplateList.
func (in *AWSNodeTemplateList) DeepCopy() *AWSNodeTemplateList {
if in == nil {
return nil
}
out := new(AWSNodeTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *AWSNodeTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AWSNodeTemplateSpec) DeepCopyInto(out *AWSNodeTemplateSpec) {
*out = *in
if in.UserData != nil {
in, out := &in.UserData, &out.UserData
*out = new(string)
**out = **in
}
in.AWS.DeepCopyInto(&out.AWS)
if in.AMISelector != nil {
in, out := &in.AMISelector, &out.AMISelector
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.DetailedMonitoring != nil {
in, out := &in.DetailedMonitoring, &out.DetailedMonitoring
*out = new(bool)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSNodeTemplateSpec.
func (in *AWSNodeTemplateSpec) DeepCopy() *AWSNodeTemplateSpec {
if in == nil {
return nil
}
out := new(AWSNodeTemplateSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AWSNodeTemplateStatus) DeepCopyInto(out *AWSNodeTemplateStatus) {
*out = *in
if in.Subnets != nil {
in, out := &in.Subnets, &out.Subnets
*out = make([]Subnet, len(*in))
copy(*out, *in)
}
if in.SecurityGroups != nil {
in, out := &in.SecurityGroups, &out.SecurityGroups
*out = make([]SecurityGroup, len(*in))
copy(*out, *in)
}
if in.AMIs != nil {
in, out := &in.AMIs, &out.AMIs
*out = make([]AMI, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSNodeTemplateStatus.
func (in *AWSNodeTemplateStatus) DeepCopy() *AWSNodeTemplateStatus {
if in == nil {
return nil
}
out := new(AWSNodeTemplateStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BlockDevice) DeepCopyInto(out *BlockDevice) {
*out = *in
if in.DeleteOnTermination != nil {
in, out := &in.DeleteOnTermination, &out.DeleteOnTermination
*out = new(bool)
**out = **in
}
if in.Encrypted != nil {
in, out := &in.Encrypted, &out.Encrypted
*out = new(bool)
**out = **in
}
if in.IOPS != nil {
in, out := &in.IOPS, &out.IOPS
*out = new(int64)
**out = **in
}
if in.KMSKeyID != nil {
in, out := &in.KMSKeyID, &out.KMSKeyID
*out = new(string)
**out = **in
}
if in.SnapshotID != nil {
in, out := &in.SnapshotID, &out.SnapshotID
*out = new(string)
**out = **in
}
if in.Throughput != nil {
in, out := &in.Throughput, &out.Throughput
*out = new(int64)
**out = **in
}
if in.VolumeSize != nil {
in, out := &in.VolumeSize, &out.VolumeSize
x := (*in).DeepCopy()
*out = &x
}
if in.VolumeType != nil {
in, out := &in.VolumeType, &out.VolumeType
*out = new(string)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BlockDevice.
func (in *BlockDevice) DeepCopy() *BlockDevice {
if in == nil {
return nil
}
out := new(BlockDevice)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BlockDeviceMapping) DeepCopyInto(out *BlockDeviceMapping) {
*out = *in
if in.DeviceName != nil {
in, out := &in.DeviceName, &out.DeviceName
*out = new(string)
**out = **in
}
if in.EBS != nil {
in, out := &in.EBS, &out.EBS
*out = new(BlockDevice)
(*in).DeepCopyInto(*out)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BlockDeviceMapping.
func (in *BlockDeviceMapping) DeepCopy() *BlockDeviceMapping {
if in == nil {
return nil
}
out := new(BlockDeviceMapping)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *LaunchTemplate) DeepCopyInto(out *LaunchTemplate) {
*out = *in
if in.LaunchTemplateName != nil {
in, out := &in.LaunchTemplateName, &out.LaunchTemplateName
*out = new(string)
**out = **in
}
if in.MetadataOptions != nil {
in, out := &in.MetadataOptions, &out.MetadataOptions
*out = new(MetadataOptions)
(*in).DeepCopyInto(*out)
}
if in.BlockDeviceMappings != nil {
in, out := &in.BlockDeviceMappings, &out.BlockDeviceMappings
*out = make([]*BlockDeviceMapping, len(*in))
for i := range *in {
if (*in)[i] != nil {
in, out := &(*in)[i], &(*out)[i]
*out = new(BlockDeviceMapping)
(*in).DeepCopyInto(*out)
}
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LaunchTemplate.
func (in *LaunchTemplate) DeepCopy() *LaunchTemplate {
if in == nil {
return nil
}
out := new(LaunchTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MetadataOptions) DeepCopyInto(out *MetadataOptions) {
*out = *in
if in.HTTPEndpoint != nil {
in, out := &in.HTTPEndpoint, &out.HTTPEndpoint
*out = new(string)
**out = **in
}
if in.HTTPProtocolIPv6 != nil {
in, out := &in.HTTPProtocolIPv6, &out.HTTPProtocolIPv6
*out = new(string)
**out = **in
}
if in.HTTPPutResponseHopLimit != nil {
in, out := &in.HTTPPutResponseHopLimit, &out.HTTPPutResponseHopLimit
*out = new(int64)
**out = **in
}
if in.HTTPTokens != nil {
in, out := &in.HTTPTokens, &out.HTTPTokens
*out = new(string)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetadataOptions.
func (in *MetadataOptions) DeepCopy() *MetadataOptions {
if in == nil {
return nil
}
out := new(MetadataOptions)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SecurityGroup) DeepCopyInto(out *SecurityGroup) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SecurityGroup.
func (in *SecurityGroup) DeepCopy() *SecurityGroup {
if in == nil {
return nil
}
out := new(SecurityGroup)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Subnet) DeepCopyInto(out *Subnet) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Subnet.
func (in *Subnet) DeepCopy() *Subnet {
if in == nil {
return nil
}
out := new(Subnet)
in.DeepCopyInto(out)
return out
}
| 414 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha5
import (
"context"
"github.com/aws/aws-sdk-go/service/ec2"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
// Provisioner is an alias type for additional validation
// +kubebuilder:object:root=true
type Provisioner v1alpha5.Provisioner
func (p *Provisioner) SupportedVerbs() []admissionregistrationv1.OperationType {
return []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
}
}
func (p *Provisioner) Validate(_ context.Context) (errs *apis.FieldError) {
if p.Spec.Provider == nil {
return nil
}
provider, err := v1alpha1.DeserializeProvider(p.Spec.Provider.Raw)
if err != nil {
return apis.ErrGeneric(err.Error())
}
return provider.Validate()
}
func (p *Provisioner) SetDefaults(_ context.Context) {
requirements := scheduling.NewNodeSelectorRequirements(p.Spec.Requirements...)
// default to linux OS
if !requirements.Has(v1.LabelOSStable) {
p.Spec.Requirements = append(p.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelOSStable, Operator: v1.NodeSelectorOpIn, Values: []string{string(v1.Linux)},
})
}
// default to amd64
if !requirements.Has(v1.LabelArchStable) {
p.Spec.Requirements = append(p.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelArchStable, Operator: v1.NodeSelectorOpIn, Values: []string{v1alpha5.ArchitectureAmd64},
})
}
// default to on-demand
if !requirements.Has(v1alpha5.LabelCapacityType) {
p.Spec.Requirements = append(p.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpIn, Values: []string{ec2.DefaultTargetCapacityTypeOnDemand},
})
}
// default to C, M, R categories if no instance type constraints are specified
if !requirements.Has(v1.LabelInstanceTypeStable) &&
!requirements.Has(v1alpha1.LabelInstanceFamily) &&
!requirements.Has(v1alpha1.LabelInstanceCategory) &&
!requirements.Has(v1alpha1.LabelInstanceGeneration) {
p.Spec.Requirements = append(p.Spec.Requirements, []v1.NodeSelectorRequirement{
{Key: v1alpha1.LabelInstanceCategory, Operator: v1.NodeSelectorOpIn, Values: []string{"c", "m", "r"}},
{Key: v1alpha1.LabelInstanceGeneration, Operator: v1.NodeSelectorOpGt, Values: []string{"2"}},
}...)
}
}
| 87 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha5_test
import (
"context"
"math"
"testing"
"github.com/Pallinder/go-randomdata"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
. "knative.dev/pkg/logging/testing"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
apisv1alpha5 "github.com/aws/karpenter/pkg/apis/v1alpha5"
)
var ctx context.Context
func TestV1Alpha5(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "v1alpha5")
ctx = TestContextWithLogger(t)
}
var _ = Describe("Provisioner", func() {
var provisioner *v1alpha5.Provisioner
BeforeEach(func() {
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: &v1alpha1.AWS{
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
}})
})
Context("SetDefaults", func() {
It("should default OS to linux", func() {
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1.LabelOSStable)).
To(Equal(scheduling.NewRequirement(v1.LabelOSStable, v1.NodeSelectorOpIn, string(v1.Linux))))
})
It("should not default OS if set", func() {
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements,
v1.NodeSelectorRequirement{Key: v1.LabelOSStable, Operator: v1.NodeSelectorOpDoesNotExist})
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1.LabelOSStable)).
To(Equal(scheduling.NewRequirement(v1.LabelOSStable, v1.NodeSelectorOpDoesNotExist)))
})
It("should default architecture to amd64", func() {
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1.LabelArchStable)).
To(Equal(scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64)))
})
It("should not default architecture if set", func() {
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements,
v1.NodeSelectorRequirement{Key: v1.LabelArchStable, Operator: v1.NodeSelectorOpDoesNotExist})
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1.LabelArchStable)).
To(Equal(scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpDoesNotExist)))
})
It("should default capacity-type to on-demand", func() {
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha5.LabelCapacityType)).
To(Equal(scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpIn, v1alpha1.CapacityTypeOnDemand)))
})
It("should not default capacity-type if set", func() {
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements,
v1.NodeSelectorRequirement{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpDoesNotExist})
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha5.LabelCapacityType)).
To(Equal(scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpDoesNotExist)))
})
It("should default instance-category, generation to c m r, gen>1", func() {
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceCategory)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceCategory, v1.NodeSelectorOpIn, "c", "m", "r")))
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceGeneration)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceGeneration, v1.NodeSelectorOpGt, "2")))
})
It("should not default instance-category, generation if set", func() {
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements,
v1.NodeSelectorRequirement{Key: v1alpha1.LabelInstanceCategory, Operator: v1.NodeSelectorOpExists})
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceCategory)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceCategory, v1.NodeSelectorOpExists)))
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceGeneration)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceGeneration, v1.NodeSelectorOpExists)))
})
It("should not default instance-category if any instance label is set", func() {
for _, label := range []string{v1.LabelInstanceTypeStable, v1alpha1.LabelInstanceFamily} {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{{Key: label, Operator: v1.NodeSelectorOpIn, Values: []string{"test"}}}
SetDefaults(ctx, provisioner)
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(label)).
To(Equal(scheduling.NewRequirement(label, v1.NodeSelectorOpIn, "test")))
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceCategory)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceCategory, v1.NodeSelectorOpExists)))
Expect(scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...).Get(v1alpha1.LabelInstanceGeneration)).
To(Equal(scheduling.NewRequirement(v1alpha1.LabelInstanceGeneration, v1.NodeSelectorOpExists)))
}
})
})
Context("Validate", func() {
It("should validate", func() {
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should succeed if provider undefined", func() {
provisioner.Spec.Provider = nil
provisioner.Spec.ProviderRef = &v1alpha5.MachineTemplateRef{
Kind: "AWSNodeTemplate",
Name: "default",
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
Context("SubnetSelector", func() {
It("should not allow empty string keys or values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
for key, value := range map[string]string{
"": "value",
"key": "",
} {
provider.SubnetSelector = map[string]string{key: value}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
}
})
})
Context("SecurityGroupSelector", func() {
It("should not allow with a custom launch template", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.LaunchTemplateName = aws.String("my-lt")
provider.SecurityGroupSelector = map[string]string{"key": "value"}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow empty string keys or values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
for key, value := range map[string]string{
"": "value",
"key": "",
} {
provider.SecurityGroupSelector = map[string]string{key: value}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
}
})
})
Context("Labels", func() {
It("should not allow unrecognized labels with the aws label prefix", func() {
provisioner.Spec.Labels = map[string]string{v1alpha1.LabelDomain + "/" + randomdata.SillyName(): randomdata.SillyName()}
Expect(Validate(ctx, provisioner)).ToNot(Succeed())
})
It("should support well known labels", func() {
for _, label := range []string{
v1alpha1.LabelInstanceHypervisor,
v1alpha1.LabelInstanceFamily,
v1alpha1.LabelInstanceSize,
v1alpha1.LabelInstanceCPU,
v1alpha1.LabelInstanceMemory,
v1alpha1.LabelInstanceGPUName,
v1alpha1.LabelInstanceGPUManufacturer,
v1alpha1.LabelInstanceGPUCount,
v1alpha1.LabelInstanceGPUMemory,
v1alpha1.LabelInstanceAcceleratorName,
v1alpha1.LabelInstanceAcceleratorManufacturer,
v1alpha1.LabelInstanceAcceleratorCount,
} {
provisioner.Spec.Labels = map[string]string{label: randomdata.SillyName()}
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
})
Context("MetadataOptions", func() {
It("should not allow with a custom launch template", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.LaunchTemplateName = aws.String("my-lt")
provider.MetadataOptions = &v1alpha1.MetadataOptions{}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should allow missing values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(provisioner.Validate(ctx)).To(Succeed())
})
Context("HTTPEndpoint", func() {
It("should allow enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
for i := range ec2.LaunchTemplateInstanceMetadataEndpointState_Values() {
value := ec2.LaunchTemplateInstanceMetadataEndpointState_Values()[i]
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPEndpoint: &value,
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
It("should not allow non-enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPEndpoint: aws.String(randomdata.SillyName()),
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
})
Context("HTTPProtocolIpv6", func() {
It("should allow enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
for i := range ec2.LaunchTemplateInstanceMetadataProtocolIpv6_Values() {
value := ec2.LaunchTemplateInstanceMetadataProtocolIpv6_Values()[i]
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPProtocolIPv6: &value,
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
It("should not allow non-enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPProtocolIPv6: aws.String(randomdata.SillyName()),
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
})
Context("HTTPPutResponseHopLimit", func() {
It("should validate inside accepted range", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPPutResponseHopLimit: aws.Int64(int64(randomdata.Number(1, 65))),
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should not validate outside accepted range", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{}
// We expect to be able to invalidate any hop limit between
// [math.MinInt64, 1). But, to avoid a panic here, we can't
// exceed math.MaxInt for the difference between bounds of
// the random number range. So we divide the range
// approximately in half and test on both halves.
provider.MetadataOptions.HTTPPutResponseHopLimit = aws.Int64(int64(randomdata.Number(math.MinInt64, math.MinInt64/2)))
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
provider.MetadataOptions.HTTPPutResponseHopLimit = aws.Int64(int64(randomdata.Number(math.MinInt64/2, 1)))
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
provider.MetadataOptions.HTTPPutResponseHopLimit = aws.Int64(int64(randomdata.Number(65, math.MaxInt64)))
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
})
Context("HTTPTokens", func() {
It("should allow enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
for _, value := range ec2.LaunchTemplateHttpTokensState_Values() {
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPTokens: aws.String(value),
}
provisioner = test.Provisioner(test.ProvisionerOptions{Provider: provider})
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
It("should not allow non-enum values", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPTokens: aws.String(randomdata.SillyName()),
}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
})
Context("BlockDeviceMappings", func() {
It("should not allow with a custom launch template", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.LaunchTemplateName = aws.String("my-lt")
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(1, resource.Giga),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should validate minimal device mapping", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(1, resource.Giga),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should validate ebs device mapping with snapshotID only", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
SnapshotID: aws.String("snap-0123456789"),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow volume size below minimum", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(100, resource.Mega),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow volume size above max", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(65, resource.Tera),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow nil device name", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(65, resource.Tera),
},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow nil volume size", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{},
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
It("should not allow empty ebs block", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
}}
Expect(Validate(ctx, test.Provisioner(test.ProvisionerOptions{Provider: provider}))).ToNot(Succeed())
})
})
})
})
})
func SetDefaults(ctx context.Context, provisioner *v1alpha5.Provisioner) {
prov := apisv1alpha5.Provisioner(*provisioner)
prov.SetDefaults(ctx)
*provisioner = v1alpha5.Provisioner(prov)
}
func Validate(ctx context.Context, provisioner *v1alpha5.Provisioner) error {
return multierr.Combine(
lo.ToPtr(apisv1alpha5.Provisioner(*provisioner)).Validate(ctx),
provisioner.Validate(ctx),
)
}
| 414 |
karpenter | aws | Go | //go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha5
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Provisioner) DeepCopyInto(out *Provisioner) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Provisioner.
func (in *Provisioner) DeepCopy() *Provisioner {
if in == nil {
return nil
}
out := new(Provisioner)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Provisioner) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
| 52 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// batcher implements a generic batching lib for API calls so that load can be reduced to external APIs that excessively throttle
package batcher
import (
"context"
"fmt"
"sync"
"time"
"github.com/mitchellh/hashstructure/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"golang.org/x/sync/errgroup"
"github.com/aws/karpenter-core/pkg/metrics"
)
// Options allows for configuration of the Batcher
type Options[T input, U output] struct {
Name string
IdleTimeout time.Duration
MaxTimeout time.Duration
MaxItems int
MaxRequestWorkers int
RequestHasher RequestHasher[T]
BatchExecutor BatchExecutor[T, U]
}
// Result is a container for the output and error of an execution
type Result[U output] struct {
Output *U
Err error
}
type input = any
type output = any
// request is a batched request with the calling ctx, requestor, and hash to determine the batching bucket
type request[T input, U output] struct {
ctx context.Context
hash uint64
input *T
requestor chan Result[U]
}
// Batcher is used to batch API calls with identical parameters into a single call
type Batcher[T input, U output] struct {
ctx context.Context
options Options[T, U]
mu sync.Mutex
requests map[uint64][]*request[T, U]
// trigger to initiate the batcher
trigger chan struct{}
// requestWorkers is a group of concurrent workers that execute requests
requestWorkers errgroup.Group
}
// BatchExecutor is a function that executes a slice of inputs against the batched API.
// inputs will be mutated
// The returned Result slice is expected to match the len of the input slice and be in the
// same order, if order matters for the batched API
type BatchExecutor[T input, U output] func(ctx context.Context, input []*T) []Result[U]
// RequestHasher is a function that hashes input to bucket inputs into distinct batches
type RequestHasher[T input] func(ctx context.Context, input *T) uint64
// NewBatcher creates a batcher that can batch a particular input and output type
func NewBatcher[T input, U output](ctx context.Context, options Options[T, U]) *Batcher[T, U] {
b := &Batcher[T, U]{
ctx: ctx,
options: options,
requests: map[uint64][]*request[T, U]{},
// The trigger channel is buffered since we shouldn't block the Add() method on the trigger channel
// if another Add() has already triggered it. This works because we add the request to the request map BEFORE
// we perform the trigger
trigger: make(chan struct{}, 1),
}
b.requestWorkers.SetLimit(lo.Ternary(b.options.MaxRequestWorkers != 0, b.options.MaxRequestWorkers, 100))
go b.run()
return b
}
// Add will add an input to the batcher using the batcher's hashing function
func (b *Batcher[T, U]) Add(ctx context.Context, input *T) Result[U] {
request := &request[T, U]{
ctx: ctx,
hash: b.options.RequestHasher(ctx, input),
input: input,
// The requestor channel is buffered to ensure that the exec runner can always write the result out preventing
// any single caller from blocking the others. Specifically since we register our request and then trigger, the
// request may be processed while the triggering blocks.
requestor: make(chan Result[U], 1),
}
b.mu.Lock()
b.requests[request.hash] = append(b.requests[request.hash], request)
b.mu.Unlock()
b.trigger <- struct{}{}
return <-request.requestor
}
// DefaultHasher will hash the entire input
func DefaultHasher[T input](_ context.Context, input *T) uint64 {
hash, err := hashstructure.Hash(input, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
if err != nil {
panic("error hashing")
}
return hash
}
// OneBucketHasher will return a constant hash and should be used when there is only one type of request
func OneBucketHasher[T input](_ context.Context, _ *T) uint64 {
return 0
}
func (b *Batcher[T, U]) run() {
for {
var measureDuration func()
select {
// context that we started with has completed so the app is shutting down
case <-b.ctx.Done():
_ = b.requestWorkers.Wait()
return
case <-b.trigger:
// wait to start the batch of create fleet calls
measureDuration = metrics.Measure(batchWindowDuration.WithLabelValues(b.options.Name))
}
b.waitForIdle()
measureDuration() // Observe the length of time between the start of the batch and now
// Copy the requests, so we can reset the requests for the next batching loop
b.mu.Lock()
requests := b.requests
b.requests = map[uint64][]*request[T, U]{}
b.mu.Unlock()
for _, v := range requests {
req := v // create a local closure for the requests value
b.requestWorkers.Go(func() error {
b.runCalls(req)
return nil
})
}
}
}
func (b *Batcher[T, U]) waitForIdle() {
timeout := time.NewTimer(b.options.MaxTimeout)
idle := time.NewTimer(b.options.IdleTimeout)
count := 1 // we already got a single trigger
for b.options.MaxItems == 0 || count < b.options.MaxItems {
select {
case <-b.ctx.Done():
return
case <-b.trigger:
count++
if !idle.Stop() {
<-idle.C
}
idle.Reset(b.options.IdleTimeout)
case <-timeout.C:
return
case <-idle.C:
return
}
}
}
func (b *Batcher[T, U]) runCalls(requests []*request[T, U]) {
// Measure the size of the request batch
batchSize.With(prometheus.Labels{batcherNameLabel: b.options.Name}).Observe(float64(len(requests)))
requestIdx := 0
for _, result := range b.options.BatchExecutor(requests[0].ctx, lo.Map(requests, func(req *request[T, U], _ int) *T { return req.input })) {
requests[requestIdx].requestor <- result
requestIdx++
}
// any unmapped outputs should return an error to the caller
for ; requestIdx < len(requests); requestIdx++ {
requests[requestIdx].requestor <- Result[U]{Err: fmt.Errorf("error making call")}
}
}
| 198 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"knative.dev/pkg/logging"
)
type CreateFleetBatcher struct {
batcher *Batcher[ec2.CreateFleetInput, ec2.CreateFleetOutput]
}
func NewCreateFleetBatcher(ctx context.Context, ec2api ec2iface.EC2API) *CreateFleetBatcher {
options := Options[ec2.CreateFleetInput, ec2.CreateFleetOutput]{
Name: "create_fleet",
IdleTimeout: 35 * time.Millisecond,
MaxTimeout: 1 * time.Second,
MaxItems: 1_000,
RequestHasher: DefaultHasher[ec2.CreateFleetInput],
BatchExecutor: execCreateFleetBatch(ec2api),
}
return &CreateFleetBatcher{batcher: NewBatcher(ctx, options)}
}
func (b *CreateFleetBatcher) CreateFleet(ctx context.Context, createFleetInput *ec2.CreateFleetInput) (*ec2.CreateFleetOutput, error) {
if createFleetInput.TargetCapacitySpecification != nil && *createFleetInput.TargetCapacitySpecification.TotalTargetCapacity != 1 {
return nil, fmt.Errorf("expected to receive a single instance only, found %d", *createFleetInput.TargetCapacitySpecification.TotalTargetCapacity)
}
result := b.batcher.Add(ctx, createFleetInput)
return result.Output, result.Err
}
func execCreateFleetBatch(ec2api ec2iface.EC2API) BatchExecutor[ec2.CreateFleetInput, ec2.CreateFleetOutput] {
return func(ctx context.Context, inputs []*ec2.CreateFleetInput) []Result[ec2.CreateFleetOutput] {
results := make([]Result[ec2.CreateFleetOutput], 0, len(inputs))
firstInput := inputs[0]
firstInput.TargetCapacitySpecification.TotalTargetCapacity = aws.Int64(int64(len(inputs)))
output, err := ec2api.CreateFleetWithContext(ctx, firstInput)
if err != nil {
for range inputs {
results = append(results, Result[ec2.CreateFleetOutput]{Err: err})
}
return results
}
// we can get partial fulfillment of a CreateFleet request, so we:
// 1) split out the single instance IDs and deliver to each requestor
// 2) deliver errors to any remaining requestors for which we don't have an instance
requestIdx := -1
for _, reservation := range output.Instances {
for _, instanceID := range reservation.InstanceIds {
requestIdx++
if requestIdx >= len(inputs) {
logging.FromContext(ctx).Errorf("received more instances than requested, ignoring instance %s", aws.StringValue(instanceID))
continue
}
results = append(results, Result[ec2.CreateFleetOutput]{
Output: &ec2.CreateFleetOutput{
FleetId: output.FleetId,
Errors: output.Errors,
Instances: []*ec2.CreateFleetInstance{
{
InstanceIds: []*string{instanceID},
InstanceType: reservation.InstanceType,
LaunchTemplateAndOverrides: reservation.LaunchTemplateAndOverrides,
Lifecycle: reservation.Lifecycle,
Platform: reservation.Platform,
},
},
},
})
}
}
if requestIdx != len(inputs) {
// we should receive some sort of error, but just in case
if len(output.Errors) == 0 {
output.Errors = append(output.Errors, &ec2.CreateFleetError{
ErrorCode: aws.String("too few instances returned"),
ErrorMessage: aws.String("too few instances returned"),
})
}
for i := requestIdx + 1; i < len(inputs); i++ {
results = append(results, Result[ec2.CreateFleetOutput]{
Output: &ec2.CreateFleetOutput{
Errors: output.Errors,
}})
}
}
return results
}
}
| 112 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher_test
import (
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/karpenter/pkg/batcher"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("CreateFleet Batching", func() {
var cfb *batcher.CreateFleetBatcher
BeforeEach(func() {
fakeEC2API.Reset()
cfb = batcher.NewCreateFleetBatcher(ctx, fakeEC2API)
})
It("should batch the same inputs into a single call", func() {
input := &ec2.CreateFleetInput{
LaunchTemplateConfigs: []*ec2.FleetLaunchTemplateConfigRequest{
{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: []*ec2.FleetLaunchTemplateOverridesRequest{
{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
TotalTargetCapacity: aws.Int64(1),
},
}
var wg sync.WaitGroup
var receivedInstance int64
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.CreateFleet(ctx, input)
Expect(err).To(BeNil())
var instanceIds []string
for _, rsv := range rsp.Instances {
for _, id := range rsv.InstanceIds {
instanceIds = append(instanceIds, *id)
}
}
atomic.AddInt64(&receivedInstance, 1)
Expect(instanceIds).To(HaveLen(1))
}()
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", 5))
Expect(fakeEC2API.CreateFleetBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(*call.TargetCapacitySpecification.TotalTargetCapacity).To(BeNumerically("==", 5))
})
It("should batch different inputs into multiple calls", func() {
east1input := &ec2.CreateFleetInput{
LaunchTemplateConfigs: []*ec2.FleetLaunchTemplateConfigRequest{
{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: []*ec2.FleetLaunchTemplateOverridesRequest{
{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
TotalTargetCapacity: aws.Int64(1),
},
}
east2input := &ec2.CreateFleetInput{
LaunchTemplateConfigs: []*ec2.FleetLaunchTemplateConfigRequest{
{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: []*ec2.FleetLaunchTemplateOverridesRequest{
{
AvailabilityZone: aws.String("us-east-2"),
},
},
},
},
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
TotalTargetCapacity: aws.Int64(1),
},
}
var wg sync.WaitGroup
var receivedInstance int64
for i := 0; i < 5; i++ {
wg.Add(1)
go func(i int) {
defer GinkgoRecover()
defer wg.Done()
input := east1input
// 4 instances for us-east-1 and 1 instance in us-east-2
if i == 3 {
input = east2input
}
rsp, err := cfb.CreateFleet(ctx, input)
Expect(err).To(BeNil())
var instanceIds []string
for _, rsv := range rsp.Instances {
for _, id := range rsv.InstanceIds {
instanceIds = append(instanceIds, *id)
}
}
atomic.AddInt64(&receivedInstance, 1)
Expect(instanceIds).To(HaveLen(1))
time.Sleep(100 * time.Millisecond)
}(i)
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", 5))
Expect(fakeEC2API.CreateFleetBehavior.CalledWithInput.Len()).To(BeNumerically("==", 2))
east2Call := fakeEC2API.CreateFleetBehavior.CalledWithInput.Pop()
east1Call := fakeEC2API.CreateFleetBehavior.CalledWithInput.Pop()
if *east2Call.TargetCapacitySpecification.TotalTargetCapacity > *east1Call.TargetCapacitySpecification.TotalTargetCapacity {
east2Call, east1Call = east1Call, east2Call
}
Expect(*east2Call.TargetCapacitySpecification.TotalTargetCapacity).To(BeNumerically("==", 1))
Expect(*east2Call.LaunchTemplateConfigs[0].Overrides[0].AvailabilityZone).To(Equal("us-east-2"))
Expect(*east1Call.TargetCapacitySpecification.TotalTargetCapacity).To(BeNumerically("==", 4))
Expect(*east1Call.LaunchTemplateConfigs[0].Overrides[0].AvailabilityZone).To(Equal("us-east-1"))
})
It("should return any errors to callers", func() {
input := &ec2.CreateFleetInput{
LaunchTemplateConfigs: []*ec2.FleetLaunchTemplateConfigRequest{
{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: []*ec2.FleetLaunchTemplateOverridesRequest{
{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
TotalTargetCapacity: aws.Int64(1),
},
}
fakeEC2API.CreateFleetBehavior.Output.Set(&ec2.CreateFleetOutput{
Errors: []*ec2.CreateFleetError{
{
ErrorCode: aws.String("some-error"),
ErrorMessage: aws.String("some-error"),
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecification{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: &ec2.FleetLaunchTemplateOverrides{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
{
ErrorCode: aws.String("some-other-error"),
ErrorMessage: aws.String("some-other-error"),
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecification{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: &ec2.FleetLaunchTemplateOverrides{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
FleetId: aws.String("some-id"),
Instances: []*ec2.CreateFleetInstance{
{
InstanceIds: []*string{aws.String("id-1"), aws.String("id-2"), aws.String("id-3"), aws.String("id-4"), aws.String("id-5")},
InstanceType: nil,
LaunchTemplateAndOverrides: nil,
Lifecycle: nil,
Platform: nil,
},
},
})
var wg sync.WaitGroup
var receivedInstance int64
var numErrors int64
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.CreateFleet(ctx, input)
Expect(err).To(BeNil())
if len(rsp.Errors) != 0 {
// should receive errors for each caller
atomic.AddInt64(&numErrors, 1)
}
var instanceIds []string
for _, rsv := range rsp.Instances {
for _, id := range rsv.InstanceIds {
instanceIds = append(instanceIds, *id)
}
}
atomic.AddInt64(&receivedInstance, 1)
Expect(instanceIds).To(HaveLen(1))
}()
}
wg.Wait()
Expect(fakeEC2API.CreateFleetBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.CreateFleetBehavior.CalledWithInput.Pop()
// requested 5 instances
Expect(*call.TargetCapacitySpecification.TotalTargetCapacity).To(BeNumerically("==", 5))
// but got three instances and two failures
Expect(receivedInstance).To(BeNumerically("==", 5))
Expect(numErrors).To(BeNumerically("==", 5))
})
It("should handle partial fulfillment", func() {
input := &ec2.CreateFleetInput{
LaunchTemplateConfigs: []*ec2.FleetLaunchTemplateConfigRequest{
{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: []*ec2.FleetLaunchTemplateOverridesRequest{
{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
TotalTargetCapacity: aws.Int64(1),
},
}
fakeEC2API.CreateFleetBehavior.Output.Set(&ec2.CreateFleetOutput{
Errors: []*ec2.CreateFleetError{
{
ErrorCode: aws.String("some-error"),
ErrorMessage: aws.String("some-error"),
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecification{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: &ec2.FleetLaunchTemplateOverrides{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
{
ErrorCode: aws.String("some-other-error"),
ErrorMessage: aws.String("some-other-error"),
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecification{
LaunchTemplateName: aws.String("my-template"),
},
Overrides: &ec2.FleetLaunchTemplateOverrides{
AvailabilityZone: aws.String("us-east-1"),
},
},
},
},
FleetId: aws.String("some-id"),
Instances: []*ec2.CreateFleetInstance{
{
InstanceIds: []*string{aws.String("id-1"), aws.String("id-2"), aws.String("id-3")},
InstanceType: nil,
LaunchTemplateAndOverrides: nil,
Lifecycle: nil,
Platform: nil,
},
},
})
var wg sync.WaitGroup
var receivedInstance int64
var numErrors int64
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.CreateFleet(ctx, input)
// partial fulfillment shouldn't cause an error at the CreateFleet call
Expect(err).To(BeNil())
if len(rsp.Errors) != 0 {
atomic.AddInt64(&numErrors, 1)
}
var instanceIds []string
for _, rsv := range rsp.Instances {
for _, id := range rsv.InstanceIds {
instanceIds = append(instanceIds, *id)
}
}
Expect(instanceIds).To(Or(HaveLen(0), HaveLen(1)))
if len(instanceIds) == 1 {
atomic.AddInt64(&receivedInstance, 1)
}
}()
}
wg.Wait()
Expect(fakeEC2API.CreateFleetBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.CreateFleetBehavior.CalledWithInput.Pop()
// requested 5 instances
Expect(*call.TargetCapacitySpecification.TotalTargetCapacity).To(BeNumerically("==", 5))
// but got three instances and the errors were returned to all five calls
Expect(receivedInstance).To(BeNumerically("==", 3))
Expect(numErrors).To(BeNumerically("==", 5))
})
})
| 348 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"context"
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/mitchellh/hashstructure/v2"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/logging"
)
type DescribeInstancesBatcher struct {
batcher *Batcher[ec2.DescribeInstancesInput, ec2.DescribeInstancesOutput]
}
func NewDescribeInstancesBatcher(ctx context.Context, ec2api ec2iface.EC2API) *DescribeInstancesBatcher {
options := Options[ec2.DescribeInstancesInput, ec2.DescribeInstancesOutput]{
Name: "describe_instances",
IdleTimeout: 100 * time.Millisecond,
MaxTimeout: 1 * time.Second,
MaxItems: 500,
RequestHasher: FilterHasher,
BatchExecutor: execDescribeInstancesBatch(ec2api),
}
return &DescribeInstancesBatcher{batcher: NewBatcher(ctx, options)}
}
func (b *DescribeInstancesBatcher) DescribeInstances(ctx context.Context, describeInstancesInput *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) {
if len(describeInstancesInput.InstanceIds) != 1 {
return nil, fmt.Errorf("expected to receive a single instance only, found %d", len(describeInstancesInput.InstanceIds))
}
result := b.batcher.Add(ctx, describeInstancesInput)
return result.Output, result.Err
}
func FilterHasher(ctx context.Context, input *ec2.DescribeInstancesInput) uint64 {
hash, err := hashstructure.Hash(input.Filters, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
if err != nil {
logging.FromContext(ctx).Errorf("error hashing")
}
return hash
}
func execDescribeInstancesBatch(ec2api ec2iface.EC2API) BatchExecutor[ec2.DescribeInstancesInput, ec2.DescribeInstancesOutput] {
return func(ctx context.Context, inputs []*ec2.DescribeInstancesInput) []Result[ec2.DescribeInstancesOutput] {
results := make([]Result[ec2.DescribeInstancesOutput], len(inputs))
firstInput := inputs[0]
// aggregate instanceIDs into 1 input
for _, input := range inputs[1:] {
firstInput.InstanceIds = append(firstInput.InstanceIds, input.InstanceIds...)
}
missingInstanceIDs := sets.NewString(lo.Map(firstInput.InstanceIds, func(i *string, _ int) string { return *i })...)
// Execute fully aggregated request
// We don't care about the error here since we'll break up the batch upon any sort of failure
_ = ec2api.DescribeInstancesPagesWithContext(ctx, firstInput, func(dio *ec2.DescribeInstancesOutput, b bool) bool {
for _, r := range dio.Reservations {
for _, instance := range r.Instances {
missingInstanceIDs.Delete(*instance.InstanceId)
// Find all indexes where we are requesting this instance and populate with the result
for reqID := range inputs {
if *inputs[reqID].InstanceIds[0] == *instance.InstanceId {
inst := instance // locally scoped to avoid pointer pollution in a range loop
results[reqID] = Result[ec2.DescribeInstancesOutput]{Output: &ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{{
OwnerId: r.OwnerId,
RequesterId: r.RequesterId,
ReservationId: r.ReservationId,
Instances: []*ec2.Instance{inst},
}},
}}
}
}
}
}
return true
})
// Some or all instances may have failed to be described due to eventual consistency or transient zonal issue.
// A single instance lookup failure can result in all of an availability zone's instances failing to describe.
// So we try to describe them individually now. This should be rare and only results in a handfull of extra calls per batch than without batching.
var wg sync.WaitGroup
for instanceID := range missingInstanceIDs {
wg.Add(1)
go func(instanceID string) {
defer wg.Done()
// try to execute separately
out, err := ec2api.DescribeInstancesWithContext(ctx, &ec2.DescribeInstancesInput{
Filters: firstInput.Filters,
InstanceIds: []*string{aws.String(instanceID)}})
// Find all indexes where we are requesting this instance and populate with the result
for reqID := range inputs {
if *inputs[reqID].InstanceIds[0] == instanceID {
results[reqID] = Result[ec2.DescribeInstancesOutput]{Output: out, Err: err}
}
}
}(instanceID)
}
wg.Wait()
return results
}
}
| 125 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher_test
import (
"fmt"
"sync"
"sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/karpenter/pkg/batcher"
"github.com/aws/karpenter/pkg/fake"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("DescribeInstances Batcher", func() {
var cfb *batcher.DescribeInstancesBatcher
BeforeEach(func() {
fakeEC2API.Reset()
cfb = batcher.NewDescribeInstancesBatcher(ctx, fakeEC2API)
})
It("should batch input into a single call", func() {
instanceIDs := []string{"i-1", "i-2", "i-3", "i-4", "i-5"}
for _, id := range instanceIDs {
fakeEC2API.Instances.Store(id, &ec2.Instance{InstanceId: aws.String(id)})
}
var wg sync.WaitGroup
var receivedInstance int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).To(BeNil())
atomic.AddInt64(&receivedInstance, 1)
Expect(rsp.Reservations).To(HaveLen(1))
Expect(rsp.Reservations[0].Instances).To(HaveLen(1))
}(instanceID)
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", len(instanceIDs)))
Expect(fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Pop()
Expect(len(call.InstanceIds)).To(BeNumerically("==", len(instanceIDs)))
})
It("should batch input correctly when receiving multiple calls with the same instance id", func() {
instanceIDs := []string{"i-1", "i-1", "i-1", "i-2", "i-2"}
for _, id := range instanceIDs {
fakeEC2API.Instances.Store(id, &ec2.Instance{InstanceId: aws.String(id)})
}
var wg sync.WaitGroup
var receivedInstance int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).To(BeNil())
atomic.AddInt64(&receivedInstance, 1)
Expect(rsp.Reservations).To(HaveLen(1))
Expect(rsp.Reservations[0].Instances).To(HaveLen(1))
}(instanceID)
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", len(instanceIDs)))
Expect(fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Pop()
Expect(len(call.InstanceIds)).To(BeNumerically("==", len(instanceIDs)))
})
It("should handle partial terminations on batched call and recover with individual requests", func() {
instanceIDs := []string{"i-1", "i-2", "i-3"}
// Output with only the first Instance
fakeEC2API.DescribeInstancesBehavior.Output.Set(&ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{
{
Instances: []*ec2.Instance{
{
InstanceId: aws.String("i-1"),
},
},
},
},
})
runningFilter := &ec2.Filter{
Name: aws.String("instance-state-name"),
Values: []*string{aws.String(ec2.InstanceStateNameRunning)},
}
var wg sync.WaitGroup
var receivedInstance int64
var numUnfulfilled int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
Filters: []*ec2.Filter{runningFilter},
})
Expect(err).To(BeNil())
if len(rsp.Reservations) > 0 {
Expect(len(rsp.Reservations[0].Instances)).To(BeNumerically("<=", 1))
if len(rsp.Reservations[0].Instances) == 1 {
atomic.AddInt64(&receivedInstance, 1)
} else {
atomic.AddInt64(&numUnfulfilled, 1)
}
}
}(instanceID)
}
wg.Wait()
// should execute the batched call and then one for each that failed in the batched request
Expect(fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 3))
lastCall := fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Pop()
Expect(len(lastCall.InstanceIds)).To(BeNumerically("==", 1))
Expect(len(lastCall.Filters)).To(BeNumerically("==", 1))
Expect(*lastCall.Filters[0].Name).To(Equal("instance-state-name"))
nextToLastCall := fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Pop()
Expect(len(nextToLastCall.InstanceIds)).To(BeNumerically("==", 1))
Expect(len(nextToLastCall.Filters)).To(BeNumerically("==", 1))
Expect(*lastCall.Filters[0].Name).To(Equal("instance-state-name"))
firstCall := fakeEC2API.DescribeInstancesBehavior.CalledWithInput.Pop()
Expect(len(firstCall.InstanceIds)).To(BeNumerically("==", 3))
Expect(len(firstCall.Filters)).To(BeNumerically("==", 1))
Expect(*lastCall.Filters[0].Name).To(Equal("instance-state-name"))
Expect(receivedInstance).To(BeNumerically("==", 3))
Expect(numUnfulfilled).To(BeNumerically("==", 0))
})
It("should return errors to all callers when erroring on the batched call", func() {
instanceIDs := []string{"i-1", "i-2", "i-3", "i-4", "i-5"}
fakeEC2API.DescribeInstancesBehavior.Error.Set(fmt.Errorf("error"), fake.MaxCalls(6))
var wg sync.WaitGroup
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
_, err := cfb.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).ToNot(BeNil())
}(instanceID)
}
wg.Wait()
// We expect 6 calls since we do one full batched call and 5 individual since the batched call returns an error
Expect(fakeEC2API.DescribeInstancesBehavior.Calls()).To(BeNumerically("==", 6))
})
})
| 182 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"context"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
)
type EC2API struct {
*CreateFleetBatcher
*DescribeInstancesBatcher
*TerminateInstancesBatcher
}
func EC2(ctx context.Context, ec2api ec2iface.EC2API) *EC2API {
return &EC2API{
CreateFleetBatcher: NewCreateFleetBatcher(ctx, ec2api),
DescribeInstancesBatcher: NewDescribeInstancesBatcher(ctx, ec2api),
TerminateInstancesBatcher: NewTerminateInstancesBatcher(ctx, ec2api),
}
}
| 36 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"github.com/prometheus/client_golang/prometheus"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/aws/karpenter-core/pkg/metrics"
)
const (
batcherSubsystem = "cloudprovider_batcher"
batcherNameLabel = "batcher"
)
// SizeBuckets returns a []float64 of default threshold values for size histograms.
// Each returned slice is new and may be modified without impacting other bucket definitions.
func SizeBuckets() []float64 {
return []float64{1, 2, 4, 5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200,
225, 250, 275, 300, 350, 400, 450, 500, 550, 600, 700, 800, 900, 1000}
}
var (
batchWindowDuration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: metrics.Namespace,
Subsystem: batcherSubsystem,
Name: "batch_time_seconds",
Help: "Duration of the batching window per batcher",
Buckets: metrics.DurationBuckets(),
}, []string{batcherNameLabel})
batchSize = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: metrics.Namespace,
Subsystem: batcherSubsystem,
Name: "batch_size",
Help: "Size of the request batch per batcher",
Buckets: SizeBuckets(),
}, []string{batcherNameLabel})
)
func init() {
crmetrics.Registry.MustRegister(batchWindowDuration, batchSize)
}
| 56 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher_test
import (
"context"
"sync/atomic"
"testing"
"time"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/batcher"
"github.com/aws/karpenter/pkg/fake"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "knative.dev/pkg/logging/testing"
)
var fakeEC2API *fake.EC2API
var ctx context.Context
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Batcher")
}
var _ = BeforeSuite(func() {
fakeEC2API = &fake.EC2API{}
})
var _ = Describe("Batcher", func() {
var cancelCtx context.Context
var cancel context.CancelFunc
var fakeBatcher *FakeBatcher
BeforeEach(func() {
cancelCtx, cancel = context.WithCancel(ctx)
})
AfterEach(func() {
// Cancel the context to make sure that we properly clean-up
cancel()
})
Context("Concurrency", func() {
It("should limit the number of threads that run concurrently from the batcher", func() {
// This batcher will get canceled at the end of the test run
fakeBatcher = NewFakeBatcher(cancelCtx, time.Minute, 100)
// Generate 300 items that add to the batcher
for i := 0; i < 300; i++ {
go func() {
fakeBatcher.batcher.Add(cancelCtx, lo.ToPtr(test.RandomName()))
}()
}
// Check that we get to 100 threads, and we stay at 100 threads
Eventually(fakeBatcher.activeBatches.Load).Should(BeNumerically("==", 100))
Consistently(fakeBatcher.activeBatches.Load, time.Second*10).Should(BeNumerically("==", 100))
})
It("should process 300 items in parallel to get quicker batching", func() {
// This batcher will get canceled at the end of the test run
fakeBatcher = NewFakeBatcher(cancelCtx, time.Second, 300)
// Generate 300 items that add to the batcher
for i := 0; i < 300; i++ {
go func() {
fakeBatcher.batcher.Add(cancelCtx, lo.ToPtr(test.RandomName()))
}()
}
Eventually(fakeBatcher.activeBatches.Load).Should(BeNumerically("==", 300))
Eventually(fakeBatcher.completedBatches.Load, time.Second*3).Should(BeNumerically("==", 300))
})
})
Context("Metrics", func() {
It("should create a batch_size metric when a batch is run", func() {
// This batcher will get canceled at the end of the test run
fakeBatcher = NewFakeBatcher(cancelCtx, time.Minute, 100)
// Generate 300 items that add to the batcher
for i := 0; i < 100; i++ {
go func() {
fakeBatcher.batcher.Add(cancelCtx, lo.ToPtr(test.RandomName()))
}()
}
Eventually(fakeBatcher.activeBatches.Load).Should(BeNumerically("==", 100))
metric, ok := expectations.FindMetricWithLabelValues("karpenter_cloudprovider_batcher_batch_size", map[string]string{
"batcher": "fake",
})
Expect(ok).To(BeTrue())
Expect(metric.GetHistogram().GetSampleCount()).To(BeNumerically(">=", 100))
})
It("should create a batch_window_duration metric when a batch is run", func() {
// This batcher will get canceled at the end of the test run
fakeBatcher = NewFakeBatcher(cancelCtx, time.Minute, 100)
// Generate 300 items that add to the batcher
for i := 0; i < 100; i++ {
go func() {
fakeBatcher.batcher.Add(cancelCtx, lo.ToPtr(test.RandomName()))
}()
}
Eventually(fakeBatcher.activeBatches.Load).Should(BeNumerically("==", 100))
_, ok := expectations.FindMetricWithLabelValues("karpenter_cloudprovider_batcher_batch_time_seconds", map[string]string{
"batcher": "fake",
})
Expect(ok).To(BeTrue())
})
})
})
// FakeBatcher is a batcher with a mocked request that takes a long time to execute that also ref-counts the number
// of active requests that are running at a given time
type FakeBatcher struct {
activeBatches *atomic.Int64
completedBatches *atomic.Int64
batcher *batcher.Batcher[string, string]
}
func NewFakeBatcher(ctx context.Context, requestLength time.Duration, maxRequestWorkers int) *FakeBatcher {
activeBatches := &atomic.Int64{}
completedBatches := &atomic.Int64{}
options := batcher.Options[string, string]{
Name: "fake",
IdleTimeout: 100 * time.Millisecond,
MaxTimeout: 1 * time.Second,
MaxRequestWorkers: maxRequestWorkers,
RequestHasher: batcher.DefaultHasher[string],
BatchExecutor: func(ctx context.Context, items []*string) []batcher.Result[string] {
// Keep a ref count of the number of batches that we are currently running
activeBatches.Add(1)
defer activeBatches.Add(-1)
defer completedBatches.Add(1)
// Wait for an arbitrary request length while running this call
select {
case <-ctx.Done():
case <-time.After(requestLength):
}
// Return back request responses
return lo.Map(items, func(i *string, _ int) batcher.Result[string] {
return batcher.Result[string]{
Output: lo.ToPtr[string](""),
Err: nil,
}
})
},
}
return &FakeBatcher{
activeBatches: activeBatches,
completedBatches: completedBatches,
batcher: batcher.NewBatcher(ctx, options),
}
}
| 174 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher
import (
"context"
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/logging"
)
type TerminateInstancesBatcher struct {
batcher *Batcher[ec2.TerminateInstancesInput, ec2.TerminateInstancesOutput]
}
func NewTerminateInstancesBatcher(ctx context.Context, ec2api ec2iface.EC2API) *TerminateInstancesBatcher {
options := Options[ec2.TerminateInstancesInput, ec2.TerminateInstancesOutput]{
Name: "terminate_instances",
IdleTimeout: 100 * time.Millisecond,
MaxTimeout: 1 * time.Second,
MaxItems: 500,
RequestHasher: OneBucketHasher[ec2.TerminateInstancesInput],
BatchExecutor: execTerminateInstancesBatch(ec2api),
}
return &TerminateInstancesBatcher{batcher: NewBatcher(ctx, options)}
}
func (b *TerminateInstancesBatcher) TerminateInstances(ctx context.Context, terminateInstancesInput *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) {
if len(terminateInstancesInput.InstanceIds) != 1 {
return nil, fmt.Errorf("expected to receive a single instance only, found %d", len(terminateInstancesInput.InstanceIds))
}
result := b.batcher.Add(ctx, terminateInstancesInput)
return result.Output, result.Err
}
func execTerminateInstancesBatch(ec2api ec2iface.EC2API) BatchExecutor[ec2.TerminateInstancesInput, ec2.TerminateInstancesOutput] {
return func(ctx context.Context, inputs []*ec2.TerminateInstancesInput) []Result[ec2.TerminateInstancesOutput] {
results := make([]Result[ec2.TerminateInstancesOutput], len(inputs))
firstInput := inputs[0]
// aggregate instanceIDs into 1 input
for _, input := range inputs[1:] {
firstInput.InstanceIds = append(firstInput.InstanceIds, input.InstanceIds...)
}
// Create a set of all instance IDs
stillRunning := sets.NewString(lo.Map(firstInput.InstanceIds, func(i *string, _ int) string { return *i })...)
// Execute fully aggregated request
// We don't care about the error here since we'll break up the batch upon any sort of failure
output, err := ec2api.TerminateInstancesWithContext(ctx, firstInput)
if err != nil {
logging.FromContext(ctx).Errorf("terminating instances, %s", err)
}
if output == nil {
output = &ec2.TerminateInstancesOutput{}
}
// Check the fulfillment for partial or no fulfillment by checking for missing instance IDs or invalid instance states
for _, instanceStateChanges := range output.TerminatingInstances {
// Remove all instances that successfully terminated and separate into distinct outputs
if lo.Contains([]string{ec2.InstanceStateNameShuttingDown, ec2.InstanceStateNameTerminated}, *instanceStateChanges.CurrentState.Name) {
stillRunning.Delete(*instanceStateChanges.InstanceId)
// Find all indexes where we are requesting this instance and populate with the result
for reqID := range inputs {
if *inputs[reqID].InstanceIds[0] == *instanceStateChanges.InstanceId {
results[reqID] = Result[ec2.TerminateInstancesOutput]{
Output: &ec2.TerminateInstancesOutput{
TerminatingInstances: []*ec2.InstanceStateChange{{
InstanceId: instanceStateChanges.InstanceId,
CurrentState: instanceStateChanges.CurrentState,
PreviousState: instanceStateChanges.PreviousState,
}},
},
}
}
}
}
}
// Some or all instances may have failed to terminate due to instance protection or some other error.
// A single instance failure can result in all of an availability zone's instances failing to terminate.
// So we try to terminate them individually now. This should be rare and only results in 1 extra call per batch than without batching.
var wg sync.WaitGroup
for instanceID := range stillRunning {
wg.Add(1)
go func(instanceID string) {
defer wg.Done()
// try to execute separately
out, err := ec2api.TerminateInstancesWithContext(ctx, &ec2.TerminateInstancesInput{InstanceIds: []*string{aws.String(instanceID)}})
// Find all indexes where we are requesting this instance and populate with the result
for reqID := range inputs {
if *inputs[reqID].InstanceIds[0] == instanceID {
results[reqID] = Result[ec2.TerminateInstancesOutput]{Output: out, Err: err}
}
}
}(instanceID)
}
wg.Wait()
return results
}
}
| 124 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batcher_test
import (
"fmt"
"sync"
"sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/karpenter/pkg/batcher"
"github.com/aws/karpenter/pkg/fake"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("TerminateInstances Batcher", func() {
var cfb *batcher.TerminateInstancesBatcher
BeforeEach(func() {
fakeEC2API.Reset()
cfb = batcher.NewTerminateInstancesBatcher(ctx, fakeEC2API)
})
It("should batch input into a single call", func() {
instanceIDs := []string{"i-1", "i-2", "i-3", "i-4", "i-5"}
for _, id := range instanceIDs {
fakeEC2API.Instances.Store(id, &ec2.Instance{})
}
var wg sync.WaitGroup
var receivedInstance int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).To(BeNil())
atomic.AddInt64(&receivedInstance, 1)
Expect(rsp.TerminatingInstances).To(HaveLen(1))
}(instanceID)
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", len(instanceIDs)))
Expect(fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Pop()
Expect(len(call.InstanceIds)).To(BeNumerically("==", len(instanceIDs)))
})
It("should batch input correctly when receiving multiple calls with the same instance id", func() {
instanceIDs := []string{"i-1", "i-1", "i-1", "i-2", "i-2"}
for _, id := range instanceIDs {
fakeEC2API.Instances.Store(id, &ec2.Instance{})
}
var wg sync.WaitGroup
var receivedInstance int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).To(BeNil())
atomic.AddInt64(&receivedInstance, 1)
Expect(rsp.TerminatingInstances).To(HaveLen(1))
}(instanceID)
}
wg.Wait()
Expect(receivedInstance).To(BeNumerically("==", len(instanceIDs)))
Expect(fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
call := fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Pop()
Expect(len(call.InstanceIds)).To(BeNumerically("==", len(instanceIDs)))
})
It("should handle partial terminations on batched call and recover with individual requests", func() {
instanceIDs := []string{"i-1", "i-2", "i-3"}
// Output with only the first Terminating Instance
fakeEC2API.TerminateInstancesBehavior.Output.Set(&ec2.TerminateInstancesOutput{
TerminatingInstances: []*ec2.InstanceStateChange{
{
PreviousState: &ec2.InstanceState{Name: aws.String(ec2.InstanceStateNameRunning), Code: aws.Int64(16)},
CurrentState: &ec2.InstanceState{Name: aws.String(ec2.InstanceStateNameShuttingDown), Code: aws.Int64(32)},
InstanceId: aws.String(instanceIDs[0]),
},
},
})
var wg sync.WaitGroup
var receivedInstance int64
var numUnfulfilled int64
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
rsp, err := cfb.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).To(BeNil())
Expect(len(rsp.TerminatingInstances)).To(BeNumerically("<=", 1))
if len(rsp.TerminatingInstances) == 0 {
atomic.AddInt64(&numUnfulfilled, 1)
} else {
atomic.AddInt64(&receivedInstance, 1)
}
}(instanceID)
}
wg.Wait()
// should execute the batched call and then one for each that failed in the batched request
Expect(fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Len()).To(BeNumerically("==", 3))
lastCall := fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Pop()
Expect(len(lastCall.InstanceIds)).To(BeNumerically("==", 1))
nextToLastCall := fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Pop()
Expect(len(nextToLastCall.InstanceIds)).To(BeNumerically("==", 1))
firstCall := fakeEC2API.TerminateInstancesBehavior.CalledWithInput.Pop()
Expect(len(firstCall.InstanceIds)).To(BeNumerically("==", 3))
Expect(receivedInstance).To(BeNumerically("==", 3))
Expect(numUnfulfilled).To(BeNumerically("==", 0))
})
It("should return errors to all callers when erroring on the batched call", func() {
instanceIDs := []string{"i-1", "i-2", "i-3", "i-4", "i-5"}
fakeEC2API.TerminateInstancesBehavior.Error.Set(fmt.Errorf("error"), fake.MaxCalls(6))
var wg sync.WaitGroup
for _, instanceID := range instanceIDs {
wg.Add(1)
go func(instanceID string) {
defer GinkgoRecover()
defer wg.Done()
_, err := cfb.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
})
Expect(err).ToNot(BeNil())
}(instanceID)
}
wg.Wait()
// We expect 6 calls since we do one full batched call and 5 individual since the batched call returns an error
Expect(fakeEC2API.TerminateInstancesBehavior.Calls()).To(BeNumerically("==", 6))
})
})
| 161 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache
import "time"
const (
// DefaultTTL restricts QPS to AWS APIs to this interval for verifying setup
// resources. This value represents the maximum eventual consistency between
// AWS actual state and the controller's ability to provision those
// resources. Cache hits enable faster provisioning and reduced API load on
// AWS APIs, which can have a serious impact on performance and scalability.
// DO NOT CHANGE THIS VALUE WITHOUT DUE CONSIDERATION
DefaultTTL = time.Minute
// UnavailableOfferingsTTL is the time before offerings that were marked as unavailable
// are removed from the cache and are available for launch again
UnavailableOfferingsTTL = 3 * time.Minute
// InstanceTypesAndZonesTTL is the time before we refresh instance types and zones at EC2
InstanceTypesAndZonesTTL = 5 * time.Minute
)
const (
// DefaultCleanupInterval triggers cache cleanup (lazy eviction) at this interval.
DefaultCleanupInterval = 10 * time.Minute
)
| 38 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache
import (
"fmt"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/events"
)
func UnavailableOfferingEvent(instanceType, availabilityZone, capacityType string) events.Event {
return events.Event{
Type: v1.EventTypeWarning,
Reason: "UnavailableOffering",
Message: fmt.Sprintf(`UnavailableOffering for {"instanceType": %q, "availabilityZone": %q, "capacityType": %q}`, instanceType, availabilityZone, capacityType),
DedupeValues: []string{instanceType, availabilityZone, capacityType},
}
}
| 33 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache_test
import (
"context"
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "knative.dev/pkg/logging/testing"
_ "knative.dev/pkg/system/testing"
)
var ctx context.Context
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Cache")
}
| 34 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache
import (
"context"
"fmt"
"sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/patrickmn/go-cache"
"knative.dev/pkg/logging"
"github.com/aws/karpenter-core/pkg/events"
)
// UnavailableOfferings stores any offerings that return ICE (insufficient capacity errors) when
// attempting to launch the capacity. These offerings are ignored as long as they are in the cache on
// GetInstanceTypes responses
type UnavailableOfferings struct {
// key: <capacityType>:<instanceType>:<zone>, value: struct{}{}
cache *cache.Cache
SeqNum uint64
recorder events.Recorder
}
func NewUnavailableOfferings(recorder events.Recorder) *UnavailableOfferings {
return &UnavailableOfferings{
cache: cache.New(UnavailableOfferingsTTL, DefaultCleanupInterval),
SeqNum: 0,
recorder: recorder,
}
}
// IsUnavailable returns true if the offering appears in the cache
func (u *UnavailableOfferings) IsUnavailable(instanceType, zone, capacityType string) bool {
_, found := u.cache.Get(u.key(instanceType, zone, capacityType))
return found
}
// MarkUnavailable communicates recently observed temporary capacity shortages in the provided offerings
func (u *UnavailableOfferings) MarkUnavailable(ctx context.Context, unavailableReason, instanceType, zone, capacityType string) {
// even if the key is already in the cache, we still need to call Set to extend the cached entry's TTL
logging.FromContext(ctx).With(
"reason", unavailableReason,
"instance-type", instanceType,
"zone", zone,
"capacity-type", capacityType,
"ttl", UnavailableOfferingsTTL).Debugf("removing offering from offerings")
u.cache.SetDefault(u.key(instanceType, zone, capacityType), struct{}{})
atomic.AddUint64(&u.SeqNum, 1)
// Add a k8s event for the instance type and zone without the involved object which has an ICE error
u.recorder.Publish(UnavailableOfferingEvent(instanceType, zone, capacityType))
}
func (u *UnavailableOfferings) MarkUnavailableForFleetErr(ctx context.Context, fleetErr *ec2.CreateFleetError, capacityType string) {
instanceType := aws.StringValue(fleetErr.LaunchTemplateAndOverrides.Overrides.InstanceType)
zone := aws.StringValue(fleetErr.LaunchTemplateAndOverrides.Overrides.AvailabilityZone)
u.MarkUnavailable(ctx, aws.StringValue(fleetErr.ErrorCode), instanceType, zone, capacityType)
}
func (u *UnavailableOfferings) Delete(instanceType string, zone string, capacityType string) {
u.cache.Delete(u.key(instanceType, zone, capacityType))
}
func (u *UnavailableOfferings) Flush() {
u.cache.Flush()
}
// key returns the cache key for all offerings in the cache
func (u *UnavailableOfferings) key(instanceType string, zone string, capacityType string) string {
return fmt.Sprintf("%s:%s:%s", capacityType, instanceType, zone)
}
| 88 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cache_test
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
_ "knative.dev/pkg/system/testing"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/cache"
)
var unavailableOfferingsCache *cache.UnavailableOfferings
var recorder *test.EventRecorder
var _ = Describe("UnavailableOfferings", func() {
BeforeEach(func() {
ctx = context.Background()
recorder = test.NewEventRecorder()
unavailableOfferingsCache = cache.NewUnavailableOfferings(recorder)
})
AfterEach(func() {
recorder.Reset()
})
It("should create an UnavailableOfferingEvent when receiving a CreateFleet error", func() {
unavailableOfferingsCache.MarkUnavailableForFleetErr(ctx, &ec2.CreateFleetError{
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
Overrides: &ec2.FleetLaunchTemplateOverrides{
InstanceType: aws.String("c5.large"),
AvailabilityZone: aws.String("test-zone-1a"),
},
},
}, v1alpha5.CapacityTypeSpot)
Expect(recorder.Calls("UnavailableOffering")).To(BeNumerically("==", 1))
Expect(recorder.DetectedEvent(`UnavailableOffering for {"instanceType": "c5.large", "availabilityZone": "test-zone-1a", "capacityType": "spot"}`))
})
It("should create an UnavailableOfferingEvent when marking an offering as unavailable", func() {
unavailableOfferingsCache.MarkUnavailable(ctx, "offering is unavailable", "c5.large", "test-zone-1a", v1alpha5.CapacityTypeSpot)
Expect(recorder.Calls("UnavailableOffering")).To(BeNumerically("==", 1))
Expect(recorder.DetectedEvent(`UnavailableOffering for {"instanceType": "c5.large", "availabilityZone": "test-zone-1a", "capacityType": "spot"}`))
})
It("should create multiple UnavailableOfferingEvent when marking multiple offerings as unavailable", func() {
type offering struct {
instanceType string
availabilityZone string
capacityType string
}
offerings := []offering{
{
instanceType: "c5.large",
availabilityZone: "test-zone-1a",
capacityType: v1alpha5.CapacityTypeSpot,
},
{
instanceType: "g4dn.xlarge",
availabilityZone: "test-zone-1b",
capacityType: v1alpha5.CapacityTypeOnDemand,
},
{
instanceType: "inf1.24xlarge",
availabilityZone: "test-zone-1d",
capacityType: v1alpha5.CapacityTypeSpot,
},
{
instanceType: "t3.nano",
availabilityZone: "test-zone-1b",
capacityType: v1alpha5.CapacityTypeOnDemand,
},
}
for _, of := range offerings {
unavailableOfferingsCache.MarkUnavailable(ctx, "offering is unavailable", of.instanceType, of.availabilityZone, of.capacityType)
}
Expect(recorder.Calls("UnavailableOffering")).To(BeNumerically("==", len(offerings)))
})
})
| 98 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudprovider
import (
"context"
"fmt"
"net/http"
"time"
"github.com/aws/aws-sdk-go/service/ec2"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/runtime/schema"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/instance"
"github.com/aws/karpenter/pkg/providers/instancetype"
"github.com/aws/karpenter/pkg/providers/securitygroup"
"github.com/aws/karpenter/pkg/providers/subnet"
coreapis "github.com/aws/karpenter-core/pkg/apis"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
)
func init() {
v1alpha5.NormalizedLabels = lo.Assign(v1alpha5.NormalizedLabels, map[string]string{"topology.ebs.csi.aws.com/zone": v1.LabelTopologyZone})
coreapis.Settings = append(coreapis.Settings, apis.Settings...)
}
var _ cloudprovider.CloudProvider = (*CloudProvider)(nil)
type CloudProvider struct {
instanceTypeProvider *instancetype.Provider
instanceProvider *instance.Provider
kubeClient client.Client
amiProvider *amifamily.Provider
securityGroupProvider *securitygroup.Provider
subnetProvider *subnet.Provider
}
func New(instanceTypeProvider *instancetype.Provider, instanceProvider *instance.Provider,
kubeClient client.Client, amiProvider *amifamily.Provider, securityGroupProvider *securitygroup.Provider, subnetProvider *subnet.Provider) *CloudProvider {
return &CloudProvider{
instanceTypeProvider: instanceTypeProvider,
instanceProvider: instanceProvider,
kubeClient: kubeClient,
amiProvider: amiProvider,
securityGroupProvider: securityGroupProvider,
subnetProvider: subnetProvider,
}
}
// Create a machine given the constraints.
func (c *CloudProvider) Create(ctx context.Context, machine *v1alpha5.Machine) (*v1alpha5.Machine, error) {
nodeTemplate, err := c.resolveNodeTemplate(ctx, []byte(machine.
Annotations[v1alpha5.ProviderCompatabilityAnnotationKey]), machine.
Spec.MachineTemplateRef)
if err != nil {
return nil, fmt.Errorf("resolving node template, %w", err)
}
instanceTypes, err := c.resolveInstanceTypes(ctx, machine, nodeTemplate)
if err != nil {
return nil, fmt.Errorf("resolving instance types, %w", err)
}
if len(instanceTypes) == 0 {
return nil, cloudprovider.NewInsufficientCapacityError(fmt.Errorf("all requested instance types were unavailable during launch"))
}
instance, err := c.instanceProvider.Create(ctx, nodeTemplate, machine, instanceTypes)
if err != nil {
return nil, fmt.Errorf("creating instance, %w", err)
}
instanceType, _ := lo.Find(instanceTypes, func(i *cloudprovider.InstanceType) bool {
return i.Name == instance.Type
})
return c.instanceToMachine(instance, instanceType), nil
}
// Link adds a tag to the cloudprovider machine to tell the cloudprovider that it's now owned by a Machine
func (c *CloudProvider) Link(ctx context.Context, machine *v1alpha5.Machine) error {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("machine", machine.Name))
id, err := utils.ParseInstanceID(machine.Status.ProviderID)
if err != nil {
return fmt.Errorf("getting instance ID, %w", err)
}
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("id", id))
return c.instanceProvider.Link(ctx, id, machine.Labels[v1alpha5.ProvisionerNameLabelKey])
}
func (c *CloudProvider) List(ctx context.Context) ([]*v1alpha5.Machine, error) {
instances, err := c.instanceProvider.List(ctx)
if err != nil {
return nil, fmt.Errorf("listing instances, %w", err)
}
var machines []*v1alpha5.Machine
for _, instance := range instances {
instanceType, err := c.resolveInstanceTypeFromInstance(ctx, instance)
if err != nil {
return nil, fmt.Errorf("resolving instance type, %w", err)
}
machines = append(machines, c.instanceToMachine(instance, instanceType))
}
return machines, nil
}
func (c *CloudProvider) Get(ctx context.Context, providerID string) (*v1alpha5.Machine, error) {
id, err := utils.ParseInstanceID(providerID)
if err != nil {
return nil, fmt.Errorf("getting instance ID, %w", err)
}
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("id", id))
instance, err := c.instanceProvider.Get(ctx, id)
if err != nil {
return nil, fmt.Errorf("getting instance, %w", err)
}
instanceType, err := c.resolveInstanceTypeFromInstance(ctx, instance)
if err != nil {
return nil, fmt.Errorf("resolving instance type, %w", err)
}
return c.instanceToMachine(instance, instanceType), nil
}
func (c *CloudProvider) LivenessProbe(req *http.Request) error {
return c.instanceTypeProvider.LivenessProbe(req)
}
// GetInstanceTypes returns all available InstanceTypes
func (c *CloudProvider) GetInstanceTypes(ctx context.Context, provisioner *v1alpha5.Provisioner) ([]*cloudprovider.InstanceType, error) {
if provisioner == nil {
return c.instanceTypeProvider.List(ctx, &v1alpha5.KubeletConfiguration{}, &v1alpha1.AWSNodeTemplate{})
}
var rawProvider []byte
if provisioner.Spec.Provider != nil {
rawProvider = provisioner.Spec.Provider.Raw
}
nodeTemplate, err := c.resolveNodeTemplate(ctx, rawProvider, provisioner.Spec.ProviderRef)
if err != nil {
return nil, err
}
// TODO, break this coupling
instanceTypes, err := c.instanceTypeProvider.List(ctx, provisioner.Spec.KubeletConfiguration, nodeTemplate)
if err != nil {
return nil, err
}
return instanceTypes, nil
}
func (c *CloudProvider) Delete(ctx context.Context, machine *v1alpha5.Machine) error {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("machine", machine.Name))
providerID := lo.Ternary(machine.Status.ProviderID != "", machine.Status.ProviderID, machine.Annotations[v1alpha5.MachineLinkedAnnotationKey])
id, err := utils.ParseInstanceID(providerID)
if err != nil {
return fmt.Errorf("getting instance ID, %w", err)
}
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("id", id))
return c.instanceProvider.Delete(ctx, id)
}
func (c *CloudProvider) IsMachineDrifted(ctx context.Context, machine *v1alpha5.Machine) (bool, error) {
// Not needed when GetInstanceTypes removes provisioner dependency
provisioner := &v1alpha5.Provisioner{}
if err := c.kubeClient.Get(ctx, types.NamespacedName{Name: machine.Labels[v1alpha5.ProvisionerNameLabelKey]}, provisioner); err != nil {
return false, client.IgnoreNotFound(fmt.Errorf("getting provisioner, %w", err))
}
if provisioner.Spec.ProviderRef == nil {
return false, nil
}
nodeTemplate, err := c.resolveNodeTemplate(ctx, nil, provisioner.Spec.ProviderRef)
if err != nil {
return false, client.IgnoreNotFound(fmt.Errorf("resolving node template, %w", err))
}
drifted, err := c.isNodeTemplateDrifted(ctx, machine, provisioner, nodeTemplate)
if err != nil {
return false, err
}
return drifted, nil
}
// Name returns the CloudProvider implementation name.
func (c *CloudProvider) Name() string {
return "aws"
}
func (c *CloudProvider) resolveNodeTemplate(ctx context.Context, raw []byte, objRef *v1alpha5.MachineTemplateRef) (*v1alpha1.AWSNodeTemplate, error) {
nodeTemplate := &v1alpha1.AWSNodeTemplate{}
if objRef != nil {
if err := c.kubeClient.Get(ctx, types.NamespacedName{Name: objRef.Name}, nodeTemplate); err != nil {
return nil, fmt.Errorf("getting providerRef, %w", err)
}
return nodeTemplate, nil
}
aws, err := v1alpha1.DeserializeProvider(raw)
if err != nil {
return nil, err
}
nodeTemplate.Spec.AWS = lo.FromPtr(aws)
return nodeTemplate, nil
}
func (c *CloudProvider) resolveInstanceTypes(ctx context.Context, machine *v1alpha5.Machine, nodeTemplate *v1alpha1.AWSNodeTemplate) ([]*cloudprovider.InstanceType, error) {
instanceTypes, err := c.instanceTypeProvider.List(ctx, machine.Spec.Kubelet, nodeTemplate)
if err != nil {
return nil, fmt.Errorf("getting instance types, %w", err)
}
reqs := scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...)
return lo.Filter(instanceTypes, func(i *cloudprovider.InstanceType, _ int) bool {
return reqs.Compatible(i.Requirements) == nil &&
len(i.Offerings.Requirements(reqs).Available()) > 0 &&
resources.Fits(machine.Spec.Resources.Requests, i.Allocatable())
}), nil
}
func (c *CloudProvider) resolveInstanceTypeFromInstance(ctx context.Context, instance *instance.Instance) (*cloudprovider.InstanceType, error) {
provisioner, err := c.resolveProvisionerFromInstance(ctx, instance)
if err != nil {
// If we can't resolve the provisioner, we fall back to not getting instance type info
return nil, client.IgnoreNotFound(fmt.Errorf("resolving provisioner, %w", err))
}
instanceTypes, err := c.GetInstanceTypes(ctx, provisioner)
if err != nil {
// If we can't resolve the provisioner, we fall back to not getting instance type info
return nil, client.IgnoreNotFound(fmt.Errorf("resolving node template, %w", err))
}
instanceType, _ := lo.Find(instanceTypes, func(i *cloudprovider.InstanceType) bool {
return i.Name == instance.Type
})
return instanceType, nil
}
func (c *CloudProvider) resolveProvisionerFromInstance(ctx context.Context, instance *instance.Instance) (*v1alpha5.Provisioner, error) {
provisioner := &v1alpha5.Provisioner{}
provisionerName, ok := instance.Tags[v1alpha5.ProvisionerNameLabelKey]
if !ok {
return nil, errors.NewNotFound(schema.GroupResource{Group: v1alpha5.Group, Resource: "Provisioner"}, "")
}
if err := c.kubeClient.Get(ctx, types.NamespacedName{Name: provisionerName}, provisioner); err != nil {
return nil, err
}
return provisioner, nil
}
func (c *CloudProvider) instanceToMachine(i *instance.Instance, instanceType *cloudprovider.InstanceType) *v1alpha5.Machine {
machine := &v1alpha5.Machine{}
labels := map[string]string{}
annotations := map[string]string{}
if instanceType != nil {
for key, req := range instanceType.Requirements {
if req.Len() == 1 {
labels[key] = req.Values()[0]
}
}
machine.Status.Capacity = functional.FilterMap(instanceType.Capacity, func(_ v1.ResourceName, v resource.Quantity) bool { return !resources.IsZero(v) })
machine.Status.Allocatable = functional.FilterMap(instanceType.Allocatable(), func(_ v1.ResourceName, v resource.Quantity) bool { return !resources.IsZero(v) })
}
labels[v1.LabelTopologyZone] = i.Zone
labels[v1alpha5.LabelCapacityType] = i.CapacityType
if v, ok := i.Tags[v1alpha5.ProvisionerNameLabelKey]; ok {
labels[v1alpha5.ProvisionerNameLabelKey] = v
}
if v, ok := i.Tags[v1alpha5.MachineManagedByAnnotationKey]; ok {
annotations[v1alpha5.MachineManagedByAnnotationKey] = v
}
machine.Labels = labels
machine.Annotations = annotations
machine.CreationTimestamp = metav1.Time{Time: i.LaunchTime}
// Set the deletionTimestamp to be the current time if the instance is currently terminating
if i.State == ec2.InstanceStateNameShuttingDown || i.State == ec2.InstanceStateNameTerminated {
machine.DeletionTimestamp = &metav1.Time{Time: time.Now()}
}
machine.Status.ProviderID = fmt.Sprintf("aws:///%s/%s", i.Zone, i.ID)
return machine
}
| 303 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudprovider
import (
"context"
"fmt"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/utils/sets"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/instance"
"github.com/aws/karpenter/pkg/utils"
)
func (c *CloudProvider) isNodeTemplateDrifted(ctx context.Context, machine *v1alpha5.Machine, provisioner *v1alpha5.Provisioner, nodeTemplate *v1alpha1.AWSNodeTemplate) (bool, error) {
instance, err := c.getInstance(ctx, machine.Status.ProviderID)
if err != nil {
return false, err
}
amiDrifted, err := c.isAMIDrifted(ctx, machine, provisioner, instance, nodeTemplate)
if err != nil {
return false, fmt.Errorf("calculating ami drift, %w", err)
}
securitygroupDrifted, err := c.areSecurityGroupsDrifted(instance, nodeTemplate)
if err != nil {
return false, fmt.Errorf("calculating securitygroup drift, %w", err)
}
subnetDrifted, err := c.isSubnetDrifted(instance, nodeTemplate)
if err != nil {
return false, fmt.Errorf("calculating subnet drift, %w", err)
}
return amiDrifted || securitygroupDrifted || subnetDrifted, nil
}
func (c *CloudProvider) isAMIDrifted(ctx context.Context, machine *v1alpha5.Machine, provisioner *v1alpha5.Provisioner,
instance *instance.Instance, nodeTemplate *v1alpha1.AWSNodeTemplate) (bool, error) {
instanceTypes, err := c.GetInstanceTypes(ctx, provisioner)
if err != nil {
return false, fmt.Errorf("getting instanceTypes, %w", err)
}
nodeInstanceType, found := lo.Find(instanceTypes, func(instType *cloudprovider.InstanceType) bool {
return instType.Name == machine.Labels[v1.LabelInstanceTypeStable]
})
if !found {
return false, fmt.Errorf(`finding node instance type "%s"`, machine.Labels[v1.LabelInstanceTypeStable])
}
if nodeTemplate.Spec.LaunchTemplateName != nil {
return false, nil
}
amis, err := c.amiProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
if err != nil {
return false, fmt.Errorf("getting amis, %w", err)
}
if len(amis) == 0 {
return false, fmt.Errorf("no amis exist given constraints")
}
mappedAMIs := amifamily.MapInstanceTypes(amis, []*cloudprovider.InstanceType{nodeInstanceType})
if len(mappedAMIs) == 0 {
return false, fmt.Errorf("no instance types satisfy requirements of amis %v,", amis)
}
return !lo.Contains(lo.Keys(mappedAMIs), instance.ImageID), nil
}
func (c *CloudProvider) isSubnetDrifted(instance *instance.Instance, nodeTemplate *v1alpha1.AWSNodeTemplate) (bool, error) {
// If the node template status does not have subnets, wait for the subnets to be populated before continuing
if nodeTemplate.Status.Subnets == nil {
return false, fmt.Errorf("AWSNodeTemplate has no subnets")
}
_, found := lo.Find(nodeTemplate.Status.Subnets, func(subnet v1alpha1.Subnet) bool {
return subnet.ID == instance.SubnetID
})
return !found, nil
}
// Checks if the security groups are drifted, by comparing the AWSNodeTemplate.Status.SecurityGroups
// to the ec2 instance security groups
func (c *CloudProvider) areSecurityGroupsDrifted(ec2Instance *instance.Instance, nodeTemplate *v1alpha1.AWSNodeTemplate) (bool, error) {
// nodeTemplate.Spec.SecurityGroupSelector can be nil if the user is using a launchTemplateName to define SecurityGroups
// Karpenter will not drift on changes to securitygroup in the launchTemplateName
if nodeTemplate.Spec.LaunchTemplateName != nil {
return false, nil
}
securityGroupIds := sets.New(lo.Map(nodeTemplate.Status.SecurityGroups, func(sg v1alpha1.SecurityGroup, _ int) string { return sg.ID })...)
if len(securityGroupIds) == 0 {
return false, fmt.Errorf("no security groups exist in the AWSNodeTemplate Status")
}
return !securityGroupIds.Equal(sets.New(ec2Instance.SecurityGroupIDs...)), nil
}
func (c *CloudProvider) getInstance(ctx context.Context, providerID string) (*instance.Instance, error) {
// Get InstanceID to fetch from EC2
instanceID, err := utils.ParseInstanceID(providerID)
if err != nil {
return nil, err
}
instance, err := c.instanceProvider.Get(ctx, instanceID)
if err != nil {
return nil, fmt.Errorf("getting instance, %w", err)
}
return instance, nil
}
| 121 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudprovider_test
import (
"context"
"fmt"
"net"
"testing"
"time"
"github.com/samber/lo"
"k8s.io/client-go/tools/record"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
clock "k8s.io/utils/clock/testing"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ssm"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "knative.dev/pkg/logging/testing"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/fake"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudproivder "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/controllers/provisioning"
"github.com/aws/karpenter-core/pkg/controllers/state"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/operator/options"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
)
var ctx context.Context
var stop context.CancelFunc
var opts options.Options
var env *coretest.Environment
var awsEnv *test.Environment
var prov *provisioning.Provisioner
var cloudProvider *cloudprovider.CloudProvider
var cluster *state.Cluster
var fakeClock *clock.FakeClock
var provisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
var machine *v1alpha5.Machine
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "cloudProvider/AWS")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
ctx, stop = context.WithCancel(ctx)
awsEnv = test.NewEnvironment(ctx, env)
fakeClock = clock.NewFakeClock(time.Now())
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
cluster = state.NewCluster(fakeClock, env.Client, cloudProvider)
prov = provisioning.NewProvisioner(env.Client, env.KubernetesInterface.CoreV1(), events.NewRecorder(&record.FakeRecorder{}), cloudProvider, cluster)
})
var _ = AfterSuite(func() {
stop()
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
ctx = injection.WithOptions(ctx, opts)
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
nodeTemplate = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
},
}
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
machine = coretest.Machine(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
},
},
Spec: v1alpha5.MachineSpec{
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
cluster.Reset()
awsEnv.Reset()
awsEnv.LaunchTemplateProvider.KubeDNSIP = net.ParseIP("10.0.100.10")
awsEnv.LaunchTemplateProvider.ClusterEndpoint = "https://test-cluster"
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("CloudProvider", func() {
It("should return an ICE error when there are no instance types to launch", func() {
// Specify no instance types and expect to receive a capacity error
machine.Spec.Requirements = []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate, machine)
cloudProviderMachine, err := cloudProvider.Create(ctx, machine)
Expect(corecloudproivder.IsInsufficientCapacityError(err)).To(BeTrue())
Expect(cloudProviderMachine).To(BeNil())
})
Context("Defaulting", func() {
// Intent here is that if updates occur on the provisioningController, the Provisioner doesn't need to be recreated
It("should not set the InstanceProfile with the default if none provided in Provisioner", func() {
provisioner.SetDefaults(ctx)
constraints, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
Expect(constraints.InstanceProfile).To(BeNil())
})
It("should default requirements", func() {
provisioner.SetDefaults(ctx)
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeOnDemand},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
}))
})
})
Context("EC2 Context", func() {
It("should set context on the CreateFleet request if specified on the Provisioner", func() {
provider, err := v1alpha1.DeserializeProvider(provisioner.Spec.Provider.Raw)
Expect(err).ToNot(HaveOccurred())
provider.Context = aws.String("context-1234")
provider.SubnetSelector = map[string]string{"*": "*"}
provider.SecurityGroupSelector = map[string]string{"*": "*"}
provisioner = coretest.Provisioner(coretest.ProvisionerOptions{Provider: provider})
provisioner.SetDefaults(ctx)
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(aws.StringValue(createFleetInput.Context)).To(Equal("context-1234"))
})
It("should default to no EC2 Context", func() {
provisioner.SetDefaults(ctx)
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.Context).To(BeNil())
})
})
Context("Machine Drift", func() {
var validAMI string
var validSecurityGroup string
var selectedInstanceType *corecloudproivder.InstanceType
var instance *ec2.Instance
var validSubnet1 string
var validSubnet2 string
BeforeEach(func() {
validAMI = fake.ImageID()
validSecurityGroup = fake.SecurityGroupID()
validSubnet1 = fake.SubnetID()
validSubnet2 = fake.SubnetID()
awsEnv.SSMAPI.GetParameterOutput = &ssm.GetParameterOutput{
Parameter: &ssm.Parameter{Value: aws.String(validAMI)},
}
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String(validAMI),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2022-08-15T12:00:00Z"),
}},
})
nodeTemplate.Status.SecurityGroups = []v1alpha1.SecurityGroup{
{
ID: validSecurityGroup,
Name: "test-securitygroup",
},
}
nodeTemplate.Status.Subnets = []v1alpha1.Subnet{
{
ID: validSubnet1,
Zone: "zone-1",
},
{
ID: validSubnet2,
Zone: "zone-2",
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
instanceTypes, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).ToNot(HaveOccurred())
selectedInstanceType = instanceTypes[0]
// Create the instance we want returned from the EC2 API
instance = &ec2.Instance{
ImageId: aws.String(validAMI),
InstanceType: aws.String(selectedInstanceType.Name),
SubnetId: aws.String(validSubnet1),
SpotInstanceRequestId: aws.String(coretest.RandomName()),
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
InstanceId: aws.String(fake.InstanceID()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
SecurityGroups: []*ec2.GroupIdentifier{{GroupId: aws.String(validSecurityGroup)}},
}
awsEnv.EC2API.DescribeInstancesBehavior.Output.Set(&ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{{Instances: []*ec2.Instance{instance}}},
})
})
It("should not fail if node template does not exist", func() {
ExpectDeleted(ctx, env.Client, nodeTemplate)
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
drifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(drifted).To(BeFalse())
})
It("should return false if providerRef is not defined", func() {
provisioner.Spec.ProviderRef = nil
ExpectApplied(ctx, env.Client, provisioner)
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
drifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(drifted).To(BeFalse())
})
It("should not fail if provisioner does not exist", func() {
ExpectDeleted(ctx, env.Client, provisioner)
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
drifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(drifted).To(BeFalse())
})
It("should return drifted if the AMI is not valid", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
// Instance is a reference to what we return in the GetInstances call
instance.ImageId = aws.String(fake.ImageID())
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeTrue())
})
It("should return drifted if the subnet is not valid", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
instance.SubnetId = aws.String(fake.SubnetID())
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeTrue())
})
It("should return an error if AWSNodeTemplate subnets are empty", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
nodeTemplate.Status.Subnets = []v1alpha1.Subnet{}
ExpectApplied(ctx, env.Client, nodeTemplate)
_, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).To(HaveOccurred())
})
It("should not return drifted if the machine is valid", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeFalse())
})
It("should return an error if the AWSNodeTemplate securitygroup are empty", func() {
nodeTemplate.Status.SecurityGroups = []v1alpha1.SecurityGroup{}
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
ExpectApplied(ctx, env.Client, nodeTemplate)
// Instance is a reference to what we return in the GetInstances call
instance.SecurityGroups = []*ec2.GroupIdentifier{{GroupId: aws.String(fake.SecurityGroupID())}}
_, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).To(HaveOccurred())
})
It("should return drifted if the instance securitygroup do not match the AWSNodeTemplateStatus", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
// Instance is a reference to what we return in the GetInstances call
instance.SecurityGroups = []*ec2.GroupIdentifier{{GroupId: aws.String(fake.SecurityGroupID())}}
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeTrue())
})
It("should return drifted if there are more instance securitygroups are present than AWSNodeTemplate Status", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
// Instance is a reference to what we return in the GetInstances call
instance.SecurityGroups = []*ec2.GroupIdentifier{{GroupId: aws.String(fake.SecurityGroupID())}, {GroupId: aws.String(validSecurityGroup)}}
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeTrue())
})
It("should return drifted if more AWSNodeTemplate securitygroups are present than instance securitygroups", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
nodeTemplate.Status.SecurityGroups = []v1alpha1.SecurityGroup{
{
ID: validSecurityGroup,
Name: "test-securitygroup",
},
{
ID: fake.SecurityGroupID(),
Name: "test-securitygroup",
},
}
ExpectApplied(ctx, env.Client, nodeTemplate)
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeTrue())
})
It("should not return drifted if launchTemplateName is defined", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
nodeTemplate.Spec.LaunchTemplateName = aws.String("validLaunchTemplateName")
nodeTemplate.Spec.SecurityGroupSelector = nil
nodeTemplate.Status.SecurityGroups = nil
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeFalse())
})
It("should not return drifted if the securitygroups match", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).ToNot(HaveOccurred())
Expect(isDrifted).To(BeFalse())
})
It("should error if the machine doesn't have the instance-type label", func() {
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
},
},
})
_, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).To(HaveOccurred())
})
It("should error drift if machine doesn't have provider id", func() {
machine := coretest.Machine(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
isDrifted, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).To(HaveOccurred())
Expect(isDrifted).To(BeFalse())
})
It("should error drift if the underlying machine does not exist", func() {
awsEnv.EC2API.DescribeInstancesBehavior.Output.Set(&ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{{Instances: []*ec2.Instance{}}},
})
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(lo.FromPtr(instance.InstanceId)),
},
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: selectedInstanceType.Name,
},
},
})
_, err := cloudProvider.IsMachineDrifted(ctx, machine)
Expect(err).To(HaveOccurred())
})
})
Context("Provider Backwards Compatibility", func() {
It("should launch a machine using provider defaults", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Provider: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
launchSpecNames := lo.Map(createFleetInput.LaunchTemplateConfigs, func(req *ec2.FleetLaunchTemplateConfigRequest, _ int) string {
return *req.LaunchTemplateSpecification.LaunchTemplateName
})
Expect(len(createFleetInput.LaunchTemplateConfigs)).To(BeNumerically("==", awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(launchSpecNames).To(ContainElement(*ltInput.LaunchTemplateName))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Encrypted).To(Equal(aws.Bool(true)))
})
for _, ltSpec := range createFleetInput.LaunchTemplateConfigs {
Expect(*ltSpec.LaunchTemplateSpecification.Version).To(Equal("$Latest"))
}
})
It("should discover security groups by ID", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Provider: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"aws-ids": "sg-test1"},
},
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(aws.StringValueSlice(ltInput.LaunchTemplateData.SecurityGroupIds)).To(ConsistOf("sg-test1"))
})
})
It("should discover security groups by ID in the LT when no network interfaces are defined", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Provider: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"aws-ids": "subnet-test2"},
SecurityGroupSelector: map[string]string{"aws-ids": "sg-test1"},
},
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(aws.StringValueSlice(ltInput.LaunchTemplateData.SecurityGroupIds)).To(ConsistOf("sg-test1"))
})
})
It("should discover subnets by ID", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Provider: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"aws-ids": "subnet-test1"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("subnet-test1"))
})
It("should use the instance profile on the Provisioner when specified", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Provider: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
InstanceProfile: aws.String("overridden-profile"),
},
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(*ltInput.LaunchTemplateData.IamInstanceProfile.Name).To(Equal("overridden-profile"))
})
})
})
Context("Subnet Compatibility", func() {
// Note when debugging these tests -
// hard coded fixture data (ex. what the aws api will return) is maintained in fake/ec2api.go
It("should default to the cluster's subnets", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(
coretest.PodOptions{NodeSelector: map[string]string{v1.LabelArchStable: v1alpha5.ArchitectureAmd64}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
input := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(len(input.LaunchTemplateConfigs)).To(BeNumerically(">=", 1))
foundNonGPULT := false
for _, v := range input.LaunchTemplateConfigs {
for _, ov := range v.Overrides {
if *ov.InstanceType == "m5.large" {
foundNonGPULT = true
Expect(v.Overrides).To(ContainElements(
&ec2.FleetLaunchTemplateOverridesRequest{SubnetId: aws.String("subnet-test1"), InstanceType: aws.String("m5.large"), AvailabilityZone: aws.String("test-zone-1a")},
&ec2.FleetLaunchTemplateOverridesRequest{SubnetId: aws.String("subnet-test2"), InstanceType: aws.String("m5.large"), AvailabilityZone: aws.String("test-zone-1b")},
&ec2.FleetLaunchTemplateOverridesRequest{SubnetId: aws.String("subnet-test3"), InstanceType: aws.String("m5.large"), AvailabilityZone: aws.String("test-zone-1c")},
))
}
}
}
Expect(foundNonGPULT).To(BeTrue())
})
It("should launch instances into subnet with the most available IP addresses", func() {
awsEnv.EC2API.DescribeSubnetsOutput.Set(&ec2.DescribeSubnetsOutput{Subnets: []*ec2.Subnet{
{SubnetId: aws.String("test-subnet-1"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(10),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-1")}}},
{SubnetId: aws.String("test-subnet-2"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(100),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-2")}}},
}})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("test-subnet-2"))
})
It("should launch instances into subnet with the most available IP addresses in-between cache refreshes", func() {
awsEnv.EC2API.DescribeSubnetsOutput.Set(&ec2.DescribeSubnetsOutput{Subnets: []*ec2.Subnet{
{SubnetId: aws.String("test-subnet-1"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(10),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-1")}}},
{SubnetId: aws.String("test-subnet-2"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(11),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-2")}}},
}})
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{MaxPods: aws.Int32(1)}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod1 := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"}})
pod2 := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod1, pod2)
ExpectScheduled(ctx, env.Client, pod1)
ExpectScheduled(ctx, env.Client, pod2)
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("test-subnet-2"))
// Provision for another pod that should now use the other subnet since we've consumed some from the first launch.
pod3 := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod3)
ExpectScheduled(ctx, env.Client, pod3)
createFleetInput = awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("test-subnet-1"))
})
It("should update in-flight IPs when a CreateFleet error occurs", func() {
awsEnv.EC2API.DescribeSubnetsOutput.Set(&ec2.DescribeSubnetsOutput{Subnets: []*ec2.Subnet{
{SubnetId: aws.String("test-subnet-1"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(10),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-1")}}},
}})
pod1 := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"}})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate, pod1)
awsEnv.EC2API.CreateFleetBehavior.Error.Set(fmt.Errorf("CreateFleet synthetic error"))
bindings := ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod1)
Expect(len(bindings)).To(Equal(0))
})
It("should launch instances into subnets that are excluded by another provisioner", func() {
awsEnv.EC2API.DescribeSubnetsOutput.Set(&ec2.DescribeSubnetsOutput{Subnets: []*ec2.Subnet{
{SubnetId: aws.String("test-subnet-1"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(10),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-1")}}},
{SubnetId: aws.String("test-subnet-2"), AvailabilityZone: aws.String("test-zone-1b"), AvailableIpAddressCount: aws.Int64(100),
Tags: []*ec2.Tag{{Key: aws.String("Name"), Value: aws.String("test-subnet-2")}}},
}})
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-1"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
podSubnet1 := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, podSubnet1)
ExpectScheduled(ctx, env.Client, podSubnet1)
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("test-subnet-1"))
provisioner = test.Provisioner(coretest.ProvisionerOptions{Provider: &v1alpha1.AWS{
SubnetSelector: map[string]string{"Name": "test-subnet-2"},
SecurityGroupSelector: map[string]string{"*": "*"},
}})
ExpectApplied(ctx, env.Client, provisioner)
podSubnet2 := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{v1alpha5.ProvisionerNameLabelKey: provisioner.Name}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, podSubnet2)
ExpectScheduled(ctx, env.Client, podSubnet2)
createFleetInput = awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(fake.SubnetsFromFleetRequest(createFleetInput)).To(ConsistOf("test-subnet-2"))
})
})
})
| 781 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"k8s.io/utils/clock"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/cache"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/controllers/interruption"
machinegarbagecollection "github.com/aws/karpenter/pkg/controllers/machine/garbagecollection"
machinelink "github.com/aws/karpenter/pkg/controllers/machine/link"
"github.com/aws/karpenter/pkg/controllers/nodetemplate"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/pricing"
"github.com/aws/karpenter/pkg/providers/securitygroup"
"github.com/aws/karpenter/pkg/providers/subnet"
"github.com/aws/karpenter/pkg/utils/project"
"github.com/aws/karpenter-core/pkg/operator/controller"
)
func NewControllers(ctx context.Context, sess *session.Session, clk clock.Clock, kubeClient client.Client, recorder events.Recorder,
unavailableOfferings *cache.UnavailableOfferings, cloudProvider *cloudprovider.CloudProvider, subnetProvider *subnet.Provider,
securityGroupProvider *securitygroup.Provider, pricingProvider *pricing.Provider, amiProvider *amifamily.Provider) []controller.Controller {
logging.FromContext(ctx).With("version", project.Version).Debugf("discovered version")
linkController := machinelink.NewController(kubeClient, cloudProvider)
controllers := []controller.Controller{
nodetemplate.NewController(kubeClient, subnetProvider, securityGroupProvider, amiProvider),
linkController,
machinegarbagecollection.NewController(kubeClient, cloudProvider, linkController),
}
if settings.FromContext(ctx).InterruptionQueueName != "" {
controllers = append(controllers, interruption.NewController(kubeClient, clk, recorder, interruption.NewSQSProvider(sqs.New(sess)), unavailableOfferings))
}
if settings.FromContext(ctx).IsolatedVPC {
logging.FromContext(ctx).Infof("assuming isolated VPC, pricing information will not be updated")
} else {
controllers = append(controllers, pricing.NewController(pricingProvider))
}
return controllers
}
| 65 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package interruption
import (
"context"
"fmt"
"time"
sqsapi "github.com/aws/aws-sdk-go/service/sqs"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/util/workqueue"
"k8s.io/utils/clock"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/utils/pretty"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cache"
interruptionevents "github.com/aws/karpenter/pkg/controllers/interruption/events"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/statechange"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/metrics"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
)
type Action string
const (
CordonAndDrain Action = "CordonAndDrain"
NoAction Action = "NoAction"
)
// Controller is an AWS interruption controller.
// It continually polls an SQS queue for events from aws.ec2 and aws.health that
// trigger node health events or node spot interruption/rebalance events.
type Controller struct {
kubeClient client.Client
clk clock.Clock
recorder events.Recorder
sqsProvider *SQSProvider
unavailableOfferingsCache *cache.UnavailableOfferings
parser *EventParser
cm *pretty.ChangeMonitor
}
func NewController(kubeClient client.Client, clk clock.Clock, recorder events.Recorder,
sqsProvider *SQSProvider, unavailableOfferingsCache *cache.UnavailableOfferings) *Controller {
return &Controller{
kubeClient: kubeClient,
clk: clk,
recorder: recorder,
sqsProvider: sqsProvider,
unavailableOfferingsCache: unavailableOfferingsCache,
parser: NewEventParser(DefaultParsers...),
cm: pretty.NewChangeMonitor(),
}
}
func (c *Controller) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("queue", settings.FromContext(ctx).InterruptionQueueName))
if c.cm.HasChanged(settings.FromContext(ctx).InterruptionQueueName, nil) {
logging.FromContext(ctx).Debugf("watching interruption queue")
}
sqsMessages, err := c.sqsProvider.GetSQSMessages(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("getting messages from queue, %w", err)
}
if len(sqsMessages) == 0 {
return reconcile.Result{}, nil
}
machineInstanceIDMap, err := c.makeMachineInstanceIDMap(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("making machine instance id map, %w", err)
}
nodeInstanceIDMap, err := c.makeNodeInstanceIDMap(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("making node instance id map, %w", err)
}
errs := make([]error, len(sqsMessages))
workqueue.ParallelizeUntil(ctx, 10, len(sqsMessages), func(i int) {
msg, e := c.parseMessage(sqsMessages[i])
if e != nil {
// If we fail to parse, then we should delete the message but still log the error
logging.FromContext(ctx).Errorf("parsing message, %v", e)
errs[i] = c.deleteMessage(ctx, sqsMessages[i])
return
}
if e = c.handleMessage(ctx, machineInstanceIDMap, nodeInstanceIDMap, msg); e != nil {
errs[i] = fmt.Errorf("handling message, %w", e)
return
}
errs[i] = c.deleteMessage(ctx, sqsMessages[i])
})
return reconcile.Result{}, multierr.Combine(errs...)
}
func (c *Controller) Name() string {
return "interruption"
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.NewSingletonManagedBy(m)
}
// parseMessage parses the passed SQS message into an internal Message interface
func (c *Controller) parseMessage(raw *sqsapi.Message) (messages.Message, error) {
// No message to parse in this case
if raw == nil || raw.Body == nil {
return nil, fmt.Errorf("message or message body is nil")
}
msg, err := c.parser.Parse(*raw.Body)
if err != nil {
return nil, fmt.Errorf("parsing sqs message, %w", err)
}
return msg, nil
}
// handleMessage takes an action against every node involved in the message that is owned by a Provisioner
func (c *Controller) handleMessage(ctx context.Context, machineInstanceIDMap map[string]*v1alpha5.Machine,
nodeInstanceIDMap map[string]*v1.Node, msg messages.Message) (err error) {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("messageKind", msg.Kind()))
receivedMessages.WithLabelValues(string(msg.Kind())).Inc()
if msg.Kind() == messages.NoOpKind {
return nil
}
for _, instanceID := range msg.EC2InstanceIDs() {
machine, ok := machineInstanceIDMap[instanceID]
if !ok {
continue
}
node := nodeInstanceIDMap[instanceID]
if e := c.handleMachine(ctx, msg, machine, node); e != nil {
err = multierr.Append(err, e)
}
}
messageLatency.Observe(time.Since(msg.StartTime()).Seconds())
if err != nil {
return fmt.Errorf("acting on machines, %w", err)
}
return nil
}
// deleteMessage removes the passed SQS message from the queue and fires a metric for the deletion
func (c *Controller) deleteMessage(ctx context.Context, msg *sqsapi.Message) error {
if err := c.sqsProvider.DeleteSQSMessage(ctx, msg); err != nil {
return fmt.Errorf("deleting sqs message, %w", err)
}
deletedMessages.Inc()
return nil
}
// handleMachine retrieves the action for the message and then performs the appropriate action against the node
func (c *Controller) handleMachine(ctx context.Context, msg messages.Message, machine *v1alpha5.Machine, node *v1.Node) error {
action := actionForMessage(msg)
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("machine", machine.Name))
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("action", string(action)))
if node != nil {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("node", node.Name))
}
// Record metric and event for this action
c.notifyForMessage(msg, machine, node)
actionsPerformed.WithLabelValues(string(action)).Inc()
// Mark the offering as unavailable in the ICE cache since we got a spot interruption warning
if msg.Kind() == messages.SpotInterruptionKind {
zone := machine.Labels[v1.LabelTopologyZone]
instanceType := machine.Labels[v1.LabelInstanceTypeStable]
if zone != "" && instanceType != "" {
c.unavailableOfferingsCache.MarkUnavailable(ctx, string(msg.Kind()), instanceType, zone, v1alpha1.CapacityTypeSpot)
}
}
if action != NoAction {
return c.deleteMachine(ctx, machine, node)
}
return nil
}
// deleteMachine removes the machine from the api-server
func (c *Controller) deleteMachine(ctx context.Context, machine *v1alpha5.Machine, node *v1.Node) error {
if !machine.DeletionTimestamp.IsZero() {
return nil
}
if err := c.kubeClient.Delete(ctx, machine); err != nil {
return client.IgnoreNotFound(fmt.Errorf("deleting the node on interruption message, %w", err))
}
logging.FromContext(ctx).Infof("initiating delete for machine from interruption message")
c.recorder.Publish(interruptionevents.TerminatingOnInterruption(node, machine)...)
metrics.MachinesTerminatedCounter.With(prometheus.Labels{
metrics.ReasonLabel: terminationReasonLabel,
metrics.ProvisionerLabel: machine.Labels[v1alpha5.ProvisionerNameLabelKey],
}).Inc()
return nil
}
// notifyForMessage publishes the relevant alert based on the message kind
func (c *Controller) notifyForMessage(msg messages.Message, m *v1alpha5.Machine, n *v1.Node) {
switch msg.Kind() {
case messages.RebalanceRecommendationKind:
c.recorder.Publish(interruptionevents.RebalanceRecommendation(n, m)...)
case messages.ScheduledChangeKind:
c.recorder.Publish(interruptionevents.Unhealthy(n, m)...)
case messages.SpotInterruptionKind:
c.recorder.Publish(interruptionevents.SpotInterrupted(n, m)...)
case messages.StateChangeKind:
typed := msg.(statechange.Message)
if lo.Contains([]string{"stopping", "stopped"}, typed.Detail.State) {
c.recorder.Publish(interruptionevents.Stopping(n, m)...)
} else {
c.recorder.Publish(interruptionevents.Terminating(n, m)...)
}
default:
}
}
// makeMachineInstanceIDMap builds a map between the instance id that is stored in the
// machine .status.providerID and the machine
func (c *Controller) makeMachineInstanceIDMap(ctx context.Context) (map[string]*v1alpha5.Machine, error) {
m := map[string]*v1alpha5.Machine{}
machineList := &v1alpha5.MachineList{}
if err := c.kubeClient.List(ctx, machineList); err != nil {
return nil, fmt.Errorf("listing machines, %w", err)
}
for i := range machineList.Items {
if machineList.Items[i].Status.ProviderID == "" {
continue
}
id, err := utils.ParseInstanceID(machineList.Items[i].Status.ProviderID)
if err != nil || id == "" {
continue
}
m[id] = &machineList.Items[i]
}
return m, nil
}
// makeNodeInstanceIDMap builds a map between the instance id that is stored in the
// node .spec.providerID and the node
func (c *Controller) makeNodeInstanceIDMap(ctx context.Context) (map[string]*v1.Node, error) {
m := map[string]*v1.Node{}
nodeList := &v1.NodeList{}
if err := c.kubeClient.List(ctx, nodeList); err != nil {
return nil, fmt.Errorf("listing nodes, %w", err)
}
for i := range nodeList.Items {
if nodeList.Items[i].Spec.ProviderID == "" {
continue
}
id, err := utils.ParseInstanceID(nodeList.Items[i].Spec.ProviderID)
if err != nil || id == "" {
continue
}
m[id] = &nodeList.Items[i]
}
return m, nil
}
func actionForMessage(msg messages.Message) Action {
switch msg.Kind() {
case messages.ScheduledChangeKind, messages.SpotInterruptionKind, messages.StateChangeKind:
return CordonAndDrain
default:
return NoAction
}
}
| 296 |
karpenter | aws | Go | //go:build test_performance
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:gosec
package interruption_test
import (
"context"
"fmt"
"math/rand"
"testing"
"time"
"github.com/avast/retry-go"
"github.com/aws/aws-sdk-go/aws"
awsclient "github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/samber/lo"
"go.uber.org/multierr"
"go.uber.org/zap"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/util/workqueue"
clock "k8s.io/utils/clock/testing"
"knative.dev/pkg/logging"
controllerruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/operator/scheme"
"github.com/aws/karpenter/pkg/apis/settings"
awscache "github.com/aws/karpenter/pkg/cache"
"github.com/aws/karpenter/pkg/controllers/interruption"
"github.com/aws/karpenter/pkg/controllers/interruption/events"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/test"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
coretest "github.com/aws/karpenter-core/pkg/test"
)
var r = rand.New(rand.NewSource(time.Now().Unix()))
func BenchmarkNotification15000(b *testing.B) {
benchmarkNotificationController(b, 15000)
}
func BenchmarkNotification5000(b *testing.B) {
benchmarkNotificationController(b, 5000)
}
func BenchmarkNotification1000(b *testing.B) {
benchmarkNotificationController(b, 1000)
}
func BenchmarkNotification100(b *testing.B) {
benchmarkNotificationController(b, 100)
}
//nolint:gocyclo
func benchmarkNotificationController(b *testing.B, messageCount int) {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("message-count", messageCount))
fakeClock = &clock.FakeClock{}
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ClusterName: lo.ToPtr("karpenter-notification-benchmarking"),
IsolatedVPC: lo.ToPtr(true),
InterruptionQueueName: lo.ToPtr("test-cluster"),
}))
env = coretest.NewEnvironment(scheme.Scheme)
// Stop the coretest environment after the coretest completes
defer func() {
if err := retry.Do(func() error {
return env.Stop()
}); err != nil {
b.Fatalf("stopping coretest environment, %v", err)
}
}()
providers := newProviders(env.Client)
if err := providers.makeInfrastructure(ctx); err != nil {
b.Fatalf("standing up infrastructure, %v", err)
}
// Cleanup the infrastructure after the coretest completes
defer func() {
if err := retry.Do(func() error {
return providers.cleanupInfrastructure(ctx)
}); err != nil {
b.Fatalf("deleting infrastructure, %v", err)
}
}()
// Load all the fundamental components before setting up the controllers
recorder := coretest.NewEventRecorder()
unavailableOfferingsCache = awscache.NewUnavailableOfferings()
// Set-up the controllers
interruptionController := interruption.NewController(env.Client, fakeClock, recorder, providers.sqsProvider, unavailableOfferingsCache)
messages, nodes := makeDiverseMessagesAndNodes(messageCount)
logging.FromContext(ctx).Infof("provisioning nodes")
if err := provisionNodes(ctx, env.Client, nodes); err != nil {
b.Fatalf("provisioning nodes, %v", err)
}
logging.FromContext(ctx).Infof("completed provisioning nodes")
logging.FromContext(ctx).Infof("provisioning messages into the SQS Queue")
if err := providers.provisionMessages(ctx, messages...); err != nil {
b.Fatalf("provisioning messages, %v", err)
}
logging.FromContext(ctx).Infof("completed provisioning messages into the SQS Queue")
m, err := controllerruntime.NewManager(env.Config, controllerruntime.Options{
BaseContext: func() context.Context { return logging.WithLogger(ctx, zap.NewNop().Sugar()) },
})
if err != nil {
b.Fatalf("creating manager, %v", err)
}
// Registering controller with the manager
if err = interruptionController.Builder(ctx, m).Complete(interruptionController); err != nil {
b.Fatalf("registering interruption controller, %v", err)
}
b.ResetTimer()
start := time.Now()
managerErr := make(chan error)
go func() {
logging.FromContext(ctx).Infof("starting controller manager")
managerErr <- m.Start(ctx)
}()
select {
case <-providers.monitorMessagesProcessed(ctx, recorder, messageCount):
case err = <-managerErr:
b.Fatalf("running manager, %v", err)
}
duration := time.Since(start)
b.ReportMetric(float64(messageCount), "Messages")
b.ReportMetric(duration.Seconds(), "TotalDurationInSeconds")
b.ReportMetric(float64(messageCount)/duration.Seconds(), "Messages/Second")
}
type providerSet struct {
kubeClient client.Client
sqsAPI *sqs.SQS
sqsProvider *interruption.SQSProvider
}
func newProviders(kubeClient client.Client) providerSet {
sess := session.Must(session.NewSession(
request.WithRetryer(
&aws.Config{STSRegionalEndpoint: endpoints.RegionalSTSEndpoint},
awsclient.DefaultRetryer{NumMaxRetries: awsclient.DefaultRetryerMaxNumRetries},
),
))
sqsAPI := sqs.New(sess)
return providerSet{
kubeClient: kubeClient,
sqsAPI: sqsAPI,
sqsProvider: interruption.NewSQSProvider(sqsAPI),
}
}
func (p *providerSet) makeInfrastructure(ctx context.Context) error {
if _, err := p.sqsAPI.CreateQueueWithContext(ctx, &sqs.CreateQueueInput{
QueueName: lo.ToPtr(settings.FromContext(ctx).InterruptionQueueName),
Attributes: map[string]*string{
sqs.QueueAttributeNameMessageRetentionPeriod: aws.String("1200"), // 20 minutes for this test
},
}); err != nil {
return fmt.Errorf("creating sqs queue, %w", err)
}
return nil
}
func (p *providerSet) cleanupInfrastructure(ctx context.Context) error {
queueURL, err := p.sqsProvider.DiscoverQueueURL(ctx)
if err != nil {
return fmt.Errorf("discovering queue url for deletion, %w", err)
}
if _, err = p.sqsAPI.DeleteQueueWithContext(ctx, &sqs.DeleteQueueInput{
QueueUrl: lo.ToPtr(queueURL),
}); err != nil {
return fmt.Errorf("deleting sqs queue, %w", err)
}
return nil
}
func (p *providerSet) provisionMessages(ctx context.Context, messages ...interface{}) error {
errs := make([]error, len(messages))
workqueue.ParallelizeUntil(ctx, 20, len(messages), func(i int) {
_, err := p.sqsProvider.SendMessage(ctx, messages[i])
errs[i] = err
})
return multierr.Combine(errs...)
}
func (p *providerSet) monitorMessagesProcessed(ctx context.Context, eventRecorder *coretest.EventRecorder, expectedProcessed int) <-chan struct{} {
done := make(chan struct{})
totalProcessed := 0
go func() {
for totalProcessed < expectedProcessed {
totalProcessed = eventRecorder.Calls(events.InstanceStopping(coretest.Node()).Reason) +
eventRecorder.Calls(events.InstanceTerminating(coretest.Node()).Reason) +
eventRecorder.Calls(events.InstanceUnhealthy(coretest.Node()).Reason) +
eventRecorder.Calls(events.InstanceRebalanceRecommendation(coretest.Node()).Reason) +
eventRecorder.Calls(events.InstanceSpotInterrupted(coretest.Node()).Reason)
logging.FromContext(ctx).With("processed-message-count", totalProcessed).Infof("processed messages from the queue")
time.Sleep(time.Second)
}
close(done)
}()
return done
}
func provisionNodes(ctx context.Context, kubeClient client.Client, nodes []*v1.Node) error {
errs := make([]error, len(nodes))
workqueue.ParallelizeUntil(ctx, 20, len(nodes), func(i int) {
if err := retry.Do(func() error {
return kubeClient.Create(ctx, nodes[i])
}); err != nil {
errs[i] = fmt.Errorf("provisioning node, %w", err)
}
})
return multierr.Combine(errs...)
}
func makeDiverseMessagesAndNodes(count int) ([]interface{}, []*v1.Node) {
var messages []interface{}
var nodes []*v1.Node
newMessages, newNodes := makeScheduledChangeMessagesAndNodes(count / 3)
messages = append(messages, newMessages...)
nodes = append(nodes, newNodes...)
newMessages, newNodes = makeSpotInterruptionMessagesAndNodes(count / 3)
messages = append(messages, newMessages...)
nodes = append(nodes, newNodes...)
newMessages, newNodes = makeStateChangeMessagesAndNodes(count-len(messages), []string{
"stopping", "stopped", "shutting-down", "terminated",
})
messages = append(messages, newMessages...)
nodes = append(nodes, newNodes...)
return messages, nodes
}
func makeScheduledChangeMessagesAndNodes(count int) ([]interface{}, []*v1.Node) {
var msgs []interface{}
var nodes []*v1.Node
for i := 0; i < count; i++ {
instanceID := fake.InstanceID()
msgs = append(msgs, scheduledChangeMessage(instanceID))
nodes = append(nodes, coretest.Node(coretest.NodeOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
ProviderID: fake.ProviderID(instanceID),
}))
}
return msgs, nodes
}
func makeStateChangeMessagesAndNodes(count int, states []string) ([]interface{}, []*v1.Node) {
var msgs []interface{}
var nodes []*v1.Node
for i := 0; i < count; i++ {
state := states[r.Intn(len(states))]
instanceID := fake.InstanceID()
msgs = append(msgs, stateChangeMessage(instanceID, state))
nodes = append(nodes, coretest.Node(coretest.NodeOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
ProviderID: fake.ProviderID(instanceID),
}))
}
return msgs, nodes
}
func makeSpotInterruptionMessagesAndNodes(count int) ([]interface{}, []*v1.Node) {
var msgs []interface{}
var nodes []*v1.Node
for i := 0; i < count; i++ {
instanceID := fake.InstanceID()
msgs = append(msgs, spotInterruptionMessage(instanceID))
nodes = append(nodes, coretest.Node(coretest.NodeOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
ProviderID: fake.ProviderID(instanceID),
}))
}
return msgs, nodes
}
| 321 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package interruption
import (
"github.com/prometheus/client_golang/prometheus"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/aws/karpenter-core/pkg/metrics"
)
const (
interruptionSubsystem = "interruption"
messageTypeLabel = "message_type"
actionTypeLabel = "action_type"
terminationReasonLabel = "interruption"
)
var (
receivedMessages = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: metrics.Namespace,
Subsystem: interruptionSubsystem,
Name: "received_messages",
Help: "Count of messages received from the SQS queue. Broken down by message type and whether the message was actionable.",
},
[]string{messageTypeLabel},
)
deletedMessages = prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: metrics.Namespace,
Subsystem: interruptionSubsystem,
Name: "deleted_messages",
Help: "Count of messages deleted from the SQS queue.",
},
)
messageLatency = prometheus.NewHistogram(
prometheus.HistogramOpts{
Namespace: metrics.Namespace,
Subsystem: interruptionSubsystem,
Name: "message_latency_time_seconds",
Help: "Length of time between message creation in queue and an action taken on the message by the controller.",
Buckets: metrics.DurationBuckets(),
},
)
actionsPerformed = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: metrics.Namespace,
Subsystem: interruptionSubsystem,
Name: "actions_performed",
Help: "Number of notification actions performed. Labeled by action",
},
[]string{actionTypeLabel},
)
)
func init() {
crmetrics.Registry.MustRegister(receivedMessages, deletedMessages, messageLatency, actionsPerformed)
}
| 72 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package interruption
import (
"encoding/json"
"fmt"
"github.com/samber/lo"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/noop"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/rebalancerecommendation"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/scheduledchange"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/spotinterruption"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/statechange"
)
type parserKey struct {
Version string
Source string
DetailType string
}
func newParserKey(metadata messages.Metadata) parserKey {
return parserKey{
Version: metadata.Version,
Source: metadata.Source,
DetailType: metadata.DetailType,
}
}
func newParserKeyFromParser(p messages.Parser) parserKey {
return parserKey{
Version: p.Version(),
Source: p.Source(),
DetailType: p.DetailType(),
}
}
var (
DefaultParsers = []messages.Parser{
statechange.Parser{},
spotinterruption.Parser{},
scheduledchange.Parser{},
rebalancerecommendation.Parser{},
}
)
type EventParser struct {
parserMap map[parserKey]messages.Parser
}
func NewEventParser(parsers ...messages.Parser) *EventParser {
return &EventParser{
parserMap: lo.SliceToMap(parsers, func(p messages.Parser) (parserKey, messages.Parser) {
return newParserKeyFromParser(p), p
}),
}
}
func (p EventParser) Parse(msg string) (messages.Message, error) {
if msg == "" {
return noop.Message{}, nil
}
md := messages.Metadata{}
if err := json.Unmarshal([]byte(msg), &md); err != nil {
return noop.Message{}, fmt.Errorf("unmarshalling the message as Metadata, %w", err)
}
if parser, ok := p.parserMap[newParserKey(md)]; ok {
evt, err := parser.Parse(msg)
if err != nil {
return noop.Message{}, fmt.Errorf("parsing event message, %w", err)
}
if evt == nil {
return noop.Message{}, nil
}
return evt, nil
}
return noop.Message{Metadata: md}, nil
}
| 94 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package interruption
import (
"context"
"encoding/json"
"fmt"
syncatomic "sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/utils/atomic"
"github.com/aws/karpenter/pkg/apis/settings"
awserrors "github.com/aws/karpenter/pkg/errors"
)
type SQSProvider struct {
client sqsiface.SQSAPI
queueURL atomic.Lazy[string]
queueName syncatomic.Pointer[string]
}
func NewSQSProvider(client sqsiface.SQSAPI) *SQSProvider {
provider := &SQSProvider{
client: client,
}
provider.queueURL.Resolve = func(ctx context.Context) (string, error) {
input := &sqs.GetQueueUrlInput{
QueueName: aws.String(settings.FromContext(ctx).InterruptionQueueName),
}
ret, err := provider.client.GetQueueUrlWithContext(ctx, input)
if err != nil {
return "", fmt.Errorf("fetching queue url, %w", err)
}
return aws.StringValue(ret.QueueUrl), nil
}
return provider
}
func (s *SQSProvider) QueueExists(ctx context.Context) (bool, error) {
_, err := s.queueURL.TryGet(ctx, atomic.IgnoreCacheOption)
if err != nil {
if awserrors.IsNotFound(err) {
return false, nil
}
return false, err
}
return true, nil
}
func (s *SQSProvider) DiscoverQueueURL(ctx context.Context) (string, error) {
if settings.FromContext(ctx).InterruptionQueueName != lo.FromPtr(s.queueName.Load()) {
res, err := s.queueURL.TryGet(ctx, atomic.IgnoreCacheOption)
if err != nil {
return res, err
}
s.queueName.Store(lo.ToPtr(settings.FromContext(ctx).InterruptionQueueName))
return res, nil
}
return s.queueURL.TryGet(ctx)
}
func (s *SQSProvider) GetSQSMessages(ctx context.Context) ([]*sqs.Message, error) {
queueURL, err := s.DiscoverQueueURL(ctx)
if err != nil {
return nil, fmt.Errorf("discovering queue url, %w", err)
}
input := &sqs.ReceiveMessageInput{
MaxNumberOfMessages: aws.Int64(10),
VisibilityTimeout: aws.Int64(20), // Seconds
WaitTimeSeconds: aws.Int64(20), // Seconds, maximum for long polling
AttributeNames: []*string{
aws.String(sqs.MessageSystemAttributeNameSentTimestamp),
},
MessageAttributeNames: []*string{
aws.String(sqs.QueueAttributeNameAll),
},
QueueUrl: aws.String(queueURL),
}
result, err := s.client.ReceiveMessageWithContext(ctx, input)
if err != nil {
return nil, fmt.Errorf("receiving sqs messages, %w", err)
}
return result.Messages, nil
}
func (s *SQSProvider) SendMessage(ctx context.Context, body interface{}) (string, error) {
raw, err := json.Marshal(body)
if err != nil {
return "", fmt.Errorf("marshaling the passed body as json, %w", err)
}
queueURL, err := s.DiscoverQueueURL(ctx)
if err != nil {
return "", fmt.Errorf("fetching queue url, %w", err)
}
input := &sqs.SendMessageInput{
MessageBody: aws.String(string(raw)),
QueueUrl: aws.String(queueURL),
}
result, err := s.client.SendMessage(input)
if err != nil {
return "", fmt.Errorf("sending messages to sqs queue, %w", err)
}
return aws.StringValue(result.MessageId), nil
}
func (s *SQSProvider) DeleteSQSMessage(ctx context.Context, msg *sqs.Message) error {
queueURL, err := s.DiscoverQueueURL(ctx)
if err != nil {
return fmt.Errorf("failed fetching queue url, %w", err)
}
input := &sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: msg.ReceiptHandle,
}
_, err = s.client.DeleteMessageWithContext(ctx, input)
if err != nil {
return fmt.Errorf("deleting messages from sqs queue, %w", err)
}
return nil
}
func (s *SQSProvider) Reset() {
s.queueURL.Set("")
s.queueName.Store(nil)
}
| 149 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package interruption_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/sqs"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/client-go/tools/record"
clock "k8s.io/utils/clock/testing"
. "knative.dev/pkg/logging/testing"
_ "knative.dev/pkg/system/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awscache "github.com/aws/karpenter/pkg/cache"
"github.com/aws/karpenter/pkg/controllers/interruption"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/scheduledchange"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/spotinterruption"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/statechange"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/utils"
)
const (
defaultAccountID = "000000000000"
defaultRegion = "us-west-2"
ec2Source = "aws.ec2"
healthSource = "aws.health"
)
var ctx context.Context
var env *coretest.Environment
var sqsapi *fake.SQSAPI
var sqsProvider *interruption.SQSProvider
var unavailableOfferingsCache *awscache.UnavailableOfferings
var fakeClock *clock.FakeClock
var controller *interruption.Controller
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "AWSInterruption")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
fakeClock = &clock.FakeClock{}
unavailableOfferingsCache = awscache.NewUnavailableOfferings(events.NewRecorder(&record.FakeRecorder{}))
sqsapi = &fake.SQSAPI{}
sqsProvider = interruption.NewSQSProvider(sqsapi)
controller = interruption.NewController(env.Client, fakeClock, events.NewRecorder(&record.FakeRecorder{}), sqsProvider, unavailableOfferingsCache)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
sqsProvider = interruption.NewSQSProvider(sqsapi)
controller = interruption.NewController(env.Client, fakeClock, events.NewRecorder(&record.FakeRecorder{}), sqsProvider, unavailableOfferingsCache)
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
InterruptionQueueName: lo.ToPtr("test-cluster"),
}))
unavailableOfferingsCache.Flush()
sqsapi.Reset()
sqsProvider.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("AWSInterruption", func() {
Context("Processing Messages", func() {
It("should delete the machine when receiving a spot interruption warning", func() {
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.RandomProviderID(),
},
})
ExpectMessagesCreated(spotInterruptionMessage(lo.Must(utils.ParseInstanceID(machine.Status.ProviderID))))
ExpectApplied(ctx, env.Client, machine, node)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectNotFound(ctx, env.Client, machine)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(1))
})
It("should delete the machine when receiving a scheduled change message", func() {
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.RandomProviderID(),
},
})
ExpectMessagesCreated(scheduledChangeMessage(lo.Must(utils.ParseInstanceID(machine.Status.ProviderID))))
ExpectApplied(ctx, env.Client, machine, node)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectNotFound(ctx, env.Client, machine)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(1))
})
It("should delete the machine when receiving a state change message", func() {
var machines []*v1alpha5.Machine
var nodes []*v1.Node
var messages []interface{}
for _, state := range []string{"terminated", "stopped", "stopping", "shutting-down"} {
instanceID := fake.InstanceID()
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(instanceID),
},
})
machines = append(machines, machine)
nodes = append(nodes, node)
messages = append(messages, stateChangeMessage(instanceID, state))
}
ExpectMessagesCreated(messages...)
ExpectApplied(ctx, env.Client, lo.Map(machines, func(m *v1alpha5.Machine, _ int) client.Object { return m })...)
ExpectApplied(ctx, env.Client, lo.Map(nodes, func(n *v1.Node, _ int) client.Object { return n })...)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectNotFound(ctx, env.Client, lo.Map(machines, func(m *v1alpha5.Machine, _ int) client.Object { return m })...)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(4))
})
It("should handle multiple messages that cause machine deletion", func() {
var machines []*v1alpha5.Machine
var nodes []*v1.Node
var instanceIDs []string
for i := 0; i < 100; i++ {
instanceID := fake.InstanceID()
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.ProviderID(instanceID),
},
})
instanceIDs = append(instanceIDs, instanceID)
machines = append(machines, machine)
nodes = append(nodes, node)
}
var messages []interface{}
for _, id := range instanceIDs {
messages = append(messages, spotInterruptionMessage(id))
}
ExpectMessagesCreated(messages...)
ExpectApplied(ctx, env.Client, lo.Map(machines, func(m *v1alpha5.Machine, _ int) client.Object { return m })...)
ExpectApplied(ctx, env.Client, lo.Map(nodes, func(n *v1.Node, _ int) client.Object { return n })...)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectNotFound(ctx, env.Client, lo.Map(machines, func(m *v1alpha5.Machine, _ int) client.Object { return m })...)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(100))
})
It("should delete a message when the message can't be parsed", func() {
badMessage := &sqs.Message{
Body: aws.String(string(lo.Must(json.Marshal(map[string]string{
"field1": "value1",
"field2": "value2",
})))),
MessageId: aws.String(string(uuid.NewUUID())),
}
ExpectMessagesCreated(badMessage)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(1))
})
It("should delete a state change message when the state isn't in accepted states", func() {
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.RandomProviderID(),
},
})
ExpectMessagesCreated(stateChangeMessage(lo.Must(utils.ParseInstanceID(machine.Status.ProviderID)), "creating"))
ExpectApplied(ctx, env.Client, machine, node)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectExists(ctx, env.Client, machine)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(1))
})
It("should mark the ICE cache for the offering when getting a spot interruption warning", func() {
machine, node := coretest.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "default",
v1.LabelTopologyZone: "coretest-zone-1a",
v1.LabelInstanceTypeStable: "t3.large",
v1alpha5.LabelCapacityType: v1alpha1.CapacityTypeSpot,
},
},
Status: v1alpha5.MachineStatus{
ProviderID: fake.RandomProviderID(),
},
})
ExpectMessagesCreated(spotInterruptionMessage(lo.Must(utils.ParseInstanceID(machine.Status.ProviderID))))
ExpectApplied(ctx, env.Client, machine, node)
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Expect(sqsapi.ReceiveMessageBehavior.SuccessfulCalls()).To(Equal(1))
ExpectNotFound(ctx, env.Client, machine)
Expect(sqsapi.DeleteMessageBehavior.SuccessfulCalls()).To(Equal(1))
// Expect a t3.large in coretest-zone-1a to be added to the ICE cache
Expect(unavailableOfferingsCache.IsUnavailable("t3.large", "coretest-zone-1a", v1alpha1.CapacityTypeSpot)).To(BeTrue())
})
})
Context("Error Handling", func() {
It("should send an error on polling when QueueNotExists", func() {
sqsapi.ReceiveMessageBehavior.Error.Set(awsErrWithCode(sqs.ErrCodeQueueDoesNotExist), fake.MaxCalls(0))
ExpectReconcileFailed(ctx, controller, types.NamespacedName{})
})
It("should send an error on polling when AccessDenied", func() {
sqsapi.ReceiveMessageBehavior.Error.Set(awsErrWithCode("AccessDenied"), fake.MaxCalls(0))
ExpectReconcileFailed(ctx, controller, types.NamespacedName{})
})
It("should not return an error when deleting a machine that is already deleted", func() {
ExpectMessagesCreated(spotInterruptionMessage(fake.InstanceID()))
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
})
})
})
func ExpectMessagesCreated(messages ...interface{}) {
raw := lo.Map(messages, func(m interface{}, _ int) *sqs.Message {
return &sqs.Message{
Body: aws.String(string(lo.Must(json.Marshal(m)))),
MessageId: aws.String(string(uuid.NewUUID())),
}
})
sqsapi.ReceiveMessageBehavior.Output.Set(
&sqs.ReceiveMessageOutput{
Messages: raw,
},
)
}
func awsErrWithCode(code string) awserr.Error {
return awserr.New(code, "", fmt.Errorf(""))
}
func spotInterruptionMessage(involvedInstanceID string) spotinterruption.Message {
return spotinterruption.Message{
Metadata: messages.Metadata{
Version: "0",
Account: defaultAccountID,
DetailType: "EC2 Spot Instance Interruption Warning",
ID: string(uuid.NewUUID()),
Region: defaultRegion,
Resources: []string{
fmt.Sprintf("arn:aws:ec2:%s:instance/%s", defaultRegion, involvedInstanceID),
},
Source: ec2Source,
Time: time.Now(),
},
Detail: spotinterruption.Detail{
InstanceID: involvedInstanceID,
InstanceAction: "terminate",
},
}
}
func stateChangeMessage(involvedInstanceID, state string) statechange.Message {
return statechange.Message{
Metadata: messages.Metadata{
Version: "0",
Account: defaultAccountID,
DetailType: "EC2 Instance State-change Notification",
ID: string(uuid.NewUUID()),
Region: defaultRegion,
Resources: []string{
fmt.Sprintf("arn:aws:ec2:%s:instance/%s", defaultRegion, involvedInstanceID),
},
Source: ec2Source,
Time: time.Now(),
},
Detail: statechange.Detail{
InstanceID: involvedInstanceID,
State: state,
},
}
}
func scheduledChangeMessage(involvedInstanceID string) scheduledchange.Message {
return scheduledchange.Message{
Metadata: messages.Metadata{
Version: "0",
Account: defaultAccountID,
DetailType: "AWS Health Event",
ID: string(uuid.NewUUID()),
Region: defaultRegion,
Resources: []string{
fmt.Sprintf("arn:aws:ec2:%s:instance/%s", defaultRegion, involvedInstanceID),
},
Source: healthSource,
Time: time.Now(),
},
Detail: scheduledchange.Detail{
Service: "EC2",
EventTypeCategory: "scheduledChange",
AffectedEntities: []scheduledchange.AffectedEntity{
{
EntityValue: involvedInstanceID,
},
},
},
}
}
| 374 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package events
import (
"fmt"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/events"
)
func SpotInterrupted(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "SpotInterrupted",
Message: fmt.Sprintf("Machine %s event: A spot interruption warning was triggered for the machine", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeWarning,
Reason: "SpotInterrupted",
Message: fmt.Sprintf("Node %s event: A spot interruption warning was triggered for the node", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
func RebalanceRecommendation(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeNormal,
Reason: "SpotRebalanceRecommendation",
Message: fmt.Sprintf("Machine %s event: A spot rebalance recommendation was triggered for the machine", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeNormal,
Reason: "SpotRebalanceRecommendation",
Message: fmt.Sprintf("Node %s event: A spot rebalance recommendation was triggered for the node", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
func Stopping(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "Stopping",
Message: fmt.Sprintf("Machine %s event: Machine is stopping", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeWarning,
Reason: "Stopping",
Message: fmt.Sprintf("Node %s event: Node is stopping", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
func Terminating(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "Terminating",
Message: fmt.Sprintf("Machine %s event: Machine is terminating", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeWarning,
Reason: "Terminating",
Message: fmt.Sprintf("Node %s event: Node is terminating", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
func Unhealthy(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "Unhealthy",
Message: fmt.Sprintf("Machine %s event: An unhealthy warning was triggered for the machine", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeWarning,
Reason: "Unhealthy",
Message: fmt.Sprintf("Node %s event: An unhealthy warning was triggered for the node", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
func TerminatingOnInterruption(node *v1.Node, machine *v1alpha5.Machine) []events.Event {
evts := []events.Event{
{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "TerminatingOnInterruption",
Message: fmt.Sprintf("Machine %s event: Interruption triggered termination for the machine", machine.Name),
DedupeValues: []string{machine.Name},
},
}
if node != nil {
evts = append(evts, events.Event{
InvolvedObject: node,
Type: v1.EventTypeWarning,
Reason: "TerminatingOnInterruption",
Message: fmt.Sprintf("Node %s event: Interruption triggered termination for the node", node.Name),
DedupeValues: []string{node.Name},
})
}
return evts
}
| 157 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package messages
import (
"time"
)
type Parser interface {
Parse(string) (Message, error)
Version() string
Source() string
DetailType() string
}
type Message interface {
EC2InstanceIDs() []string
Kind() Kind
StartTime() time.Time
}
type Kind string
const (
RebalanceRecommendationKind Kind = "RebalanceRecommendationKind"
ScheduledChangeKind Kind = "ScheduledChangeKind"
SpotInterruptionKind Kind = "SpotInterruptionKind"
StateChangeKind Kind = "StateChangeKind"
NoOpKind Kind = "NoOpKind"
)
type Metadata struct {
Account string `json:"account"`
DetailType string `json:"detail-type"`
ID string `json:"id"`
Region string `json:"region"`
Resources []string `json:"resources"`
Source string `json:"source"`
Time time.Time `json:"time"`
Version string `json:"version"`
}
func (m Metadata) StartTime() time.Time {
return m.Time
}
| 59 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package noop
import (
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
type Message struct {
messages.Metadata
}
func (Message) EC2InstanceIDs() []string {
return []string{}
}
func (Message) Kind() messages.Kind {
return messages.NoOpKind
}
| 32 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rebalancerecommendation
import (
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
// Message contains the properties defined by
// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/rebalance-recommendations.html#monitor-rebalance-recommendations
type Message struct {
messages.Metadata
Detail Detail `json:"detail"`
}
type Detail struct {
InstanceID string `json:"instance-id"`
}
func (m Message) EC2InstanceIDs() []string {
return []string{m.Detail.InstanceID}
}
func (Message) Kind() messages.Kind {
return messages.RebalanceRecommendationKind
}
| 40 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rebalancerecommendation
import (
"encoding/json"
"fmt"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
type Parser struct{}
func (p Parser) Parse(raw string) (messages.Message, error) {
msg := Message{}
if err := json.Unmarshal([]byte(raw), &msg); err != nil {
return nil, fmt.Errorf("unmarhsalling the message as EC2InstanceRebalanceRecommendation, %w", err)
}
return msg, nil
}
func (p Parser) Version() string {
return "0"
}
func (p Parser) Source() string {
return "aws.ec2"
}
func (p Parser) DetailType() string {
return "EC2 Instance Rebalance Recommendation"
}
| 45 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scheduledchange
import (
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
// Message contains the properties defined in AWS EventBridge schema
// aws.health@AWSHealthEvent v0.
type Message struct {
messages.Metadata
Detail Detail `json:"detail"`
}
func (m Message) EC2InstanceIDs() []string {
ids := make([]string, len(m.Detail.AffectedEntities))
for i, entity := range m.Detail.AffectedEntities {
ids[i] = entity.EntityValue
}
return ids
}
func (Message) Kind() messages.Kind {
return messages.ScheduledChangeKind
}
type Detail struct {
EventARN string `json:"eventArn"`
EventTypeCode string `json:"eventTypeCode"`
Service string `json:"service"`
EventDescription []EventDescription `json:"eventDescription"`
StartTime string `json:"startTime"`
EndTime string `json:"endTime"`
EventTypeCategory string `json:"eventTypeCategory"`
AffectedEntities []AffectedEntity `json:"affectedEntities"`
}
type EventDescription struct {
LatestDescription string `json:"latestDescription"`
Language string `json:"language"`
}
type AffectedEntity struct {
EntityValue string `json:"entityValue"`
}
| 60 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scheduledchange
import (
"encoding/json"
"fmt"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
const (
acceptedService = "EC2"
acceptedEventTypeCategory = "scheduledChange"
)
type Parser struct{}
func (p Parser) Parse(raw string) (messages.Message, error) {
msg := Message{}
if err := json.Unmarshal([]byte(raw), &msg); err != nil {
return nil, fmt.Errorf("unmarhsalling the message as AWSHealthEvent, %w", err)
}
// We ignore services and event categories that we don't watch
if msg.Detail.Service != acceptedService ||
msg.Detail.EventTypeCategory != acceptedEventTypeCategory {
return nil, nil
}
return msg, nil
}
func (p Parser) Version() string {
return "0"
}
func (p Parser) Source() string {
return "aws.health"
}
func (p Parser) DetailType() string {
return "AWS Health Event"
}
| 56 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spotinterruption
import (
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
// Message contains the properties defined in AWS EventBridge schema
// aws.ec2@EC2SpotInstanceInterruptionWarning v0.
type Message struct {
messages.Metadata
Detail Detail `json:"detail"`
}
type Detail struct {
InstanceID string `json:"instance-id"`
InstanceAction string `json:"instance-action"`
}
func (m Message) EC2InstanceIDs() []string {
return []string{m.Detail.InstanceID}
}
func (Message) Kind() messages.Kind {
return messages.SpotInterruptionKind
}
| 41 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spotinterruption
import (
"encoding/json"
"fmt"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
type Parser struct{}
func (p Parser) Parse(raw string) (messages.Message, error) {
msg := Message{}
if err := json.Unmarshal([]byte(raw), &msg); err != nil {
return nil, fmt.Errorf("unmarhsalling the message as EC2SpotInstanceInterruptionWarning, %w", err)
}
return msg, nil
}
func (p Parser) Version() string {
return "0"
}
func (p Parser) Source() string {
return "aws.ec2"
}
func (p Parser) DetailType() string {
return "EC2 Spot Instance Interruption Warning"
}
| 45 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package statechange
import (
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
// Message contains the properties defined in AWS EventBridge schema
// aws.ec2@EC2InstanceStateChangeNotification v1.
type Message struct {
messages.Metadata
Detail Detail `json:"detail"`
}
type Detail struct {
InstanceID string `json:"instance-id"`
State string `json:"state"`
}
func (m Message) EC2InstanceIDs() []string {
return []string{m.Detail.InstanceID}
}
func (Message) Kind() messages.Kind {
return messages.StateChangeKind
}
| 41 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package statechange
import (
"encoding/json"
"fmt"
"strings"
"k8s.io/apimachinery/pkg/util/sets"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
)
var acceptedStates = sets.NewString("stopping", "stopped", "shutting-down", "terminated")
type Parser struct{}
func (p Parser) Parse(raw string) (messages.Message, error) {
msg := Message{}
if err := json.Unmarshal([]byte(raw), &msg); err != nil {
return nil, fmt.Errorf("unmarhsalling the message as EC2InstanceStateChangeNotification, %w", err)
}
// We ignore states that are not in the set of states we can react to
if !acceptedStates.Has(strings.ToLower(msg.Detail.State)) {
return nil, nil
}
return msg, nil
}
func (p Parser) Version() string {
return "0"
}
func (p Parser) Source() string {
return "aws.ec2"
}
func (p Parser) DetailType() string {
return "EC2 Instance State-change Notification"
}
| 55 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package garbagecollection
import (
"context"
"fmt"
"time"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/util/workqueue"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/utils/sets"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/controllers/machine/link"
)
type Controller struct {
kubeClient client.Client
cloudProvider *cloudprovider.CloudProvider
successfulCount uint64 // keeps track of successful reconciles for more aggressive requeueing near the start of the controller
linkController *link.Controller // get machines recently linked by this controller
}
func NewController(kubeClient client.Client, cloudProvider *cloudprovider.CloudProvider, linkController *link.Controller) *Controller {
return &Controller{
kubeClient: kubeClient,
cloudProvider: cloudProvider,
successfulCount: 0,
linkController: linkController,
}
}
func (c *Controller) Name() string {
return "machine.garbagecollection"
}
func (c *Controller) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
// We LIST machines on the CloudProvider BEFORE we grab Machines/Nodes on the cluster so that we make sure that, if
// LISTing instances takes a long time, our information is more updated by the time we get to Machine and Node LIST
// This works since our CloudProvider instances are deleted based on whether the Machine exists or not, not vise-versa
retrieved, err := c.cloudProvider.List(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("listing cloudprovider machines, %w", err)
}
managedRetrieved := lo.Filter(retrieved, func(m *v1alpha5.Machine, _ int) bool {
return m.Annotations[v1alpha5.MachineManagedByAnnotationKey] != "" && m.DeletionTimestamp.IsZero()
})
machineList := &v1alpha5.MachineList{}
if err := c.kubeClient.List(ctx, machineList); err != nil {
return reconcile.Result{}, err
}
nodeList := &v1.NodeList{}
if err := c.kubeClient.List(ctx, nodeList); err != nil {
return reconcile.Result{}, err
}
resolvedMachines := lo.Filter(machineList.Items, func(m v1alpha5.Machine, _ int) bool {
return m.Status.ProviderID != "" || m.Annotations[v1alpha5.MachineLinkedAnnotationKey] != ""
})
resolvedProviderIDs := sets.New[string](lo.Map(resolvedMachines, func(m v1alpha5.Machine, _ int) string {
if m.Status.ProviderID != "" {
return m.Status.ProviderID
}
return m.Annotations[v1alpha5.MachineLinkedAnnotationKey]
})...)
errs := make([]error, len(retrieved))
workqueue.ParallelizeUntil(ctx, 100, len(managedRetrieved), func(i int) {
_, recentlyLinked := c.linkController.Cache.Get(managedRetrieved[i].Status.ProviderID)
if !recentlyLinked &&
!resolvedProviderIDs.Has(managedRetrieved[i].Status.ProviderID) &&
time.Since(managedRetrieved[i].CreationTimestamp.Time) > time.Second*30 {
errs[i] = c.garbageCollect(ctx, managedRetrieved[i], nodeList)
}
})
c.successfulCount++
return reconcile.Result{RequeueAfter: lo.Ternary(c.successfulCount <= 20, time.Second*10, time.Minute*2)}, multierr.Combine(errs...)
}
func (c *Controller) garbageCollect(ctx context.Context, machine *v1alpha5.Machine, nodeList *v1.NodeList) error {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("provider-id", machine.Status.ProviderID))
if err := c.cloudProvider.Delete(ctx, machine); err != nil {
return corecloudprovider.IgnoreMachineNotFoundError(err)
}
logging.FromContext(ctx).Debugf("garbage collected cloudprovider machine")
// Go ahead and cleanup the node if we know that it exists to make scheduling go quicker
if node, ok := lo.Find(nodeList.Items, func(n v1.Node) bool {
return n.Spec.ProviderID == machine.Status.ProviderID
}); ok {
if err := c.kubeClient.Delete(ctx, &node); err != nil {
return client.IgnoreNotFound(err)
}
logging.FromContext(ctx).With("node", node.Name).Debugf("garbage collected node")
}
return nil
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) controller.Builder {
return controller.NewSingletonManagedBy(m)
}
| 124 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package garbagecollection_test
import (
"context"
"fmt"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
. "knative.dev/pkg/logging/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/controllers/machine/garbagecollection"
"github.com/aws/karpenter/pkg/controllers/machine/link"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/test"
)
var ctx context.Context
var awsEnv *test.Environment
var env *coretest.Environment
var garbageCollectionController controller.Controller
var linkedMachineCache *cache.Cache
var cloudProvider *cloudprovider.CloudProvider
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Machine")
}
var _ = BeforeSuite(func() {
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
awsEnv = test.NewEnvironment(ctx, env)
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
linkedMachineCache = cache.New(time.Minute*10, time.Second*10)
linkController := &link.Controller{
Cache: linkedMachineCache,
}
garbageCollectionController = garbagecollection.NewController(env.Client, cloudProvider, linkController)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
awsEnv.Reset()
})
var _ = Describe("MachineGarbageCollection", func() {
var instance *ec2.Instance
var providerID string
BeforeEach(func() {
instanceID := fake.InstanceID()
providerID = fmt.Sprintf("aws:///test-zone-1a/%s", instanceID)
nodeTemplate := test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{})
provisioner := test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: v1alpha5.TestingGroup + "v1alpha1",
Kind: "NodeTemplate",
Name: nodeTemplate.Name,
},
})
instance = &ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
},
{
Key: aws.String(v1alpha5.MachineManagedByAnnotationKey),
Value: aws.String(settings.FromContext(ctx).ClusterName),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
}
})
AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
linkedMachineCache.Flush()
})
It("should delete an instance if there is no machine owner", func() {
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).To(HaveOccurred())
Expect(corecloudprovider.IsMachineNotFoundError(err)).To(BeTrue())
})
It("should delete an instance along with the node if there is no machine owner (to quicken scheduling)", func() {
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
node := coretest.Node(coretest.NodeOptions{
ProviderID: providerID,
})
ExpectApplied(ctx, env.Client, node)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).To(HaveOccurred())
Expect(corecloudprovider.IsMachineNotFoundError(err)).To(BeTrue())
ExpectNotFound(ctx, env.Client, node)
})
It("should delete many instances if they all don't have machine owners", func() {
// Generate 100 instances that have different instanceIDs
var ids []string
for i := 0; i < 100; i++ {
instanceID := fake.InstanceID()
awsEnv.EC2API.Instances.Store(
instanceID,
&ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String("default"),
},
{
Key: aws.String(v1alpha5.MachineManagedByAnnotationKey),
Value: aws.String(settings.FromContext(ctx).ClusterName),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
// Launch time was 1m ago
LaunchTime: aws.Time(time.Now().Add(-time.Minute)),
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
},
)
ids = append(ids, instanceID)
}
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
wg := sync.WaitGroup{}
for _, id := range ids {
wg.Add(1)
go func(id string) {
defer GinkgoRecover()
defer wg.Done()
_, err := cloudProvider.Get(ctx, fmt.Sprintf("aws:///test-zone-1a/%s", id))
Expect(err).To(HaveOccurred())
Expect(corecloudprovider.IsMachineNotFoundError(err)).To(BeTrue())
}(id)
}
wg.Wait()
})
It("should not delete all instances if they all have machine owners", func() {
// Generate 100 instances that have different instanceIDs
var ids []string
var machines []*v1alpha5.Machine
for i := 0; i < 100; i++ {
instanceID := fake.InstanceID()
awsEnv.EC2API.Instances.Store(
instanceID,
&ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String("default"),
},
{
Key: aws.String(v1alpha5.MachineManagedByAnnotationKey),
Value: aws.String(settings.FromContext(ctx).ClusterName),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
// Launch time was 10m ago
LaunchTime: aws.Time(time.Now().Add(-time.Minute)),
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
},
)
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: fmt.Sprintf("aws:///test-zone-1a/%s", instanceID),
},
})
ExpectApplied(ctx, env.Client, machine)
machines = append(machines, machine)
ids = append(ids, instanceID)
}
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
wg := sync.WaitGroup{}
for _, id := range ids {
wg.Add(1)
go func(id string) {
defer GinkgoRecover()
defer wg.Done()
_, err := cloudProvider.Get(ctx, fmt.Sprintf("aws:///test-zone-1a/%s", id))
Expect(err).ToNot(HaveOccurred())
}(id)
}
wg.Wait()
for _, machine := range machines {
ExpectExists(ctx, env.Client, machine)
}
})
It("should not delete an instance if it is within the machine resolution window (1m)", func() {
// Launch time just happened
instance.LaunchTime = aws.Time(time.Now())
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).NotTo(HaveOccurred())
})
It("should not delete an instance if it was not launched by a machine", func() {
// Remove the "karpenter.sh/managed-by" tag (this isn't launched by a machine)
instance.Tags = lo.Reject(instance.Tags, func(t *ec2.Tag, _ int) bool {
return aws.StringValue(t.Key) == v1alpha5.MachineManagedByAnnotationKey
})
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).NotTo(HaveOccurred())
})
It("should not delete the instance or node if it already has a machine that matches it", func() {
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
machine := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: providerID,
},
})
node := coretest.Node(coretest.NodeOptions{
ProviderID: providerID,
})
ExpectApplied(ctx, env.Client, machine, node)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).ToNot(HaveOccurred())
ExpectExists(ctx, env.Client, node)
})
It("should not delete an instance if it is linked", func() {
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
// Create a machine that is actively linking
machine := coretest.Machine(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.MachineLinkedAnnotationKey: providerID,
},
},
})
machine.Status.ProviderID = ""
ExpectApplied(ctx, env.Client, machine)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).NotTo(HaveOccurred())
})
It("should not delete an instance if it is recently linked but the machine doesn't exist", func() {
// Launch time was 10m ago
instance.LaunchTime = aws.Time(time.Now().Add(-time.Minute))
awsEnv.EC2API.Instances.Store(aws.StringValue(instance.InstanceId), instance)
// Add a provider id to the recently linked cache
linkedMachineCache.SetDefault(providerID, nil)
ExpectReconcileSucceeded(ctx, garbageCollectionController, client.ObjectKey{})
_, err := cloudProvider.Get(ctx, providerID)
Expect(err).NotTo(HaveOccurred())
})
})
| 352 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package link
import (
"context"
"fmt"
"math"
"time"
"github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/util/workqueue"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/metrics"
"github.com/aws/karpenter-core/pkg/operator/controller"
machineutil "github.com/aws/karpenter-core/pkg/utils/machine"
"github.com/aws/karpenter/pkg/cloudprovider"
)
const creationReasonLabel = "linking"
type Controller struct {
kubeClient client.Client
cloudProvider *cloudprovider.CloudProvider
Cache *cache.Cache // exists due to eventual consistency on the controller-runtime cache
}
func NewController(kubeClient client.Client, cloudProvider *cloudprovider.CloudProvider) *Controller {
return &Controller{
kubeClient: kubeClient,
cloudProvider: cloudProvider,
Cache: cache.New(time.Minute, time.Second*10),
}
}
func (c *Controller) Name() string {
return "machine.link"
}
func (c *Controller) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
// We LIST machines on the CloudProvider BEFORE we grab Machines/Nodes on the cluster so that we make sure that, if
// LISTing instances takes a long time, our information is more updated by the time we get to Machine and Node LIST
retrieved, err := c.cloudProvider.List(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("listing cloudprovider machines, %w", err)
}
machineList := &v1alpha5.MachineList{}
if err := c.kubeClient.List(ctx, machineList); err != nil {
return reconcile.Result{}, err
}
nodeList := &v1.NodeList{}
if err := c.kubeClient.List(ctx, nodeList, client.HasLabels{v1alpha5.ProvisionerNameLabelKey}); err != nil {
return reconcile.Result{}, err
}
retrievedIDs := sets.NewString(lo.Map(retrieved, func(m *v1alpha5.Machine, _ int) string { return m.Status.ProviderID })...)
// Inject any nodes that are re-owned using karpenter.sh/provisioner-name but aren't found from the cloudprovider.List() call
for i := range nodeList.Items {
if _, ok := lo.Find(retrieved, func(r *v1alpha5.Machine) bool {
return retrievedIDs.Has(nodeList.Items[i].Spec.ProviderID)
}); !ok {
retrieved = append(retrieved, machineutil.NewFromNode(&nodeList.Items[i]))
}
}
// Filter out any machines that shouldn't be linked
retrieved = lo.Filter(retrieved, func(m *v1alpha5.Machine, _ int) bool {
_, ok := m.Annotations[v1alpha5.MachineManagedByAnnotationKey]
return !ok && m.DeletionTimestamp.IsZero() && m.Labels[v1alpha5.ProvisionerNameLabelKey] != ""
})
errs := make([]error, len(retrieved))
workqueue.ParallelizeUntil(ctx, 100, len(retrieved), func(i int) {
errs[i] = c.link(ctx, retrieved[i], machineList.Items)
})
// Effectively, don't requeue this again once it succeeds
return reconcile.Result{RequeueAfter: math.MaxInt64}, multierr.Combine(errs...)
}
func (c *Controller) link(ctx context.Context, retrieved *v1alpha5.Machine, existingMachines []v1alpha5.Machine) error {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("provider-id", retrieved.Status.ProviderID, "provisioner", retrieved.Labels[v1alpha5.ProvisionerNameLabelKey]))
provisioner := &v1alpha5.Provisioner{}
if err := c.kubeClient.Get(ctx, types.NamespacedName{Name: retrieved.Labels[v1alpha5.ProvisionerNameLabelKey]}, provisioner); err != nil {
return client.IgnoreNotFound(err)
}
if c.shouldCreateLinkedMachine(retrieved, existingMachines) {
machine := machineutil.New(&v1.Node{}, provisioner)
machine.GenerateName = fmt.Sprintf("%s-", provisioner.Name)
// This annotation communicates to the machine controller that this is a machine linking scenario, not
// a case where we want to provision a new machine
machine.Annotations = lo.Assign(machine.Annotations, map[string]string{
v1alpha5.MachineLinkedAnnotationKey: retrieved.Status.ProviderID,
})
if err := c.kubeClient.Create(ctx, machine); err != nil {
return err
}
logging.FromContext(ctx).With("machine", machine.Name).Debugf("generated cluster machine from cloudprovider")
metrics.MachinesCreatedCounter.With(prometheus.Labels{
metrics.ReasonLabel: creationReasonLabel,
metrics.ProvisionerLabel: machine.Labels[v1alpha5.ProvisionerNameLabelKey],
}).Inc()
c.Cache.SetDefault(retrieved.Status.ProviderID, nil)
}
return corecloudprovider.IgnoreMachineNotFoundError(c.cloudProvider.Link(ctx, retrieved))
}
func (c *Controller) shouldCreateLinkedMachine(retrieved *v1alpha5.Machine, existingMachines []v1alpha5.Machine) bool {
// Machine was already created but controller-runtime cache didn't update
if _, ok := c.Cache.Get(retrieved.Status.ProviderID); ok {
return false
}
// We have a machine registered for this, so no need to hydrate it
if _, ok := lo.Find(existingMachines, func(m v1alpha5.Machine) bool {
return m.Annotations[v1alpha5.MachineLinkedAnnotationKey] == retrieved.Status.ProviderID ||
m.Status.ProviderID == retrieved.Status.ProviderID
}); ok {
return false
}
return true
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) controller.Builder {
return controller.NewSingletonManagedBy(m)
}
| 146 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package link_test
import (
"context"
"encoding/json"
"fmt"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
. "knative.dev/pkg/logging/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/controllers/machine/link"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/utils"
)
var ctx context.Context
var awsEnv *test.Environment
var env *coretest.Environment
var linkController controller.Controller
var cloudProvider *cloudprovider.CloudProvider
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Machine")
}
var _ = BeforeSuite(func() {
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
awsEnv = test.NewEnvironment(ctx, env)
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
linkController = link.NewController(env.Client, cloudProvider)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
awsEnv.Reset()
})
var _ = Describe("MachineLink", func() {
var instanceID string
var providerID string
var provisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
BeforeEach(func() {
instanceID = fake.InstanceID()
providerID = fmt.Sprintf("aws:///test-zone-1a/%s", instanceID)
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{})
provisioner = test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: v1alpha5.TestingGroup + "v1alpha1",
Kind: "NodeTemplate",
Name: nodeTemplate.Name,
},
})
// Store the instance as existing at DescribeInstances
awsEnv.EC2API.Instances.Store(
instanceID,
&ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
},
)
})
AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
It("should link an instance with basic spec set", func() {
provisioner.Spec.Taints = []v1.Taint{
{
Key: "testkey",
Value: "testvalue",
Effect: v1.TaintEffectNoSchedule,
},
}
provisioner.Spec.StartupTaints = []v1.Taint{
{
Key: "othertestkey",
Value: "othertestvalue",
Effect: v1.TaintEffectNoExecute,
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
// Expect machine to have populated fields from the node
Expect(machine.Spec.Taints).To(Equal(provisioner.Spec.Taints))
Expect(machine.Spec.StartupTaints).To(Equal(provisioner.Spec.StartupTaints))
Expect(machine.Spec.MachineTemplateRef.Kind).To(Equal(provisioner.Spec.ProviderRef.Kind))
Expect(machine.Spec.MachineTemplateRef.Name).To(Equal(provisioner.Spec.ProviderRef.Name))
// Expect machine has linking annotation to get machine details
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectManagedByTagExists(instance)
})
It("should link and instance with expected requirements and labels", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{
Key: v1.LabelTopologyZone,
Operator: v1.NodeSelectorOpIn,
Values: []string{"test-zone-1a", "test-zone-1b", "test-zone-1c"},
},
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux), string(v1.Windows)},
},
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
Expect(machine.Spec.Requirements).To(HaveLen(3))
Expect(machine.Spec.Requirements).To(ContainElements(
v1.NodeSelectorRequirement{
Key: v1.LabelTopologyZone,
Operator: v1.NodeSelectorOpIn,
Values: []string{"test-zone-1a", "test-zone-1b", "test-zone-1c"},
},
v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux), string(v1.Windows)},
},
v1.NodeSelectorRequirement{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
))
// Expect machine has linking annotation to get machine details
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectManagedByTagExists(instance)
})
It("should link an instance with expected kubelet from provisioner kubelet configuration", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
ClusterDNS: []string{"10.0.0.1"},
ContainerRuntime: lo.ToPtr("containerd"),
MaxPods: lo.ToPtr[int32](10),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
Expect(machine.Spec.Kubelet).ToNot(BeNil())
Expect(machine.Spec.Kubelet.ClusterDNS[0]).To(Equal("10.0.0.1"))
Expect(lo.FromPtr(machine.Spec.Kubelet.ContainerRuntime)).To(Equal("containerd"))
Expect(lo.FromPtr(machine.Spec.Kubelet.MaxPods)).To(BeNumerically("==", 10))
// Expect machine has linking annotation to get machine details
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectManagedByTagExists(instance)
})
It("should link many instances to many machines", func() {
awsEnv.EC2API.Reset() // Reset so we don't store the extra instance
ExpectApplied(ctx, env.Client, provisioner)
// Generate 100 instances that have different instanceIDs
var ids []string
for i := 0; i < 100; i++ {
instanceID = fake.InstanceID()
awsEnv.EC2API.EC2Behavior.Instances.Store(
instanceID,
&ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
},
)
ids = append(ids, instanceID)
}
// Generate a reconcile loop to link the machines
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(100))
machineInstanceIDs := sets.NewString(lo.Map(machineList.Items, func(m v1alpha5.Machine, _ int) string {
return lo.Must(utils.ParseInstanceID(m.Annotations[v1alpha5.MachineLinkedAnnotationKey]))
})...)
Expect(machineInstanceIDs).To(HaveLen(len(ids)))
for _, id := range ids {
Expect(machineInstanceIDs.Has(id)).To(BeTrue())
instance := ExpectInstanceExists(awsEnv.EC2API, id)
ExpectManagedByTagExists(instance)
}
})
It("should link an instance using provider and no providerRef", func() {
raw := &runtime.RawExtension{}
lo.Must0(raw.UnmarshalJSON(lo.Must(json.Marshal(v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
}))))
provisioner.Spec.ProviderRef = nil
provisioner.Spec.Provider = raw
ExpectApplied(ctx, env.Client, provisioner)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
Expect(machine.Annotations).To(HaveKey(v1alpha5.ProviderCompatabilityAnnotationKey))
// Expect machine has linking annotation to get machine details
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectManagedByTagExists(instance)
})
It("should link an instance without node template existence", func() {
// No node template has been applied here
ExpectApplied(ctx, env.Client, provisioner)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
Expect(machine.Spec.MachineTemplateRef.Kind).To(Equal(provisioner.Spec.ProviderRef.Kind))
Expect(machine.Spec.MachineTemplateRef.Name).To(Equal(provisioner.Spec.ProviderRef.Name))
// Expect machine has linking annotation to get machine details
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
ExpectManagedByTagExists(instance)
})
It("should link an instance that was re-owned with a provisioner-name label", func() {
awsEnv.EC2API.Reset() // Reset so we don't store the extra instance
// Don't include the provisioner-name tag
awsEnv.EC2API.EC2Behavior.Instances.Store(
instanceID,
&ec2.Instance{
State: &ec2.InstanceState{
Name: aws.String(ec2.InstanceStateNameRunning),
},
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)),
Value: aws.String("owned"),
},
},
PrivateDnsName: aws.String(fake.PrivateDNSName()),
Placement: &ec2.Placement{
AvailabilityZone: aws.String("test-zone-1a"),
},
InstanceId: aws.String(instanceID),
InstanceType: aws.String("m5.large"),
},
)
node := coretest.Node(coretest.NodeOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
},
},
ProviderID: providerID,
})
ExpectApplied(ctx, env.Client, node, provisioner, nodeTemplate)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
machine := machineList.Items[0]
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.MachineLinkedAnnotationKey, providerID))
})
It("should not link an instance without a provisioner tag", func() {
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
instance.Tags = lo.Reject(instance.Tags, func(t *ec2.Tag, _ int) bool {
return aws.StringValue(t.Key) == v1alpha5.ProvisionerNameLabelKey
})
awsEnv.EC2API.Instances.Store(instanceID, instance)
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(0))
})
It("should not link an instance without a provisioner that exists on the cluster", func() {
// No provisioner has been applied here
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(0))
// Expect that the instance was left alone if the provisioner wasn't found
ExpectInstanceExists(awsEnv.EC2API, instanceID)
})
It("should not link an instance for an instance that is already linked", func() {
m := coretest.Machine(v1alpha5.Machine{
Status: v1alpha5.MachineStatus{
ProviderID: providerID,
},
})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate, m)
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
// Expect that we go to link machines, and we don't add extra machines from the existing one
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(1))
})
It("should not link an instance that is terminated", func() {
// Update the state of the existing instance
instance := ExpectInstanceExists(awsEnv.EC2API, instanceID)
instance.State.Name = aws.String(ec2.InstanceStateNameTerminated)
awsEnv.EC2API.Instances.Store(instanceID, instance)
ExpectReconcileSucceeded(ctx, linkController, client.ObjectKey{})
machineList := &v1alpha5.MachineList{}
Expect(env.Client.List(ctx, machineList)).To(Succeed())
Expect(machineList.Items).To(HaveLen(0))
})
})
func ExpectInstanceExists(api *fake.EC2API, instanceID string) *ec2.Instance {
raw, ok := api.Instances.Load(instanceID)
Expect(ok).To(BeTrue())
return raw.(*ec2.Instance)
}
func ExpectManagedByTagExists(instance *ec2.Instance) *ec2.Tag {
tag, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == v1alpha5.MachineManagedByAnnotationKey
})
Expect(ok).To(BeTrue())
return tag
}
| 442 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nodetemplate
import (
"context"
"fmt"
"sort"
"time"
"go.uber.org/multierr"
"golang.org/x/time/rate"
"k8s.io/client-go/util/workqueue"
controllerruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/securitygroup"
"github.com/aws/karpenter/pkg/providers/subnet"
)
var _ corecontroller.TypedController[*v1alpha1.AWSNodeTemplate] = (*Controller)(nil)
type Controller struct {
kubeClient client.Client
subnetProvider *subnet.Provider
securityGroupProvider *securitygroup.Provider
amiProvider *amifamily.Provider
}
func NewController(kubeClient client.Client, subnetProvider *subnet.Provider, securityGroups *securitygroup.Provider, amiprovider *amifamily.Provider) corecontroller.Controller {
return corecontroller.Typed[*v1alpha1.AWSNodeTemplate](kubeClient, &Controller{
kubeClient: kubeClient,
subnetProvider: subnetProvider,
securityGroupProvider: securityGroups,
amiProvider: amiprovider,
})
}
func (c *Controller) Reconcile(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) (reconcile.Result, error) {
stored := nodeTemplate.DeepCopy()
err := multierr.Combine(
c.resolveSubnets(ctx, nodeTemplate),
c.resolveSecurityGroups(ctx, nodeTemplate),
c.resolveAMIs(ctx, nodeTemplate),
)
if patchErr := c.kubeClient.Status().Patch(ctx, nodeTemplate, client.MergeFrom(stored)); patchErr != nil {
err = multierr.Append(err, client.IgnoreNotFound(patchErr))
}
return reconcile.Result{RequeueAfter: 5 * time.Minute}, err
}
func (c *Controller) Name() string {
return "awsnodetemplate"
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1alpha1.AWSNodeTemplate{}).
WithEventFilter(predicate.GenerationChangedPredicate{}).
WithOptions(controller.Options{
RateLimiter: workqueue.NewMaxOfRateLimiter(
workqueue.NewItemExponentialFailureRateLimiter(100*time.Millisecond, 1*time.Minute),
// 10 qps, 100 bucket size
&workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},
),
MaxConcurrentReconciles: 10,
}))
}
func (c *Controller) resolveSubnets(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) error {
subnetList, err := c.subnetProvider.List(ctx, nodeTemplate)
if err != nil {
return err
}
if len(subnetList) == 0 {
nodeTemplate.Status.Subnets = nil
return fmt.Errorf("no subnets exist given constraints")
}
sort.Slice(subnetList, func(i, j int) bool {
return int(*subnetList[i].AvailableIpAddressCount) > int(*subnetList[j].AvailableIpAddressCount)
})
nodeTemplate.Status.Subnets = lo.Map(subnetList, func(ec2subnet *ec2.Subnet, _ int) v1alpha1.Subnet {
return v1alpha1.Subnet{
ID: *ec2subnet.SubnetId,
Zone: *ec2subnet.AvailabilityZone,
}
})
return nil
}
func (c *Controller) resolveSecurityGroups(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) error {
securityGroups, err := c.securityGroupProvider.List(ctx, nodeTemplate)
if err != nil {
return err
}
if len(securityGroups) == 0 && nodeTemplate.Spec.SecurityGroupSelector != nil {
nodeTemplate.Status.SecurityGroups = nil
return fmt.Errorf("no security groups exist given constraints")
}
nodeTemplate.Status.SecurityGroups = lo.Map(securityGroups, func(securityGroup *ec2.SecurityGroup, _ int) v1alpha1.SecurityGroup {
return v1alpha1.SecurityGroup{
ID: *securityGroup.GroupId,
Name: *securityGroup.GroupName,
}
})
return nil
}
func (c *Controller) resolveAMIs(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) error {
amis, err := c.amiProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
if err != nil {
return err
}
if len(amis) == 0 {
nodeTemplate.Status.AMIs = nil
return fmt.Errorf("no amis exist given constraints")
}
nodeTemplate.Status.AMIs = lo.Map(amis, func(ami amifamily.AMI, _ int) v1alpha1.AMI {
return v1alpha1.AMI{
Name: ami.Name,
ID: ami.AmiID,
Requirements: ami.Requirements.NodeSelectorRequirements(),
}
})
return nil
}
| 160 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package nodetemplate_test
import (
"context"
"fmt"
"sort"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
. "knative.dev/pkg/logging/testing"
_ "knative.dev/pkg/system/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/operator/options"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/controllers/nodetemplate"
"github.com/aws/karpenter/pkg/test"
)
var ctx context.Context
var env *coretest.Environment
var awsEnv *test.Environment
var opts options.Options
var nodeTemplate *v1alpha1.AWSNodeTemplate
var controller corecontroller.Controller
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "AWSNodeTemplateController")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
awsEnv = test.NewEnvironment(ctx, env)
controller = nodetemplate.NewController(env.Client, awsEnv.SubnetProvider, awsEnv.SecurityGroupProvider, awsEnv.AMIProvider)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
ctx = injection.WithOptions(ctx, opts)
nodeTemplate = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
AMISelector: map[string]string{"*": "*"},
},
}
awsEnv.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("AWSNodeTemplateController", func() {
Context("Subnet Status", func() {
It("Should update AWSNodeTemplate status for Subnets", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
{
ID: "subnet-test3",
Zone: "test-zone-1c",
},
}))
})
It("Should have the correct ordering for the Subnets", func() {
awsEnv.EC2API.DescribeSubnetsOutput.Set(&ec2.DescribeSubnetsOutput{Subnets: []*ec2.Subnet{
{SubnetId: aws.String("subnet-test1"), AvailabilityZone: aws.String("test-zone-1a"), AvailableIpAddressCount: aws.Int64(20)},
{SubnetId: aws.String("subnet-test2"), AvailabilityZone: aws.String("test-zone-1b"), AvailableIpAddressCount: aws.Int64(100)},
{SubnetId: aws.String("subnet-test3"), AvailabilityZone: aws.String("test-zone-1c"), AvailableIpAddressCount: aws.Int64(50)},
}})
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
{
ID: "subnet-test3",
Zone: "test-zone-1c",
},
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
}))
})
It("Should resolve a valid selectors for Subnet by tags", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{`Name`: `test-subnet-1,test-subnet-2`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
}))
})
It("Should resolve a valid selectors for Subnet by ids", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{`aws-ids`: `subnet-test1`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
}))
})
It("Should update Subnet status when the Subnet selector gets updated by tags", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
{
ID: "subnet-test3",
Zone: "test-zone-1c",
},
}))
nodeTemplate.Spec.SubnetSelector = map[string]string{`Name`: `test-subnet-1,test-subnet-2`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
}))
})
It("Should update Subnet status when the Subnet selector gets updated by ids", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
{
ID: "subnet-test3",
Zone: "test-zone-1c",
},
}))
nodeTemplate.Spec.SubnetSelector = map[string]string{`aws-ids`: `subnet-test1`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
}))
})
It("Should not resolve a invalid selectors for Subnet", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{`foo`: `invalid`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileFailed(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(BeNil())
})
It("Should not resolve a invalid selectors for an updated Subnet selectors", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(Equal([]v1alpha1.Subnet{
{
ID: "subnet-test1",
Zone: "test-zone-1a",
},
{
ID: "subnet-test2",
Zone: "test-zone-1b",
},
{
ID: "subnet-test3",
Zone: "test-zone-1c",
},
}))
nodeTemplate.Spec.SubnetSelector = map[string]string{`foo`: `invalid`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileFailed(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.Subnets).To(BeNil())
})
})
Context("Security Groups Status", func() {
It("Should expect no errors when security groups are not in the AWSNodeTemplate", func() {
// TODO: Remove test for v1beta1, as security groups will be required
nodeTemplate.Spec.SecurityGroupSelector = nil
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
Expect(nodeTemplate.Status.SecurityGroups).To(BeNil())
})
It("Should update AWSNodeTemplate status for Security Groups", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
{
ID: "sg-test3",
Name: "securityGroup-test3",
},
}))
})
It("Should resolve a valid selectors for Security Groups by tags", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`Name`: `test-security-group-1,test-security-group-2`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
}))
})
It("Should resolve a valid selectors for Security Groups by ids", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`aws-ids`: `sg-test1`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
}))
})
It("Should update Security Groups status when the Security Groups selector gets updated by tags", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
{
ID: "sg-test3",
Name: "securityGroup-test3",
},
}))
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`Name`: `test-security-group-1,test-security-group-2`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
}))
})
It("Should update Security Groups status when the Security Groups selector gets updated by ids", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
{
ID: "sg-test3",
Name: "securityGroup-test3",
},
}))
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`aws-ids`: `sg-test1`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
}))
})
It("Should not resolve a invalid selectors for Security Groups", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`foo`: `invalid`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileFailed(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(BeNil())
})
It("Should not resolve a invalid selectors for an updated Security Groups selector", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(Equal([]v1alpha1.SecurityGroup{
{
ID: "sg-test1",
Name: "securityGroup-test1",
},
{
ID: "sg-test2",
Name: "securityGroup-test2",
},
{
ID: "sg-test3",
Name: "securityGroup-test3",
},
}))
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{`foo`: `invalid`}
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileFailed(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.SecurityGroups).To(BeNil())
})
})
Context("AMI Status", func() {
BeforeEach(func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String("test-ami-1"),
ImageId: aws.String("ami-test1"),
CreationDate: aws.String(time.Now().Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-1")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String("test-ami-2"),
ImageId: aws.String("ami-test2"),
CreationDate: aws.String(time.Now().Add(time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-2")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String("test-ami-3"),
ImageId: aws.String("ami-test3"),
CreationDate: aws.String(time.Now().Add(2 * time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-3")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
},
})
})
It("should resolve amiSelector AMIs and requirements into status", func() {
version := lo.Must(awsEnv.AMIProvider.KubeServerVersion(ctx))
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", version): "ami-id-123",
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-gpu/recommended/image_id", version): "ami-id-456",
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2%s/recommended/image_id", version, fmt.Sprintf("-%s", v1alpha5.ArchitectureArm64)): "ami-id-789",
}
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String("test-ami-1"),
ImageId: aws.String("ami-id-123"),
CreationDate: aws.String(time.Now().Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-1")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String("test-ami-2"),
ImageId: aws.String("ami-id-456"),
CreationDate: aws.String(time.Now().Add(time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-2")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String("test-ami-3"),
ImageId: aws.String("ami-id-789"),
CreationDate: aws.String(time.Now().Add(2 * time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-3")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
},
})
nodeTemplate.Spec.AMISelector = nil
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
sortRequirements(nodeTemplate.Status.AMIs)
Expect(nodeTemplate.Status.AMIs).To(ContainElements([]v1alpha1.AMI{
{
Name: "test-ami-1",
ID: "ami-id-123",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
{
Key: v1alpha1.LabelInstanceGPUCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
{
Key: v1alpha1.LabelInstanceAcceleratorCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
},
},
{
Name: "test-ami-3",
ID: "ami-id-789",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureArm64},
},
{
Key: v1alpha1.LabelInstanceGPUCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
{
Key: v1alpha1.LabelInstanceAcceleratorCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
},
},
{
Name: "test-ami-2",
ID: "ami-id-456",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
{
Key: v1alpha1.LabelInstanceGPUCount,
Operator: v1.NodeSelectorOpExists,
},
},
},
{
Name: "test-ami-2",
ID: "ami-id-456",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
{
Key: v1alpha1.LabelInstanceAcceleratorCount,
Operator: v1.NodeSelectorOpExists,
},
},
},
}))
})
It("should resolve amiSelector AMis and requirements into status when all SSM aliases don't resolve", func() {
version := lo.Must(awsEnv.AMIProvider.KubeServerVersion(ctx))
// This parameter set doesn't include any of the Nvidia AMIs
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/x86_64/latest/image_id", version): "ami-id-123",
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/arm64/latest/image_id", version): "ami-id-456",
}
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
nodeTemplate.Spec.AMISelector = nil
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String("test-ami-1"),
ImageId: aws.String("ami-id-123"),
CreationDate: aws.String(time.Now().Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-1")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String("test-ami-2"),
ImageId: aws.String("ami-id-456"),
CreationDate: aws.String(time.Now().Add(time.Minute).Format(time.RFC3339)),
Architecture: aws.String("arm64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-2")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
},
})
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
sortRequirements(nodeTemplate.Status.AMIs)
Expect(nodeTemplate.Status.AMIs).To(ContainElements([]v1alpha1.AMI{
{
Name: "test-ami-1",
ID: "ami-id-123",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
{
Key: v1alpha1.LabelInstanceGPUCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
{
Key: v1alpha1.LabelInstanceAcceleratorCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
},
},
{
Name: "test-ami-2",
ID: "ami-id-456",
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureArm64},
},
{
Key: v1alpha1.LabelInstanceGPUCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
{
Key: v1alpha1.LabelInstanceAcceleratorCount,
Operator: v1.NodeSelectorOpDoesNotExist,
},
},
},
}))
})
It("Should resolve a valid AMI selector", func() {
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
Expect(nodeTemplate.Status.AMIs).To(ContainElements(
[]v1alpha1.AMI{
{
Name: "test-ami-3",
ID: "ami-test3",
Requirements: []v1.NodeSelectorRequirement{
{
Key: "kubernetes.io/arch",
Operator: "In",
Values: []string{
"amd64",
},
},
},
},
},
))
})
It("should resolve amiSelector AMIs that have well-known tags as AMI requirements into status", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String("test-ami-4"),
ImageId: aws.String("ami-test4"),
CreationDate: aws.String(time.Now().Add(2 * time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-ami-3")},
{Key: aws.String("foo"), Value: aws.String("bar")},
{Key: aws.String("kubernetes.io/os"), Value: aws.String("test-requirement-1")},
},
},
},
})
ExpectApplied(ctx, env.Client, nodeTemplate)
ExpectReconcileSucceeded(ctx, controller, client.ObjectKeyFromObject(nodeTemplate))
nodeTemplate = ExpectExists(ctx, env.Client, nodeTemplate)
sortRequirements(nodeTemplate.Status.AMIs)
Expect(nodeTemplate.Status.AMIs).To(ContainElements([]v1alpha1.AMI{
{
Name: "test-ami-4",
ID: "ami-test4",
Requirements: []v1.NodeSelectorRequirement{
{
Key: "kubernetes.io/os",
Operator: "In",
Values: []string{
"test-requirement-1",
},
},
{
Key: "kubernetes.io/arch",
Operator: "In",
Values: []string{
"amd64",
},
},
},
},
},
))
})
})
})
func sortRequirements(amis []v1alpha1.AMI) {
for i := range amis {
sort.Slice(amis[i].Requirements, func(p, q int) bool {
return amis[i].Requirements[p].Key > amis[i].Requirements[q].Key
})
}
}
| 732 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package errors
import (
"errors"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/sqs"
"k8s.io/apimachinery/pkg/util/sets"
)
const (
launchTemplateNotFoundCode = "InvalidLaunchTemplateName.NotFoundException"
)
var (
// This is not an exhaustive list, add to it as needed
notFoundErrorCodes = sets.NewString(
"InvalidInstanceID.NotFound",
launchTemplateNotFoundCode,
sqs.ErrCodeQueueDoesNotExist,
)
// unfulfillableCapacityErrorCodes signify that capacity is temporarily unable to be launched
unfulfillableCapacityErrorCodes = sets.NewString(
"InsufficientInstanceCapacity",
"MaxSpotInstanceCountExceeded",
"VcpuLimitExceeded",
"UnfulfillableCapacity",
"Unsupported",
)
)
// IsNotFound returns true if the err is an AWS error (even if it's
// wrapped) and is a known to mean "not found" (as opposed to a more
// serious or unexpected error)
func IsNotFound(err error) bool {
if err == nil {
return false
}
var awsError awserr.Error
if errors.As(err, &awsError) {
return notFoundErrorCodes.Has(awsError.Code())
}
return false
}
// IsUnfulfillableCapacity returns true if the Fleet err means
// capacity is temporarily unavailable for launching.
// This could be due to account limits, insufficient ec2 capacity, etc.
func IsUnfulfillableCapacity(err *ec2.CreateFleetError) bool {
return unfulfillableCapacityErrorCodes.Has(*err.ErrorCode)
}
func IsLaunchTemplateNotFound(err error) bool {
if err == nil {
return false
}
var awsError awserr.Error
if errors.As(err, &awsError) {
return awsError.Code() == launchTemplateNotFoundCode
}
return false
}
| 78 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"bytes"
"encoding/json"
"log"
"math"
"sync"
)
// AtomicPtr is intended for use in mocks to easily expose variables for use in testing. It makes setting and retrieving
// the values race free by wrapping the pointer itself in a mutex. There is no Get() method, but instead a Clone() method
// deep copies the object being stored by serializing/de-serializing it from JSON. This pattern shouldn't be followed
// anywhere else but is an easy way to eliminate races in our tests.
type AtomicPtr[T any] struct {
mu sync.Mutex
value *T
}
func (a *AtomicPtr[T]) Set(v *T) {
a.mu.Lock()
defer a.mu.Unlock()
a.value = v
}
func (a *AtomicPtr[T]) IsNil() bool {
a.mu.Lock()
defer a.mu.Unlock()
return a.value == nil
}
func (a *AtomicPtr[T]) Clone() *T {
a.mu.Lock()
defer a.mu.Unlock()
return clone(a.value)
}
func clone[T any](v *T) *T {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(v); err != nil {
log.Fatalf("encoding %T, %s", v, err)
}
dec := json.NewDecoder(&buf)
var cp T
if err := dec.Decode(&cp); err != nil {
log.Fatalf("encoding %T, %s", v, err)
}
return &cp
}
func (a *AtomicPtr[T]) Reset() {
a.mu.Lock()
defer a.mu.Unlock()
a.value = nil
}
type AtomicError struct {
mu sync.Mutex
err error
calls int
maxCalls int
}
func (e *AtomicError) Reset() {
e.mu.Lock()
defer e.mu.Unlock()
e.err = nil
e.calls = 0
e.maxCalls = 0
}
func (e *AtomicError) IsNil() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.err == nil
}
// Get is equivalent to the error being called, so we increase
// number of calls in this function
func (e *AtomicError) Get() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.calls >= e.maxCalls {
return nil
}
e.calls++
return e.err
}
func (e *AtomicError) Set(err error, opts ...AtomicErrorOption) {
e.mu.Lock()
defer e.mu.Unlock()
e.err = err
for _, opt := range opts {
opt(e)
}
if e.maxCalls == 0 {
e.maxCalls = 1
}
}
type AtomicErrorOption func(atomicError *AtomicError)
func MaxCalls(maxCalls int) AtomicErrorOption {
// Setting to 0 is equivalent to allowing infinite errors to API
if maxCalls <= 0 {
maxCalls = math.MaxInt
}
return func(e *AtomicError) {
e.maxCalls = maxCalls
}
}
// AtomicPtrSlice exposes a slice of a pointer type in a race-free manner. The interface is just enough to replace the
// set.Set usage in our previous tests.
type AtomicPtrSlice[T any] struct {
mu sync.RWMutex
values []*T
}
func (a *AtomicPtrSlice[T]) Reset() {
a.mu.Lock()
defer a.mu.Unlock()
a.values = nil
}
func (a *AtomicPtrSlice[T]) Add(input *T) {
a.mu.Lock()
defer a.mu.Unlock()
a.values = append(a.values, clone(input))
}
func (a *AtomicPtrSlice[T]) Len() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.values)
}
func (a *AtomicPtrSlice[T]) Pop() *T {
a.mu.Lock()
defer a.mu.Unlock()
last := a.values[len(a.values)-1]
a.values = a.values[0 : len(a.values)-1]
return last
}
func (a *AtomicPtrSlice[T]) ForEach(fn func(*T)) {
a.mu.RLock()
defer a.mu.RUnlock()
for _, t := range a.values {
fn(clone(t))
}
}
| 170 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
const (
defaultRegion = "us-west-2"
)
var _ corecloudprovider.CloudProvider = (*CloudProvider)(nil)
type CloudProvider struct {
InstanceTypes []*corecloudprovider.InstanceType
ValidAMIs []string
}
func (c *CloudProvider) Create(_ context.Context, _ *v1alpha5.Machine) (*v1alpha5.Machine, error) {
name := test.RandomName()
return &v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Name: name,
},
Status: v1alpha5.MachineStatus{
ProviderID: RandomProviderID(),
},
}, nil
}
func (c *CloudProvider) GetInstanceTypes(_ context.Context, _ *v1alpha5.Provisioner) ([]*corecloudprovider.InstanceType, error) {
if c.InstanceTypes != nil {
return c.InstanceTypes, nil
}
return []*corecloudprovider.InstanceType{
{Name: "default-instance-type"},
}, nil
}
func (c *CloudProvider) IsMachineDrifted(_ context.Context, machine *v1alpha5.Machine) (bool, error) {
nodeAMI := machine.Labels[v1alpha1.LabelInstanceAMIID]
for _, ami := range c.ValidAMIs {
if nodeAMI == ami {
return false, nil
}
}
return true, nil
}
func (c *CloudProvider) Get(context.Context, string) (*v1alpha5.Machine, error) {
return nil, nil
}
func (c *CloudProvider) List(context.Context) ([]*v1alpha5.Machine, error) {
return nil, nil
}
func (c *CloudProvider) Delete(context.Context, *v1alpha5.Machine) error {
return nil
}
// Name returns the CloudProvider implementation name.
func (c *CloudProvider) Name() string {
return "fake"
}
| 86 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/utils/sets"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter-core/pkg/utils/atomic"
)
type CapacityPool struct {
CapacityType string
InstanceType string
Zone string
}
// EC2Behavior must be reset between tests otherwise tests will
// pollute each other.
type EC2Behavior struct {
DescribeImagesOutput AtomicPtr[ec2.DescribeImagesOutput]
DescribeLaunchTemplatesOutput AtomicPtr[ec2.DescribeLaunchTemplatesOutput]
DescribeSubnetsOutput AtomicPtr[ec2.DescribeSubnetsOutput]
DescribeSecurityGroupsOutput AtomicPtr[ec2.DescribeSecurityGroupsOutput]
DescribeInstanceTypesOutput AtomicPtr[ec2.DescribeInstanceTypesOutput]
DescribeInstanceTypeOfferingsOutput AtomicPtr[ec2.DescribeInstanceTypeOfferingsOutput]
DescribeAvailabilityZonesOutput AtomicPtr[ec2.DescribeAvailabilityZonesOutput]
DescribeSpotPriceHistoryInput AtomicPtr[ec2.DescribeSpotPriceHistoryInput]
DescribeSpotPriceHistoryOutput AtomicPtr[ec2.DescribeSpotPriceHistoryOutput]
CreateFleetBehavior MockedFunction[ec2.CreateFleetInput, ec2.CreateFleetOutput]
TerminateInstancesBehavior MockedFunction[ec2.TerminateInstancesInput, ec2.TerminateInstancesOutput]
DescribeInstancesBehavior MockedFunction[ec2.DescribeInstancesInput, ec2.DescribeInstancesOutput]
CreateTagsBehavior MockedFunction[ec2.CreateTagsInput, ec2.CreateTagsOutput]
CalledWithCreateLaunchTemplateInput AtomicPtrSlice[ec2.CreateLaunchTemplateInput]
CalledWithDescribeImagesInput AtomicPtrSlice[ec2.DescribeImagesInput]
Instances sync.Map
LaunchTemplates sync.Map
InsufficientCapacityPools atomic.Slice[CapacityPool]
NextError AtomicError
}
type EC2API struct {
ec2iface.EC2API
EC2Behavior
}
// DefaultSupportedUsageClasses is a var because []*string can't be a const
var DefaultSupportedUsageClasses = aws.StringSlice([]string{"on-demand", "spot"})
// Reset must be called between tests otherwise tests will pollute
// each other.
func (e *EC2API) Reset() {
e.DescribeImagesOutput.Reset()
e.DescribeLaunchTemplatesOutput.Reset()
e.DescribeSubnetsOutput.Reset()
e.DescribeSecurityGroupsOutput.Reset()
e.DescribeInstanceTypesOutput.Reset()
e.DescribeInstanceTypeOfferingsOutput.Reset()
e.DescribeAvailabilityZonesOutput.Reset()
e.CreateFleetBehavior.Reset()
e.TerminateInstancesBehavior.Reset()
e.DescribeInstancesBehavior.Reset()
e.CalledWithCreateLaunchTemplateInput.Reset()
e.CalledWithDescribeImagesInput.Reset()
e.DescribeSpotPriceHistoryInput.Reset()
e.DescribeSpotPriceHistoryOutput.Reset()
e.Instances.Range(func(k, v any) bool {
e.Instances.Delete(k)
return true
})
e.LaunchTemplates.Range(func(k, v any) bool {
e.LaunchTemplates.Delete(k)
return true
})
e.InsufficientCapacityPools.Reset()
e.NextError.Reset()
}
// nolint: gocyclo
func (e *EC2API) CreateFleetWithContext(_ context.Context, input *ec2.CreateFleetInput, _ ...request.Option) (*ec2.CreateFleetOutput, error) {
return e.CreateFleetBehavior.Invoke(input, func(input *ec2.CreateFleetInput) (*ec2.CreateFleetOutput, error) {
if input.LaunchTemplateConfigs[0].LaunchTemplateSpecification.LaunchTemplateName == nil {
return nil, fmt.Errorf("missing launch template name")
}
var instanceIds []*string
var skippedPools []CapacityPool
var spotInstanceRequestID *string
if aws.StringValue(input.TargetCapacitySpecification.DefaultTargetCapacityType) == v1alpha5.CapacityTypeSpot {
spotInstanceRequestID = aws.String(test.RandomName())
}
fulfilled := 0
for _, ltc := range input.LaunchTemplateConfigs {
for _, override := range ltc.Overrides {
skipInstance := false
e.InsufficientCapacityPools.Range(func(pool CapacityPool) bool {
if pool.InstanceType == aws.StringValue(override.InstanceType) &&
pool.Zone == aws.StringValue(override.AvailabilityZone) &&
pool.CapacityType == aws.StringValue(input.TargetCapacitySpecification.DefaultTargetCapacityType) {
skippedPools = append(skippedPools, pool)
skipInstance = true
return false
}
return true
})
if skipInstance {
continue
}
amiID := aws.String("")
if e.CalledWithCreateLaunchTemplateInput.Len() > 0 {
lt := e.CalledWithCreateLaunchTemplateInput.Pop()
amiID = lt.LaunchTemplateData.ImageId
e.CalledWithCreateLaunchTemplateInput.Add(lt)
}
instanceState := ec2.InstanceStateNameRunning
for ; fulfilled < int(*input.TargetCapacitySpecification.TotalTargetCapacity); fulfilled++ {
instance := &ec2.Instance{
ImageId: aws.String(*amiID),
InstanceId: aws.String(test.RandomName()),
Placement: &ec2.Placement{AvailabilityZone: input.LaunchTemplateConfigs[0].Overrides[0].AvailabilityZone},
PrivateDnsName: aws.String(randomdata.IpV4Address()),
InstanceType: input.LaunchTemplateConfigs[0].Overrides[0].InstanceType,
SpotInstanceRequestId: spotInstanceRequestID,
State: &ec2.InstanceState{
Name: &instanceState,
},
}
e.Instances.Store(*instance.InstanceId, instance)
instanceIds = append(instanceIds, instance.InstanceId)
}
}
if fulfilled == int(*input.TargetCapacitySpecification.TotalTargetCapacity) {
break
}
}
result := &ec2.CreateFleetOutput{Instances: []*ec2.CreateFleetInstance{
{
InstanceIds: instanceIds,
InstanceType: input.LaunchTemplateConfigs[0].Overrides[0].InstanceType,
Lifecycle: input.TargetCapacitySpecification.DefaultTargetCapacityType,
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
Overrides: &ec2.FleetLaunchTemplateOverrides{
SubnetId: input.LaunchTemplateConfigs[0].Overrides[0].SubnetId,
InstanceType: input.LaunchTemplateConfigs[0].Overrides[0].InstanceType,
AvailabilityZone: input.LaunchTemplateConfigs[0].Overrides[0].AvailabilityZone,
},
},
},
}}
for _, pool := range skippedPools {
result.Errors = append(result.Errors, &ec2.CreateFleetError{
ErrorCode: aws.String("InsufficientInstanceCapacity"),
LaunchTemplateAndOverrides: &ec2.LaunchTemplateAndOverridesResponse{
Overrides: &ec2.FleetLaunchTemplateOverrides{
InstanceType: aws.String(pool.InstanceType),
AvailabilityZone: aws.String(pool.Zone),
},
},
})
}
return result, nil
})
}
func (e *EC2API) TerminateInstancesWithContext(_ context.Context, input *ec2.TerminateInstancesInput, _ ...request.Option) (*ec2.TerminateInstancesOutput, error) {
return e.TerminateInstancesBehavior.Invoke(input, func(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error) {
var instanceStateChanges []*ec2.InstanceStateChange
for _, id := range input.InstanceIds {
instanceID := *id
if _, ok := e.Instances.LoadAndDelete(instanceID); ok {
instanceStateChanges = append(instanceStateChanges, &ec2.InstanceStateChange{
PreviousState: &ec2.InstanceState{Name: aws.String(ec2.InstanceStateNameRunning), Code: aws.Int64(16)},
CurrentState: &ec2.InstanceState{Name: aws.String(ec2.InstanceStateNameShuttingDown), Code: aws.Int64(32)},
InstanceId: aws.String(instanceID),
})
}
}
return &ec2.TerminateInstancesOutput{TerminatingInstances: instanceStateChanges}, nil
})
}
func (e *EC2API) CreateLaunchTemplateWithContext(_ context.Context, input *ec2.CreateLaunchTemplateInput, _ ...request.Option) (*ec2.CreateLaunchTemplateOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
e.CalledWithCreateLaunchTemplateInput.Add(input)
launchTemplate := &ec2.LaunchTemplate{LaunchTemplateName: input.LaunchTemplateName}
e.LaunchTemplates.Store(input.LaunchTemplateName, launchTemplate)
return &ec2.CreateLaunchTemplateOutput{LaunchTemplate: launchTemplate}, nil
}
func (e *EC2API) CreateTagsWithContext(_ context.Context, input *ec2.CreateTagsInput, _ ...request.Option) (*ec2.CreateTagsOutput, error) {
return e.CreateTagsBehavior.Invoke(input, func(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) {
// Update passed in instances with the passed tags
for _, id := range input.Resources {
raw, ok := e.Instances.Load(aws.StringValue(id))
if !ok {
return nil, fmt.Errorf("instance with id '%s' does not exist", aws.StringValue(id))
}
instance := raw.(*ec2.Instance)
// Upsert any tags that have the same key
newTagKeys := sets.New(lo.Map(input.Tags, func(t *ec2.Tag, _ int) string { return aws.StringValue(t.Key) })...)
instance.Tags = lo.Filter(input.Tags, func(t *ec2.Tag, _ int) bool { return newTagKeys.Has(aws.StringValue(t.Key)) })
instance.Tags = append(instance.Tags, input.Tags...)
}
return nil, nil
})
}
func (e *EC2API) DescribeInstancesWithContext(_ context.Context, input *ec2.DescribeInstancesInput, _ ...request.Option) (*ec2.DescribeInstancesOutput, error) {
return e.DescribeInstancesBehavior.Invoke(input, func(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) {
var instances []*ec2.Instance
// If it's a list call and no instance ids are specified
if len(aws.StringValueSlice(input.InstanceIds)) == 0 {
e.Instances.Range(func(k interface{}, v interface{}) bool {
instances = append(instances, v.(*ec2.Instance))
return true
})
}
for _, instanceID := range input.InstanceIds {
instance, _ := e.Instances.Load(*instanceID)
if instance == nil {
continue
}
instances = append(instances, instance.(*ec2.Instance))
}
return &ec2.DescribeInstancesOutput{
Reservations: []*ec2.Reservation{{Instances: filterInstances(instances, input.Filters)}},
}, nil
})
}
func (e *EC2API) DescribeInstancesPagesWithContext(ctx context.Context, input *ec2.DescribeInstancesInput, fn func(*ec2.DescribeInstancesOutput, bool) bool, opts ...request.Option) error {
output, err := e.DescribeInstancesWithContext(ctx, input, opts...)
if err != nil {
return err
}
fn(output, false)
return nil
}
//nolint:gocyclo
func filterInstances(instances []*ec2.Instance, filters []*ec2.Filter) []*ec2.Instance {
var ret []*ec2.Instance
for _, instance := range instances {
passesFilter := true
OUTER:
for _, filter := range filters {
switch {
case aws.StringValue(filter.Name) == "instance-state-name":
if !sets.New(aws.StringValueSlice(filter.Values)...).Has(aws.StringValue(instance.State.Name)) {
passesFilter = false
break OUTER
}
case aws.StringValue(filter.Name) == "tag-key":
values := sets.New(aws.StringValueSlice(filter.Values)...)
if _, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return values.Has(aws.StringValue(t.Key))
}); !ok {
passesFilter = false
break OUTER
}
case strings.HasPrefix(aws.StringValue(filter.Name), "tag:"):
k := strings.TrimPrefix(aws.StringValue(filter.Name), "tag:")
tag, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == k
})
if !ok {
passesFilter = false
break OUTER
}
switch {
case lo.Contains(aws.StringValueSlice(filter.Values), "*"):
case lo.Contains(aws.StringValueSlice(filter.Values), aws.StringValue(tag.Value)):
default:
passesFilter = false
break OUTER
}
}
}
if passesFilter {
ret = append(ret, instance)
}
}
return ret
}
func (e *EC2API) DescribeImagesWithContext(_ context.Context, input *ec2.DescribeImagesInput, _ ...request.Option) (*ec2.DescribeImagesOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
e.CalledWithDescribeImagesInput.Add(input)
if !e.DescribeImagesOutput.IsNil() {
return e.DescribeImagesOutput.Clone(), nil
}
if aws.StringValue(input.Filters[0].Values[0]) == "invalid" {
return &ec2.DescribeImagesOutput{}, nil
}
return &ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String(test.RandomName()),
ImageId: aws.String(test.RandomName()),
CreationDate: aws.String(time.Now().Format(time.UnixDate)),
Architecture: aws.String("x86_64"),
},
},
}, nil
}
func (e *EC2API) DescribeLaunchTemplatesWithContext(_ context.Context, input *ec2.DescribeLaunchTemplatesInput, _ ...request.Option) (*ec2.DescribeLaunchTemplatesOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
if !e.DescribeLaunchTemplatesOutput.IsNil() {
return e.DescribeLaunchTemplatesOutput.Clone(), nil
}
output := &ec2.DescribeLaunchTemplatesOutput{}
e.LaunchTemplates.Range(func(key, value interface{}) bool {
launchTemplate := value.(*ec2.LaunchTemplate)
if lo.Contains(aws.StringValueSlice(input.LaunchTemplateNames), aws.StringValue(launchTemplate.LaunchTemplateName)) {
output.LaunchTemplates = append(output.LaunchTemplates, launchTemplate)
}
return true
})
if len(output.LaunchTemplates) == 0 {
return nil, awserr.New("InvalidLaunchTemplateName.NotFoundException", "not found", nil)
}
return output, nil
}
func (e *EC2API) DescribeSubnetsWithContext(_ context.Context, input *ec2.DescribeSubnetsInput, _ ...request.Option) (*ec2.DescribeSubnetsOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
if !e.DescribeSubnetsOutput.IsNil() {
describeSubnetsOutput := e.DescribeSubnetsOutput.Clone()
describeSubnetsOutput.Subnets = FilterDescribeSubnets(describeSubnetsOutput.Subnets, input.Filters)
return describeSubnetsOutput, nil
}
subnets := []*ec2.Subnet{
{
SubnetId: aws.String("subnet-test1"),
AvailabilityZone: aws.String("test-zone-1a"),
AvailableIpAddressCount: aws.Int64(100),
MapPublicIpOnLaunch: aws.Bool(false),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-subnet-1")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
SubnetId: aws.String("subnet-test2"),
AvailabilityZone: aws.String("test-zone-1b"),
AvailableIpAddressCount: aws.Int64(100),
MapPublicIpOnLaunch: aws.Bool(true),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-subnet-2")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
SubnetId: aws.String("subnet-test3"),
AvailabilityZone: aws.String("test-zone-1c"),
AvailableIpAddressCount: aws.Int64(100),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-subnet-3")},
{Key: aws.String("TestTag")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
}
if len(input.Filters) == 0 {
return nil, fmt.Errorf("InvalidParameterValue: The filter 'null' is invalid")
}
return &ec2.DescribeSubnetsOutput{Subnets: FilterDescribeSubnets(subnets, input.Filters)}, nil
}
func (e *EC2API) DescribeSecurityGroupsWithContext(_ context.Context, input *ec2.DescribeSecurityGroupsInput, _ ...request.Option) (*ec2.DescribeSecurityGroupsOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
if !e.DescribeSecurityGroupsOutput.IsNil() {
describeSecurityGroupsOutput := e.DescribeSecurityGroupsOutput.Clone()
describeSecurityGroupsOutput.SecurityGroups = FilterDescribeSecurtyGroups(describeSecurityGroupsOutput.SecurityGroups, input.Filters)
return e.DescribeSecurityGroupsOutput.Clone(), nil
}
sgs := []*ec2.SecurityGroup{
{
GroupId: aws.String("sg-test1"),
GroupName: aws.String("securityGroup-test1"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-security-group-1")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
GroupId: aws.String("sg-test2"),
GroupName: aws.String("securityGroup-test2"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-security-group-2")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
GroupId: aws.String("sg-test3"),
GroupName: aws.String("securityGroup-test3"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String("test-security-group-3")},
{Key: aws.String("TestTag")},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
}
if len(input.Filters) == 0 {
return nil, fmt.Errorf("InvalidParameterValue: The filter 'null' is invalid")
}
return &ec2.DescribeSecurityGroupsOutput{SecurityGroups: FilterDescribeSecurtyGroups(sgs, input.Filters)}, nil
}
func (e *EC2API) DescribeAvailabilityZonesWithContext(context.Context, *ec2.DescribeAvailabilityZonesInput, ...request.Option) (*ec2.DescribeAvailabilityZonesOutput, error) {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return nil, e.NextError.Get()
}
if !e.DescribeAvailabilityZonesOutput.IsNil() {
return e.DescribeAvailabilityZonesOutput.Clone(), nil
}
return &ec2.DescribeAvailabilityZonesOutput{AvailabilityZones: []*ec2.AvailabilityZone{
{ZoneName: aws.String("test-zone-1a"), ZoneId: aws.String("testzone1a")},
{ZoneName: aws.String("test-zone-1b"), ZoneId: aws.String("testzone1b")},
{ZoneName: aws.String("test-zone-1c"), ZoneId: aws.String("testzone1c")},
}}, nil
}
func (e *EC2API) DescribeInstanceTypesPagesWithContext(_ context.Context, _ *ec2.DescribeInstanceTypesInput, fn func(*ec2.DescribeInstanceTypesOutput, bool) bool, _ ...request.Option) error {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return e.NextError.Get()
}
if !e.DescribeInstanceTypesOutput.IsNil() {
fn(e.DescribeInstanceTypesOutput.Clone(), false)
return nil
}
fn(defaultDescribeInstanceTypesOutput, false)
return nil
}
func (e *EC2API) DescribeInstanceTypeOfferingsPagesWithContext(_ context.Context, _ *ec2.DescribeInstanceTypeOfferingsInput, fn func(*ec2.DescribeInstanceTypeOfferingsOutput, bool) bool, _ ...request.Option) error {
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return e.NextError.Get()
}
if !e.DescribeInstanceTypeOfferingsOutput.IsNil() {
fn(e.DescribeInstanceTypeOfferingsOutput.Clone(), false)
return nil
}
fn(&ec2.DescribeInstanceTypeOfferingsOutput{
InstanceTypeOfferings: []*ec2.InstanceTypeOffering{
{
InstanceType: aws.String("m5.large"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.large"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("m5.large"),
Location: aws.String("test-zone-1c"),
},
{
InstanceType: aws.String("m5.xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.xlarge"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("m5.2xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.4xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.8xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("p3.8xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("p3.8xlarge"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("dl1.24xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("dl1.24xlarge"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("g4dn.8xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("g4dn.8xlarge"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("t3.large"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("t3.large"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("inf1.2xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("inf1.6xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("trn1.2xlarge"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("c6g.large"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.metal"),
Location: aws.String("test-zone-1a"),
},
{
InstanceType: aws.String("m5.metal"),
Location: aws.String("test-zone-1b"),
},
{
InstanceType: aws.String("m5.metal"),
Location: aws.String("test-zone-1c"),
},
},
}, false)
return nil
}
func (e *EC2API) DescribeSpotPriceHistoryPagesWithContext(_ aws.Context, in *ec2.DescribeSpotPriceHistoryInput, fn func(*ec2.DescribeSpotPriceHistoryOutput, bool) bool, _ ...request.Option) error {
e.DescribeSpotPriceHistoryInput.Set(in)
if !e.NextError.IsNil() {
defer e.NextError.Reset()
return e.NextError.Get()
}
if !e.DescribeSpotPriceHistoryOutput.IsNil() {
fn(e.DescribeSpotPriceHistoryOutput.Clone(), false)
return nil
}
// fail if the test doesn't provide specific data which causes our pricing provider to use its static price list
return errors.New("no pricing data provided")
}
| 606 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/eks/eksiface"
)
const ()
// EKSAPIBehavior must be reset between tests otherwise tests will
// pollute each other.
type EKSAPIBehavior struct {
DescribeClusterBehaviour MockedFunction[eks.DescribeClusterInput, eks.DescribeClusterOutput]
}
type EKSAPI struct {
eksiface.EKSAPI
EKSAPIBehavior
}
// Reset must be called between tests otherwise tests will pollute
// each other.
func (s *EKSAPI) Reset() {
s.DescribeClusterBehaviour.Reset()
}
func (s *EKSAPI) DescribeCluster(input *eks.DescribeClusterInput) (*eks.DescribeClusterOutput, error) {
return s.DescribeClusterBehaviour.Invoke(input, func(*eks.DescribeClusterInput) (*eks.DescribeClusterOutput, error) {
return nil, nil
})
}
| 46 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/pricing"
"github.com/aws/aws-sdk-go/service/pricing/pricingiface"
)
type PricingAPI struct {
pricingiface.PricingAPI
PricingBehavior
}
type PricingBehavior struct {
NextError AtomicError
GetProductsOutput AtomicPtr[pricing.GetProductsOutput]
}
func (p *PricingAPI) Reset() {
p.NextError.Reset()
p.GetProductsOutput.Reset()
}
func (p *PricingAPI) GetProductsPagesWithContext(_ aws.Context, _ *pricing.GetProductsInput, fn func(*pricing.GetProductsOutput, bool) bool, _ ...request.Option) error {
if !p.NextError.IsNil() {
return p.NextError.Get()
}
if !p.GetProductsOutput.IsNil() {
fn(p.GetProductsOutput.Clone(), false)
return nil
}
// fail if the test doesn't provide specific data which causes our pricing provider to use its static price list
return errors.New("no pricing data provided")
}
func NewOnDemandPrice(instanceType string, price float64) aws.JSONValue {
return aws.JSONValue{
"product": map[string]interface{}{
"attributes": map[string]interface{}{
"instanceType": instanceType,
},
},
"terms": map[string]interface{}{
"OnDemand": map[string]interface{}{
"JRTCKXETXF.foo": map[string]interface{}{
"offerTermCode": "JRTCKXETXF",
"priceDimensions": map[string]interface{}{
"JRTCKXETXF.foo.bar": map[string]interface{}{
"pricePerUnit": map[string]interface{}{"USD": fmt.Sprintf("%f", price)},
},
},
},
},
},
}
}
| 74 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
)
const (
dummyQueueURL = "https://sqs.us-west-2.amazonaws.com/000000000000/Karpenter-cluster-Queue"
)
// SQSBehavior must be reset between tests otherwise tests will
// pollute each other.
type SQSBehavior struct {
GetQueueURLBehavior MockedFunction[sqs.GetQueueUrlInput, sqs.GetQueueUrlOutput]
GetQueueAttributesBehavior MockedFunction[sqs.GetQueueAttributesInput, sqs.GetQueueAttributesOutput]
ReceiveMessageBehavior MockedFunction[sqs.ReceiveMessageInput, sqs.ReceiveMessageOutput]
DeleteMessageBehavior MockedFunction[sqs.DeleteMessageInput, sqs.DeleteMessageOutput]
}
type SQSAPI struct {
sqsiface.SQSAPI
SQSBehavior
}
// Reset must be called between tests otherwise tests will pollute
// each other.
func (s *SQSAPI) Reset() {
s.GetQueueURLBehavior.Reset()
s.GetQueueAttributesBehavior.Reset()
s.ReceiveMessageBehavior.Reset()
s.DeleteMessageBehavior.Reset()
}
//nolint:revive,stylecheck
func (s *SQSAPI) GetQueueUrlWithContext(_ context.Context, input *sqs.GetQueueUrlInput, _ ...request.Option) (*sqs.GetQueueUrlOutput, error) {
return s.GetQueueURLBehavior.Invoke(input, func(_ *sqs.GetQueueUrlInput) (*sqs.GetQueueUrlOutput, error) {
return &sqs.GetQueueUrlOutput{
QueueUrl: aws.String(dummyQueueURL),
}, nil
})
}
func (s *SQSAPI) ReceiveMessageWithContext(_ context.Context, input *sqs.ReceiveMessageInput, _ ...request.Option) (*sqs.ReceiveMessageOutput, error) {
return s.ReceiveMessageBehavior.Invoke(input, func(_ *sqs.ReceiveMessageInput) (*sqs.ReceiveMessageOutput, error) {
return nil, nil
})
}
func (s *SQSAPI) DeleteMessageWithContext(_ context.Context, input *sqs.DeleteMessageInput, _ ...request.Option) (*sqs.DeleteMessageOutput, error) {
return s.DeleteMessageBehavior.Invoke(input, func(_ *sqs.DeleteMessageInput) (*sqs.DeleteMessageOutput, error) {
return nil, nil
})
}
| 73 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/mitchellh/hashstructure/v2"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
)
type SSMAPI struct {
ssmiface.SSMAPI
Parameters map[string]string
GetParameterOutput *ssm.GetParameterOutput
WantErr error
}
func (a SSMAPI) GetParameterWithContext(_ context.Context, input *ssm.GetParameterInput, _ ...request.Option) (*ssm.GetParameterOutput, error) {
if a.WantErr != nil {
return nil, a.WantErr
}
if len(a.Parameters) > 0 {
if amiID, ok := a.Parameters[*input.Name]; ok {
return &ssm.GetParameterOutput{
Parameter: &ssm.Parameter{Value: aws.String(amiID)},
}, nil
}
return nil, awserr.New(ssm.ErrCodeParameterNotFound, fmt.Sprintf("%s couldn't be found", *input.Name), nil)
}
hc, _ := hashstructure.Hash(input.Name, hashstructure.FormatV2, nil)
if a.GetParameterOutput != nil {
return a.GetParameterOutput, nil
}
return &ssm.GetParameterOutput{
Parameter: &ssm.Parameter{Value: aws.String(fmt.Sprintf("test-ami-id-%x", hc))},
}, nil
}
func (a *SSMAPI) Reset() {
a.GetParameterOutput = nil
a.Parameters = nil
a.WantErr = nil
}
| 64 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"sync/atomic"
)
type MockedFunction[I any, O any] struct {
Output AtomicPtr[O] // Output to return on call to this function
CalledWithInput AtomicPtrSlice[I] // Slice used to keep track of passed input to this function
Error AtomicError // Error to return a certain number of times defined by custom error options
successfulCalls atomic.Int32 // Internal construct to keep track of the number of times this function has successfully been called
failedCalls atomic.Int32 // Internal construct to keep track of the number of times this function has failed (with error)
}
// Reset must be called between tests otherwise tests will pollute
// each other.
func (m *MockedFunction[I, O]) Reset() {
m.Output.Reset()
m.CalledWithInput.Reset()
m.Error.Reset()
m.successfulCalls.Store(0)
m.failedCalls.Store(0)
}
func (m *MockedFunction[I, O]) Invoke(input *I, defaultTransformer func(*I) (*O, error)) (*O, error) {
err := m.Error.Get()
if err != nil {
m.failedCalls.Add(1)
return nil, err
}
m.CalledWithInput.Add(input)
if !m.Output.IsNil() {
m.successfulCalls.Add(1)
return m.Output.Clone(), nil
}
out, err := defaultTransformer(input)
if err != nil {
m.failedCalls.Add(1)
} else {
m.successfulCalls.Add(1)
}
return out, err
}
func (m *MockedFunction[I, O]) Calls() int {
return m.SuccessfulCalls() + m.FailedCalls()
}
func (m *MockedFunction[I, O]) SuccessfulCalls() int {
return int(m.successfulCalls.Load())
}
func (m *MockedFunction[I, O]) FailedCalls() int {
return int(m.failedCalls.Load())
}
| 73 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"fmt"
"strings"
"github.com/Pallinder/go-randomdata"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
)
func InstanceID() string {
return fmt.Sprintf("i-%s", randomdata.Alphanumeric(17))
}
func RandomProviderID() string {
return ProviderID(InstanceID())
}
func ProviderID(id string) string {
return fmt.Sprintf("aws:///%s/%s", defaultRegion, id)
}
func ImageID() string {
return fmt.Sprintf("ami-%s", randomdata.Alphanumeric(17))
}
func SecurityGroupID() string {
return fmt.Sprintf("sg-%s", randomdata.Alphanumeric(17))
}
func SubnetID() string {
return fmt.Sprintf("subnet-%s", randomdata.Alphanumeric(17))
}
func PrivateDNSName() string {
return fmt.Sprintf("ip-192-168-%d-%d.%s.compute.internal", randomdata.Number(0, 256), randomdata.Number(0, 256), defaultRegion)
}
// SubnetsFromFleetRequest returns a unique slice of subnetIDs passed as overrides from a CreateFleetInput
func SubnetsFromFleetRequest(createFleetInput *ec2.CreateFleetInput) []string {
return lo.Uniq(lo.Flatten(lo.Map(createFleetInput.LaunchTemplateConfigs, func(ltReq *ec2.FleetLaunchTemplateConfigRequest, _ int) []string {
var subnets []string
for _, override := range ltReq.Overrides {
if override.SubnetId != nil {
subnets = append(subnets, *override.SubnetId)
}
}
return subnets
})))
}
// FilterDescribeSecurtyGroups filters the passed in security groups based on the filters passed in.
// Filters are chained with a logical "AND"
func FilterDescribeSecurtyGroups(sgs []*ec2.SecurityGroup, filters []*ec2.Filter) []*ec2.SecurityGroup {
return lo.Filter(sgs, func(group *ec2.SecurityGroup, _ int) bool {
return Filter(filters, *group.GroupId, group.Tags)
})
}
// FilterDescribeSubnets filters the passed in subnets based on the filters passed in.
// Filters are chained with a logical "AND"
func FilterDescribeSubnets(subnets []*ec2.Subnet, filters []*ec2.Filter) []*ec2.Subnet {
return lo.Filter(subnets, func(subnet *ec2.Subnet, _ int) bool {
return Filter(filters, *subnet.SubnetId, subnet.Tags)
})
}
func Filter(filters []*ec2.Filter, id string, tags []*ec2.Tag) bool {
return lo.EveryBy(filters, func(filter *ec2.Filter) bool {
switch filterName := aws.StringValue(filter.Name); {
case filterName == "subnet-id" || filterName == "group-id":
for _, val := range filter.Values {
if id == aws.StringValue(val) {
return true
}
}
case strings.HasPrefix(filterName, "tag"):
if matchTags(tags, filter) {
return true
}
default:
panic("Unsupported mock filter")
}
return false
})
}
// matchTags is a predicate that matches a slice of tags with a tag:<key> or tag-keys filter
// nolint: gocyclo
func matchTags(tags []*ec2.Tag, filter *ec2.Filter) bool {
if strings.HasPrefix(*filter.Name, "tag:") {
tagKey := strings.Split(*filter.Name, ":")[1]
for _, val := range filter.Values {
for _, tag := range tags {
if tagKey == *tag.Key && (*val == "*" || *val == *tag.Value) {
return true
}
}
}
} else if strings.HasPrefix(*filter.Name, "tag-key") {
for _, v := range filter.Values {
if aws.StringValue(v) == "*" {
return true
}
for _, t := range tags {
if aws.StringValue(t.Key) == aws.StringValue(v) {
return true
}
}
}
}
return false
}
| 129 |
karpenter | aws | Go | //go:build !ignore_autogenerated
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fake
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
)
// GENERATED FILE. DO NOT EDIT DIRECTLY.
// Update hack/code/instancetype_testdata_gen.go and re-generate to edit
// You can add instance types by adding to the --instance-types CLI flag
var defaultDescribeInstanceTypesOutput = &ec2.DescribeInstanceTypesOutput{
InstanceTypes: []*ec2.InstanceTypeInfo{
{
InstanceType: aws.String("c6g.large"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"arm64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(2),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(4096),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(3),
Ipv4AddressesPerInterface: aws.Int64(10),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(3),
},
},
},
},
{
InstanceType: aws.String("dl1.24xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(48),
DefaultVCpus: aws.Int64(96),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(786432),
},
GpuInfo: &ec2.GpuInfo{
Gpus: []*ec2.GpuDeviceInfo{
{
Name: aws.String("Gaudi HL-205"),
Manufacturer: aws.String("Habana"),
Count: aws.Int64(8),
MemoryInfo: &ec2.GpuDeviceMemoryInfo{
SizeInMiB: aws.Int64(32768),
},
},
},
},
InstanceStorageInfo: &ec2.InstanceStorageInfo{NvmeSupport: aws.String("required"),
TotalSizeInGB: aws.Int64(4000),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(60),
Ipv4AddressesPerInterface: aws.Int64(50),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(15),
},
{
NetworkCardIndex: aws.Int64(1),
MaximumNetworkInterfaces: aws.Int64(15),
},
{
NetworkCardIndex: aws.Int64(2),
MaximumNetworkInterfaces: aws.Int64(15),
},
{
NetworkCardIndex: aws.Int64(3),
MaximumNetworkInterfaces: aws.Int64(15),
},
},
},
},
{
InstanceType: aws.String("g4dn.8xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(16),
DefaultVCpus: aws.Int64(32),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(131072),
},
GpuInfo: &ec2.GpuInfo{
Gpus: []*ec2.GpuDeviceInfo{
{
Name: aws.String("T4"),
Manufacturer: aws.String("NVIDIA"),
Count: aws.Int64(1),
MemoryInfo: &ec2.GpuDeviceMemoryInfo{
SizeInMiB: aws.Int64(16384),
},
},
},
},
InstanceStorageInfo: &ec2.InstanceStorageInfo{NvmeSupport: aws.String("required"),
TotalSizeInGB: aws.Int64(900),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(4),
Ipv4AddressesPerInterface: aws.Int64(15),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(4),
},
},
},
},
{
InstanceType: aws.String("inf1.2xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(4),
DefaultVCpus: aws.Int64(8),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(16384),
},
InferenceAcceleratorInfo: &ec2.InferenceAcceleratorInfo{
Accelerators: []*ec2.InferenceDeviceInfo{
{
Name: aws.String("Inferentia"),
Manufacturer: aws.String("AWS"),
Count: aws.Int64(1),
},
},
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(4),
Ipv4AddressesPerInterface: aws.Int64(10),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(4),
},
},
},
},
{
InstanceType: aws.String("inf1.6xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(12),
DefaultVCpus: aws.Int64(24),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(49152),
},
InferenceAcceleratorInfo: &ec2.InferenceAcceleratorInfo{
Accelerators: []*ec2.InferenceDeviceInfo{
{
Name: aws.String("Inferentia"),
Manufacturer: aws.String("AWS"),
Count: aws.Int64(4),
},
},
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(8),
Ipv4AddressesPerInterface: aws.Int64(30),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(8),
},
},
},
},
{
InstanceType: aws.String("m5.large"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(1),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(8192),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(3),
Ipv4AddressesPerInterface: aws.Int64(10),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(3),
},
},
},
},
{
InstanceType: aws.String("m5.metal"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(true),
Hypervisor: aws.String(""),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(48),
DefaultVCpus: aws.Int64(96),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(393216),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(15),
Ipv4AddressesPerInterface: aws.Int64(50),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(15),
},
},
},
},
{
InstanceType: aws.String("m5.xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(2),
DefaultVCpus: aws.Int64(4),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(16384),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(4),
Ipv4AddressesPerInterface: aws.Int64(15),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(4),
},
},
},
},
{
InstanceType: aws.String("m6idn.32xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(64),
DefaultVCpus: aws.Int64(128),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(524288),
},
InstanceStorageInfo: &ec2.InstanceStorageInfo{NvmeSupport: aws.String("required"),
TotalSizeInGB: aws.Int64(7600),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(14),
Ipv4AddressesPerInterface: aws.Int64(50),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(7),
},
{
NetworkCardIndex: aws.Int64(1),
MaximumNetworkInterfaces: aws.Int64(7),
},
},
},
},
{
InstanceType: aws.String("p3.8xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("xen"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(16),
DefaultVCpus: aws.Int64(32),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(249856),
},
GpuInfo: &ec2.GpuInfo{
Gpus: []*ec2.GpuDeviceInfo{
{
Name: aws.String("V100"),
Manufacturer: aws.String("NVIDIA"),
Count: aws.Int64(4),
MemoryInfo: &ec2.GpuDeviceMemoryInfo{
SizeInMiB: aws.Int64(16384),
},
},
},
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(8),
Ipv4AddressesPerInterface: aws.Int64(30),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(8),
},
},
},
},
{
InstanceType: aws.String("t3.large"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(true),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(1),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(8192),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(3),
Ipv4AddressesPerInterface: aws.Int64(12),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(3),
},
},
},
},
{
InstanceType: aws.String("t4g.medium"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(true),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"arm64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(2),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(4096),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(3),
Ipv4AddressesPerInterface: aws.Int64(6),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(3),
},
},
},
},
{
InstanceType: aws.String("t4g.small"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(true),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"arm64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(2),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(2048),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(3),
Ipv4AddressesPerInterface: aws.Int64(4),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(3),
},
},
},
},
{
InstanceType: aws.String("t4g.xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(true),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"arm64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(4),
DefaultVCpus: aws.Int64(4),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(16384),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(4),
Ipv4AddressesPerInterface: aws.Int64(15),
EncryptionInTransitSupported: aws.Bool(false),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(4),
},
},
},
},
{
InstanceType: aws.String("trn1.2xlarge"),
SupportedUsageClasses: aws.StringSlice([]string{"on-demand", "spot"}),
SupportedVirtualizationTypes: aws.StringSlice([]string{"hvm"}),
BurstablePerformanceSupported: aws.Bool(false),
BareMetal: aws.Bool(false),
Hypervisor: aws.String("nitro"),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(4),
DefaultVCpus: aws.Int64(8),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(32768),
},
InstanceStorageInfo: &ec2.InstanceStorageInfo{NvmeSupport: aws.String("required"),
TotalSizeInGB: aws.Int64(474),
},
NetworkInfo: &ec2.NetworkInfo{
MaximumNetworkInterfaces: aws.Int64(4),
Ipv4AddressesPerInterface: aws.Int64(15),
EncryptionInTransitSupported: aws.Bool(true),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{
{
NetworkCardIndex: aws.Int64(0),
MaximumNetworkInterfaces: aws.Int64(4),
},
},
},
},
},
}
| 564 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator
import (
"context"
"encoding/base64"
"errors"
"fmt"
"net"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
awsclient "github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/eks/eksiface"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/transport"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/operator"
"github.com/aws/karpenter/pkg/apis/settings"
awscache "github.com/aws/karpenter/pkg/cache"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/instance"
"github.com/aws/karpenter/pkg/providers/instancetype"
"github.com/aws/karpenter/pkg/providers/launchtemplate"
"github.com/aws/karpenter/pkg/providers/pricing"
"github.com/aws/karpenter/pkg/providers/securitygroup"
"github.com/aws/karpenter/pkg/providers/subnet"
"github.com/aws/karpenter/pkg/utils/project"
)
// Operator is injected into the AWS CloudProvider's factories
type Operator struct {
*operator.Operator
Session *session.Session
UnavailableOfferingsCache *awscache.UnavailableOfferings
EC2API ec2iface.EC2API
SubnetProvider *subnet.Provider
SecurityGroupProvider *securitygroup.Provider
AMIProvider *amifamily.Provider
AMIResolver *amifamily.Resolver
LaunchTemplateProvider *launchtemplate.Provider
PricingProvider *pricing.Provider
InstanceTypesProvider *instancetype.Provider
InstanceProvider *instance.Provider
}
func NewOperator(ctx context.Context, operator *operator.Operator) (context.Context, *Operator) {
sess := withUserAgent(session.Must(session.NewSession(
request.WithRetryer(
&aws.Config{STSRegionalEndpoint: endpoints.RegionalSTSEndpoint},
awsclient.DefaultRetryer{NumMaxRetries: awsclient.DefaultRetryerMaxNumRetries},
),
)))
if *sess.Config.Region == "" {
logging.FromContext(ctx).Debug("retrieving region from IMDS")
region, err := ec2metadata.New(sess).Region()
*sess.Config.Region = lo.Must(region, err, "failed to get region from metadata server")
}
ec2api := ec2.New(sess)
if err := checkEC2Connectivity(ctx, ec2api); err != nil {
logging.FromContext(ctx).Fatalf("Checking EC2 API connectivity, %s", err)
}
logging.FromContext(ctx).With("region", *sess.Config.Region).Debugf("discovered region")
clusterEndpoint, err := ResolveClusterEndpoint(ctx, eks.New(sess))
if err != nil {
logging.FromContext(ctx).Fatalf("unable to detect the cluster endpoint, %s", err)
} else {
logging.FromContext(ctx).With("cluster-endpoint", clusterEndpoint).Debugf("discovered cluster endpoint")
}
// We perform best-effort on resolving the kube-dns IP
kubeDNSIP, err := kubeDNSIP(ctx, operator.KubernetesInterface)
if err != nil {
// If we fail to get the kube-dns IP, we don't want to crash because this causes issues with custom DNS setups
// https://github.com/aws/karpenter/issues/2787
logging.FromContext(ctx).Debugf("unable to detect the IP of the kube-dns service, %s", err)
} else {
logging.FromContext(ctx).With("kube-dns-ip", kubeDNSIP).Debugf("discovered kube dns")
}
unavailableOfferingsCache := awscache.NewUnavailableOfferings(operator.EventRecorder)
subnetProvider := subnet.NewProvider(ec2api, cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval))
securityGroupProvider := securitygroup.NewProvider(ec2api, cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval))
pricingProvider := pricing.NewProvider(
ctx,
pricing.NewAPI(sess, *sess.Config.Region),
ec2api,
*sess.Config.Region,
)
amiProvider := amifamily.NewProvider(operator.GetClient(), operator.KubernetesInterface, ssm.New(sess), ec2api,
cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval), cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval), cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval))
amiResolver := amifamily.New(amiProvider)
launchTemplateProvider := launchtemplate.NewProvider(
ctx,
cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval),
ec2api,
amiResolver,
securityGroupProvider,
subnetProvider,
lo.Must(getCABundle(operator.GetConfig())),
operator.Elected(),
kubeDNSIP,
clusterEndpoint,
)
instanceTypeProvider := instancetype.NewProvider(
*sess.Config.Region,
cache.New(awscache.InstanceTypesAndZonesTTL, awscache.DefaultCleanupInterval),
ec2api,
subnetProvider,
unavailableOfferingsCache,
pricingProvider,
)
instanceProvider := instance.NewProvider(
ctx,
aws.StringValue(sess.Config.Region),
ec2api,
unavailableOfferingsCache,
instanceTypeProvider,
subnetProvider,
launchTemplateProvider,
)
return ctx, &Operator{
Operator: operator,
Session: sess,
UnavailableOfferingsCache: unavailableOfferingsCache,
EC2API: ec2api,
SubnetProvider: subnetProvider,
SecurityGroupProvider: securityGroupProvider,
AMIProvider: amiProvider,
AMIResolver: amiResolver,
LaunchTemplateProvider: launchTemplateProvider,
PricingProvider: pricingProvider,
InstanceTypesProvider: instanceTypeProvider,
InstanceProvider: instanceProvider,
}
}
// withUserAgent adds a karpenter specific user-agent string to AWS session
func withUserAgent(sess *session.Session) *session.Session {
userAgent := fmt.Sprintf("karpenter.sh-%s", project.Version)
sess.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler(userAgent))
return sess
}
// checkEC2Connectivity makes a dry-run call to DescribeInstanceTypes. If it fails, we provide an early indicator that we
// are having issues connecting to the EC2 API.
func checkEC2Connectivity(ctx context.Context, api *ec2.EC2) error {
_, err := api.DescribeInstanceTypesWithContext(ctx, &ec2.DescribeInstanceTypesInput{DryRun: aws.Bool(true)})
var aerr awserr.Error
if errors.As(err, &aerr) && aerr.Code() == "DryRunOperation" {
return nil
}
return err
}
func ResolveClusterEndpoint(ctx context.Context, eksAPI eksiface.EKSAPI) (string, error) {
clusterEndpointFromSettings := settings.FromContext(ctx).ClusterEndpoint
if clusterEndpointFromSettings != "" {
return clusterEndpointFromSettings, nil // cluster endpoint is explicitly set
}
out, err := eksAPI.DescribeCluster(&eks.DescribeClusterInput{
Name: aws.String(settings.FromContext(ctx).ClusterName),
})
if err != nil {
return "", fmt.Errorf("failed to resolve cluster endpoint, %w", err)
}
return *out.Cluster.Endpoint, nil
}
func getCABundle(restConfig *rest.Config) (*string, error) {
// Discover CA Bundle from the REST client. We could alternatively
// have used the simpler client-go InClusterConfig() method.
// However, that only works when Karpenter is running as a Pod
// within the same cluster it's managing.
transportConfig, err := restConfig.TransportConfig()
if err != nil {
return nil, fmt.Errorf("discovering caBundle, loading transport config, %w", err)
}
_, err = transport.TLSConfigFor(transportConfig) // fills in CAData!
if err != nil {
return nil, fmt.Errorf("discovering caBundle, loading TLS config, %w", err)
}
return ptr.String(base64.StdEncoding.EncodeToString(transportConfig.TLS.CAData)), nil
}
func kubeDNSIP(ctx context.Context, kubernetesInterface kubernetes.Interface) (net.IP, error) {
if kubernetesInterface == nil {
return nil, fmt.Errorf("no K8s client provided")
}
dnsService, err := kubernetesInterface.CoreV1().Services("kube-system").Get(ctx, "kube-dns", metav1.GetOptions{})
if err != nil {
return nil, err
}
kubeDNSIP := net.ParseIP(dnsService.Spec.ClusterIP)
if kubeDNSIP == nil {
return nil, fmt.Errorf("parsing cluster IP")
}
return kubeDNSIP, nil
}
| 228 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package operator_test
import (
"context"
"errors"
"testing"
"github.com/aws/aws-sdk-go/service/eks"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
. "knative.dev/pkg/logging/testing"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/fake"
awscontext "github.com/aws/karpenter/pkg/operator"
"github.com/aws/karpenter/pkg/test"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
)
var ctx context.Context
var stop context.CancelFunc
var env *coretest.Environment
var fakeEKSAPI *fake.EKSAPI
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "CloudProvider/AWS")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
ctx, stop = context.WithCancel(ctx)
fakeEKSAPI = &fake.EKSAPI{}
})
var _ = AfterSuite(func() {
stop()
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
fakeEKSAPI.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("Operator", func() {
It("should resolve endpoint if set via configuration", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ClusterEndpoint: lo.ToPtr("https://api.test-cluster.k8s.local"),
}))
endpoint, err := awscontext.ResolveClusterEndpoint(ctx, fakeEKSAPI)
Expect(err).ToNot(HaveOccurred())
Expect(endpoint).To(Equal("https://api.test-cluster.k8s.local"))
})
It("should resolve endpoint if not set, via call to API", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ClusterEndpoint: lo.ToPtr(""),
}))
fakeEKSAPI.DescribeClusterBehaviour.Output.Set(
&eks.DescribeClusterOutput{
Cluster: &eks.Cluster{
Endpoint: lo.ToPtr("https://cluster-endpoint.test-cluster.k8s.local"),
},
},
)
endpoint, err := awscontext.ResolveClusterEndpoint(ctx, fakeEKSAPI)
Expect(err).ToNot(HaveOccurred())
Expect(endpoint).To(Equal("https://cluster-endpoint.test-cluster.k8s.local"))
})
It("should propagate error if API fails", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ClusterEndpoint: lo.ToPtr(""),
}))
fakeEKSAPI.DescribeClusterBehaviour.Error.Set(errors.New("test error"))
_, err := awscontext.ResolveClusterEndpoint(ctx, fakeEKSAPI)
Expect(err).To(HaveOccurred())
})
})
| 111 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
)
type AL2 struct {
DefaultFamily
*Options
}
// DefaultAMIs returns the AMI name, and Requirements, with an SSM query
func (a AL2) DefaultAMIs(version string) []DefaultAMIOutput {
return []DefaultAMIOutput{
{
Query: fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpDoesNotExist),
),
},
{
Query: fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-gpu/recommended/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpExists),
),
},
{
Query: fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-gpu/recommended/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpExists),
),
},
{
Query: fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-%s/recommended/image_id", version, v1alpha5.ArchitectureArm64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureArm64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpDoesNotExist),
),
},
}
}
// UserData returns the exact same string for equivalent input,
// even if elements of those inputs are in differing orders,
// guaranteeing it won't cause spurious hash differences.
// AL2 userdata also works on Ubuntu
func (a AL2) UserData(kubeletConfig *v1alpha5.KubeletConfiguration, taints []v1.Taint, labels map[string]string, caBundle *string, _ []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper {
containerRuntime := aws.String("containerd")
if kubeletConfig != nil && kubeletConfig.ContainerRuntime != nil {
containerRuntime = kubeletConfig.ContainerRuntime
}
return bootstrap.EKS{
ContainerRuntime: *containerRuntime,
Options: bootstrap.Options{
ClusterName: a.Options.ClusterName,
ClusterEndpoint: a.Options.ClusterEndpoint,
AWSENILimitedPodDensity: a.Options.AWSENILimitedPodDensity,
KubeletConfig: kubeletConfig,
Taints: taints,
Labels: labels,
CABundle: caBundle,
CustomUserData: customUserData,
},
}
}
// DefaultBlockDeviceMappings returns the default block device mappings for the AMI Family
func (a AL2) DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping {
return []*v1alpha1.BlockDeviceMapping{{
DeviceName: a.EphemeralBlockDevice(),
EBS: &DefaultEBS,
}}
}
func (a AL2) EphemeralBlockDevice() *string {
return aws.String("/dev/xvda")
}
| 107 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"context"
"fmt"
"sort"
"strings"
"time"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/ssm/ssmiface"
"github.com/mitchellh/hashstructure/v2"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/logging"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/pretty"
"github.com/aws/karpenter-core/pkg/utils/sets"
)
type Provider struct {
ssmCache *cache.Cache
ec2Cache *cache.Cache
kubernetesVersionCache *cache.Cache
ssm ssmiface.SSMAPI
kubeClient client.Client
ec2api ec2iface.EC2API
cm *pretty.ChangeMonitor
kubernetesInterface kubernetes.Interface
}
type AMI struct {
Name string
AmiID string
CreationDate string
Requirements scheduling.Requirements
}
const (
kubernetesVersionCacheKey = "kubernetesVersion"
)
func NewProvider(kubeClient client.Client, kubernetesInterface kubernetes.Interface, ssm ssmiface.SSMAPI, ec2api ec2iface.EC2API,
ssmCache, ec2Cache, kubernetesVersionCache *cache.Cache) *Provider {
return &Provider{
ssmCache: ssmCache,
ec2Cache: ec2Cache,
kubernetesVersionCache: kubernetesVersionCache,
ssm: ssm,
kubeClient: kubeClient,
ec2api: ec2api,
cm: pretty.NewChangeMonitor(),
kubernetesInterface: kubernetesInterface,
}
}
func (p *Provider) KubeServerVersion(ctx context.Context) (string, error) {
if version, ok := p.kubernetesVersionCache.Get(kubernetesVersionCacheKey); ok {
return version.(string), nil
}
serverVersion, err := p.kubernetesInterface.Discovery().ServerVersion()
if err != nil {
return "", err
}
version := fmt.Sprintf("%s.%s", serverVersion.Major, strings.TrimSuffix(serverVersion.Minor, "+"))
p.kubernetesVersionCache.SetDefault(kubernetesVersionCacheKey, version)
if p.cm.HasChanged("kubernetes-version", version) {
logging.FromContext(ctx).With("version", version).Debugf("discovered kubernetes version")
}
return version, nil
}
// MapInstanceTypes returns a map of AMIIDs that are the most recent on creationDate to compatible instancetypes
func MapInstanceTypes(amis []AMI, instanceTypes []*cloudprovider.InstanceType) map[string][]*cloudprovider.InstanceType {
amiIDs := map[string][]*cloudprovider.InstanceType{}
for _, instanceType := range instanceTypes {
for _, ami := range amis {
if err := instanceType.Requirements.Compatible(ami.Requirements); err == nil {
amiIDs[ami.AmiID] = append(amiIDs[ami.AmiID], instanceType)
break
}
}
}
return amiIDs
}
// Get Returning a list of AMIs with its associated requirements
func (p *Provider) Get(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, options *Options) ([]AMI, error) {
var err error
var amis []AMI
if len(nodeTemplate.Spec.AMISelector) == 0 {
amis, err = p.getDefaultAMIFromSSM(ctx, nodeTemplate, options)
if err != nil {
return nil, err
}
} else {
amis, err = p.getAMIsFromSelector(ctx, nodeTemplate.Spec.AMISelector)
if err != nil {
return nil, err
}
}
amis = groupAMIsByRequirements(SortAMIsByCreationDate(amis))
if p.cm.HasChanged(fmt.Sprintf("amis/%s", nodeTemplate.Name), amis) {
logging.FromContext(ctx).With("ids", amiList(amis), "count", len(amis)).Debugf("discovered amis")
}
return amis, nil
}
// groupAMIsByRequirements gets the most recent AMIs, by creation date, that have a unique set of requirements
func groupAMIsByRequirements(amis []AMI) []AMI {
var result []AMI
requirementsHash := sets.New[uint64]()
for _, ami := range amis {
hash := lo.Must(hashstructure.Hash(ami.Requirements.NodeSelectorRequirements(), hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true}))
if !requirementsHash.Has(hash) {
result = append(result, ami)
}
requirementsHash.Insert(hash)
}
return result
}
func (p *Provider) getDefaultAMIFromSSM(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, options *Options) ([]AMI, error) {
amiFamily := GetAMIFamily(nodeTemplate.Spec.AMIFamily, options)
kubernetesVersion, err := p.KubeServerVersion(ctx)
if err != nil {
return nil, fmt.Errorf("getting kubernetes version %w", err)
}
var amis []AMI
ssmRequirements := amiFamily.DefaultAMIs(kubernetesVersion)
for _, ssmOutput := range ssmRequirements {
amiID, err := p.fetchAMIsFromSSM(ctx, ssmOutput.Query)
if err != nil {
logging.FromContext(ctx).With("query", ssmOutput.Query).Errorf("discovering amis from ssm, %s", err)
continue
}
amis = append(amis, AMI{AmiID: amiID, Requirements: ssmOutput.Requirements})
}
amis, err = p.findAMINames(ctx, amis)
if err != nil {
return nil, err
}
return amis, nil
}
// Associate a list of amiIDs with there ec2 AMI names
func (p *Provider) findAMINames(ctx context.Context, amis []AMI) ([]AMI, error) {
// Creating selector filter by making a string of amiIds into a comma delineated string
ids := lo.Reduce(amis, func(agg string, item AMI, _ int) string {
return agg + item.AmiID + ","
}, "")
selector := map[string]string{"aws-ids": ids}
// Collecting the AMI details of the default AMIs from EC2
amisDetails, err := p.fetchAMIsFromEC2(ctx, selector)
if err != nil {
return nil, err
}
// matching up the AMIs details that is received from EC2 with the default AMIs
// collecting the names of the default AMIs
amis = lo.Map(amis, func(x AMI, _ int) AMI {
ami, ok := lo.Find(amisDetails, func(image *ec2.Image) bool {
return *image.ImageId == x.AmiID
})
if ok {
x.Name = *ami.Name
}
return x
})
return amis, nil
}
func (p *Provider) fetchAMIsFromSSM(ctx context.Context, ssmQuery string) (string, error) {
if id, ok := p.ssmCache.Get(ssmQuery); ok {
return id.(string), nil
}
output, err := p.ssm.GetParameterWithContext(ctx, &ssm.GetParameterInput{Name: aws.String(ssmQuery)})
if err != nil {
return "", fmt.Errorf("getting ssm parameter %q, %w", ssmQuery, err)
}
ami := aws.StringValue(output.Parameter.Value)
p.ssmCache.SetDefault(ssmQuery, ami)
return ami, nil
}
func (p *Provider) getAMIsFromSelector(ctx context.Context, selector map[string]string) (amis []AMI, err error) {
ec2AMIs, err := p.fetchAMIsFromEC2(ctx, selector)
if err != nil {
return nil, err
}
for _, ec2AMI := range ec2AMIs {
a := AMI{*ec2AMI.Name, *ec2AMI.ImageId, *ec2AMI.CreationDate, p.getRequirementsFromImage(ec2AMI)}
// Only support well-known architectures for AMI resolution
if v1alpha1.WellKnownArchitectures.Has(a.Requirements.Get(v1.LabelArchStable).Any()) {
amis = append(amis, a)
}
}
return amis, nil
}
func (p *Provider) fetchAMIsFromEC2(ctx context.Context, amiSelector map[string]string) ([]*ec2.Image, error) {
filters, owners := GetFiltersAndOwners(amiSelector)
hash, err := hashstructure.Hash(filters, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
if err != nil {
return nil, err
}
if amis, ok := p.ec2Cache.Get(fmt.Sprint(hash)); ok {
return amis.([]*ec2.Image), nil
}
describeImagesInput := &ec2.DescribeImagesInput{Owners: owners}
// Don't include filters in the Describe Images call as EC2 API doesn't allow empty filters.
if len(filters) != 0 {
describeImagesInput.Filters = filters
}
// This API is not paginated, so a single call suffices.
output, err := p.ec2api.DescribeImagesWithContext(ctx, describeImagesInput)
if err != nil {
return nil, fmt.Errorf("describing images %+v, %w", filters, err)
}
p.ec2Cache.SetDefault(fmt.Sprint(hash), output.Images)
return output.Images, nil
}
func amiList(amis []AMI) string {
var sb strings.Builder
ids := lo.Map(amis, func(a AMI, _ int) string { return a.AmiID })
if len(amis) > 25 {
sb.WriteString(strings.Join(ids[:25], ", "))
sb.WriteString(fmt.Sprintf(" and %d other(s)", len(amis)-25))
} else {
sb.WriteString(strings.Join(ids, ", "))
}
return sb.String()
}
func GetFiltersAndOwners(amiSelector map[string]string) ([]*ec2.Filter, []*string) {
var filters []*ec2.Filter
var owners []*string
imagesSet := false
for key, value := range amiSelector {
switch key {
case "aws-ids", "aws::ids":
filterValues := functional.SplitCommaSeparatedString(value)
filters = append(filters, &ec2.Filter{
Name: aws.String("image-id"),
Values: aws.StringSlice(filterValues),
})
imagesSet = true
case "aws::owners":
ownerValues := functional.SplitCommaSeparatedString(value)
owners = aws.StringSlice(ownerValues)
case "aws::name":
filters = append(filters, &ec2.Filter{
Name: aws.String("name"),
Values: []*string{aws.String(value)},
})
default:
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(value)},
})
}
}
if owners == nil && !imagesSet {
owners = []*string{aws.String("self"), aws.String("amazon")}
}
return filters, owners
}
// SortAMIsByCreationDate the AMIs are sorted by creation date in descending order.
// If creation date is nil or two AMIs have the same creation date, the AMIs will be sorted by name in ascending order.
func SortAMIsByCreationDate(amis []AMI) []AMI {
sort.Slice(amis, func(i, j int) bool {
if amis[i].CreationDate != "" || amis[j].CreationDate != "" {
itime, _ := time.Parse(time.RFC3339, amis[i].CreationDate)
jtime, _ := time.Parse(time.RFC3339, amis[j].CreationDate)
if itime.Unix() != jtime.Unix() {
return itime.Unix() >= jtime.Unix()
}
}
return amis[i].Name >= amis[j].Name
})
return amis
}
func (p *Provider) getRequirementsFromImage(ec2Image *ec2.Image) scheduling.Requirements {
requirements := scheduling.NewRequirements()
for _, tag := range ec2Image.Tags {
if v1alpha5.WellKnownLabels.Has(*tag.Key) {
requirements.Add(scheduling.NewRequirement(*tag.Key, v1.NodeSelectorOpIn, *tag.Value))
}
}
// Always add the architecture of an image as a requirement, irrespective of what's specified in EC2 tags.
architecture := *ec2Image.Architecture
if value, ok := v1alpha1.AWSToKubeArchitectures[architecture]; ok {
architecture = value
}
requirements.Add(scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, architecture))
return requirements
}
| 333 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
. "knative.dev/pkg/logging/testing"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/operator/scheme"
"github.com/aws/karpenter-core/pkg/scheduling"
coretest "github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/test"
)
var ctx context.Context
var env *coretest.Environment
var awsEnv *test.Environment
var nodeTemplate *v1alpha1.AWSNodeTemplate
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "AMISelector")
}
const (
amd64AMIName = "amd64-ami"
arm64AMIName = "arm64-ami"
amd64NvidiaAMIName = "amd64-nvidia-ami"
arm64NvidiaAMIName = "arm64-nvidia-ami"
)
var (
defaultOwners = []*string{aws.String("self"), aws.String("amazon")}
)
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
awsEnv = test.NewEnvironment(ctx, env)
})
var _ = BeforeEach(func() {
// Set up the DescribeImages API so that we can call it by ID with the mock parameters that we generate
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{
Images: []*ec2.Image{
{
Name: aws.String(amd64AMIName),
ImageId: aws.String("amd64-ami-id"),
CreationDate: aws.String(time.Now().Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String(amd64AMIName)},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String(arm64AMIName),
ImageId: aws.String("arm64-ami-id"),
CreationDate: aws.String(time.Now().Add(time.Minute).Format(time.RFC3339)),
Architecture: aws.String("arm64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String(arm64AMIName)},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String(amd64NvidiaAMIName),
ImageId: aws.String("amd64-nvidia-ami-id"),
CreationDate: aws.String(time.Now().Add(2 * time.Minute).Format(time.RFC3339)),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String(amd64NvidiaAMIName)},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
{
Name: aws.String(arm64NvidiaAMIName),
ImageId: aws.String("arm64-nvidia-ami-id"),
CreationDate: aws.String(time.Now().Add(2 * time.Minute).Format(time.RFC3339)),
Architecture: aws.String("arm64"),
Tags: []*ec2.Tag{
{Key: aws.String("Name"), Value: aws.String(arm64NvidiaAMIName)},
{Key: aws.String("foo"), Value: aws.String("bar")},
},
},
},
})
})
var _ = AfterEach(func() {
awsEnv.Reset()
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = Describe("AMI Provider", func() {
var version string
BeforeEach(func() {
version = lo.Must(awsEnv.AMIProvider.KubeServerVersion(ctx))
})
It("should succeed to resolve AMIs (AL2)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
})
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", version): amd64AMIName,
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-gpu/recommended/image_id", version): amd64NvidiaAMIName,
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-arm64/recommended/image_id", version): arm64AMIName,
}
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(4))
})
It("should succeed to resolve AMIs (Bottlerocket)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
},
})
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/x86_64/latest/image_id", version): amd64AMIName,
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/x86_64/latest/image_id", version): amd64NvidiaAMIName,
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/arm64/latest/image_id", version): arm64AMIName,
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/arm64/latest/image_id", version): arm64NvidiaAMIName,
}
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(6))
})
It("should succeed to resolve AMIs (Ubuntu)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyUbuntu,
},
})
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/canonical/ubuntu/eks/20.04/%s/stable/current/amd64/hvm/ebs-gp2/ami-id", version): amd64AMIName,
fmt.Sprintf("/aws/service/canonical/ubuntu/eks/20.04/%s/stable/current/arm64/hvm/ebs-gp2/ami-id", version): arm64AMIName,
}
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(2))
})
It("should succeed to resolve AMIs (Custom)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
})
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(0))
})
It("should succeed to partially resolve AMIs if all SSM aliases don't exist (Al2)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
})
// No GPU AMI exists here
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", version): amd64AMIName,
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2-arm64/recommended/image_id", version): arm64AMIName,
}
// Only 2 of the requirements sets for the SSM aliases will resolve
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(2))
})
It("should succeed to partially resolve AMIs if all SSM aliases don't exist (Bottlerocket)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
},
})
// No GPU AMI exists for AM64 here
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/x86_64/latest/image_id", version): amd64AMIName,
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/x86_64/latest/image_id", version): amd64NvidiaAMIName,
fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/arm64/latest/image_id", version): arm64AMIName,
}
// Only 4 of the requirements sets for the SSM aliases will resolve
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(4))
})
It("should succeed to partially resolve AMIs if all SSM aliases don't exist (Ubuntu)", func() {
nodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyUbuntu,
},
})
// No AMD64 AMI exists here
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/canonical/ubuntu/eks/20.04/%s/stable/current/arm64/hvm/ebs-gp2/ami-id", version): arm64AMIName,
}
// Only 1 of the requirements sets for the SSM aliases will resolve
amis, err := awsEnv.AMIProvider.Get(ctx, nodeTemplate, &amifamily.Options{})
Expect(err).ToNot(HaveOccurred())
Expect(amis).To(HaveLen(1))
})
Context("AMI Selectors", func() {
It("should have default owners and use tags when prefixes aren't set", func() {
amiSelector := map[string]string{
"Name": "my-ami",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(ConsistOf(defaultOwners))
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: aws.StringSlice([]string{"my-ami"}),
},
}))
})
It("should have default owners and use name when prefixed", func() {
amiSelector := map[string]string{
"aws::name": "my-ami",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(ConsistOf(defaultOwners))
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("name"),
Values: aws.StringSlice([]string{"my-ami"}),
},
}))
})
It("should not set owners when legacy ids are passed", func() {
amiSelector := map[string]string{
"aws-ids": "ami-abcd1234,ami-cafeaced",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(BeNil())
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("image-id"),
Values: aws.StringSlice([]string{
"ami-abcd1234",
"ami-cafeaced",
}),
},
}))
})
It("should not set owners when prefixed ids are passed", func() {
amiSelector := map[string]string{
"aws::ids": "ami-abcd1234,ami-cafeaced",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(BeNil())
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("image-id"),
Values: aws.StringSlice([]string{
"ami-abcd1234",
"ami-cafeaced",
}),
},
}))
})
It("should allow only specifying owners", func() {
amiSelector := map[string]string{
"aws::owners": "abcdef,123456789012",
}
_, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(ConsistOf(
[]*string{aws.String("abcdef"), aws.String("123456789012")},
))
})
It("should allow prefixed id, prefixed name, and prefixed owners", func() {
amiSelector := map[string]string{
"aws::name": "my-ami",
"aws::ids": "ami-abcd1234,ami-cafeaced",
"aws::owners": "self,amazon",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(ConsistOf(defaultOwners))
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("name"),
Values: aws.StringSlice([]string{"my-ami"}),
},
{
Name: aws.String("image-id"),
Values: aws.StringSlice([]string{
"ami-abcd1234",
"ami-cafeaced",
}),
},
}))
})
It("should allow prefixed name and prefixed owners", func() {
amiSelector := map[string]string{
"aws::name": "my-ami",
"aws::owners": "0123456789,self",
}
filters, owners := amifamily.GetFiltersAndOwners(amiSelector)
Expect(owners).Should(ConsistOf([]*string{
aws.String("0123456789"),
aws.String("self"),
}))
Expect(filters).Should(ConsistOf([]*ec2.Filter{
{
Name: aws.String("name"),
Values: aws.StringSlice([]string{"my-ami"}),
},
}))
})
It("should sort amis by creationDate", func() {
amis := []amifamily.AMI{
{
Name: "test-ami-1",
AmiID: "test-ami-1-id",
CreationDate: "2021-08-31T00:10:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-2",
AmiID: "test-ami-2-id",
CreationDate: "2021-08-31T00:12:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-3",
AmiID: "test-ami-3-id",
CreationDate: "2021-08-31T00:08:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-4",
AmiID: "test-ami-4-id",
CreationDate: "",
Requirements: scheduling.NewRequirements(),
},
}
amifamily.SortAMIsByCreationDate(amis)
Expect(amis).To(Equal(
[]amifamily.AMI{
{
Name: "test-ami-2",
AmiID: "test-ami-2-id",
CreationDate: "2021-08-31T00:12:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-1",
AmiID: "test-ami-1-id",
CreationDate: "2021-08-31T00:10:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-3",
AmiID: "test-ami-3-id",
CreationDate: "2021-08-31T00:08:42.000Z",
Requirements: scheduling.NewRequirements(),
},
{
Name: "test-ami-4",
AmiID: "test-ami-4-id",
CreationDate: "",
Requirements: scheduling.NewRequirements(),
},
},
))
})
})
})
| 400 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"fmt"
"github.com/samber/lo"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
type Bottlerocket struct {
DefaultFamily
*Options
}
// DefaultAMIs returns the AMI name, and Requirements, with an SSM query
func (b Bottlerocket) DefaultAMIs(version string) []DefaultAMIOutput {
return []DefaultAMIOutput{
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/x86_64/latest/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpDoesNotExist),
),
},
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/x86_64/latest/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpExists),
),
},
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/x86_64/latest/image_id", version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpExists),
),
},
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/%s/latest/image_id", version, v1alpha5.ArchitectureArm64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureArm64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpDoesNotExist),
),
},
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/%s/latest/image_id", version, v1alpha5.ArchitectureArm64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureArm64),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpExists),
),
},
{
Query: fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s-nvidia/%s/latest/image_id", version, v1alpha5.ArchitectureArm64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureArm64),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpExists),
),
},
}
}
// UserData returns the default userdata script for the AMI Family
func (b Bottlerocket) UserData(kubeletConfig *v1alpha5.KubeletConfiguration, taints []v1.Taint, labels map[string]string, caBundle *string, _ []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper {
return bootstrap.Bottlerocket{
Options: bootstrap.Options{
ClusterName: b.Options.ClusterName,
ClusterEndpoint: b.Options.ClusterEndpoint,
AWSENILimitedPodDensity: b.Options.AWSENILimitedPodDensity,
KubeletConfig: kubeletConfig,
Taints: taints,
Labels: labels,
CABundle: caBundle,
CustomUserData: customUserData,
},
}
}
// DefaultBlockDeviceMappings returns the default block device mappings for the AMI Family
func (b Bottlerocket) DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping {
xvdaEBS := DefaultEBS
xvdaEBS.VolumeSize = lo.ToPtr(resource.MustParse("4Gi"))
return []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &xvdaEBS,
},
{
DeviceName: b.EphemeralBlockDevice(),
EBS: &DefaultEBS,
},
}
}
func (b Bottlerocket) EphemeralBlockDevice() *string {
return aws.String("/dev/xvdb")
}
// PodsPerCoreEnabled is currently disabled for Bottlerocket AMIFamily because it does
// not currently support the podsPerCore parameter passed through the kubernetes settings TOML userData
// If a Provisioner sets the podsPerCore value when using the Bottlerocket AMIFamily in the provider,
// podsPerCore will be ignored
// https://github.com/bottlerocket-os/bottlerocket/issues/1721
// EvictionSoftEnabled is currently disabled for Bottlerocket AMIFamily because it does
// not currently support the evictionSoft parameter passed through the kubernetes settings TOML userData
// If a Provisioner sets the evictionSoft value when using the Bottlerocket AMIFamily in the provider,
// evictionSoft will be ignored
// https://github.com/bottlerocket-os/bottlerocket/issues/1445
func (b Bottlerocket) FeatureFlags() FeatureFlags {
return FeatureFlags{
UsesENILimitedMemoryOverhead: false,
PodsPerCoreEnabled: false,
EvictionSoftEnabled: false,
SupportsENILimitedPodDensity: true,
}
}
| 147 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
)
type Custom struct {
DefaultFamily
*Options
}
// UserData returns the default userdata script for the AMI Family
func (c Custom) UserData(_ *v1alpha5.KubeletConfiguration, _ []v1.Taint, _ map[string]string, _ *string, _ []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper {
return bootstrap.Custom{
Options: bootstrap.Options{
CustomUserData: customUserData,
},
}
}
func (c Custom) DefaultAMIs(_ string) []DefaultAMIOutput {
return nil
}
func (c Custom) DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping {
// By returning nil, we ensure that EC2 will automatically choose the volumes defined by the AMI
// and we don't need to describe the AMI ourselves.
return nil
}
// EphemeralBlockDevice is the block device that the pods on the node will use. For an AMI of a custom family, this is unknown
// to us.
func (c Custom) EphemeralBlockDevice() *string {
return nil
}
| 56 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"context"
"fmt"
"net"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/imdario/mergo"
"github.com/samber/lo"
core "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
)
var DefaultEBS = v1alpha1.BlockDevice{
Encrypted: aws.Bool(true),
VolumeType: aws.String(ec2.VolumeTypeGp3),
VolumeSize: lo.ToPtr(resource.MustParse("20Gi")),
}
// Resolver is able to fill-in dynamic launch template parameters
type Resolver struct {
amiProvider *Provider
}
// Options define the static launch template parameters
type Options struct {
ClusterName string
ClusterEndpoint string
AWSENILimitedPodDensity bool
InstanceProfile string
CABundle *string `hash:"ignore"`
// Level-triggered fields that may change out of sync.
SecurityGroups []v1alpha1.SecurityGroup
Tags map[string]string
Labels map[string]string `hash:"ignore"`
KubeDNSIP net.IP
AssociatePublicIPAddress *bool
}
// LaunchTemplate holds the dynamically generated launch template parameters
type LaunchTemplate struct {
*Options
UserData bootstrap.Bootstrapper
BlockDeviceMappings []*v1alpha1.BlockDeviceMapping
MetadataOptions *v1alpha1.MetadataOptions
AMIID string
InstanceTypes []*cloudprovider.InstanceType `hash:"ignore"`
DetailedMonitoring bool
}
// AMIFamily can be implemented to override the default logic for generating dynamic launch template parameters
type AMIFamily interface {
DefaultAMIs(version string) []DefaultAMIOutput
UserData(kubeletConfig *v1alpha5.KubeletConfiguration, taints []core.Taint, labels map[string]string, caBundle *string, instanceTypes []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper
DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping
DefaultMetadataOptions() *v1alpha1.MetadataOptions
EphemeralBlockDevice() *string
FeatureFlags() FeatureFlags
}
type DefaultAMIOutput struct {
Query string
Requirements scheduling.Requirements
}
// FeatureFlags describes whether the features below are enabled for a given AMIFamily
type FeatureFlags struct {
UsesENILimitedMemoryOverhead bool
PodsPerCoreEnabled bool
EvictionSoftEnabled bool
SupportsENILimitedPodDensity bool
}
// DefaultFamily provides default values for AMIFamilies that compose it
type DefaultFamily struct{}
func (d DefaultFamily) FeatureFlags() FeatureFlags {
return FeatureFlags{
UsesENILimitedMemoryOverhead: true,
PodsPerCoreEnabled: true,
EvictionSoftEnabled: true,
SupportsENILimitedPodDensity: true,
}
}
// New constructs a new launch template Resolver
func New(amiProvider *Provider) *Resolver {
return &Resolver{
amiProvider: amiProvider,
}
}
// Resolve generates launch templates using the static options and dynamically generates launch template parameters.
// Multiple ResolvedTemplates are returned based on the instanceTypes passed in to support special AMIs for certain instance types like GPUs.
func (r Resolver) Resolve(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType, options *Options) ([]*LaunchTemplate, error) {
amiFamily := GetAMIFamily(nodeTemplate.Spec.AMIFamily, options)
amis, err := r.amiProvider.Get(ctx, nodeTemplate, options)
if err != nil {
return nil, err
}
if len(amis) == 0 {
return nil, fmt.Errorf("no amis exist given constraints")
}
mappedAMIs := MapInstanceTypes(amis, instanceTypes)
if len(mappedAMIs) == 0 {
return nil, fmt.Errorf("no instance types satisfy requirements of amis %v,", amis)
}
var resolvedTemplates []*LaunchTemplate
for amiID, instanceTypes := range mappedAMIs {
maxPodsToInstanceTypes := lo.GroupBy(instanceTypes, func(instanceType *cloudprovider.InstanceType) int {
return int(instanceType.Capacity.Pods().Value())
})
// In order to support reserved ENIs for CNI custom networking setups,
// we need to pass down the max-pods calculation to the kubelet.
// This requires that we resolve a unique launch template per max-pods value.
for maxPods, instanceTypes := range maxPodsToInstanceTypes {
kubeletConfig := &v1alpha5.KubeletConfiguration{}
if machine.Spec.Kubelet != nil {
if err := mergo.Merge(kubeletConfig, machine.Spec.Kubelet); err != nil {
return nil, err
}
}
if kubeletConfig.MaxPods == nil {
kubeletConfig.MaxPods = lo.ToPtr(int32(maxPods))
}
resolved := &LaunchTemplate{
Options: options,
UserData: amiFamily.UserData(
r.defaultClusterDNS(options, kubeletConfig),
append(machine.Spec.Taints, machine.Spec.StartupTaints...),
options.Labels,
options.CABundle,
instanceTypes,
nodeTemplate.Spec.UserData,
),
BlockDeviceMappings: nodeTemplate.Spec.BlockDeviceMappings,
MetadataOptions: nodeTemplate.Spec.MetadataOptions,
DetailedMonitoring: aws.BoolValue(nodeTemplate.Spec.DetailedMonitoring),
AMIID: amiID,
InstanceTypes: instanceTypes,
}
if resolved.BlockDeviceMappings == nil {
resolved.BlockDeviceMappings = amiFamily.DefaultBlockDeviceMappings()
}
if resolved.MetadataOptions == nil {
resolved.MetadataOptions = amiFamily.DefaultMetadataOptions()
}
resolvedTemplates = append(resolvedTemplates, resolved)
}
}
return resolvedTemplates, nil
}
func GetAMIFamily(amiFamily *string, options *Options) AMIFamily {
switch aws.StringValue(amiFamily) {
case v1alpha1.AMIFamilyBottlerocket:
return &Bottlerocket{Options: options}
case v1alpha1.AMIFamilyUbuntu:
return &Ubuntu{Options: options}
case v1alpha1.AMIFamilyWindows2019:
return &Windows{Options: options, Version: v1alpha1.Windows2019, Build: v1alpha1.Windows2019Build}
case v1alpha1.AMIFamilyWindows2022:
return &Windows{Options: options, Version: v1alpha1.Windows2022, Build: v1alpha1.Windows2022Build}
case v1alpha1.AMIFamilyCustom:
return &Custom{Options: options}
default:
return &AL2{Options: options}
}
}
func (o Options) DefaultMetadataOptions() *v1alpha1.MetadataOptions {
return &v1alpha1.MetadataOptions{
HTTPEndpoint: aws.String(ec2.LaunchTemplateInstanceMetadataEndpointStateEnabled),
HTTPProtocolIPv6: aws.String(lo.Ternary(o.KubeDNSIP == nil || o.KubeDNSIP.To4() != nil, ec2.LaunchTemplateInstanceMetadataProtocolIpv6Disabled, ec2.LaunchTemplateInstanceMetadataProtocolIpv6Enabled)),
HTTPPutResponseHopLimit: aws.Int64(2),
HTTPTokens: aws.String(ec2.LaunchTemplateHttpTokensStateRequired),
}
}
func (r Resolver) defaultClusterDNS(opts *Options, kubeletConfig *v1alpha5.KubeletConfiguration) *v1alpha5.KubeletConfiguration {
if opts.KubeDNSIP == nil {
return kubeletConfig
}
if kubeletConfig != nil && len(kubeletConfig.ClusterDNS) != 0 {
return kubeletConfig
}
if kubeletConfig == nil {
return &v1alpha5.KubeletConfiguration{
ClusterDNS: []string{opts.KubeDNSIP.String()},
}
}
newKubeletConfig := kubeletConfig.DeepCopy()
newKubeletConfig.ClusterDNS = []string{opts.KubeDNSIP.String()}
return newKubeletConfig
}
| 219 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
)
type Ubuntu struct {
DefaultFamily
*Options
}
// DefaultAMIs returns the AMI name, and Requirements, with an SSM query
func (u Ubuntu) DefaultAMIs(version string) []DefaultAMIOutput {
return []DefaultAMIOutput{
{
Query: fmt.Sprintf("/aws/service/canonical/ubuntu/eks/20.04/%s/stable/current/%s/hvm/ebs-gp2/ami-id", version, v1alpha5.ArchitectureAmd64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
),
},
{
Query: fmt.Sprintf("/aws/service/canonical/ubuntu/eks/20.04/%s/stable/current/%s/hvm/ebs-gp2/ami-id", version, v1alpha5.ArchitectureArm64),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureArm64),
),
},
}
}
// UserData returns the default userdata script for the AMI Family
func (u Ubuntu) UserData(kubeletConfig *v1alpha5.KubeletConfiguration, taints []v1.Taint, labels map[string]string, caBundle *string, _ []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper {
return bootstrap.EKS{
Options: bootstrap.Options{
ClusterName: u.Options.ClusterName,
ClusterEndpoint: u.Options.ClusterEndpoint,
AWSENILimitedPodDensity: u.Options.AWSENILimitedPodDensity,
KubeletConfig: kubeletConfig,
Taints: taints,
Labels: labels,
CABundle: caBundle,
CustomUserData: customUserData,
},
}
}
// DefaultBlockDeviceMappings returns the default block device mappings for the AMI Family
func (u Ubuntu) DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping {
return []*v1alpha1.BlockDeviceMapping{{
DeviceName: u.EphemeralBlockDevice(),
EBS: &DefaultEBS,
}}
}
func (u Ubuntu) EphemeralBlockDevice() *string {
return aws.String("/dev/sda1")
}
| 81 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package amifamily
import (
"fmt"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
type Windows struct {
DefaultFamily
*Options
Version string
Build string
}
func (w Windows) DefaultAMIs(version string) []DefaultAMIOutput {
return []DefaultAMIOutput{
{
Query: fmt.Sprintf("/aws/service/ami-windows-latest/Windows_Server-%s-English-%s-EKS_Optimized-%s/image_id", w.Version, v1alpha1.WindowsCore, version),
Requirements: scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, v1alpha5.ArchitectureAmd64),
scheduling.NewRequirement(v1.LabelOSStable, v1.NodeSelectorOpIn, string(v1.Windows)),
scheduling.NewRequirement(v1.LabelWindowsBuild, v1.NodeSelectorOpIn, w.Build),
),
},
}
}
// UserData returns the default userdata script for the AMI Family
func (w Windows) UserData(kubeletConfig *v1alpha5.KubeletConfiguration, taints []v1.Taint, labels map[string]string, caBundle *string, _ []*cloudprovider.InstanceType, customUserData *string) bootstrap.Bootstrapper {
return bootstrap.Windows{
Options: bootstrap.Options{
ClusterName: w.Options.ClusterName,
ClusterEndpoint: w.Options.ClusterEndpoint,
KubeletConfig: kubeletConfig,
Taints: taints,
Labels: labels,
CABundle: caBundle,
CustomUserData: customUserData,
},
}
}
// DefaultBlockDeviceMappings returns the default block device mappings for the AMI Family
func (w Windows) DefaultBlockDeviceMappings() []*v1alpha1.BlockDeviceMapping {
sda1EBS := DefaultEBS
sda1EBS.VolumeSize = lo.ToPtr(resource.MustParse("50Gi"))
return []*v1alpha1.BlockDeviceMapping{{
DeviceName: w.EphemeralBlockDevice(),
EBS: &sda1EBS,
}}
}
func (w Windows) EphemeralBlockDevice() *string {
return aws.String("/dev/sda1")
}
func (w Windows) FeatureFlags() FeatureFlags {
return FeatureFlags{
UsesENILimitedMemoryOverhead: false,
PodsPerCoreEnabled: true,
EvictionSoftEnabled: true,
SupportsENILimitedPodDensity: false,
}
}
| 94 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"fmt"
"sort"
"strings"
"github.com/samber/lo"
core "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/utils/resources"
)
// Options is the node bootstrapping parameters passed from Karpenter to the provisioning node
type Options struct {
ClusterName string
ClusterEndpoint string
KubeletConfig *v1alpha5.KubeletConfiguration
Taints []core.Taint `hash:"set"`
Labels map[string]string `hash:"set"`
CABundle *string
AWSENILimitedPodDensity bool
ContainerRuntime *string
CustomUserData *string
}
func (o Options) kubeletExtraArgs() (args []string) {
args = append(args, o.nodeLabelArg(), o.nodeTaintArg())
if o.KubeletConfig == nil {
return lo.Compact(args)
}
if o.KubeletConfig.MaxPods != nil {
args = append(args, fmt.Sprintf("--max-pods=%d", ptr.Int32Value(o.KubeletConfig.MaxPods)))
}
if o.KubeletConfig.PodsPerCore != nil {
args = append(args, fmt.Sprintf("--pods-per-core=%d", ptr.Int32Value(o.KubeletConfig.PodsPerCore)))
}
// We have to convert some of these maps so that their values return the correct string
args = append(args, joinParameterArgs("--system-reserved", resources.StringMap(o.KubeletConfig.SystemReserved), "="))
args = append(args, joinParameterArgs("--kube-reserved", resources.StringMap(o.KubeletConfig.KubeReserved), "="))
args = append(args, joinParameterArgs("--eviction-hard", o.KubeletConfig.EvictionHard, "<"))
args = append(args, joinParameterArgs("--eviction-soft", o.KubeletConfig.EvictionSoft, "<"))
args = append(args, joinParameterArgs("--eviction-soft-grace-period", lo.MapValues(o.KubeletConfig.EvictionSoftGracePeriod, func(v metav1.Duration, _ string) string { return v.Duration.String() }), "="))
if o.KubeletConfig.EvictionMaxPodGracePeriod != nil {
args = append(args, fmt.Sprintf("--eviction-max-pod-grace-period=%d", ptr.Int32Value(o.KubeletConfig.EvictionMaxPodGracePeriod)))
}
if o.KubeletConfig.ImageGCHighThresholdPercent != nil {
args = append(args, fmt.Sprintf("--image-gc-high-threshold=%d", ptr.Int32Value(o.KubeletConfig.ImageGCHighThresholdPercent)))
}
if o.KubeletConfig.ImageGCLowThresholdPercent != nil {
args = append(args, fmt.Sprintf("--image-gc-low-threshold=%d", ptr.Int32Value(o.KubeletConfig.ImageGCLowThresholdPercent)))
}
if o.KubeletConfig.CPUCFSQuota != nil {
args = append(args, fmt.Sprintf("--cpu-cfs-quota=%t", lo.FromPtr(o.KubeletConfig.CPUCFSQuota)))
}
return lo.Compact(args)
}
func (o Options) nodeTaintArg() string {
if len(o.Taints) == 0 {
return ""
}
var taintStrings []string
for _, taint := range o.Taints {
taintStrings = append(taintStrings, fmt.Sprintf("%s=%s:%s", taint.Key, taint.Value, taint.Effect))
}
return fmt.Sprintf("--register-with-taints=%q", strings.Join(taintStrings, ","))
}
func (o Options) nodeLabelArg() string {
if len(o.Labels) == 0 {
return ""
}
var labelStrings []string
keys := lo.Keys(o.Labels)
sort.Strings(keys) // ensures this list is deterministic, for easy testing.
for _, key := range keys {
if v1alpha5.LabelDomainExceptions.Has(key) {
continue
}
labelStrings = append(labelStrings, fmt.Sprintf("%s=%v", key, o.Labels[key]))
}
return fmt.Sprintf("--node-labels=%q", strings.Join(labelStrings, ","))
}
// joinParameterArgs joins a map of keys and values by their separator. The separator will sit between the
// arguments in a comma-separated list i.e. arg1<sep>val1,arg2<sep>val2
func joinParameterArgs[K comparable, V any](name string, m map[K]V, separator string) string {
var args []string
for k, v := range m {
args = append(args, fmt.Sprintf("%v%s%v", k, separator, v))
}
if len(args) > 0 {
return fmt.Sprintf("%s=%q", name, strings.Join(args, ","))
}
return ""
}
// Bootstrapper can be implemented to generate a bootstrap script
// that uses the params from the Bootstrap type for a specific
// bootstrapping method.
// Examples are the Bottlerocket config and the eks-bootstrap script
type Bootstrapper interface {
Script() (string, error)
}
| 126 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"encoding/base64"
"fmt"
"strconv"
"knative.dev/pkg/ptr"
"github.com/imdario/mergo"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/aws-sdk-go/aws"
)
type Bottlerocket struct {
Options
}
// nolint:gocyclo
func (b Bottlerocket) Script() (string, error) {
s, err := NewBottlerocketConfig(b.CustomUserData)
if err != nil {
return "", fmt.Errorf("invalid UserData %w", err)
}
// Karpenter will overwrite settings present inside custom UserData
// based on other fields specified in the provisioner
s.Settings.Kubernetes.ClusterName = &b.ClusterName
s.Settings.Kubernetes.APIServer = &b.ClusterEndpoint
s.Settings.Kubernetes.ClusterCertificate = b.CABundle
if err := mergo.MergeWithOverwrite(&s.Settings.Kubernetes.NodeLabels, b.Labels); err != nil {
return "", err
}
// Backwards compatibility for AWSENILimitedPodDensity flag
if b.KubeletConfig != nil && b.KubeletConfig.MaxPods != nil {
s.Settings.Kubernetes.MaxPods = aws.Int(int(ptr.Int32Value(b.KubeletConfig.MaxPods)))
} else if !b.AWSENILimitedPodDensity {
s.Settings.Kubernetes.MaxPods = aws.Int(110)
}
if b.KubeletConfig != nil {
if len(b.KubeletConfig.ClusterDNS) > 0 {
s.Settings.Kubernetes.ClusterDNSIP = &b.KubeletConfig.ClusterDNS[0]
}
if b.KubeletConfig.SystemReserved != nil {
s.Settings.Kubernetes.SystemReserved = resources.StringMap(b.KubeletConfig.SystemReserved)
}
if b.KubeletConfig.KubeReserved != nil {
s.Settings.Kubernetes.KubeReserved = resources.StringMap(b.KubeletConfig.KubeReserved)
}
if b.KubeletConfig.EvictionHard != nil {
s.Settings.Kubernetes.EvictionHard = b.KubeletConfig.EvictionHard
}
if b.KubeletConfig.ImageGCHighThresholdPercent != nil {
s.Settings.Kubernetes.ImageGCHighThresholdPercent = lo.ToPtr(strconv.FormatInt(int64(*b.KubeletConfig.ImageGCHighThresholdPercent), 10))
}
if b.KubeletConfig.ImageGCLowThresholdPercent != nil {
s.Settings.Kubernetes.ImageGCLowThresholdPercent = lo.ToPtr(strconv.FormatInt(int64(*b.KubeletConfig.ImageGCLowThresholdPercent), 10))
}
}
s.Settings.Kubernetes.NodeTaints = map[string][]string{}
for _, taint := range b.Taints {
s.Settings.Kubernetes.NodeTaints[taint.Key] = append(s.Settings.Kubernetes.NodeTaints[taint.Key], fmt.Sprintf("%s:%s", taint.Value, taint.Effect))
}
script, err := s.MarshalTOML()
if err != nil {
return "", fmt.Errorf("constructing toml UserData %w", err)
}
return base64.StdEncoding.EncodeToString(script), nil
}
| 89 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"github.com/pelletier/go-toml/v2"
)
func NewBottlerocketConfig(userdata *string) (*BottlerocketConfig, error) {
c := &BottlerocketConfig{}
if userdata == nil {
return c, nil
}
if err := c.UnmarshalTOML([]byte(*userdata)); err != nil {
return c, err
}
return c, nil
}
// BottlerocketConfig is the root of the bottlerocket config, see more here https://github.com/bottlerocket-os/bottlerocket#using-user-data
type BottlerocketConfig struct {
SettingsRaw map[string]interface{} `toml:"settings"`
Settings BottlerocketSettings `toml:"-"`
}
// BottlerocketSettings is a subset of all configuration in https://github.com/bottlerocket-os/bottlerocket/blob/develop/sources/models/src/aws-k8s-1.22/mod.rs
// These settings apply across all K8s versions that karpenter supports.
type BottlerocketSettings struct {
Kubernetes BottlerocketKubernetes `toml:"kubernetes"`
}
// BottlerocketKubernetes is k8s specific configuration for bottlerocket api
type BottlerocketKubernetes struct {
APIServer *string `toml:"api-server"`
CloudProvider *string `toml:"cloud-provider"`
ClusterCertificate *string `toml:"cluster-certificate"`
ClusterName *string `toml:"cluster-name"`
ClusterDNSIP *string `toml:"cluster-dns-ip,omitempty"`
NodeLabels map[string]string `toml:"node-labels,omitempty"`
NodeTaints map[string][]string `toml:"node-taints,omitempty"`
MaxPods *int `toml:"max-pods,omitempty"`
StaticPods map[string]BottlerocketStaticPod `toml:"static-pods,omitempty"`
EvictionHard map[string]string `toml:"eviction-hard,omitempty"`
KubeReserved map[string]string `toml:"kube-reserved,omitempty"`
SystemReserved map[string]string `toml:"system-reserved,omitempty"`
AllowedUnsafeSysctls []string `toml:"allowed-unsafe-sysctls,omitempty"`
ServerTLSBootstrap *bool `toml:"server-tls-bootstrap,omitempty"`
RegistryQPS *int `toml:"registry-qps,omitempty"`
RegistryBurst *int `toml:"registry-burst,omitempty"`
EventQPS *int `toml:"event-qps,omitempty"`
EventBurst *int `toml:"event-burst,omitempty"`
KubeAPIQPS *int `toml:"kube-api-qps,omitempty"`
KubeAPIBurst *int `toml:"kube-api-burst,omitempty"`
ContainerLogMaxSize *string `toml:"container-log-max-size,omitempty"`
ContainerLogMaxFiles *int `toml:"container-log-max-files,omitempty"`
CPUManagerPolicy *string `toml:"cpu-manager-policy,omitempty"`
CPUManagerReconcilePeriod *string `toml:"cpu-manager-reconcile-period,omitempty"`
TopologyManagerScope *string `toml:"topology-manager-scope,omitempty"`
ImageGCHighThresholdPercent *string `toml:"image-gc-high-threshold-percent,omitempty"`
ImageGCLowThresholdPercent *string `toml:"image-gc-low-threshold-percent,omitempty"`
}
type BottlerocketStaticPod struct {
Enabled *bool `toml:"enabled,omitempty"`
Manifest *string `toml:"manifest,omitempty"`
}
func (c *BottlerocketConfig) UnmarshalTOML(data []byte) error {
// unmarshal known settings
s := struct {
Settings BottlerocketSettings `toml:"settings"`
}{}
if err := toml.Unmarshal(data, &s); err != nil {
return err
}
// unmarshal untyped settings
if err := toml.Unmarshal(data, c); err != nil {
return err
}
c.Settings = s.Settings
return nil
}
func (c *BottlerocketConfig) MarshalTOML() ([]byte, error) {
if c.SettingsRaw == nil {
c.SettingsRaw = map[string]interface{}{}
}
c.SettingsRaw["kubernetes"] = c.Settings.Kubernetes
return toml.Marshal(c)
}
| 103 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"encoding/base64"
"github.com/aws/aws-sdk-go/aws"
)
type Custom struct {
Options
}
func (e Custom) Script() (string, error) {
return base64.StdEncoding.EncodeToString([]byte(aws.StringValue(e.Options.CustomUserData))), nil
}
| 30 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net"
"net/mail"
"net/textproto"
"strings"
"github.com/samber/lo"
)
type EKS struct {
Options
ContainerRuntime string
}
const (
Boundary = "//"
MIMEVersionHeader = "MIME-Version: 1.0"
MIMEContentTypeHeaderTemplate = "Content-Type: multipart/mixed; boundary=\"%s\""
)
func (e EKS) Script() (string, error) {
userData, err := e.mergeCustomUserData(lo.Compact([]string{lo.FromPtr(e.CustomUserData), e.eksBootstrapScript()})...)
if err != nil {
return "", err
}
// The mime/multipart package adds carriage returns, while the rest of our logic does not. Remove all
// carriage returns for consistency.
return base64.StdEncoding.EncodeToString([]byte(strings.ReplaceAll(userData, "\r", ""))), nil
}
//nolint:gocyclo
func (e EKS) eksBootstrapScript() string {
var caBundleArg string
if e.CABundle != nil {
caBundleArg = fmt.Sprintf("--b64-cluster-ca '%s'", *e.CABundle)
}
var userData bytes.Buffer
userData.WriteString("#!/bin/bash -xe\n")
userData.WriteString("exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1\n")
// Due to the way bootstrap.sh is written, parameters should not be passed to it with an equal sign
userData.WriteString(fmt.Sprintf("/etc/eks/bootstrap.sh '%s' --apiserver-endpoint '%s' %s", e.ClusterName, e.ClusterEndpoint, caBundleArg))
if e.isIPv6() {
userData.WriteString(" \\\n--ip-family ipv6")
}
if e.ContainerRuntime != "" {
userData.WriteString(fmt.Sprintf(" \\\n--container-runtime %s", e.ContainerRuntime))
}
if e.KubeletConfig != nil && len(e.KubeletConfig.ClusterDNS) > 0 {
userData.WriteString(fmt.Sprintf(" \\\n--dns-cluster-ip '%s'", e.KubeletConfig.ClusterDNS[0]))
}
if (e.KubeletConfig != nil && e.KubeletConfig.MaxPods != nil) || !e.AWSENILimitedPodDensity {
userData.WriteString(" \\\n--use-max-pods false")
}
if args := e.kubeletExtraArgs(); len(args) > 0 {
userData.WriteString(fmt.Sprintf(" \\\n--kubelet-extra-args '%s'", strings.Join(args, " ")))
}
return userData.String()
}
// kubeletExtraArgs for the EKS bootstrap.sh script uses the concept of ENI-limited pod density to set pods
// If this argument is explicitly disabled, then set the max-pods value on the kubelet to the static value of 110
func (e EKS) kubeletExtraArgs() []string {
args := e.Options.kubeletExtraArgs()
// Set the static value for --max-pods to 110 when AWSENILimitedPodDensity is explicitly disabled and the value isn't set
if !e.AWSENILimitedPodDensity && (e.KubeletConfig == nil || e.KubeletConfig.MaxPods == nil) {
args = append(args, "--max-pods=110")
}
return args
}
func (e EKS) mergeCustomUserData(userDatas ...string) (string, error) {
var outputBuffer bytes.Buffer
writer := multipart.NewWriter(&outputBuffer)
if err := writer.SetBoundary(Boundary); err != nil {
return "", fmt.Errorf("defining boundary for merged user data %w", err)
}
outputBuffer.WriteString(MIMEVersionHeader + "\n")
outputBuffer.WriteString(fmt.Sprintf(MIMEContentTypeHeaderTemplate, Boundary) + "\n\n")
for _, userData := range userDatas {
mimedUserData, err := e.mimeify(userData)
if err != nil {
return "", err
}
if err := copyCustomUserDataParts(writer, mimedUserData); err != nil {
return "", err
}
}
writer.Close()
return outputBuffer.String(), nil
}
func (e EKS) isIPv6() bool {
if e.KubeletConfig == nil || len(e.KubeletConfig.ClusterDNS) == 0 {
return false
}
return net.ParseIP(e.KubeletConfig.ClusterDNS[0]).To4() == nil
}
// mimeify returns userData in a mime format
// if the userData passed in is already in a mime format, then the input is returned without modification
func (e EKS) mimeify(customUserData string) (string, error) {
if strings.HasPrefix(strings.TrimSpace(customUserData), "MIME-Version:") {
return customUserData, nil
}
var outputBuffer bytes.Buffer
writer := multipart.NewWriter(&outputBuffer)
outputBuffer.WriteString(MIMEVersionHeader + "\n")
outputBuffer.WriteString(fmt.Sprintf(MIMEContentTypeHeaderTemplate, writer.Boundary()) + "\n\n")
partWriter, err := writer.CreatePart(textproto.MIMEHeader{
"Content-Type": []string{`text/x-shellscript; charset="us-ascii"`},
})
if err != nil {
return "", fmt.Errorf("creating multi-part section from custom user-data: %w", err)
}
_, err = partWriter.Write([]byte(customUserData))
if err != nil {
return "", fmt.Errorf("writing custom user-data input: %w", err)
}
writer.Close()
return outputBuffer.String(), nil
}
// copyCustomUserDataParts reads the mime parts in the userData passed in and writes
// to a new mime part in the passed in writer.
func copyCustomUserDataParts(writer *multipart.Writer, customUserData string) error {
if customUserData == "" {
// No custom user data specified, so nothing to copy over.
return nil
}
reader, err := getMultiPartReader(customUserData)
if err != nil {
return fmt.Errorf("parsing custom user data input %w", err)
}
for {
p, err := reader.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("parsing custom user data input %w", err)
}
slurp, err := io.ReadAll(p)
if err != nil {
return fmt.Errorf("parsing custom user data input %w", err)
}
partWriter, err := writer.CreatePart(p.Header)
if err != nil {
return fmt.Errorf("parsing custom user data input %w", err)
}
_, err = partWriter.Write(slurp)
if err != nil {
return fmt.Errorf("parsing custom user data input %w", err)
}
}
return nil
}
func getMultiPartReader(userData string) (*multipart.Reader, error) {
mailMsg, err := mail.ReadMessage(strings.NewReader(userData))
if err != nil {
return nil, fmt.Errorf("unreadable user data %w", err)
}
mediaType, params, err := mime.ParseMediaType(mailMsg.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("user data does not define a content-type header %w", err)
}
if !strings.HasPrefix(mediaType, "multipart/") {
return nil, fmt.Errorf("user data is not in multipart MIME format")
}
return multipart.NewReader(mailMsg.Body, params["boundary"]), nil
}
| 196 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package bootstrap
import (
"bytes"
"encoding/base64"
"fmt"
"strings"
)
type Windows struct {
Options
}
// nolint:gocyclo
func (w Windows) Script() (string, error) {
var userData bytes.Buffer
userData.WriteString("<powershell>\n")
userData.WriteString("[string]$EKSBootstrapScriptFile = \"$env:ProgramFiles\\Amazon\\EKS\\Start-EKSBootstrap.ps1\"\n")
userData.WriteString(fmt.Sprintf(`& $EKSBootstrapScriptFile -EKSClusterName '%s' -APIServerEndpoint '%s'`, w.ClusterName, w.ClusterEndpoint))
if w.CABundle != nil {
userData.WriteString(fmt.Sprintf(` -Base64ClusterCA '%s'`, *w.CABundle))
}
if args := w.kubeletExtraArgs(); len(args) > 0 {
userData.WriteString(fmt.Sprintf(` -KubeletExtraArgs '%s'`, strings.Join(args, " ")))
}
if w.KubeletConfig != nil && len(w.KubeletConfig.ClusterDNS) > 0 {
userData.WriteString(fmt.Sprintf(` -DNSClusterIP '%s'`, w.KubeletConfig.ClusterDNS[0]))
}
if w.KubeletConfig != nil && w.KubeletConfig.ContainerRuntime != nil {
userData.WriteString(fmt.Sprintf(` -ContainerRuntime '%s'`, *w.KubeletConfig.ContainerRuntime))
}
userData.WriteString("\n</powershell>")
return base64.StdEncoding.EncodeToString(userData.Bytes()), nil
}
| 49 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instance
import (
"context"
"errors"
"fmt"
"math"
"sort"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/logging"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/batcher"
"github.com/aws/karpenter/pkg/cache"
awserrors "github.com/aws/karpenter/pkg/errors"
"github.com/aws/karpenter/pkg/providers/instancetype"
"github.com/aws/karpenter/pkg/providers/launchtemplate"
"github.com/aws/karpenter/pkg/providers/subnet"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
)
var (
// MaxInstanceTypes defines the number of instance type options to pass to CreateFleet
MaxInstanceTypes = 60
instanceTypeFlexibilityThreshold = 5 // falling back to on-demand without flexibility risks insufficient capacity errors
instanceStateFilter = &ec2.Filter{
Name: aws.String("instance-state-name"),
Values: aws.StringSlice([]string{ec2.InstanceStateNamePending, ec2.InstanceStateNameRunning, ec2.InstanceStateNameStopping, ec2.InstanceStateNameStopped, ec2.InstanceStateNameShuttingDown}),
}
)
type Provider struct {
region string
ec2api ec2iface.EC2API
unavailableOfferings *cache.UnavailableOfferings
instanceTypeProvider *instancetype.Provider
subnetProvider *subnet.Provider
launchTemplateProvider *launchtemplate.Provider
ec2Batcher *batcher.EC2API
}
func NewProvider(ctx context.Context, region string, ec2api ec2iface.EC2API, unavailableOfferings *cache.UnavailableOfferings,
instanceTypeProvider *instancetype.Provider, subnetProvider *subnet.Provider, launchTemplateProvider *launchtemplate.Provider) *Provider {
return &Provider{
region: region,
ec2api: ec2api,
unavailableOfferings: unavailableOfferings,
instanceTypeProvider: instanceTypeProvider,
subnetProvider: subnetProvider,
launchTemplateProvider: launchTemplateProvider,
ec2Batcher: batcher.EC2(ctx, ec2api),
}
}
func (p *Provider) Create(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType) (*Instance, error) {
instanceTypes = p.filterInstanceTypes(machine, instanceTypes)
instanceTypes = orderInstanceTypesByPrice(instanceTypes, scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...))
if len(instanceTypes) > MaxInstanceTypes {
instanceTypes = instanceTypes[0:MaxInstanceTypes]
}
tags := getTags(ctx, nodeTemplate, machine)
fleetInstance, err := p.launchInstance(ctx, nodeTemplate, machine, instanceTypes, tags)
if awserrors.IsLaunchTemplateNotFound(err) {
// retry once if launch template is not found. This allows karpenter to generate a new LT if the
// cache was out-of-sync on the first try
fleetInstance, err = p.launchInstance(ctx, nodeTemplate, machine, instanceTypes, tags)
}
if err != nil {
return nil, err
}
return NewInstanceFromFleet(fleetInstance, tags), nil
}
func (p *Provider) Link(ctx context.Context, id, provisionerName string) error {
_, err := p.ec2api.CreateTagsWithContext(ctx, &ec2.CreateTagsInput{
Resources: aws.StringSlice([]string{id}),
Tags: []*ec2.Tag{
{
Key: aws.String(v1alpha5.MachineManagedByAnnotationKey),
Value: aws.String(settings.FromContext(ctx).ClusterName),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisionerName),
},
},
})
if err != nil {
if awserrors.IsNotFound(err) {
return cloudprovider.NewMachineNotFoundError(fmt.Errorf("linking tags, %w", err))
}
return fmt.Errorf("linking tags, %w", err)
}
return nil
}
func (p *Provider) Get(ctx context.Context, id string) (*Instance, error) {
out, err := p.ec2Batcher.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
InstanceIds: aws.StringSlice([]string{id}),
Filters: []*ec2.Filter{instanceStateFilter},
})
if awserrors.IsNotFound(err) {
return nil, cloudprovider.NewMachineNotFoundError(err)
}
if err != nil {
return nil, fmt.Errorf("failed to describe ec2 instances, %w", err)
}
instances, err := instancesFromOutput(out)
if err != nil {
return nil, fmt.Errorf("getting instances from output, %w", err)
}
if len(instances) != 1 {
return nil, fmt.Errorf("expected a single instance, %w", err)
}
return instances[0], nil
}
func (p *Provider) List(ctx context.Context) ([]*Instance, error) {
var out = &ec2.DescribeInstancesOutput{}
err := p.ec2api.DescribeInstancesPagesWithContext(ctx, &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag-key"),
Values: aws.StringSlice([]string{v1alpha5.ProvisionerNameLabelKey}),
},
{
Name: aws.String("tag-key"),
Values: aws.StringSlice([]string{fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName)}),
},
instanceStateFilter,
},
}, func(page *ec2.DescribeInstancesOutput, _ bool) bool {
out.Reservations = append(out.Reservations, page.Reservations...)
return true
})
if err != nil {
return nil, fmt.Errorf("describing ec2 instances, %w", err)
}
instances, err := instancesFromOutput(out)
return instances, cloudprovider.IgnoreMachineNotFoundError(err)
}
func (p *Provider) Delete(ctx context.Context, id string) error {
if _, err := p.ec2Batcher.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: []*string{aws.String(id)},
}); err != nil {
if awserrors.IsNotFound(err) {
return cloudprovider.NewMachineNotFoundError(fmt.Errorf("instance already terminated"))
}
if _, e := p.Get(ctx, id); err != nil {
if cloudprovider.IsMachineNotFoundError(e) {
return e
}
err = multierr.Append(err, e)
}
return fmt.Errorf("terminating instance, %w", err)
}
return nil
}
func (p *Provider) launchInstance(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType, tags map[string]string) (*ec2.CreateFleetInstance, error) {
capacityType := p.getCapacityType(machine, instanceTypes)
zonalSubnets, err := p.subnetProvider.ZonalSubnetsForLaunch(ctx, nodeTemplate, instanceTypes, capacityType)
if err != nil {
return nil, fmt.Errorf("getting subnets, %w", err)
}
// Get Launch Template Configs, which may differ due to GPU or Architecture requirements
launchTemplateConfigs, err := p.getLaunchTemplateConfigs(ctx, nodeTemplate, machine, instanceTypes, zonalSubnets, capacityType, tags)
if err != nil {
return nil, fmt.Errorf("getting launch template configs, %w", err)
}
if err := p.checkODFallback(machine, instanceTypes, launchTemplateConfigs); err != nil {
logging.FromContext(ctx).Warn(err.Error())
}
// Create fleet
createFleetInput := &ec2.CreateFleetInput{
Type: aws.String(ec2.FleetTypeInstant),
Context: nodeTemplate.Spec.Context,
LaunchTemplateConfigs: launchTemplateConfigs,
TargetCapacitySpecification: &ec2.TargetCapacitySpecificationRequest{
DefaultTargetCapacityType: aws.String(capacityType),
TotalTargetCapacity: aws.Int64(1),
},
TagSpecifications: []*ec2.TagSpecification{
{ResourceType: aws.String(ec2.ResourceTypeInstance), Tags: utils.MergeTags(tags)},
{ResourceType: aws.String(ec2.ResourceTypeVolume), Tags: utils.MergeTags(tags)},
{ResourceType: aws.String(ec2.ResourceTypeFleet), Tags: utils.MergeTags(tags)},
},
}
if capacityType == v1alpha5.CapacityTypeSpot {
createFleetInput.SpotOptions = &ec2.SpotOptionsRequest{AllocationStrategy: aws.String(ec2.SpotAllocationStrategyPriceCapacityOptimized)}
} else {
createFleetInput.OnDemandOptions = &ec2.OnDemandOptionsRequest{AllocationStrategy: aws.String(ec2.FleetOnDemandAllocationStrategyLowestPrice)}
}
createFleetOutput, err := p.ec2Batcher.CreateFleet(ctx, createFleetInput)
p.subnetProvider.UpdateInflightIPs(createFleetInput, createFleetOutput, instanceTypes, lo.Values(zonalSubnets), capacityType)
if err != nil {
if awserrors.IsLaunchTemplateNotFound(err) {
for _, lt := range launchTemplateConfigs {
p.launchTemplateProvider.Invalidate(ctx, aws.StringValue(lt.LaunchTemplateSpecification.LaunchTemplateName), aws.StringValue(lt.LaunchTemplateSpecification.LaunchTemplateId))
}
return nil, fmt.Errorf("creating fleet %w", err)
}
var reqFailure awserr.RequestFailure
if errors.As(err, &reqFailure) {
return nil, fmt.Errorf("creating fleet %w (%s)", err, reqFailure.RequestID())
}
return nil, fmt.Errorf("creating fleet %w", err)
}
p.updateUnavailableOfferingsCache(ctx, createFleetOutput.Errors, capacityType)
if len(createFleetOutput.Instances) == 0 || len(createFleetOutput.Instances[0].InstanceIds) == 0 {
return nil, combineFleetErrors(createFleetOutput.Errors)
}
return createFleetOutput.Instances[0], nil
}
func getTags(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine) map[string]string {
overridableTags := map[string]string{
"Name": fmt.Sprintf("%s/%s", v1alpha5.ProvisionerNameLabelKey, machine.Labels[v1alpha5.ProvisionerNameLabelKey]),
}
staticTags := map[string]string{
fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(ctx).ClusterName): "owned",
v1alpha5.ProvisionerNameLabelKey: machine.Labels[v1alpha5.ProvisionerNameLabelKey],
v1alpha5.MachineManagedByAnnotationKey: settings.FromContext(ctx).ClusterName,
}
return lo.Assign(overridableTags, settings.FromContext(ctx).Tags, nodeTemplate.Spec.Tags, staticTags)
}
func (p *Provider) checkODFallback(machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType, launchTemplateConfigs []*ec2.FleetLaunchTemplateConfigRequest) error {
// only evaluate for on-demand fallback if the capacity type for the request is OD and both OD and spot are allowed in requirements
if p.getCapacityType(machine, instanceTypes) != v1alpha5.CapacityTypeOnDemand || !scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...).Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeSpot) {
return nil
}
// loop through the LT configs for currently considered instance types to get the flexibility count
instanceTypeZones := map[string]struct{}{}
for _, ltc := range launchTemplateConfigs {
for _, override := range ltc.Overrides {
if override.InstanceType != nil {
instanceTypeZones[*override.InstanceType] = struct{}{}
}
}
}
if len(instanceTypes) < instanceTypeFlexibilityThreshold {
return fmt.Errorf("at least %d instance types are recommended when flexible to spot but requesting on-demand, "+
"the current provisioning request only has %d instance type options", instanceTypeFlexibilityThreshold, len(instanceTypes))
}
return nil
}
func (p *Provider) getLaunchTemplateConfigs(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine,
instanceTypes []*cloudprovider.InstanceType, zonalSubnets map[string]*ec2.Subnet, capacityType string, tags map[string]string) ([]*ec2.FleetLaunchTemplateConfigRequest, error) {
var launchTemplateConfigs []*ec2.FleetLaunchTemplateConfigRequest
launchTemplates, err := p.launchTemplateProvider.EnsureAll(ctx, nodeTemplate, machine, instanceTypes, map[string]string{v1alpha5.LabelCapacityType: capacityType}, tags)
if err != nil {
return nil, fmt.Errorf("getting launch templates, %w", err)
}
for launchTemplateName, instanceTypes := range launchTemplates {
launchTemplateConfig := &ec2.FleetLaunchTemplateConfigRequest{
Overrides: p.getOverrides(instanceTypes, zonalSubnets, scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...).Get(v1.LabelTopologyZone), capacityType),
LaunchTemplateSpecification: &ec2.FleetLaunchTemplateSpecificationRequest{
LaunchTemplateName: aws.String(launchTemplateName),
Version: aws.String("$Latest"),
},
}
if len(launchTemplateConfig.Overrides) > 0 {
launchTemplateConfigs = append(launchTemplateConfigs, launchTemplateConfig)
}
}
if len(launchTemplateConfigs) == 0 {
return nil, fmt.Errorf("no capacity offerings are currently available given the constraints")
}
return launchTemplateConfigs, nil
}
// getOverrides creates and returns launch template overrides for the cross product of InstanceTypes and subnets (with subnets being constrained by
// zones and the offerings in InstanceTypes)
func (p *Provider) getOverrides(instanceTypes []*cloudprovider.InstanceType, zonalSubnets map[string]*ec2.Subnet, zones *scheduling.Requirement, capacityType string) []*ec2.FleetLaunchTemplateOverridesRequest {
// Unwrap all the offerings to a flat slice that includes a pointer
// to the parent instance type name
type offeringWithParentName struct {
cloudprovider.Offering
parentInstanceTypeName string
}
var unwrappedOfferings []offeringWithParentName
for _, it := range instanceTypes {
ofs := lo.Map(it.Offerings.Available(), func(of cloudprovider.Offering, _ int) offeringWithParentName {
return offeringWithParentName{
Offering: of,
parentInstanceTypeName: it.Name,
}
})
unwrappedOfferings = append(unwrappedOfferings, ofs...)
}
var overrides []*ec2.FleetLaunchTemplateOverridesRequest
for _, offering := range unwrappedOfferings {
if capacityType != offering.CapacityType {
continue
}
if !zones.Has(offering.Zone) {
continue
}
subnet, ok := zonalSubnets[offering.Zone]
if !ok {
continue
}
overrides = append(overrides, &ec2.FleetLaunchTemplateOverridesRequest{
InstanceType: aws.String(offering.parentInstanceTypeName),
SubnetId: subnet.SubnetId,
// This is technically redundant, but is useful if we have to parse insufficient capacity errors from
// CreateFleet so that we can figure out the zone rather than additional API calls to look up the subnet
AvailabilityZone: subnet.AvailabilityZone,
})
}
return overrides
}
func (p *Provider) updateUnavailableOfferingsCache(ctx context.Context, errors []*ec2.CreateFleetError, capacityType string) {
for _, err := range errors {
if awserrors.IsUnfulfillableCapacity(err) {
p.unavailableOfferings.MarkUnavailableForFleetErr(ctx, err, capacityType)
}
}
}
// getCapacityType selects spot if both constraints are flexible and there is an
// available offering. The AWS Cloud Provider defaults to [ on-demand ], so spot
// must be explicitly included in capacity type requirements.
func (p *Provider) getCapacityType(machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType) string {
requirements := scheduling.NewNodeSelectorRequirements(machine.
Spec.Requirements...)
if requirements.Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeSpot) {
for _, instanceType := range instanceTypes {
for _, offering := range instanceType.Offerings.Available() {
if requirements.Get(v1.LabelTopologyZone).Has(offering.Zone) && offering.CapacityType == v1alpha5.CapacityTypeSpot {
return v1alpha5.CapacityTypeSpot
}
}
}
}
return v1alpha5.CapacityTypeOnDemand
}
func orderInstanceTypesByPrice(instanceTypes []*cloudprovider.InstanceType, requirements scheduling.Requirements) []*cloudprovider.InstanceType {
// Order instance types so that we get the cheapest instance types of the available offerings
sort.Slice(instanceTypes, func(i, j int) bool {
iPrice := math.MaxFloat64
jPrice := math.MaxFloat64
if len(instanceTypes[i].Offerings.Available().Requirements(requirements)) > 0 {
iPrice = instanceTypes[i].Offerings.Available().Requirements(requirements).Cheapest().Price
}
if len(instanceTypes[j].Offerings.Available().Requirements(requirements)) > 0 {
jPrice = instanceTypes[j].Offerings.Available().Requirements(requirements).Cheapest().Price
}
if iPrice == jPrice {
return instanceTypes[i].Name < instanceTypes[j].Name
}
return iPrice < jPrice
})
return instanceTypes
}
// filterInstanceTypes is used to provide filtering on the list of potential instance types to further limit it to those
// that make the most sense given our specific AWS cloudprovider.
func (p *Provider) filterInstanceTypes(machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType) []*cloudprovider.InstanceType {
instanceTypes = filterExoticInstanceTypes(instanceTypes)
// If we could potentially launch either a spot or on-demand node, we want to filter out the spot instance types that
// are more expensive than the cheapest on-demand type.
if p.isMixedCapacityLaunch(machine, instanceTypes) {
instanceTypes = filterUnwantedSpot(instanceTypes)
}
return instanceTypes
}
// isMixedCapacityLaunch returns true if provisioners and available offerings could potentially allow either a spot or
// and on-demand node to launch
func (p *Provider) isMixedCapacityLaunch(machine *v1alpha5.Machine, instanceTypes []*cloudprovider.InstanceType) bool {
requirements := scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...)
// requirements must allow both
if !requirements.Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeSpot) ||
!requirements.Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeOnDemand) {
return false
}
hasSpotOfferings := false
hasODOffering := false
if requirements.Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeSpot) {
for _, instanceType := range instanceTypes {
for _, offering := range instanceType.Offerings.Available() {
if requirements.Get(v1.LabelTopologyZone).Has(offering.Zone) {
if offering.CapacityType == v1alpha5.CapacityTypeSpot {
hasSpotOfferings = true
} else {
hasODOffering = true
}
}
}
}
}
return hasSpotOfferings && hasODOffering
}
// filterUnwantedSpot is used to filter out spot types that are more expensive than the cheapest on-demand type that we
// could launch during mixed capacity-type launches
func filterUnwantedSpot(instanceTypes []*cloudprovider.InstanceType) []*cloudprovider.InstanceType {
cheapestOnDemand := math.MaxFloat64
// first, find the price of our cheapest available on-demand instance type that could support this node
for _, it := range instanceTypes {
for _, o := range it.Offerings.Available() {
if o.CapacityType == v1alpha5.CapacityTypeOnDemand && o.Price < cheapestOnDemand {
cheapestOnDemand = o.Price
}
}
}
// Filter out any types where the cheapest offering, which should be spot, is more expensive than the cheapest
// on-demand instance type that would have worked. This prevents us from getting a larger more-expensive spot
// instance type compared to the cheapest sufficiently large on-demand instance type
instanceTypes = lo.Filter(instanceTypes, func(item *cloudprovider.InstanceType, index int) bool {
available := item.Offerings.Available()
if len(available) == 0 {
return false
}
return available.Cheapest().Price <= cheapestOnDemand
})
return instanceTypes
}
// filterExoticInstanceTypes is used to eliminate less desirable instance types (like GPUs) from the list of possible instance types when
// a set of more appropriate instance types would work. If a set of more desirable instance types is not found, then the original slice
// of instance types are returned.
func filterExoticInstanceTypes(instanceTypes []*cloudprovider.InstanceType) []*cloudprovider.InstanceType {
var genericInstanceTypes []*cloudprovider.InstanceType
for _, it := range instanceTypes {
// deprioritize metal even if our opinionated filter isn't applied due to something like an instance family
// requirement
if it.Requirements.Get(v1alpha1.LabelInstanceSize).Has("metal") {
continue
}
if !resources.IsZero(it.Capacity[v1alpha1.ResourceAWSNeuron]) ||
!resources.IsZero(it.Capacity[v1alpha1.ResourceAMDGPU]) ||
!resources.IsZero(it.Capacity[v1alpha1.ResourceNVIDIAGPU]) ||
!resources.IsZero(it.Capacity[v1alpha1.ResourceHabanaGaudi]) {
continue
}
genericInstanceTypes = append(genericInstanceTypes, it)
}
// if we got some subset of instance types, then prefer to use those
if len(genericInstanceTypes) != 0 {
return genericInstanceTypes
}
return instanceTypes
}
func instancesFromOutput(out *ec2.DescribeInstancesOutput) ([]*Instance, error) {
if len(out.Reservations) == 0 {
return nil, cloudprovider.NewMachineNotFoundError(fmt.Errorf("instance not found"))
}
instances := lo.Flatten(lo.Map(out.Reservations, func(r *ec2.Reservation, _ int) []*ec2.Instance {
return r.Instances
}))
if len(instances) == 0 {
return nil, cloudprovider.NewMachineNotFoundError(fmt.Errorf("instance not found"))
}
// Get a consistent ordering for instances
sort.Slice(instances, func(i, j int) bool {
return aws.StringValue(instances[i].InstanceId) < aws.StringValue(instances[j].InstanceId)
})
return lo.Map(instances, func(i *ec2.Instance, _ int) *Instance { return NewInstance(i) }), nil
}
func combineFleetErrors(errors []*ec2.CreateFleetError) (errs error) {
unique := sets.NewString()
for _, err := range errors {
unique.Insert(fmt.Sprintf("%s: %s", aws.StringValue(err.ErrorCode), aws.StringValue(err.ErrorMessage)))
}
for errorCode := range unique {
errs = multierr.Append(errs, fmt.Errorf(errorCode))
}
// If all the Fleet errors are ICE errors then we should wrap the combined error in the generic ICE error
iceErrorCount := lo.CountBy(errors, func(err *ec2.CreateFleetError) bool { return awserrors.IsUnfulfillableCapacity(err) })
if iceErrorCount == len(errors) {
return cloudprovider.NewInsufficientCapacityError(fmt.Errorf("with fleet error(s), %w", errs))
}
return fmt.Errorf("with fleet error(s), %w", errs)
}
| 519 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instance_test
import (
"context"
"testing"
"github.com/aws/aws-sdk-go/aws"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
. "knative.dev/pkg/logging/testing"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/operator/options"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/test"
)
var ctx context.Context
var opts options.Options
var env *coretest.Environment
var awsEnv *test.Environment
var provisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
var machine *v1alpha5.Machine
var cloudProvider *cloudprovider.CloudProvider
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Provider/AWS")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
awsEnv = test.NewEnvironment(ctx, env)
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
ctx = injection.WithOptions(ctx, opts)
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
nodeTemplate = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
},
}
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
machine = coretest.Machine(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
},
},
Spec: v1alpha5.MachineSpec{
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
})
var _ = Describe("InstanceProvider", func() {
It("should return an ICE error when all attempted instance types return an ICE error", func() {
ExpectApplied(ctx, env.Client, machine, provisioner, nodeTemplate)
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{
{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "m5.xlarge", Zone: "test-zone-1a"},
{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "m5.xlarge", Zone: "test-zone-1b"},
{CapacityType: v1alpha5.CapacityTypeSpot, InstanceType: "m5.xlarge", Zone: "test-zone-1a"},
{CapacityType: v1alpha5.CapacityTypeSpot, InstanceType: "m5.xlarge", Zone: "test-zone-1b"},
})
instanceTypes, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).ToNot(HaveOccurred())
// Filter down to a single instance type
instanceTypes = lo.Filter(instanceTypes, func(i *corecloudprovider.InstanceType, _ int) bool { return i.Name == "m5.xlarge" })
// Since all the capacity pools are ICEd. This should return back an ICE error
instance, err := awsEnv.InstanceProvider.Create(ctx, nodeTemplate, machine, instanceTypes)
Expect(corecloudprovider.IsInsufficientCapacityError(err)).To(BeTrue())
Expect(instance).To(BeNil())
})
})
| 134 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instance
import (
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
)
// Instance is an internal data representation of either an ec2.Instance or an ec2.FleetInstance
// It contains all the common data that is needed to inject into the Machine from either of these responses
type Instance struct {
LaunchTime time.Time
State string
ID string
ImageID string
Type string
Zone string
CapacityType string
SecurityGroupIDs []string
SubnetID string
Tags map[string]string
}
func NewInstance(out *ec2.Instance) *Instance {
return &Instance{
LaunchTime: aws.TimeValue(out.LaunchTime),
State: aws.StringValue(out.State.Name),
ID: aws.StringValue(out.InstanceId),
ImageID: aws.StringValue(out.ImageId),
Type: aws.StringValue(out.InstanceType),
Zone: aws.StringValue(out.Placement.AvailabilityZone),
CapacityType: lo.Ternary(out.SpotInstanceRequestId != nil, v1alpha5.CapacityTypeSpot, v1alpha5.CapacityTypeOnDemand),
SecurityGroupIDs: lo.Map(out.SecurityGroups, func(securitygroup *ec2.GroupIdentifier, _ int) string {
return aws.StringValue(securitygroup.GroupId)
}),
SubnetID: aws.StringValue(out.SubnetId),
Tags: lo.SliceToMap(out.Tags, func(t *ec2.Tag) (string, string) { return aws.StringValue(t.Key), aws.StringValue(t.Value) }),
}
}
func NewInstanceFromFleet(out *ec2.CreateFleetInstance, tags map[string]string) *Instance {
return &Instance{
LaunchTime: time.Now(), // estimate the launch time since we just launched
State: ec2.StatePending,
ID: aws.StringValue(out.InstanceIds[0]),
ImageID: "", // we don't know the image id when we get the output from fleet
Type: aws.StringValue(out.InstanceType),
Zone: aws.StringValue(out.LaunchTemplateAndOverrides.Overrides.AvailabilityZone),
CapacityType: aws.StringValue(out.Lifecycle),
SubnetID: aws.StringValue(out.LaunchTemplateAndOverrides.Overrides.SubnetId),
Tags: tags,
}
}
| 73 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instancetype
import (
"context"
"fmt"
"net/http"
"sync"
"sync/atomic"
"github.com/prometheus/client_golang/prometheus"
awscache "github.com/aws/karpenter/pkg/cache"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/mitchellh/hashstructure/v2"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/logging"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/pricing"
"github.com/aws/karpenter/pkg/providers/subnet"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/utils/pretty"
)
const (
InstanceTypesCacheKey = "types"
InstanceTypeZonesCacheKeyPrefix = "zones:"
)
type Provider struct {
region string
ec2api ec2iface.EC2API
subnetProvider *subnet.Provider
pricingProvider *pricing.Provider
// Has one cache entry for all the instance types (key: InstanceTypesCacheKey)
// Has one cache entry for all the zones for each subnet selector (key: InstanceTypesZonesCacheKeyPrefix:<hash_of_selector>)
// Values cached *before* considering insufficient capacity errors from the unavailableOfferings cache.
// Fully initialized Instance Types are also cached based on the set of all instance types, zones, unavailableOfferings cache,
// node template, and kubelet configuration from the provisioner
mu sync.Mutex
cache *cache.Cache
unavailableOfferings *awscache.UnavailableOfferings
cm *pretty.ChangeMonitor
// instanceTypesSeqNum is a monotonically increasing change counter used to avoid the expensive hashing operation on instance types
instanceTypesSeqNum uint64
}
func NewProvider(region string, cache *cache.Cache, ec2api ec2iface.EC2API, subnetProvider *subnet.Provider,
unavailableOfferingsCache *awscache.UnavailableOfferings, pricingProvider *pricing.Provider) *Provider {
return &Provider{
ec2api: ec2api,
region: region,
subnetProvider: subnetProvider,
pricingProvider: pricingProvider,
cache: cache,
unavailableOfferings: unavailableOfferingsCache,
cm: pretty.NewChangeMonitor(),
instanceTypesSeqNum: 0,
}
}
func (p *Provider) List(ctx context.Context, kc *v1alpha5.KubeletConfiguration, nodeTemplate *v1alpha1.AWSNodeTemplate) ([]*cloudprovider.InstanceType, error) {
// Get InstanceTypes from EC2
instanceTypes, err := p.GetInstanceTypes(ctx)
if err != nil {
return nil, err
}
// Get Viable EC2 Purchase offerings
instanceTypeZones, err := p.getInstanceTypeZones(ctx, nodeTemplate)
if err != nil {
return nil, err
}
// Compute fully initialized instance types hash key
instanceTypeZonesHash, _ := hashstructure.Hash(instanceTypeZones, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
kcHash, _ := hashstructure.Hash(kc, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
key := fmt.Sprintf("%d-%d-%s-%016x-%016x", p.instanceTypesSeqNum, p.unavailableOfferings.SeqNum, nodeTemplate.UID, instanceTypeZonesHash, kcHash)
if item, ok := p.cache.Get(key); ok {
return item.([]*cloudprovider.InstanceType), nil
}
result := lo.Map(instanceTypes, func(i *ec2.InstanceTypeInfo, _ int) *cloudprovider.InstanceType {
return NewInstanceType(ctx, i, kc, p.region, nodeTemplate, p.createOfferings(ctx, i, instanceTypeZones[aws.StringValue(i.InstanceType)]))
})
for _, instanceType := range instanceTypes {
InstanceTypeVCPU.With(prometheus.Labels{
InstanceTypeLabel: *instanceType.InstanceType,
}).Set(float64(aws.Int64Value(instanceType.VCpuInfo.DefaultVCpus)))
InstanceTypeMemory.With(prometheus.Labels{
InstanceTypeLabel: *instanceType.InstanceType,
}).Set(float64(aws.Int64Value(instanceType.MemoryInfo.SizeInMiB) * 1024 * 1024))
}
p.cache.SetDefault(key, result)
return result, nil
}
func (p *Provider) LivenessProbe(req *http.Request) error {
if err := p.subnetProvider.LivenessProbe(req); err != nil {
return err
}
return p.pricingProvider.LivenessProbe(req)
}
func (p *Provider) createOfferings(ctx context.Context, instanceType *ec2.InstanceTypeInfo, zones sets.String) []cloudprovider.Offering {
var offerings []cloudprovider.Offering
for zone := range zones {
// while usage classes should be a distinct set, there's no guarantee of that
for capacityType := range sets.NewString(aws.StringValueSlice(instanceType.SupportedUsageClasses)...) {
// exclude any offerings that have recently seen an insufficient capacity error from EC2
isUnavailable := p.unavailableOfferings.IsUnavailable(*instanceType.InstanceType, zone, capacityType)
var price float64
var ok bool
switch capacityType {
case ec2.UsageClassTypeSpot:
price, ok = p.pricingProvider.SpotPrice(*instanceType.InstanceType, zone)
case ec2.UsageClassTypeOnDemand:
price, ok = p.pricingProvider.OnDemandPrice(*instanceType.InstanceType)
default:
logging.FromContext(ctx).Errorf("Received unknown capacity type %s for instance type %s", capacityType, *instanceType.InstanceType)
continue
}
available := !isUnavailable && ok
offerings = append(offerings, cloudprovider.Offering{
Zone: zone,
CapacityType: capacityType,
Price: price,
Available: available,
})
}
}
return offerings
}
func (p *Provider) getInstanceTypeZones(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) (map[string]sets.String, error) {
// DO NOT REMOVE THIS LOCK ----------------------------------------------------------------------------
// We lock here so that multiple callers to getInstanceTypeZones do not result in cache misses and multiple
// calls to EC2 when we could have just made one call.
// TODO @joinnis: This can be made more efficient by holding a Read lock and only obtaining the Write if not in cache
p.mu.Lock()
defer p.mu.Unlock()
subnetSelectorHash, err := hashstructure.Hash(nodeTemplate.Spec.SubnetSelector, hashstructure.FormatV2, nil)
if err != nil {
return nil, fmt.Errorf("failed to hash the subnet selector: %w", err)
}
cacheKey := fmt.Sprintf("%s%016x", InstanceTypeZonesCacheKeyPrefix, subnetSelectorHash)
if cached, ok := p.cache.Get(cacheKey); ok {
return cached.(map[string]sets.String), nil
}
// Constrain AZs from subnets
subnets, err := p.subnetProvider.List(ctx, nodeTemplate)
if err != nil {
return nil, err
}
if len(subnets) == 0 {
return nil, fmt.Errorf("no subnets matched selector %v", nodeTemplate.Spec.SubnetSelector)
}
zones := sets.NewString(lo.Map(subnets, func(subnet *ec2.Subnet, _ int) string {
return aws.StringValue(subnet.AvailabilityZone)
})...)
// Get offerings from EC2
instanceTypeZones := map[string]sets.String{}
if err := p.ec2api.DescribeInstanceTypeOfferingsPagesWithContext(ctx, &ec2.DescribeInstanceTypeOfferingsInput{LocationType: aws.String("availability-zone")},
func(output *ec2.DescribeInstanceTypeOfferingsOutput, lastPage bool) bool {
for _, offering := range output.InstanceTypeOfferings {
if zones.Has(aws.StringValue(offering.Location)) {
if _, ok := instanceTypeZones[aws.StringValue(offering.InstanceType)]; !ok {
instanceTypeZones[aws.StringValue(offering.InstanceType)] = sets.NewString()
}
instanceTypeZones[aws.StringValue(offering.InstanceType)].Insert(aws.StringValue(offering.Location))
}
}
return true
}); err != nil {
return nil, fmt.Errorf("describing instance type zone offerings, %w", err)
}
if p.cm.HasChanged("zonal-offerings", nodeTemplate.Spec.SubnetSelector) {
logging.FromContext(ctx).With("zones", zones.List(), "instance-type-count", len(instanceTypeZones), "node-template", nodeTemplate.Name).Debugf("discovered offerings for instance types")
}
p.cache.SetDefault(cacheKey, instanceTypeZones)
return instanceTypeZones, nil
}
// GetInstanceTypes retrieves all instance types from the ec2 DescribeInstanceTypes API using some opinionated filters
func (p *Provider) GetInstanceTypes(ctx context.Context) ([]*ec2.InstanceTypeInfo, error) {
// DO NOT REMOVE THIS LOCK ----------------------------------------------------------------------------
// We lock here so that multiple callers to GetInstanceTypes do not result in cache misses and multiple
// calls to EC2 when we could have just made one call. This lock is here because multiple callers to EC2 result
// in A LOT of extra memory generated from the response for simultaneous callers.
// TODO @joinnis: This can be made more efficient by holding a Read lock and only obtaining the Write if not in cache
p.mu.Lock()
defer p.mu.Unlock()
if cached, ok := p.cache.Get(InstanceTypesCacheKey); ok {
return cached.([]*ec2.InstanceTypeInfo), nil
}
var instanceTypes []*ec2.InstanceTypeInfo
if err := p.ec2api.DescribeInstanceTypesPagesWithContext(ctx, &ec2.DescribeInstanceTypesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("supported-virtualization-type"),
Values: []*string{aws.String("hvm")},
},
{
Name: aws.String("processor-info.supported-architecture"),
Values: aws.StringSlice([]string{"x86_64", "arm64"}),
},
},
}, func(page *ec2.DescribeInstanceTypesOutput, lastPage bool) bool {
instanceTypes = append(instanceTypes, page.InstanceTypes...)
return true
}); err != nil {
return nil, fmt.Errorf("fetching instance types using ec2.DescribeInstanceTypes, %w", err)
}
if p.cm.HasChanged("instance-types", instanceTypes) {
logging.FromContext(ctx).With(
"count", len(instanceTypes)).Debugf("discovered instance types")
}
atomic.AddUint64(&p.instanceTypesSeqNum, 1)
p.cache.SetDefault(InstanceTypesCacheKey, instanceTypes)
return instanceTypes, nil
}
| 248 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instancetype
import (
"github.com/prometheus/client_golang/prometheus"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/aws/karpenter-core/pkg/metrics"
)
const (
cloudProviderSubsystem = "cloudprovider"
)
var (
InstanceTypeLabel = "instance_type"
InstanceTypeVCPU = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: metrics.Namespace,
Subsystem: cloudProviderSubsystem,
Name: "instance_type_cpu_cores",
Help: "VCPUs cores for a given instance type.",
},
[]string{
InstanceTypeLabel,
})
InstanceTypeMemory = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: metrics.Namespace,
Subsystem: cloudProviderSubsystem,
Name: "instance_type_memory_bytes",
Help: "Memory, in bytes, for a given instance type.",
},
[]string{
InstanceTypeLabel,
})
)
func init() {
crmetrics.Registry.MustRegister(InstanceTypeVCPU, InstanceTypeMemory)
}
| 57 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instancetype_test
import (
"context"
"fmt"
"math"
"net"
"sort"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/record"
clock "k8s.io/utils/clock/testing"
. "knative.dev/pkg/logging/testing"
"knative.dev/pkg/ptr"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/controllers/provisioning"
"github.com/aws/karpenter-core/pkg/controllers/state"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/operator/options"
"github.com/aws/karpenter-core/pkg/operator/scheme"
"github.com/aws/karpenter-core/pkg/scheduling"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/providers/instance"
"github.com/aws/karpenter/pkg/providers/instancetype"
"github.com/aws/karpenter/pkg/providers/pricing"
"github.com/aws/karpenter/pkg/test"
)
var ctx context.Context
var stop context.CancelFunc
var opts options.Options
var env *coretest.Environment
var awsEnv *test.Environment
var fakeClock *clock.FakeClock
var prov *provisioning.Provisioner
var provisioner *v1alpha5.Provisioner
var windowsProvisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
var windowsNodeTemplate *v1alpha1.AWSNodeTemplate
var cluster *state.Cluster
var cloudProvider *cloudprovider.CloudProvider
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Provider/AWS")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
ctx, stop = context.WithCancel(ctx)
awsEnv = test.NewEnvironment(ctx, env)
fakeClock = &clock.FakeClock{}
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
cluster = state.NewCluster(fakeClock, env.Client, cloudProvider)
prov = provisioning.NewProvisioner(env.Client, env.KubernetesInterface.CoreV1(), events.NewRecorder(&record.FakeRecorder{}), cloudProvider, cluster)
})
var _ = AfterSuite(func() {
stop()
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
ctx = injection.WithOptions(ctx, opts)
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
nodeTemplate = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
},
}
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
windowsNodeTemplate = test.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyWindows2022,
},
})
windowsProvisioner = test.Provisioner(coretest.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
},
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Windows)},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: windowsNodeTemplate.Name,
},
})
cluster.Reset()
awsEnv.Reset()
awsEnv.LaunchTemplateProvider.KubeDNSIP = net.ParseIP("10.0.100.10")
awsEnv.LaunchTemplateProvider.ClusterEndpoint = "https://test-cluster"
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("Instance Types", func() {
It("should support individual instance type labels", func() {
ExpectApplied(ctx, env.Client, provisioner, windowsProvisioner, nodeTemplate, windowsNodeTemplate)
nodeSelector := map[string]string{
// Well known
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelTopologyRegion: "",
v1.LabelTopologyZone: "test-zone-1a",
v1.LabelInstanceTypeStable: "g4dn.8xlarge",
v1.LabelOSStable: "linux",
v1.LabelArchStable: "amd64",
v1alpha5.LabelCapacityType: "on-demand",
// Well Known to AWS
v1alpha1.LabelInstanceHypervisor: "nitro",
v1alpha1.LabelInstanceEncryptionInTransitSupported: "true",
v1alpha1.LabelInstanceCategory: "g",
v1alpha1.LabelInstanceGeneration: "4",
v1alpha1.LabelInstanceFamily: "g4dn",
v1alpha1.LabelInstanceSize: "8xlarge",
v1alpha1.LabelInstanceCPU: "32",
v1alpha1.LabelInstanceMemory: "131072",
v1alpha1.LabelInstanceNetworkBandwidth: "50000",
v1alpha1.LabelInstancePods: "58",
v1alpha1.LabelInstanceGPUName: "t4",
v1alpha1.LabelInstanceGPUManufacturer: "nvidia",
v1alpha1.LabelInstanceGPUCount: "1",
v1alpha1.LabelInstanceGPUMemory: "16384",
v1alpha1.LabelInstanceLocalNVME: "900",
v1alpha1.LabelInstanceAcceleratorName: "inferentia",
v1alpha1.LabelInstanceAcceleratorManufacturer: "aws",
v1alpha1.LabelInstanceAcceleratorCount: "1",
// Deprecated Labels
v1.LabelFailureDomainBetaRegion: "",
v1.LabelFailureDomainBetaZone: "test-zone-1a",
"beta.kubernetes.io/arch": "amd64",
"beta.kubernetes.io/os": "linux",
v1.LabelInstanceType: "g4dn.8xlarge",
"topology.ebs.csi.aws.com/zone": "test-zone-1a",
v1.LabelWindowsBuild: v1alpha1.Windows2022Build,
}
// Ensure that we're exercising all well known labels
Expect(lo.Keys(nodeSelector)).To(ContainElements(append(v1alpha5.WellKnownLabels.UnsortedList(), lo.Keys(v1alpha5.NormalizedLabels)...)))
var pods []*v1.Pod
for key, value := range nodeSelector {
pods = append(pods, coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: map[string]string{key: value}}))
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
ExpectScheduled(ctx, env.Client, pod)
}
})
It("should support combined instance type labels", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
nodeSelector := map[string]string{
// Well known
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelTopologyRegion: "",
v1.LabelTopologyZone: "test-zone-1a",
v1.LabelInstanceTypeStable: "g4dn.8xlarge",
v1.LabelOSStable: "linux",
v1.LabelArchStable: "amd64",
v1alpha5.LabelCapacityType: "on-demand",
// Well Known to AWS
v1alpha1.LabelInstanceHypervisor: "nitro",
v1alpha1.LabelInstanceEncryptionInTransitSupported: "true",
v1alpha1.LabelInstanceCategory: "g",
v1alpha1.LabelInstanceGeneration: "4",
v1alpha1.LabelInstanceFamily: "g4dn",
v1alpha1.LabelInstanceSize: "8xlarge",
v1alpha1.LabelInstanceCPU: "32",
v1alpha1.LabelInstanceMemory: "131072",
v1alpha1.LabelInstanceNetworkBandwidth: "50000",
v1alpha1.LabelInstancePods: "58",
v1alpha1.LabelInstanceGPUName: "t4",
v1alpha1.LabelInstanceGPUManufacturer: "nvidia",
v1alpha1.LabelInstanceGPUCount: "1",
v1alpha1.LabelInstanceGPUMemory: "16384",
v1alpha1.LabelInstanceLocalNVME: "900",
// Deprecated Labels
v1.LabelFailureDomainBetaRegion: "",
v1.LabelFailureDomainBetaZone: "test-zone-1a",
"beta.kubernetes.io/arch": "amd64",
"beta.kubernetes.io/os": "linux",
v1.LabelInstanceType: "g4dn.8xlarge",
"topology.ebs.csi.aws.com/zone": "test-zone-1a",
}
// Ensure that we're exercising all well known labels except for accelerator labels
Expect(lo.Keys(nodeSelector)).To(ContainElements(
append(
v1alpha5.WellKnownLabels.Difference(sets.NewString(
v1alpha1.LabelInstanceAcceleratorCount,
v1alpha1.LabelInstanceAcceleratorName,
v1alpha1.LabelInstanceAcceleratorManufacturer,
v1.LabelWindowsBuild,
)).UnsortedList(), lo.Keys(v1alpha5.NormalizedLabels)...)))
pod := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: nodeSelector})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should support instance type labels with accelerator", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
nodeSelector := map[string]string{
// Well known
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelTopologyRegion: "",
v1.LabelTopologyZone: "test-zone-1a",
v1.LabelInstanceTypeStable: "inf1.2xlarge",
v1.LabelOSStable: "linux",
v1.LabelArchStable: "amd64",
v1alpha5.LabelCapacityType: "on-demand",
// Well Known to AWS
v1alpha1.LabelInstanceHypervisor: "nitro",
v1alpha1.LabelInstanceEncryptionInTransitSupported: "true",
v1alpha1.LabelInstanceCategory: "inf",
v1alpha1.LabelInstanceGeneration: "1",
v1alpha1.LabelInstanceFamily: "inf1",
v1alpha1.LabelInstanceSize: "2xlarge",
v1alpha1.LabelInstanceCPU: "8",
v1alpha1.LabelInstanceMemory: "16384",
v1alpha1.LabelInstanceNetworkBandwidth: "5000",
v1alpha1.LabelInstancePods: "38",
v1alpha1.LabelInstanceAcceleratorName: "inferentia",
v1alpha1.LabelInstanceAcceleratorManufacturer: "aws",
v1alpha1.LabelInstanceAcceleratorCount: "1",
// Deprecated Labels
v1.LabelFailureDomainBetaRegion: "",
v1.LabelFailureDomainBetaZone: "test-zone-1a",
"beta.kubernetes.io/arch": "amd64",
"beta.kubernetes.io/os": "linux",
v1.LabelInstanceType: "inf1.2xlarge",
"topology.ebs.csi.aws.com/zone": "test-zone-1a",
}
// Ensure that we're exercising all well known labels except for gpu labels and nvme
expectedLabels := append(v1alpha5.WellKnownLabels.Difference(sets.NewString(
v1alpha1.LabelInstanceGPUCount,
v1alpha1.LabelInstanceGPUName,
v1alpha1.LabelInstanceGPUManufacturer,
v1alpha1.LabelInstanceGPUMemory,
v1alpha1.LabelInstanceLocalNVME,
v1.LabelWindowsBuild,
)).UnsortedList(), lo.Keys(v1alpha5.NormalizedLabels)...)
Expect(lo.Keys(nodeSelector)).To(ContainElements(expectedLabels))
pod := coretest.UnschedulablePod(coretest.PodOptions{NodeSelector: nodeSelector})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should not launch AWS Pod ENI on a t3", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{
v1.LabelInstanceTypeStable: "t3.large",
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should order the instance types by price and only consider the cheapest ones", func() {
instances := makeFakeInstances()
awsEnv.EC2API.DescribeInstanceTypesOutput.Set(&ec2.DescribeInstanceTypesOutput{
InstanceTypes: makeFakeInstances(),
})
awsEnv.EC2API.DescribeInstanceTypeOfferingsOutput.Set(&ec2.DescribeInstanceTypeOfferingsOutput{
InstanceTypeOfferings: makeFakeInstanceOfferings(instances),
})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
its, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).To(BeNil())
// Order all the instances by their price
// We need some way to deterministically order them if their prices match
reqs := scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...)
sort.Slice(its, func(i, j int) bool {
iPrice := its[i].Offerings.Requirements(reqs).Cheapest().Price
jPrice := its[j].Offerings.Requirements(reqs).Cheapest().Price
if iPrice == jPrice {
return its[i].Name < its[j].Name
}
return iPrice < jPrice
})
// Expect that the launch template overrides gives the 60 cheapest instance types
expected := sets.NewString(lo.Map(its[:instance.MaxInstanceTypes], func(i *corecloudprovider.InstanceType, _ int) string {
return i.Name
})...)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
call := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(call.LaunchTemplateConfigs).To(HaveLen(1))
Expect(call.LaunchTemplateConfigs[0].Overrides).To(HaveLen(instance.MaxInstanceTypes))
for _, override := range call.LaunchTemplateConfigs[0].Overrides {
Expect(expected.Has(aws.StringValue(override.InstanceType))).To(BeTrue(), fmt.Sprintf("expected %s to exist in set", aws.StringValue(override.InstanceType)))
}
})
It("should order the instance types by price and only consider the spot types that are cheaper than the cheapest on-demand", func() {
instances := makeFakeInstances()
awsEnv.EC2API.DescribeInstanceTypesOutput.Set(&ec2.DescribeInstanceTypesOutput{
InstanceTypes: makeFakeInstances(),
})
awsEnv.EC2API.DescribeInstanceTypeOfferingsOutput.Set(&ec2.DescribeInstanceTypeOfferingsOutput{
InstanceTypeOfferings: makeFakeInstanceOfferings(instances),
})
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{
v1alpha5.CapacityTypeSpot,
v1alpha5.CapacityTypeOnDemand,
},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(generateSpotPricing(cloudProvider, provisioner))
Expect(awsEnv.PricingProvider.UpdateSpotPricing(ctx)).To(Succeed())
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
its, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).To(BeNil())
// Order all the instances by their price
// We need some way to deterministically order them if their prices match
reqs := scheduling.NewNodeSelectorRequirements(provisioner.Spec.Requirements...)
sort.Slice(its, func(i, j int) bool {
iPrice := its[i].Offerings.Requirements(reqs).Cheapest().Price
jPrice := its[j].Offerings.Requirements(reqs).Cheapest().Price
if iPrice == jPrice {
return its[i].Name < its[j].Name
}
return iPrice < jPrice
})
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
call := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(call.LaunchTemplateConfigs).To(HaveLen(1))
// find the cheapest OD price that works
cheapestODPrice := math.MaxFloat64
for _, override := range call.LaunchTemplateConfigs[0].Overrides {
odPrice, ok := awsEnv.PricingProvider.OnDemandPrice(*override.InstanceType)
Expect(ok).To(BeTrue())
if odPrice < cheapestODPrice {
cheapestODPrice = odPrice
}
}
// and our spot prices should be cheaper than the OD price
for _, override := range call.LaunchTemplateConfigs[0].Overrides {
spotPrice, ok := awsEnv.PricingProvider.SpotPrice(*override.InstanceType, *override.AvailabilityZone)
Expect(ok).To(BeTrue())
Expect(spotPrice).To(BeNumerically("<", cheapestODPrice))
}
})
It("should de-prioritize metal", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
call := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
for _, ltc := range call.LaunchTemplateConfigs {
for _, ovr := range ltc.Overrides {
Expect(strings.HasSuffix(aws.StringValue(ovr.InstanceType), "metal")).To(BeFalse())
}
}
})
It("should de-prioritize gpu types", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
call := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
for _, ltc := range call.LaunchTemplateConfigs {
for _, ovr := range ltc.Overrides {
Expect(strings.HasPrefix(aws.StringValue(ovr.InstanceType), "g")).To(BeFalse())
}
}
})
It("should launch on metal", func() {
// add a provisioner requirement for instance type exists to remove our default filter for metal sizes
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpExists,
})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{
v1alpha1.LabelInstanceSize: "metal",
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should fail to launch AWS Pod ENI if the setting enabling it isn't set", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnablePodENI: lo.ToPtr(false),
}))
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should launch AWS Pod ENI on a compatible instance type", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSPodENI: resource.MustParse("1")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKey(v1.LabelInstanceTypeStable))
supportsPodENI := func() bool {
limits, ok := instancetype.Limits[node.Labels[v1.LabelInstanceTypeStable]]
return ok && limits.IsTrunkingCompatible
}
Expect(supportsPodENI()).To(Equal(true))
})
It("should launch instances for Nvidia GPU resource requests", func() {
nodeNames := sets.NewString()
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1")},
},
}),
// Should pack onto same instance
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("2")},
Limits: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("2")},
},
}),
// Should pack onto a separate instance
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("4")},
Limits: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("4")},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1.LabelInstanceTypeStable, "p3.8xlarge"))
nodeNames.Insert(node.Name)
}
Expect(nodeNames.Len()).To(Equal(2))
})
It("should launch instances for Habana GPU resource requests", func() {
nodeNames := sets.NewString()
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("1")},
},
}),
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("2")},
Limits: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("2")},
},
}),
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("4")},
Limits: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("4")},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1.LabelInstanceTypeStable, "dl1.24xlarge"))
nodeNames.Insert(node.Name)
}
Expect(nodeNames.Len()).To(Equal(1))
})
It("should launch instances for AWS Neuron resource requests", func() {
nodeNames := sets.NewString()
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
},
}),
// Should pack onto same instance
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("2")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("2")},
},
}),
// Should pack onto a separate instance
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("4")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("4")},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1.LabelInstanceTypeStable, "inf1.6xlarge"))
nodeNames.Insert(node.Name)
}
Expect(nodeNames.Len()).To(Equal(2))
})
It("should launch trn1 instances for AWS Neuron resource requests", func() {
nodeNames := sets.NewString()
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"trn1.2xlarge"},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1.LabelInstanceTypeStable, "trn1.2xlarge"))
nodeNames.Insert(node.Name)
}
Expect(nodeNames.Len()).To(Equal(1))
})
It("should set pods to 110 if not using ENI-based pod density", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 110))
}
})
It("should not set pods to 110 if using ENI-based pod density", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).ToNot(BeNumerically("==", 110))
}
})
It("should set pods to 110 even ENILimitedPodDensity is enabled in awssettings but amifamily doesn't support", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
windowsNodeTemplate := &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyWindows2019),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
},
}
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(true),
}))
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", windowsNodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 110))
}
})
It("should expose vcpu metrics for instance types", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.List(ctx, provisioner.Spec.KubeletConfiguration, nodeTemplate)
Expect(err).To(BeNil())
Expect(len(instanceInfo)).To(BeNumerically(">", 0))
for _, info := range instanceInfo {
metric, ok := FindMetricWithLabelValues("karpenter_cloudprovider_instance_type_cpu_cores", map[string]string{
instancetype.InstanceTypeLabel: info.Name,
})
Expect(ok).To(BeTrue())
Expect(metric).To(Not(BeNil()))
value := metric.GetGauge().Value
Expect(aws.Float64Value(value)).To(BeNumerically(">", 0))
}
})
It("should expose memory metrics for instance types", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.List(ctx, provisioner.Spec.KubeletConfiguration, nodeTemplate)
Expect(err).To(BeNil())
Expect(len(instanceInfo)).To(BeNumerically(">", 0))
for _, info := range instanceInfo {
metric, ok := FindMetricWithLabelValues("karpenter_cloudprovider_instance_type_memory_bytes", map[string]string{
instancetype.InstanceTypeLabel: info.Name,
})
Expect(ok).To(BeTrue())
Expect(metric).To(Not(BeNil()))
value := metric.GetGauge().Value
Expect(aws.Float64Value(value)).To(BeNumerically(">", 0))
}
})
Context("Overhead", func() {
var info *ec2.InstanceTypeInfo
BeforeEach(func() {
ctx, err := (&settings.Settings{}).Inject(ctx, &v1.ConfigMap{
Data: map[string]string{
"aws.clusterName": "karpenter-cluster",
},
})
Expect(err).To(BeNil())
s := settings.FromContext(ctx)
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
VMMemoryOverheadPercent: &s.VMMemoryOverheadPercent,
}))
var ok bool
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
info, ok = lo.Find(instanceInfo, func(i *ec2.InstanceTypeInfo) bool {
return aws.StringValue(i.InstanceType) == "m5.xlarge"
})
Expect(ok).To(BeTrue())
})
Context("System Reserved Resources", func() {
It("should use defaults when no kubelet is specified", func() {
it := instancetype.NewInstanceType(ctx, info, &v1alpha5.KubeletConfiguration{}, "", nodeTemplate, nil)
Expect(it.Overhead.SystemReserved.Cpu().String()).To(Equal("0"))
Expect(it.Overhead.SystemReserved.Memory().String()).To(Equal("0"))
Expect(it.Overhead.SystemReserved.StorageEphemeral().String()).To(Equal("0"))
})
It("should override system reserved cpus when specified", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("20Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.SystemReserved.Cpu().String()).To(Equal("2"))
Expect(it.Overhead.SystemReserved.Memory().String()).To(Equal("20Gi"))
Expect(it.Overhead.SystemReserved.StorageEphemeral().String()).To(Equal("10Gi"))
})
})
Context("Kube Reserved Resources", func() {
It("should use defaults when no kubelet is specified", func() {
it := instancetype.NewInstanceType(ctx, info, &v1alpha5.KubeletConfiguration{}, "", nodeTemplate, nil)
Expect(it.Overhead.KubeReserved.Cpu().String()).To(Equal("80m"))
Expect(it.Overhead.KubeReserved.Memory().String()).To(Equal("893Mi"))
Expect(it.Overhead.KubeReserved.StorageEphemeral().String()).To(Equal("1Gi"))
})
It("should override kube reserved when specified", func() {
it := instancetype.NewInstanceType(ctx, info, &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("1"),
v1.ResourceMemory: resource.MustParse("20Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("10Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("2Gi"),
},
}, "", nodeTemplate, nil)
Expect(it.Overhead.KubeReserved.Cpu().String()).To(Equal("2"))
Expect(it.Overhead.KubeReserved.Memory().String()).To(Equal("10Gi"))
Expect(it.Overhead.KubeReserved.StorageEphemeral().String()).To(Equal("2Gi"))
})
})
Context("Eviction Thresholds", func() {
BeforeEach(func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
VMMemoryOverheadPercent: lo.ToPtr[float64](0),
}))
})
Context("Eviction Hard", func() {
It("should override eviction threshold when specified as a quantity", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "500Mi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("500Mi"))
})
It("should override eviction threshold when specified as a percentage value", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "10%",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().Value()).To(BeNumerically("~", float64(it.Capacity.Memory().Value())*0.1, 10))
})
It("should consider the eviction threshold disabled when specified as 100%", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "100%",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("0"))
})
It("should used default eviction threshold for memory when evictionHard not specified", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "50Mi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("50Mi"))
})
})
Context("Eviction Soft", func() {
It("should override eviction threshold when specified as a quantity", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "500Mi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("500Mi"))
})
It("should override eviction threshold when specified as a percentage value", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "5%",
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "10%",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().Value()).To(BeNumerically("~", float64(it.Capacity.Memory().Value())*0.1, 10))
})
It("should consider the eviction threshold disabled when specified as 100%", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "100%",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("0"))
})
It("should ignore eviction threshold when using Bottlerocket AMI", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "1Gi",
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "10Gi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("1Gi"))
})
})
It("should take the default eviction threshold when none is specified", func() {
it := instancetype.NewInstanceType(ctx, info, &v1alpha5.KubeletConfiguration{}, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Cpu().String()).To(Equal("0"))
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("100Mi"))
Expect(it.Overhead.EvictionThreshold.StorageEphemeral().AsApproximateFloat64()).To(BeNumerically("~", resources.Quantity("2Gi").AsApproximateFloat64()))
})
It("should take the greater of evictionHard and evictionSoft for overhead as a value", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "3Gi",
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "1Gi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().String()).To(Equal("3Gi"))
})
It("should take the greater of evictionHard and evictionSoft for overhead as a value", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "2%",
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "5%",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().Value()).To(BeNumerically("~", float64(it.Capacity.Memory().Value())*0.05, 10))
})
It("should take the greater of evictionHard and evictionSoft for overhead with mixed percentage/value", func() {
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("20Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceMemory: resource.MustParse("10Gi"),
},
EvictionSoft: map[string]string{
instancetype.MemoryAvailable: "10%",
},
EvictionHard: map[string]string{
instancetype.MemoryAvailable: "1Gi",
},
},
})
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Overhead.EvictionThreshold.Memory().Value()).To(BeNumerically("~", float64(it.Capacity.Memory().Value())*0.1, 10))
})
})
It("should default max pods based off of network interfaces", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{})
for _, info := range instanceInfo {
if *info.InstanceType == "t3.large" {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 35))
}
if *info.InstanceType == "m6idn.32xlarge" {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 345))
}
}
})
It("should set max-pods to user-defined value if specified", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{MaxPods: ptr.Int32(10)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 10))
}
})
It("should override max-pods value when AWSENILimitedPodDensity is unset", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnablePodENI: lo.ToPtr(false),
}))
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{MaxPods: ptr.Int32(10)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 10))
}
})
It("should reserve ENIs when aws.reservedENIs is set and is used in max-pods calculation", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ReservedENIs: lo.ToPtr(1),
}))
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
t3Large, ok := lo.Find(instanceInfo, func(info *ec2.InstanceTypeInfo) bool {
return *info.InstanceType == "t3.large"
})
Expect(ok).To(Equal(true))
it := instancetype.NewInstanceType(ctx, t3Large, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
// t3.large
// maxInterfaces = 3
// maxIPv4PerInterface = 12
// reservedENIs = 1
// (3 - 1) * (12 - 1) + 2 = 24
maxPods := 24
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", maxPods))
})
It("should reserve ENIs when aws.reservedENIs is set and not go below 0 ENIs in max-pods calculation", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
ReservedENIs: lo.ToPtr(1_000_000),
}))
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
t3Large, ok := lo.Find(instanceInfo, func(info *ec2.InstanceTypeInfo) bool {
return *info.InstanceType == "t3.large"
})
Expect(ok).To(Equal(true))
it := instancetype.NewInstanceType(ctx, t3Large, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
// t3.large
// maxInterfaces = 3
// maxIPv4PerInterface = 12
// reservedENIs = 1,000,000
// max(3 - 1,000,000, 0) * (12 - 1) + 2 = 2
// if max-pods is 2, we output 0
maxPods := 0
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", maxPods))
})
It("should override pods-per-core value", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{PodsPerCore: ptr.Int32(1)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", ptr.Int64Value(info.VCpuInfo.DefaultVCpus)))
}
})
It("should take the minimum of pods-per-core and max-pods", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{PodsPerCore: ptr.Int32(4), MaxPods: ptr.Int32(20)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", lo.Min([]int64{20, ptr.Int64Value(info.VCpuInfo.DefaultVCpus) * 4})))
}
})
It("should ignore pods-per-core when using Bottlerocket AMI", func() {
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{PodsPerCore: ptr.Int32(1)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
limitedPods := instancetype.ENILimitedPods(ctx, info)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", limitedPods.Value()))
}
})
It("should take 110 to be the default pods number when pods-per-core is 0 and AWSENILimitedPodDensity is unset", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
instanceInfo, err := awsEnv.InstanceTypesProvider.GetInstanceTypes(ctx)
Expect(err).To(BeNil())
provisioner = test.Provisioner(coretest.ProvisionerOptions{Kubelet: &v1alpha5.KubeletConfiguration{PodsPerCore: ptr.Int32(0)}})
for _, info := range instanceInfo {
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
Expect(it.Capacity.Pods().Value()).To(BeNumerically("==", 110))
}
})
It("shouldn't report more resources than are actually available on instances", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
its, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).To(BeNil())
instanceTypes := map[string]*corecloudprovider.InstanceType{}
for _, it := range its {
instanceTypes[it.Name] = it
}
for _, tc := range []struct {
InstanceType string
// Actual allocatable values as reported by the node from kubelet. You find these
// by launching the node and inspecting the node status allocatable.
Memory resource.Quantity
CPU resource.Quantity
}{
{
InstanceType: "t4g.small",
Memory: resource.MustParse("1408312Ki"),
CPU: resource.MustParse("1930m"),
},
{
InstanceType: "t4g.medium",
Memory: resource.MustParse("3377496Ki"),
CPU: resource.MustParse("1930m"),
},
{
InstanceType: "t4g.xlarge",
Memory: resource.MustParse("15136012Ki"),
CPU: resource.MustParse("3920m"),
},
{
InstanceType: "m5.large",
Memory: resource.MustParse("7220184Ki"),
CPU: resource.MustParse("1930m"),
},
} {
it, ok := instanceTypes[tc.InstanceType]
Expect(ok).To(BeTrue(), fmt.Sprintf("didn't find instance type %q, add to instanceTypeTestData in ./hack/codegen.sh", tc.InstanceType))
allocatable := it.Allocatable()
// We need to ensure that our estimate of the allocatable resources <= the value that kubelet reports. If it's greater,
// we can launch nodes that can't actually run the pods.
Expect(allocatable.Memory().AsApproximateFloat64()).To(BeNumerically("<=", tc.Memory.AsApproximateFloat64()),
fmt.Sprintf("memory estimate for %s was too large, had %s vs %s", tc.InstanceType, allocatable.Memory().String(), tc.Memory.String()))
Expect(allocatable.Cpu().AsApproximateFloat64()).To(BeNumerically("<=", tc.CPU.AsApproximateFloat64()),
fmt.Sprintf("CPU estimate for %s was too large, had %s vs %s", tc.InstanceType, allocatable.Cpu().String(), tc.CPU.String()))
}
})
})
Context("Insufficient Capacity Error Cache", func() {
It("should launch instances of different type on second reconciliation attempt with Insufficient Capacity Error Cache fallback", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "inf1.6xlarge", Zone: "test-zone-1a"}})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
},
}),
coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{v1.LabelTopologyZone: "test-zone-1a"},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("1")},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
// it should've tried to pack them on a single inf1.6xlarge then hit an insufficient capacity error
for _, pod := range pods {
ExpectNotScheduled(ctx, env.Client, pod)
}
nodeNames := sets.NewString()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1alpha1.LabelInstanceAcceleratorName, "inferentia"))
nodeNames.Insert(node.Name)
}
Expect(nodeNames.Len()).To(Equal(2))
})
It("should launch instances in a different zone on second reconciliation attempt with Insufficient Capacity Error Cache fallback", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "p3.8xlarge", Zone: "test-zone-1a"}})
pod := coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{v1.LabelInstanceTypeStable: "p3.8xlarge"},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1")},
},
})
pod.Spec.Affinity = &v1.Affinity{NodeAffinity: &v1.NodeAffinity{PreferredDuringSchedulingIgnoredDuringExecution: []v1.PreferredSchedulingTerm{
{
Weight: 1, Preference: v1.NodeSelectorTerm{MatchExpressions: []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test-zone-1a"}},
}},
},
}}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// it should've tried to pack them in test-zone-1a on a p3.8xlarge then hit insufficient capacity, the next attempt will try test-zone-1b
ExpectNotScheduled(ctx, env.Client, pod)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(SatisfyAll(
HaveKeyWithValue(v1.LabelInstanceTypeStable, "p3.8xlarge"),
HaveKeyWithValue(v1.LabelTopologyZone, "test-zone-1b")))
})
It("should launch smaller instances than optimal if larger instance launch results in Insufficient Capacity Error", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{
{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "m5.xlarge", Zone: "test-zone-1a"},
})
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelInstanceType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"m5.large", "m5.xlarge"},
})
pods := []*v1.Pod{}
for i := 0; i < 2; i++ {
pods = append(pods, coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
NodeSelector: map[string]string{
v1.LabelTopologyZone: "test-zone-1a",
},
}))
}
// Provisions 2 m5.large instances since m5.xlarge was ICE'd
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
ExpectNotScheduled(ctx, env.Client, pod)
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels[v1.LabelInstanceTypeStable]).To(Equal("m5.large"))
}
})
It("should launch instances on later reconciliation attempt with Insufficient Capacity Error Cache expiry", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "inf1.6xlarge", Zone: "test-zone-1a"}})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{v1.LabelInstanceTypeStable: "inf1.6xlarge"},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("2")},
Limits: v1.ResourceList{v1alpha1.ResourceAWSNeuron: resource.MustParse("2")},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
// capacity shortage is over - expire the item from the cache and try again
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{})
awsEnv.UnavailableOfferingsCache.Delete("inf1.6xlarge", "test-zone-1a", v1alpha5.CapacityTypeOnDemand)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1.LabelInstanceTypeStable, "inf1.6xlarge"))
})
It("should launch instances in a different zone on second reconciliation attempt with Insufficient Capacity Error Cache fallback (Habana)", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "dl1.24xlarge", Zone: "test-zone-1a"}})
pod := coretest.UnschedulablePod(coretest.PodOptions{
NodeSelector: map[string]string{v1.LabelInstanceTypeStable: "dl1.24xlarge"},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("1")},
Limits: v1.ResourceList{v1alpha1.ResourceHabanaGaudi: resource.MustParse("1")},
},
})
pod.Spec.Affinity = &v1.Affinity{NodeAffinity: &v1.NodeAffinity{PreferredDuringSchedulingIgnoredDuringExecution: []v1.PreferredSchedulingTerm{
{
Weight: 1, Preference: v1.NodeSelectorTerm{MatchExpressions: []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test-zone-1a"}},
}},
},
}}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// it should've tried to pack them in test-zone-1a on a dl1.24xlarge then hit insufficient capacity, the next attempt will try test-zone-1b
ExpectNotScheduled(ctx, env.Client, pod)
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(SatisfyAll(
HaveKeyWithValue(v1.LabelInstanceTypeStable, "dl1.24xlarge"),
HaveKeyWithValue(v1.LabelTopologyZone, "test-zone-1b")))
})
It("should launch on-demand capacity if flexible to both spot and on-demand, but spot is unavailable", func() {
Expect(awsEnv.EC2API.DescribeInstanceTypesPagesWithContext(ctx, &ec2.DescribeInstanceTypesInput{}, func(dito *ec2.DescribeInstanceTypesOutput, b bool) bool {
for _, it := range dito.InstanceTypes {
awsEnv.EC2API.InsufficientCapacityPools.Add(fake.CapacityPool{CapacityType: v1alpha5.CapacityTypeSpot, InstanceType: aws.StringValue(it.InstanceType), Zone: "test-zone-1a"})
}
return true
})).To(Succeed())
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpIn, Values: []string{v1alpha5.CapacityTypeSpot, v1alpha5.CapacityTypeOnDemand}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test-zone-1a"}},
}
// Spot Unavailable
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
// include deprioritized instance types
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// Fallback to OD
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1alpha5.LabelCapacityType, v1alpha5.CapacityTypeOnDemand))
})
It("should return all instance types, even though with no offerings due to Insufficient Capacity Error", func() {
awsEnv.EC2API.InsufficientCapacityPools.Set([]fake.CapacityPool{
{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "m5.xlarge", Zone: "test-zone-1a"},
{CapacityType: v1alpha5.CapacityTypeOnDemand, InstanceType: "m5.xlarge", Zone: "test-zone-1b"},
{CapacityType: v1alpha5.CapacityTypeSpot, InstanceType: "m5.xlarge", Zone: "test-zone-1a"},
{CapacityType: v1alpha5.CapacityTypeSpot, InstanceType: "m5.xlarge", Zone: "test-zone-1b"},
})
provisioner.Spec.Requirements = nil
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelInstanceType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"m5.xlarge"},
})
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"spot", "on-demand"},
})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
for _, ct := range []string{v1alpha5.CapacityTypeOnDemand, v1alpha5.CapacityTypeSpot} {
for _, zone := range []string{"test-zone-1a", "test-zone-1b"} {
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov,
coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
NodeSelector: map[string]string{
v1alpha5.LabelCapacityType: ct,
v1.LabelTopologyZone: zone,
},
}))
}
}
awsEnv.InstanceTypeCache.Flush()
instanceTypes, err := cloudProvider.GetInstanceTypes(ctx, provisioner)
Expect(err).To(BeNil())
instanceTypeNames := sets.NewString()
for _, it := range instanceTypes {
instanceTypeNames.Insert(it.Name)
if it.Name == "m5.xlarge" {
// should have no valid offerings
Expect(it.Offerings.Available()).To(HaveLen(0))
}
}
Expect(instanceTypeNames.Has("m5.xlarge"))
})
})
Context("CapacityType", func() {
It("should default to on-demand", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1alpha5.LabelCapacityType, v1alpha5.CapacityTypeOnDemand))
})
It("should launch spot capacity if flexible to both spot and on demand", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpIn, Values: []string{v1alpha5.CapacityTypeSpot, v1alpha5.CapacityTypeOnDemand}}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1alpha5.LabelCapacityType, v1alpha5.CapacityTypeSpot))
})
It("should fail to launch capacity when there is no zonal availability for spot", func() {
now := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("m5.large"),
SpotPrice: aws.String("0.004"),
Timestamp: &now,
},
},
})
Expect(awsEnv.PricingProvider.UpdateSpotPricing(ctx)).To(Succeed())
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(now) }).Should(BeTrue())
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpIn, Values: []string{v1alpha5.CapacityTypeSpot}},
{Key: v1.LabelInstanceTypeStable, Operator: v1.NodeSelectorOpIn, Values: []string{"m5.large"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test-zone-1b"}},
}
// Instance type with no zonal availability for spot shouldn't be scheduled
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should succeed to launch spot instance when zonal availability exists", func() {
now := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("m5.large"),
SpotPrice: aws.String("0.004"),
Timestamp: &now,
},
},
})
Expect(awsEnv.PricingProvider.UpdateSpotPricing(ctx)).To(Succeed())
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(now) }).Should(BeTrue())
// not restricting to the zone so we can get any zone
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpIn, Values: []string{v1alpha5.CapacityTypeSpot}},
{Key: v1.LabelInstanceTypeStable, Operator: v1.NodeSelectorOpIn, Values: []string{"m5.large"}},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKeyWithValue(v1alpha5.ProvisionerNameLabelKey, provisioner.Name))
})
})
Context("Ephemeral Storage", func() {
BeforeEach(func() {
nodeTemplate.Spec.AMIFamily = aws.String(v1alpha1.AMIFamilyAL2)
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
SnapshotID: aws.String("snap-xxxxxxxx"),
},
},
}
})
It("should default to EBS defaults when volumeSize is not defined in blockDeviceMappings for custom AMIs", func() {
nodeTemplate.Spec.AMIFamily = aws.String(v1alpha1.AMIFamilyCustom)
nodeTemplate.Spec.AMISelector = map[string]string{
"*": "*",
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(*node.Status.Capacity.StorageEphemeral()).To(Equal(resource.MustParse("20Gi")))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings).To(HaveLen(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].DeviceName).To(Equal("/dev/xvda"))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.SnapshotId).To(Equal("snap-xxxxxxxx"))
})
})
It("should default to EBS defaults when volumeSize is not defined in blockDeviceMappings for AL2 Root volume", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(*node.Status.Capacity.StorageEphemeral()).To(Equal(resource.MustParse("20Gi")))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings).To(HaveLen(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].DeviceName).To(Equal("/dev/xvda"))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.SnapshotId).To(Equal("snap-xxxxxxxx"))
})
})
It("should default to EBS defaults when volumeSize is not defined in blockDeviceMappings for Bottlerocket Root volume", func() {
nodeTemplate.Spec.AMIFamily = aws.String(v1alpha1.AMIFamilyBottlerocket)
nodeTemplate.Spec.BlockDeviceMappings[0].DeviceName = aws.String("/dev/xvdb")
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(*node.Status.Capacity.StorageEphemeral()).To(Equal(resource.MustParse("20Gi")))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings).To(HaveLen(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].DeviceName).To(Equal("/dev/xvdb"))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.SnapshotId).To(Equal("snap-xxxxxxxx"))
})
})
It("should default to EBS defaults when volumeSize is not defined in blockDeviceMappings for Ubuntu Root volume", func() {
nodeTemplate.Spec.AMIFamily = aws.String(v1alpha1.AMIFamilyUbuntu)
nodeTemplate.Spec.BlockDeviceMappings[0].DeviceName = aws.String("/dev/sda1")
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(*node.Status.Capacity.StorageEphemeral()).To(Equal(resource.MustParse("20Gi")))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings).To(HaveLen(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].DeviceName).To(Equal("/dev/sda1"))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.SnapshotId).To(Equal("snap-xxxxxxxx"))
})
})
})
Context("Metadata Options", func() {
It("should default metadata options on generated launch template", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpEndpoint).To(Equal(ec2.LaunchTemplateInstanceMetadataEndpointStateEnabled))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpProtocolIpv6).To(Equal(ec2.LaunchTemplateInstanceMetadataProtocolIpv6Disabled))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit).To(Equal(int64(2)))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpTokens).To(Equal(ec2.LaunchTemplateHttpTokensStateRequired))
})
})
It("should set metadata options on generated launch template from provisioner configuration", func() {
nodeTemplate.Spec.MetadataOptions = &v1alpha1.MetadataOptions{
HTTPEndpoint: aws.String(ec2.LaunchTemplateInstanceMetadataEndpointStateDisabled),
HTTPProtocolIPv6: aws.String(ec2.LaunchTemplateInstanceMetadataProtocolIpv6Enabled),
HTTPPutResponseHopLimit: aws.Int64(1),
HTTPTokens: aws.String(ec2.LaunchTemplateHttpTokensStateOptional),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpEndpoint).To(Equal(ec2.LaunchTemplateInstanceMetadataEndpointStateDisabled))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpProtocolIpv6).To(Equal(ec2.LaunchTemplateInstanceMetadataProtocolIpv6Enabled))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit).To(Equal(int64(1)))
Expect(*ltInput.LaunchTemplateData.MetadataOptions.HttpTokens).To(Equal(ec2.LaunchTemplateHttpTokensStateOptional))
})
})
})
})
// generateSpotPricing creates a spot price history output for use in a mock that has all spot offerings discounted by 50%
// vs the on-demand offering.
func generateSpotPricing(cp *cloudprovider.CloudProvider, prov *v1alpha5.Provisioner) *ec2.DescribeSpotPriceHistoryOutput {
rsp := &ec2.DescribeSpotPriceHistoryOutput{}
instanceTypes, err := cp.GetInstanceTypes(ctx, prov)
awsEnv.InstanceTypeCache.Flush()
Expect(err).To(Succeed())
t := fakeClock.Now()
for _, it := range instanceTypes {
onDemandPrice := 1.00
for _, o := range it.Offerings {
if o.CapacityType == v1alpha5.CapacityTypeOnDemand {
onDemandPrice = o.Price
}
}
for _, o := range it.Offerings {
o := o
if o.CapacityType != v1alpha5.CapacityTypeSpot {
continue
}
spotPrice := fmt.Sprintf("%0.3f", onDemandPrice*0.5)
rsp.SpotPriceHistory = append(rsp.SpotPriceHistory, &ec2.SpotPrice{
AvailabilityZone: &o.Zone,
InstanceType: &it.Name,
SpotPrice: &spotPrice,
Timestamp: &t,
})
}
}
return rsp
}
func makeFakeInstances() []*ec2.InstanceTypeInfo {
var instanceTypes []*ec2.InstanceTypeInfo
ctx := settings.ToContext(context.Background(), &settings.Settings{IsolatedVPC: true})
// Use keys from the static pricing data so that we guarantee pricing for the data
// Create uniform instance data so all of them schedule for a given pod
for _, it := range pricing.NewProvider(ctx, nil, nil, "us-east-1").InstanceTypes() {
instanceTypes = append(instanceTypes, &ec2.InstanceTypeInfo{
InstanceType: aws.String(it),
ProcessorInfo: &ec2.ProcessorInfo{
SupportedArchitectures: aws.StringSlice([]string{"x86_64"}),
},
VCpuInfo: &ec2.VCpuInfo{
DefaultCores: aws.Int64(1),
DefaultVCpus: aws.Int64(2),
},
MemoryInfo: &ec2.MemoryInfo{
SizeInMiB: aws.Int64(8192),
},
NetworkInfo: &ec2.NetworkInfo{
Ipv4AddressesPerInterface: aws.Int64(10),
DefaultNetworkCardIndex: aws.Int64(0),
NetworkCards: []*ec2.NetworkCardInfo{{
NetworkCardIndex: lo.ToPtr(int64(0)),
MaximumNetworkInterfaces: aws.Int64(3),
}},
},
SupportedUsageClasses: fake.DefaultSupportedUsageClasses,
})
}
return instanceTypes
}
func makeFakeInstanceOfferings(instanceTypes []*ec2.InstanceTypeInfo) []*ec2.InstanceTypeOffering {
var instanceTypeOfferings []*ec2.InstanceTypeOffering
// Create uniform instance offering data so all of them schedule for a given pod
for _, instanceType := range instanceTypes {
instanceTypeOfferings = append(instanceTypeOfferings, &ec2.InstanceTypeOffering{
InstanceType: instanceType.InstanceType,
Location: aws.String("test-zone-1a"),
})
}
return instanceTypeOfferings
}
| 1,658 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instancetype
import (
"context"
"fmt"
"math"
"regexp"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"knative.dev/pkg/ptr"
awssettings "github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/utils/resources"
)
const (
MemoryAvailable = "memory.available"
NodeFSAvailable = "nodefs.available"
)
var (
instanceTypeScheme = regexp.MustCompile(`(^[a-z]+)(\-[0-9]+tb)?([0-9]+).*\.`)
)
func NewInstanceType(ctx context.Context, info *ec2.InstanceTypeInfo, kc *v1alpha5.KubeletConfiguration,
region string, nodeTemplate *v1alpha1.AWSNodeTemplate, offerings cloudprovider.Offerings) *cloudprovider.InstanceType {
amiFamily := amifamily.GetAMIFamily(nodeTemplate.Spec.AMIFamily, &amifamily.Options{})
return &cloudprovider.InstanceType{
Name: aws.StringValue(info.InstanceType),
Requirements: computeRequirements(ctx, info, offerings, region, amiFamily, kc),
Offerings: offerings,
Capacity: computeCapacity(ctx, info, amiFamily, nodeTemplate.Spec.BlockDeviceMappings, kc),
Overhead: &cloudprovider.InstanceTypeOverhead{
KubeReserved: kubeReservedResources(cpu(info), pods(ctx, info, amiFamily, kc), ENILimitedPods(ctx, info), amiFamily, kc),
SystemReserved: systemReservedResources(kc),
EvictionThreshold: evictionThreshold(memory(ctx, info), ephemeralStorage(amiFamily, nodeTemplate.Spec.BlockDeviceMappings), amiFamily, kc),
},
}
}
func computeRequirements(ctx context.Context, info *ec2.InstanceTypeInfo, offerings cloudprovider.Offerings, region string,
amiFamily amifamily.AMIFamily, kc *v1alpha5.KubeletConfiguration) scheduling.Requirements {
requirements := scheduling.NewRequirements(
// Well Known Upstream
scheduling.NewRequirement(v1.LabelInstanceTypeStable, v1.NodeSelectorOpIn, aws.StringValue(info.InstanceType)),
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, getArchitecture(info)),
scheduling.NewRequirement(v1.LabelOSStable, v1.NodeSelectorOpIn, getOS(info, amiFamily)...),
scheduling.NewRequirement(v1.LabelTopologyZone, v1.NodeSelectorOpIn, lo.Map(offerings.Available(), func(o cloudprovider.Offering, _ int) string { return o.Zone })...),
scheduling.NewRequirement(v1.LabelTopologyRegion, v1.NodeSelectorOpIn, region),
scheduling.NewRequirement(v1.LabelWindowsBuild, v1.NodeSelectorOpDoesNotExist),
// Well Known to Karpenter
scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpIn, lo.Map(offerings.Available(), func(o cloudprovider.Offering, _ int) string { return o.CapacityType })...),
// Well Known to AWS
scheduling.NewRequirement(v1alpha1.LabelInstanceCPU, v1.NodeSelectorOpIn, fmt.Sprint(aws.Int64Value(info.VCpuInfo.DefaultVCpus))),
scheduling.NewRequirement(v1alpha1.LabelInstanceMemory, v1.NodeSelectorOpIn, fmt.Sprint(aws.Int64Value(info.MemoryInfo.SizeInMiB))),
scheduling.NewRequirement(v1alpha1.LabelInstanceNetworkBandwidth, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstancePods, v1.NodeSelectorOpIn, fmt.Sprint(pods(ctx, info, amiFamily, kc))),
scheduling.NewRequirement(v1alpha1.LabelInstanceCategory, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceFamily, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceGeneration, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceLocalNVME, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceSize, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUName, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUManufacturer, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceGPUMemory, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorName, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorManufacturer, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceAcceleratorCount, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(v1alpha1.LabelInstanceHypervisor, v1.NodeSelectorOpIn, aws.StringValue(info.Hypervisor)),
scheduling.NewRequirement(v1alpha1.LabelInstanceEncryptionInTransitSupported, v1.NodeSelectorOpIn, fmt.Sprint(aws.BoolValue(info.NetworkInfo.EncryptionInTransitSupported))),
)
// Instance Type Labels
instanceFamilyParts := instanceTypeScheme.FindStringSubmatch(aws.StringValue(info.InstanceType))
if len(instanceFamilyParts) == 4 {
requirements[v1alpha1.LabelInstanceCategory].Insert(instanceFamilyParts[1])
requirements[v1alpha1.LabelInstanceGeneration].Insert(instanceFamilyParts[3])
}
instanceTypeParts := strings.Split(aws.StringValue(info.InstanceType), ".")
if len(instanceTypeParts) == 2 {
requirements.Get(v1alpha1.LabelInstanceFamily).Insert(instanceTypeParts[0])
requirements.Get(v1alpha1.LabelInstanceSize).Insert(instanceTypeParts[1])
}
if info.InstanceStorageInfo != nil && aws.StringValue(info.InstanceStorageInfo.NvmeSupport) != ec2.EphemeralNvmeSupportUnsupported {
requirements[v1alpha1.LabelInstanceLocalNVME].Insert(fmt.Sprint(aws.Int64Value(info.InstanceStorageInfo.TotalSizeInGB)))
}
// Network bandwidth
if bandwidth, ok := InstanceTypeBandwidthMegabits[aws.StringValue(info.InstanceType)]; ok {
requirements[v1alpha1.LabelInstanceNetworkBandwidth].Insert(fmt.Sprint(bandwidth))
}
// GPU Labels
if info.GpuInfo != nil && len(info.GpuInfo.Gpus) == 1 {
gpu := info.GpuInfo.Gpus[0]
requirements.Get(v1alpha1.LabelInstanceGPUName).Insert(lowerKabobCase(aws.StringValue(gpu.Name)))
requirements.Get(v1alpha1.LabelInstanceGPUManufacturer).Insert(lowerKabobCase(aws.StringValue(gpu.Manufacturer)))
requirements.Get(v1alpha1.LabelInstanceGPUCount).Insert(fmt.Sprint(aws.Int64Value(gpu.Count)))
requirements.Get(v1alpha1.LabelInstanceGPUMemory).Insert(fmt.Sprint(aws.Int64Value(gpu.MemoryInfo.SizeInMiB)))
}
// Accelerators
if info.InferenceAcceleratorInfo != nil && len(info.InferenceAcceleratorInfo.Accelerators) == 1 {
accelerator := info.InferenceAcceleratorInfo.Accelerators[0]
requirements.Get(v1alpha1.LabelInstanceAcceleratorName).Insert(lowerKabobCase(aws.StringValue(accelerator.Name)))
requirements.Get(v1alpha1.LabelInstanceAcceleratorManufacturer).Insert(lowerKabobCase(aws.StringValue(accelerator.Manufacturer)))
requirements.Get(v1alpha1.LabelInstanceAcceleratorCount).Insert(fmt.Sprint(aws.Int64Value(accelerator.Count)))
}
// Windows Build Version Labels
if family, ok := amiFamily.(*amifamily.Windows); ok {
requirements.Get(v1.LabelWindowsBuild).Insert(family.Build)
}
return hardcodeNeuron(requirements, info)
}
// TODO: remove function once DescribeInstanceTypes contains the accelerator data
// Values found from: https://aws.amazon.com/ec2/instance-types/trn1/
func hardcodeNeuron(requirements scheduling.Requirements, info *ec2.InstanceTypeInfo) scheduling.Requirements {
// Trn1 Accelerators
if strings.HasPrefix(*info.InstanceType, "trn1") {
requirements.Get(v1alpha1.LabelInstanceAcceleratorName).Insert(lowerKabobCase("Inferentia"))
requirements.Get(v1alpha1.LabelInstanceAcceleratorManufacturer).Insert(lowerKabobCase("AWS"))
requirements.Get(v1alpha1.LabelInstanceAcceleratorCount).Insert(fmt.Sprint(awsNeurons(info)))
}
return requirements
}
func getOS(info *ec2.InstanceTypeInfo, amiFamily amifamily.AMIFamily) []string {
if _, ok := amiFamily.(*amifamily.Windows); ok {
if getArchitecture(info) == v1alpha5.ArchitectureAmd64 {
return []string{string(v1.Windows)}
}
return []string{}
}
return []string{string(v1.Linux)}
}
func getArchitecture(info *ec2.InstanceTypeInfo) string {
for _, architecture := range info.ProcessorInfo.SupportedArchitectures {
if value, ok := v1alpha1.AWSToKubeArchitectures[aws.StringValue(architecture)]; ok {
return value
}
}
return fmt.Sprint(aws.StringValueSlice(info.ProcessorInfo.SupportedArchitectures)) // Unrecognized, but used for error printing
}
func computeCapacity(ctx context.Context, info *ec2.InstanceTypeInfo, amiFamily amifamily.AMIFamily,
blockDeviceMappings []*v1alpha1.BlockDeviceMapping, kc *v1alpha5.KubeletConfiguration) v1.ResourceList {
resourceList := v1.ResourceList{
v1.ResourceCPU: *cpu(info),
v1.ResourceMemory: *memory(ctx, info),
v1.ResourceEphemeralStorage: *ephemeralStorage(amiFamily, blockDeviceMappings),
v1.ResourcePods: *pods(ctx, info, amiFamily, kc),
v1alpha1.ResourceAWSPodENI: *awsPodENI(ctx, aws.StringValue(info.InstanceType)),
v1alpha1.ResourceNVIDIAGPU: *nvidiaGPUs(info),
v1alpha1.ResourceAMDGPU: *amdGPUs(info),
v1alpha1.ResourceAWSNeuron: *awsNeurons(info),
v1alpha1.ResourceHabanaGaudi: *habanaGaudis(info),
}
if _, ok := amiFamily.(*amifamily.Windows); ok {
//ResourcePrivateIPv4Address is the same as ENILimitedPods on Windows node
resourceList[v1alpha1.ResourcePrivateIPv4Address] = *privateIPv4Address(info)
}
return resourceList
}
func cpu(info *ec2.InstanceTypeInfo) *resource.Quantity {
return resources.Quantity(fmt.Sprint(*info.VCpuInfo.DefaultVCpus))
}
func memory(ctx context.Context, info *ec2.InstanceTypeInfo) *resource.Quantity {
sizeInMib := *info.MemoryInfo.SizeInMiB
// Gravitons have an extra 64 MiB of cma reserved memory that we can't use
if len(info.ProcessorInfo.SupportedArchitectures) > 0 && *info.ProcessorInfo.SupportedArchitectures[0] == "arm64" {
sizeInMib -= 64
}
mem := resources.Quantity(fmt.Sprintf("%dMi", sizeInMib))
// Account for VM overhead in calculation
mem.Sub(resource.MustParse(fmt.Sprintf("%dMi", int64(math.Ceil(float64(mem.Value())*awssettings.FromContext(ctx).VMMemoryOverheadPercent/1024/1024)))))
return mem
}
// Setting ephemeral-storage to be either the default value or what is defined in blockDeviceMappings
func ephemeralStorage(amiFamily amifamily.AMIFamily, blockDeviceMappings []*v1alpha1.BlockDeviceMapping) *resource.Quantity {
if len(blockDeviceMappings) != 0 {
switch amiFamily.(type) {
case *amifamily.Custom:
// We can't know if a custom AMI is going to have a volume size.
volumeSize := blockDeviceMappings[len(blockDeviceMappings)-1].EBS.VolumeSize
return lo.Ternary(volumeSize != nil, volumeSize, amifamily.DefaultEBS.VolumeSize)
default:
// If a block device mapping exists in the provider for the root volume, use the volume size specified in the provider. If not, use the default
if blockDeviceMapping, ok := lo.Find(blockDeviceMappings, func(bdm *v1alpha1.BlockDeviceMapping) bool {
return *bdm.DeviceName == *amiFamily.EphemeralBlockDevice()
}); ok && blockDeviceMapping.EBS.VolumeSize != nil {
return blockDeviceMapping.EBS.VolumeSize
}
}
}
//Return the ephemeralBlockDevice size if defined in ami
if ephemeralBlockDevice, ok := lo.Find(amiFamily.DefaultBlockDeviceMappings(), func(item *v1alpha1.BlockDeviceMapping) bool {
return *amiFamily.EphemeralBlockDevice() == *item.DeviceName
}); ok {
return ephemeralBlockDevice.EBS.VolumeSize
}
return amifamily.DefaultEBS.VolumeSize
}
func awsPodENI(ctx context.Context, name string) *resource.Quantity {
// https://docs.aws.amazon.com/eks/latest/userguide/security-groups-for-pods.html#supported-instance-types
limits, ok := Limits[name]
if awssettings.FromContext(ctx).EnablePodENI && ok && limits.IsTrunkingCompatible {
return resources.Quantity(fmt.Sprint(limits.BranchInterface))
}
return resources.Quantity("0")
}
func nvidiaGPUs(info *ec2.InstanceTypeInfo) *resource.Quantity {
count := int64(0)
if info.GpuInfo != nil {
for _, gpu := range info.GpuInfo.Gpus {
if *gpu.Manufacturer == "NVIDIA" {
count += *gpu.Count
}
}
}
return resources.Quantity(fmt.Sprint(count))
}
func amdGPUs(info *ec2.InstanceTypeInfo) *resource.Quantity {
count := int64(0)
if info.GpuInfo != nil {
for _, gpu := range info.GpuInfo.Gpus {
if *gpu.Manufacturer == "AMD" {
count += *gpu.Count
}
}
}
return resources.Quantity(fmt.Sprint(count))
}
// TODO: remove trn1 hardcode values once DescribeInstanceTypes contains the accelerator data
// Values found from: https://aws.amazon.com/ec2/instance-types/trn1/
func awsNeurons(info *ec2.InstanceTypeInfo) *resource.Quantity {
count := int64(0)
if *info.InstanceType == "trn1.2xlarge" {
count = int64(1)
} else if *info.InstanceType == "trn1.32xlarge" {
count = int64(16)
} else if *info.InstanceType == "trn1n.32xlarge" {
count = int64(16)
} else if info.InferenceAcceleratorInfo != nil {
for _, accelerator := range info.InferenceAcceleratorInfo.Accelerators {
count += *accelerator.Count
}
}
return resources.Quantity(fmt.Sprint(count))
}
func habanaGaudis(info *ec2.InstanceTypeInfo) *resource.Quantity {
count := int64(0)
if info.GpuInfo != nil {
for _, gpu := range info.GpuInfo.Gpus {
if *gpu.Manufacturer == "Habana" {
count += *gpu.Count
}
}
}
return resources.Quantity(fmt.Sprint(count))
}
func ENILimitedPods(ctx context.Context, info *ec2.InstanceTypeInfo) *resource.Quantity {
// The number of pods per node is calculated using the formula:
// max number of ENIs * (IPv4 Addresses per ENI -1) + 2
// https://github.com/awslabs/amazon-eks-ami/blob/master/files/eni-max-pods.txt#L20
// VPC CNI only uses the default network interface
// https://github.com/aws/amazon-vpc-cni-k8s/blob/3294231c0dce52cfe473bf6c62f47956a3b333b6/scripts/gen_vpc_ip_limits.go#L162
networkInterfaces := *info.NetworkInfo.NetworkCards[*info.NetworkInfo.DefaultNetworkCardIndex].MaximumNetworkInterfaces
usableNetworkInterfaces := lo.Max([]int64{(networkInterfaces - int64(awssettings.FromContext(ctx).ReservedENIs)), 0})
if usableNetworkInterfaces == 0 {
return resource.NewQuantity(0, resource.DecimalSI)
}
addressesPerInterface := *info.NetworkInfo.Ipv4AddressesPerInterface
return resources.Quantity(fmt.Sprint(usableNetworkInterfaces*(addressesPerInterface-1) + 2))
}
func privateIPv4Address(info *ec2.InstanceTypeInfo) *resource.Quantity {
//https://github.com/aws/amazon-vpc-resource-controller-k8s/blob/ecbd6965a0100d9a070110233762593b16023287/pkg/provider/ip/provider.go#L297
capacity := aws.Int64Value(info.NetworkInfo.Ipv4AddressesPerInterface) - 1
return resources.Quantity(fmt.Sprint(capacity))
}
func systemReservedResources(kc *v1alpha5.KubeletConfiguration) v1.ResourceList {
if kc != nil && kc.SystemReserved != nil {
return kc.SystemReserved
}
return v1.ResourceList{}
}
func kubeReservedResources(cpus, pods, eniLimitedPods *resource.Quantity, amiFamily amifamily.AMIFamily, kc *v1alpha5.KubeletConfiguration) v1.ResourceList {
if amiFamily.FeatureFlags().UsesENILimitedMemoryOverhead {
pods = eniLimitedPods
}
resources := v1.ResourceList{
v1.ResourceMemory: resource.MustParse(fmt.Sprintf("%dMi", (11*pods.Value())+255)),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"), // default kube-reserved ephemeral-storage
}
// kube-reserved Computed from
// https://github.com/bottlerocket-os/bottlerocket/pull/1388/files#diff-bba9e4e3e46203be2b12f22e0d654ebd270f0b478dd34f40c31d7aa695620f2fR611
for _, cpuRange := range []struct {
start int64
end int64
percentage float64
}{
{start: 0, end: 1000, percentage: 0.06},
{start: 1000, end: 2000, percentage: 0.01},
{start: 2000, end: 4000, percentage: 0.005},
{start: 4000, end: 1 << 31, percentage: 0.0025},
} {
if cpu := cpus.MilliValue(); cpu >= cpuRange.start {
r := float64(cpuRange.end - cpuRange.start)
if cpu < cpuRange.end {
r = float64(cpu - cpuRange.start)
}
cpuOverhead := resources.Cpu()
cpuOverhead.Add(*resource.NewMilliQuantity(int64(r*cpuRange.percentage), resource.DecimalSI))
resources[v1.ResourceCPU] = *cpuOverhead
}
}
if kc != nil && kc.KubeReserved != nil {
return lo.Assign(resources, kc.KubeReserved)
}
return resources
}
func evictionThreshold(memory *resource.Quantity, storage *resource.Quantity, amiFamily amifamily.AMIFamily, kc *v1alpha5.KubeletConfiguration) v1.ResourceList {
overhead := v1.ResourceList{
v1.ResourceMemory: resource.MustParse("100Mi"),
v1.ResourceEphemeralStorage: resource.MustParse(fmt.Sprint(math.Ceil(float64(storage.Value()) / 100 * 10))),
}
if kc == nil {
return overhead
}
override := v1.ResourceList{}
var evictionSignals []map[string]string
if kc.EvictionHard != nil {
evictionSignals = append(evictionSignals, kc.EvictionHard)
}
if kc.EvictionSoft != nil && amiFamily.FeatureFlags().EvictionSoftEnabled {
evictionSignals = append(evictionSignals, kc.EvictionSoft)
}
for _, m := range evictionSignals {
temp := v1.ResourceList{}
if v, ok := m[MemoryAvailable]; ok {
temp[v1.ResourceMemory] = computeEvictionSignal(*memory, v)
}
if v, ok := m[NodeFSAvailable]; ok {
temp[v1.ResourceEphemeralStorage] = computeEvictionSignal(*storage, v)
}
override = resources.MaxResources(override, temp)
}
// Assign merges maps from left to right so overrides will always be taken last
return lo.Assign(overhead, override)
}
func pods(ctx context.Context, info *ec2.InstanceTypeInfo, amiFamily amifamily.AMIFamily, kc *v1alpha5.KubeletConfiguration) *resource.Quantity {
var count int64
switch {
case kc != nil && kc.MaxPods != nil:
count = int64(ptr.Int32Value(kc.MaxPods))
case awssettings.FromContext(ctx).EnableENILimitedPodDensity && amiFamily.FeatureFlags().SupportsENILimitedPodDensity:
count = ENILimitedPods(ctx, info).Value()
default:
count = 110
}
if kc != nil && ptr.Int32Value(kc.PodsPerCore) > 0 && amiFamily.FeatureFlags().PodsPerCoreEnabled {
count = lo.Min([]int64{int64(ptr.Int32Value(kc.PodsPerCore)) * ptr.Int64Value(info.VCpuInfo.DefaultVCpus), count})
}
return resources.Quantity(fmt.Sprint(count))
}
func lowerKabobCase(s string) string {
return strings.ToLower(strings.ReplaceAll(s, " ", "-"))
}
// computeEvictionSignal computes the resource quantity value for an eviction signal value, computed off the
// base capacity value if the signal value is a percentage or as a resource quantity if the signal value isn't a percentage
func computeEvictionSignal(capacity resource.Quantity, signalValue string) resource.Quantity {
if strings.HasSuffix(signalValue, "%") {
p := mustParsePercentage(signalValue)
// Calculation is node.capacity * signalValue if percentage
// From https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/#eviction-signals
return resource.MustParse(fmt.Sprint(math.Ceil(capacity.AsApproximateFloat64() / 100 * p)))
}
return resource.MustParse(signalValue)
}
func mustParsePercentage(v string) float64 {
p, err := strconv.ParseFloat(strings.Trim(v, "%"), 64)
if err != nil {
panic(fmt.Sprintf("expected percentage value to be a float but got %s, %v", v, err))
}
// Setting percentage value to 100% is considered disabling the threshold according to
// https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/
if p == 100 {
p = 0
}
return p
}
| 441 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package instancetype
// GENERATED FILE. DO NOT EDIT DIRECTLY.
// Update hack/code/bandwidth_gen.go and re-generate to edit
// You can add instance types by adding to the --instance-types CLI flag
var (
InstanceTypeBandwidthMegabits = map[string]int64{
// f1.2xlarge is not available in https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html
// g3.16xlarge is not available in https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html
"t2.nano": 32,
"t3.nano": 32,
"t3a.nano": 32,
"t4g.nano": 32,
"t2.micro": 64,
"t3.micro": 64,
"t3a.micro": 64,
"t4g.micro": 64,
"t1.micro": 70,
"t2.small": 128,
"t3.small": 128,
"t3a.small": 128,
"t4g.small": 128,
"t2.medium": 256,
"t3.medium": 256,
"t3a.medium": 256,
"t4g.medium": 256,
"c1.medium": 300,
"m1.medium": 300,
"m1.small": 300,
"m2.xlarge": 300,
"m3.medium": 300,
"m4.large": 450,
"a1.medium": 500,
"c3.large": 500,
"c6g.medium": 500,
"c6gd.medium": 500,
"m6g.medium": 500,
"m6gd.medium": 500,
"r3.large": 500,
"r6g.medium": 500,
"r6gd.medium": 500,
"x2gd.medium": 500,
"t2.large": 512,
"t3.large": 512,
"t3a.large": 512,
"t4g.large": 512,
"c7g.medium": 520,
"m7g.medium": 520,
"r7g.medium": 520,
"c4.large": 625,
"x1e.xlarge": 625,
"c3.xlarge": 700,
"i2.xlarge": 700,
"m1.large": 700,
"m2.2xlarge": 700,
"m3.large": 700,
"r3.xlarge": 700,
"a1.large": 750,
"c5.large": 750,
"c5a.large": 750,
"c5ad.large": 750,
"c5d.large": 750,
"c6g.large": 750,
"c6gd.large": 750,
"i3.large": 750,
"m4.xlarge": 750,
"m5.large": 750,
"m5a.large": 750,
"m5ad.large": 750,
"m5d.large": 750,
"m6g.large": 750,
"m6gd.large": 750,
"r4.large": 750,
"r5.large": 750,
"r5a.large": 750,
"r5ad.large": 750,
"r5b.large": 750,
"r5d.large": 750,
"r6g.large": 750,
"r6gd.large": 750,
"t2.xlarge": 750,
"x2gd.large": 750,
"z1d.large": 750,
"c6a.large": 781,
"c6i.large": 781,
"c6id.large": 781,
"i4g.large": 781,
"i4i.large": 781,
"m6a.large": 781,
"m6i.large": 781,
"m6id.large": 781,
"r6a.large": 781,
"r6i.large": 781,
"r6id.large": 781,
"c7g.large": 937,
"m7g.large": 937,
"r7g.large": 937,
"c1.xlarge": 1000,
"c3.2xlarge": 1000,
"i2.2xlarge": 1000,
"m1.xlarge": 1000,
"m2.4xlarge": 1000,
"m3.2xlarge": 1000,
"m3.xlarge": 1000,
"m4.2xlarge": 1000,
"r3.2xlarge": 1000,
"t2.2xlarge": 1000,
"t3.xlarge": 1024,
"t3a.xlarge": 1024,
"t4g.xlarge": 1024,
"a1.xlarge": 1250,
"c4.xlarge": 1250,
"c5.xlarge": 1250,
"c5a.xlarge": 1250,
"c5ad.xlarge": 1250,
"c5d.xlarge": 1250,
"c6g.xlarge": 1250,
"c6gd.xlarge": 1250,
"d2.xlarge": 1250,
"g5g.xlarge": 1250,
"i3.xlarge": 1250,
"m5.xlarge": 1250,
"m5a.xlarge": 1250,
"m5ad.xlarge": 1250,
"m5d.xlarge": 1250,
"m6g.xlarge": 1250,
"m6gd.xlarge": 1250,
"r4.xlarge": 1250,
"r5.xlarge": 1250,
"r5a.xlarge": 1250,
"r5ad.xlarge": 1250,
"r5b.xlarge": 1250,
"r5d.xlarge": 1250,
"r6g.xlarge": 1250,
"r6gd.xlarge": 1250,
"x1e.2xlarge": 1250,
"x2gd.xlarge": 1250,
"z1d.xlarge": 1250,
"c6a.xlarge": 1562,
"c6i.xlarge": 1562,
"c6id.xlarge": 1562,
"is4gen.medium": 1562,
"m6a.xlarge": 1562,
"m6i.xlarge": 1562,
"m6id.xlarge": 1562,
"r6a.xlarge": 1562,
"r6i.xlarge": 1562,
"r6id.xlarge": 1562,
"c6gn.medium": 1600,
"i4g.xlarge": 1875,
"i4i.xlarge": 1875,
"x2iedn.xlarge": 1875,
"c7g.xlarge": 1876,
"m7g.xlarge": 1876,
"r7g.xlarge": 1876,
"c3.4xlarge": 2000,
"g4ad.xlarge": 2000,
"i2.4xlarge": 2000,
"m4.4xlarge": 2000,
"r3.4xlarge": 2000,
"t3.2xlarge": 2048,
"t3a.2xlarge": 2048,
"t4g.2xlarge": 2048,
"inf2.xlarge": 2083,
"i3en.large": 2100,
"m5dn.large": 2100,
"m5n.large": 2100,
"r5dn.large": 2100,
"r5n.large": 2100,
"a1.2xlarge": 2500,
"c4.2xlarge": 2500,
"c5.2xlarge": 2500,
"c5a.2xlarge": 2500,
"c5ad.2xlarge": 2500,
"c5d.2xlarge": 2500,
"c6g.2xlarge": 2500,
"c6gd.2xlarge": 2500,
"d2.2xlarge": 2500,
"g5.xlarge": 2500,
"g5g.2xlarge": 2500,
"h1.2xlarge": 2500,
"i3.2xlarge": 2500,
"m5.2xlarge": 2500,
"m5a.2xlarge": 2500,
"m5ad.2xlarge": 2500,
"m5d.2xlarge": 2500,
"m6g.2xlarge": 2500,
"m6gd.2xlarge": 2500,
"r4.2xlarge": 2500,
"r5.2xlarge": 2500,
"r5a.2xlarge": 2500,
"r5ad.2xlarge": 2500,
"r5b.2xlarge": 2500,
"r5d.2xlarge": 2500,
"r6g.2xlarge": 2500,
"r6gd.2xlarge": 2500,
"x1e.4xlarge": 2500,
"x2gd.2xlarge": 2500,
"z1d.2xlarge": 2500,
"c5n.large": 3000,
"c6gn.large": 3000,
"d3.xlarge": 3000,
"m5zn.large": 3000,
"vt1.3xlarge": 3120,
"c6a.2xlarge": 3125,
"c6i.2xlarge": 3125,
"c6id.2xlarge": 3125,
"c6in.large": 3125,
"c7gn.medium": 3125,
"im4gn.large": 3125,
"is4gen.large": 3125,
"m6a.2xlarge": 3125,
"m6i.2xlarge": 3125,
"m6id.2xlarge": 3125,
"m6idn.large": 3125,
"m6in.large": 3125,
"r6a.2xlarge": 3125,
"r6i.2xlarge": 3125,
"r6id.2xlarge": 3125,
"r6idn.large": 3125,
"r6in.large": 3125,
"trn1.2xlarge": 3125,
"c7g.2xlarge": 3750,
"m7g.2xlarge": 3750,
"r7g.2xlarge": 3750,
"m5dn.xlarge": 4100,
"m5n.xlarge": 4100,
"r5dn.xlarge": 4100,
"r5n.xlarge": 4100,
"g4ad.2xlarge": 4167,
"i3en.xlarge": 4200,
"i4g.2xlarge": 4687,
"i4i.2xlarge": 4687,
"a1.4xlarge": 5000,
"a1.metal": 5000,
"c3.8xlarge": 5000,
"c4.4xlarge": 5000,
"c4.8xlarge": 5000,
"c5.4xlarge": 5000,
"c5a.4xlarge": 5000,
"c5ad.4xlarge": 5000,
"c5d.4xlarge": 5000,
"c5n.xlarge": 5000,
"c6g.4xlarge": 5000,
"c6gd.4xlarge": 5000,
"d2.4xlarge": 5000,
"d2.8xlarge": 5000,
"g4dn.xlarge": 5000,
"g5.2xlarge": 5000,
"g5g.4xlarge": 5000,
"h1.4xlarge": 5000,
"i2.8xlarge": 5000,
"i3.4xlarge": 5000,
"inf1.2xlarge": 5000,
"inf1.xlarge": 5000,
"m4.10xlarge": 5000,
"m4.16xlarge": 5000,
"m5.4xlarge": 5000,
"m5a.4xlarge": 5000,
"m5ad.4xlarge": 5000,
"m5d.4xlarge": 5000,
"m5zn.xlarge": 5000,
"m6g.4xlarge": 5000,
"m6gd.4xlarge": 5000,
"r3.8xlarge": 5000,
"r4.4xlarge": 5000,
"r5.4xlarge": 5000,
"r5a.4xlarge": 5000,
"r5ad.4xlarge": 5000,
"r5b.4xlarge": 5000,
"r5d.4xlarge": 5000,
"r6g.4xlarge": 5000,
"r6gd.4xlarge": 5000,
"x1e.8xlarge": 5000,
"x2gd.4xlarge": 5000,
"x2iedn.2xlarge": 5000,
"z1d.3xlarge": 5000,
"d3.2xlarge": 6000,
"d3en.xlarge": 6000,
"c6a.4xlarge": 6250,
"c6i.4xlarge": 6250,
"c6id.4xlarge": 6250,
"c6in.xlarge": 6250,
"c7gn.large": 6250,
"im4gn.xlarge": 6250,
"is4gen.xlarge": 6250,
"m6a.4xlarge": 6250,
"m6i.4xlarge": 6250,
"m6id.4xlarge": 6250,
"m6idn.xlarge": 6250,
"m6in.xlarge": 6250,
"r6a.4xlarge": 6250,
"r6i.4xlarge": 6250,
"r6id.4xlarge": 6250,
"r6idn.xlarge": 6250,
"r6in.xlarge": 6250,
"vt1.6xlarge": 6250,
"c6gn.xlarge": 6300,
"c7g.4xlarge": 7500,
"m5a.8xlarge": 7500,
"m5ad.8xlarge": 7500,
"m7g.4xlarge": 7500,
"r5a.8xlarge": 7500,
"r5ad.8xlarge": 7500,
"r7g.4xlarge": 7500,
"m5dn.2xlarge": 8125,
"m5n.2xlarge": 8125,
"r5dn.2xlarge": 8125,
"r5n.2xlarge": 8125,
"g4ad.4xlarge": 8333,
"i3en.2xlarge": 8400,
"i4g.4xlarge": 9375,
"i4i.4xlarge": 9375,
"c5a.8xlarge": 10000,
"c5ad.8xlarge": 10000,
"c5n.2xlarge": 10000,
"g4dn.2xlarge": 10000,
"g5.4xlarge": 10000,
"h1.8xlarge": 10000,
"i3.8xlarge": 10000,
"m5.8xlarge": 10000,
"m5a.12xlarge": 10000,
"m5ad.12xlarge": 10000,
"m5d.8xlarge": 10000,
"m5zn.2xlarge": 10000,
"mac2.metal": 10000,
"r4.8xlarge": 10000,
"r5.8xlarge": 10000,
"r5a.12xlarge": 10000,
"r5ad.12xlarge": 10000,
"r5b.8xlarge": 10000,
"r5d.8xlarge": 10000,
"x1.16xlarge": 10000,
"x1e.16xlarge": 10000,
"c5.12xlarge": 12000,
"c5.9xlarge": 12000,
"c5a.12xlarge": 12000,
"c5ad.12xlarge": 12000,
"c5d.12xlarge": 12000,
"c5d.9xlarge": 12000,
"c6g.8xlarge": 12000,
"c6gd.8xlarge": 12000,
"g5g.8xlarge": 12000,
"m5.12xlarge": 12000,
"m5a.16xlarge": 12000,
"m5ad.16xlarge": 12000,
"m5d.12xlarge": 12000,
"m6g.8xlarge": 12000,
"m6gd.8xlarge": 12000,
"r5.12xlarge": 12000,
"r5a.16xlarge": 12000,
"r5ad.16xlarge": 12000,
"r5b.12xlarge": 12000,
"r5d.12xlarge": 12000,
"r6g.8xlarge": 12000,
"r6gd.8xlarge": 12000,
"x2gd.8xlarge": 12000,
"z1d.6xlarge": 12000,
"c6a.8xlarge": 12500,
"c6gn.2xlarge": 12500,
"c6i.8xlarge": 12500,
"c6id.8xlarge": 12500,
"c6in.2xlarge": 12500,
"c7gn.xlarge": 12500,
"d3.4xlarge": 12500,
"d3en.2xlarge": 12500,
"i3en.3xlarge": 12500,
"im4gn.2xlarge": 12500,
"is4gen.2xlarge": 12500,
"m6a.8xlarge": 12500,
"m6i.8xlarge": 12500,
"m6id.8xlarge": 12500,
"m6idn.2xlarge": 12500,
"m6in.2xlarge": 12500,
"r6a.8xlarge": 12500,
"r6i.8xlarge": 12500,
"r6id.8xlarge": 12500,
"r6idn.2xlarge": 12500,
"r6in.2xlarge": 12500,
"x2iedn.4xlarge": 12500,
"x2iezn.2xlarge": 12500,
"c5n.4xlarge": 15000,
"c6gn.4xlarge": 15000,
"c7g.8xlarge": 15000,
"g4ad.8xlarge": 15000,
"m5zn.3xlarge": 15000,
"m7g.8xlarge": 15000,
"r7g.8xlarge": 15000,
"x2iezn.4xlarge": 15000,
"m5dn.4xlarge": 16250,
"m5n.4xlarge": 16250,
"r5dn.4xlarge": 16250,
"r5n.4xlarge": 16250,
"inf2.8xlarge": 16667,
"c6a.12xlarge": 18750,
"c6i.12xlarge": 18750,
"c6id.12xlarge": 18750,
"i4g.8xlarge": 18750,
"i4i.8xlarge": 18750,
"m6a.12xlarge": 18750,
"m6i.12xlarge": 18750,
"m6id.12xlarge": 18750,
"r6a.12xlarge": 18750,
"r6i.12xlarge": 18750,
"r6id.12xlarge": 18750,
"c5a.16xlarge": 20000,
"c5a.24xlarge": 20000,
"c5ad.16xlarge": 20000,
"c5ad.24xlarge": 20000,
"c6g.12xlarge": 20000,
"c6gd.12xlarge": 20000,
"g4dn.4xlarge": 20000,
"m5.16xlarge": 20000,
"m5a.24xlarge": 20000,
"m5ad.24xlarge": 20000,
"m5d.16xlarge": 20000,
"m6g.12xlarge": 20000,
"m6gd.12xlarge": 20000,
"r5.16xlarge": 20000,
"r5a.24xlarge": 20000,
"r5ad.24xlarge": 20000,
"r5b.16xlarge": 20000,
"r5d.16xlarge": 20000,
"r6g.12xlarge": 20000,
"r6gd.12xlarge": 20000,
"x2gd.12xlarge": 20000,
"c7g.12xlarge": 22500,
"m7g.12xlarge": 22500,
"r7g.12xlarge": 22500,
"c5.18xlarge": 25000,
"c5.24xlarge": 25000,
"c5.metal": 25000,
"c5d.18xlarge": 25000,
"c5d.24xlarge": 25000,
"c5d.metal": 25000,
"c6a.16xlarge": 25000,
"c6g.16xlarge": 25000,
"c6g.metal": 25000,
"c6gd.16xlarge": 25000,
"c6gd.metal": 25000,
"c6i.16xlarge": 25000,
"c6id.16xlarge": 25000,
"c6in.4xlarge": 25000,
"c7gn.2xlarge": 25000,
"d3.8xlarge": 25000,
"d3en.4xlarge": 25000,
"g4ad.16xlarge": 25000,
"g5.16xlarge": 25000,
"g5.8xlarge": 25000,
"g5g.16xlarge": 25000,
"g5g.metal": 25000,
"h1.16xlarge": 25000,
"i3.16xlarge": 25000,
"i3.metal": 25000,
"i3en.6xlarge": 25000,
"im4gn.4xlarge": 25000,
"inf1.6xlarge": 25000,
"is4gen.4xlarge": 25000,
"m5.24xlarge": 25000,
"m5.metal": 25000,
"m5d.24xlarge": 25000,
"m5d.metal": 25000,
"m5dn.8xlarge": 25000,
"m5n.8xlarge": 25000,
"m6a.16xlarge": 25000,
"m6g.16xlarge": 25000,
"m6g.metal": 25000,
"m6gd.16xlarge": 25000,
"m6gd.metal": 25000,
"m6i.16xlarge": 25000,
"m6id.16xlarge": 25000,
"m6idn.4xlarge": 25000,
"m6in.4xlarge": 25000,
"mac1.metal": 25000,
"r4.16xlarge": 25000,
"r5.24xlarge": 25000,
"r5.metal": 25000,
"r5b.24xlarge": 25000,
"r5b.metal": 25000,
"r5d.24xlarge": 25000,
"r5d.metal": 25000,
"r5dn.8xlarge": 25000,
"r5n.8xlarge": 25000,
"r6a.16xlarge": 25000,
"r6g.16xlarge": 25000,
"r6g.metal": 25000,
"r6gd.16xlarge": 25000,
"r6gd.metal": 25000,
"r6i.16xlarge": 25000,
"r6id.16xlarge": 25000,
"r6idn.4xlarge": 25000,
"r6in.4xlarge": 25000,
"vt1.24xlarge": 25000,
"x1.32xlarge": 25000,
"x1e.32xlarge": 25000,
"x2gd.16xlarge": 25000,
"x2gd.metal": 25000,
"x2iedn.8xlarge": 25000,
"z1d.12xlarge": 25000,
"z1d.metal": 25000,
"c7g.16xlarge": 30000,
"c7g.metal": 30000,
"m7g.16xlarge": 30000,
"m7g.metal": 30000,
"r7g.16xlarge": 30000,
"r7g.metal": 30000,
"c6a.24xlarge": 37500,
"c6i.24xlarge": 37500,
"c6id.24xlarge": 37500,
"i4g.16xlarge": 37500,
"i4i.16xlarge": 37500,
"m6a.24xlarge": 37500,
"m6i.24xlarge": 37500,
"m6id.24xlarge": 37500,
"r6a.24xlarge": 37500,
"r6i.24xlarge": 37500,
"r6id.24xlarge": 37500,
"d3en.6xlarge": 40000,
"g5.12xlarge": 40000,
"c5n.9xlarge": 50000,
"c6a.32xlarge": 50000,
"c6a.48xlarge": 50000,
"c6a.metal": 50000,
"c6gn.8xlarge": 50000,
"c6i.32xlarge": 50000,
"c6i.metal": 50000,
"c6id.32xlarge": 50000,
"c6id.metal": 50000,
"c6in.8xlarge": 50000,
"c7gn.4xlarge": 50000,
"d3en.8xlarge": 50000,
"g4dn.12xlarge": 50000,
"g4dn.16xlarge": 50000,
"g4dn.8xlarge": 50000,
"g5.24xlarge": 50000,
"i3en.12xlarge": 50000,
"im4gn.8xlarge": 50000,
"inf2.24xlarge": 50000,
"is4gen.8xlarge": 50000,
"m5dn.12xlarge": 50000,
"m5n.12xlarge": 50000,
"m5zn.6xlarge": 50000,
"m6a.32xlarge": 50000,
"m6a.48xlarge": 50000,
"m6a.metal": 50000,
"m6i.32xlarge": 50000,
"m6i.metal": 50000,
"m6id.32xlarge": 50000,
"m6id.metal": 50000,
"m6idn.8xlarge": 50000,
"m6in.8xlarge": 50000,
"r5dn.12xlarge": 50000,
"r5n.12xlarge": 50000,
"r6a.32xlarge": 50000,
"r6a.48xlarge": 50000,
"r6a.metal": 50000,
"r6i.32xlarge": 50000,
"r6i.metal": 50000,
"r6id.32xlarge": 50000,
"r6id.metal": 50000,
"r6idn.8xlarge": 50000,
"r6in.8xlarge": 50000,
"u-3tb1.56xlarge": 50000,
"x2idn.16xlarge": 50000,
"x2iedn.16xlarge": 50000,
"x2iezn.6xlarge": 50000,
"c6gn.12xlarge": 75000,
"c6in.12xlarge": 75000,
"d3en.12xlarge": 75000,
"i4i.32xlarge": 75000,
"i4i.metal": 75000,
"m5dn.16xlarge": 75000,
"m5n.16xlarge": 75000,
"m6idn.12xlarge": 75000,
"m6in.12xlarge": 75000,
"r5dn.16xlarge": 75000,
"r5n.16xlarge": 75000,
"r6idn.12xlarge": 75000,
"r6in.12xlarge": 75000,
"x2idn.24xlarge": 75000,
"x2iedn.24xlarge": 75000,
"x2iezn.8xlarge": 75000,
"c5n.18xlarge": 100000,
"c5n.metal": 100000,
"c6gn.16xlarge": 100000,
"c6in.16xlarge": 100000,
"c7gn.8xlarge": 100000,
"g4dn.metal": 100000,
"g5.48xlarge": 100000,
"hpc6a.48xlarge": 100000,
"i3en.24xlarge": 100000,
"i3en.metal": 100000,
"im4gn.16xlarge": 100000,
"inf1.24xlarge": 100000,
"inf2.48xlarge": 100000,
"m5dn.24xlarge": 100000,
"m5dn.metal": 100000,
"m5n.24xlarge": 100000,
"m5n.metal": 100000,
"m5zn.12xlarge": 100000,
"m5zn.metal": 100000,
"m6idn.16xlarge": 100000,
"m6in.16xlarge": 100000,
"p3dn.24xlarge": 100000,
"r5dn.24xlarge": 100000,
"r5dn.metal": 100000,
"r5n.24xlarge": 100000,
"r5n.metal": 100000,
"r6idn.16xlarge": 100000,
"r6in.16xlarge": 100000,
"u-12tb1.112xlarge": 100000,
"u-12tb1.metal": 100000,
"u-18tb1.metal": 100000,
"u-24tb1.metal": 100000,
"u-6tb1.112xlarge": 100000,
"u-6tb1.56xlarge": 100000,
"u-6tb1.metal": 100000,
"u-9tb1.112xlarge": 100000,
"u-9tb1.metal": 100000,
"x2idn.32xlarge": 100000,
"x2idn.metal": 100000,
"x2iedn.32xlarge": 100000,
"x2iedn.metal": 100000,
"x2iezn.12xlarge": 100000,
"x2iezn.metal": 100000,
"c6in.24xlarge": 150000,
"c7gn.12xlarge": 150000,
"m6idn.24xlarge": 150000,
"m6in.24xlarge": 150000,
"r6idn.24xlarge": 150000,
"r6in.24xlarge": 150000,
"c6in.32xlarge": 200000,
"c6in.metal": 200000,
"c7gn.16xlarge": 200000,
"hpc6id.32xlarge": 200000,
"hpc7g.16xlarge": 200000,
"hpc7g.4xlarge": 200000,
"hpc7g.8xlarge": 200000,
"m6idn.32xlarge": 200000,
"m6idn.metal": 200000,
"m6in.32xlarge": 200000,
"m6in.metal": 200000,
"r6idn.32xlarge": 200000,
"r6idn.metal": 200000,
"r6in.32xlarge": 200000,
"r6in.metal": 200000,
"dl1.24xlarge": 400000,
"p4d.24xlarge": 400000,
"p4de.24xlarge": 400000,
"trn1.32xlarge": 800000,
"trn1n.32xlarge": 1600000,
}
)
| 669 |
karpenter | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
// This file is generated via an internal script not available on GitHub. This is
// done because the Instance to Branch ENI limits is not publicly available. We are
// working with concerned teams to evaluate if this API can be exposed via aws-sdk-go
// so we can get this information at runtime.
// Code generated by go generate; DO NOT EDIT.
// This file was generated at 2023-06-05T23:49:46Z
// WARNING: please add @ellistarn, @bwagner5, or @jonathan-innis from aws/karpenter to reviewers
// if you are updating this file since Karpenter is depending on this file to calculate max pods.
package instancetype
type NetworkCard struct {
// max number of interfaces supported per card
MaximumNetworkInterfaces int64
// the index of current card
NetworkCardIndex int64
NetworkPerformance string
}
type VPCLimits struct {
Interface int
IPv4PerInterface int
IsTrunkingCompatible bool
BranchInterface int
NetworkCards []NetworkCard
DefaultNetworkCardIndex int
Hypervisor string
IsBareMetal bool
}
// VPC Limits and flags for ENI and IPv4 Addresses
var Limits = map[string]*VPCLimits{
"a1.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"a1.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"a1.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"a1.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 10,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"a1.metal": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"a1.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c1.medium": {
Interface: 2,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c1.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c3.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c3.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c3.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c3.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c3.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c4.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c4.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c4.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c4.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c4.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"c5.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.18xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.9xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c5.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5ad.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.18xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.9xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5d.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c5d.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.18xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.9xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c5n.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c5n.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.48xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6a.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gd.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6gd.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6gn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6i.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6i.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6id.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6id.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.32xlarge": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c6in.metal": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c6in.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"c7g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"c7g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d2.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"d2.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"d2.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"d2.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"d3.2xlarge": {
Interface: 4,
IPv4PerInterface: 5,
IsTrunkingCompatible: true,
BranchInterface: 92,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3.4xlarge": {
Interface: 4,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 118,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3.8xlarge": {
Interface: 3,
IPv4PerInterface: 20,
IsTrunkingCompatible: true,
BranchInterface: 119,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3.xlarge": {
Interface: 4,
IPv4PerInterface: 3,
IsTrunkingCompatible: true,
BranchInterface: 42,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.12xlarge": {
Interface: 3,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 119,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.2xlarge": {
Interface: 4,
IPv4PerInterface: 5,
IsTrunkingCompatible: true,
BranchInterface: 58,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.4xlarge": {
Interface: 4,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 118,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.6xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 118,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.8xlarge": {
Interface: 4,
IPv4PerInterface: 20,
IsTrunkingCompatible: true,
BranchInterface: 118,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"d3en.xlarge": {
Interface: 4,
IPv4PerInterface: 3,
IsTrunkingCompatible: true,
BranchInterface: 24,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"dl1.24xlarge": {
Interface: 60,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 62,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 1,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 2,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 3,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"f1.16xlarge": {
Interface: 8,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"f1.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"f1.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g2.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g2.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g3.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g3.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g3.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g3s.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"g4ad.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 6,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4ad.2xlarge": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 12,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4ad.4xlarge": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 11,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4ad.8xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 10,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4ad.xlarge": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 12,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.16xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 118,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.2xlarge": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 39,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.4xlarge": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 59,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.8xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 58,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g4dn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"g4dn.xlarge": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 39,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.12xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 17,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.48xlarge": {
Interface: 7,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 115,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 34,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"g5g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"g5g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"h1.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"h1.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"h1.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"h1.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i2.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i2.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i2.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i2.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"i3.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"i3en.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 28,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.3xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 5,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i3en.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"i3en.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 12,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 26,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 52,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 112,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"i4i.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"i4i.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 6,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"im4gn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"inf1.24xlarge": {
Interface: 11,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 111,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 11,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"inf1.2xlarge": {
Interface: 4,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"inf1.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"inf1.xlarge": {
Interface: 4,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"is4gen.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m1.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m1.medium": {
Interface: 2,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m1.small": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m1.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m2.2xlarge": {
Interface: 4,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m2.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m2.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m3.2xlarge": {
Interface: 4,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m3.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m3.medium": {
Interface: 2,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m3.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.10xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.large": {
Interface: 2,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m4.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"m5.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m5.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5ad.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5d.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m5d.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5dn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m5dn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5n.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m5n.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.12xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 62,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.3xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 92,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 13,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m5zn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m5zn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 29,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.48xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6a.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6gd.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6gd.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6i.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6i.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6id.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6id.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.32xlarge": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6idn.metal": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6idn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.32xlarge": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m6in.metal": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m6in.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"m7g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"m7g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"mac1.metal": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 6,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"mac2.metal": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 6,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"p2.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p2.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p2.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p3.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p3.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p3.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"p3dn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"p4d.24xlarge": {
Interface: 60,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 62,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 1,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 2,
},
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 3,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r3.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r3.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r3.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r3.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r3.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r4.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"r5.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r5.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5ad.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5b.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r5b.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5d.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r5d.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5dn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r5dn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r5n.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r5n.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.48xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6a.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6gd.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6gd.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6i.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6i.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6id.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6id.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.32xlarge": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6idn.metal": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6idn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.32xlarge": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 84,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r6in.metal": {
Interface: 14,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 108,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 7,
NetworkCardIndex: 1,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r6in.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 4,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"r7g.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"r7g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t1.micro": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.2xlarge": {
Interface: 3,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.large": {
Interface: 3,
IPv4PerInterface: 12,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.medium": {
Interface: 3,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.micro": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.nano": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.small": {
Interface: 3,
IPv4PerInterface: 4,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t2.xlarge": {
Interface: 3,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"t3.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.large": {
Interface: 3,
IPv4PerInterface: 12,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.medium": {
Interface: 3,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.micro": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.nano": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.small": {
Interface: 3,
IPv4PerInterface: 4,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.large": {
Interface: 3,
IPv4PerInterface: 12,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.medium": {
Interface: 3,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.micro": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.nano": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.small": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t3a.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.large": {
Interface: 3,
IPv4PerInterface: 12,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.medium": {
Interface: 3,
IPv4PerInterface: 6,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.micro": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.nano": {
Interface: 2,
IPv4PerInterface: 2,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.small": {
Interface: 3,
IPv4PerInterface: 4,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"t4g.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"trn1.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 17,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"trn1.32xlarge": {
Interface: 40,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 82,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 1,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 2,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 3,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 4,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 5,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 6,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 7,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"trn1n.32xlarge": {
Interface: 80,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 120,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 0,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 1,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 2,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 3,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 4,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 5,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 6,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 7,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 8,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 9,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 10,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 11,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 12,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 13,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 14,
},
{
MaximumNetworkInterfaces: 5,
NetworkCardIndex: 15,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-12tb1.112xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-18tb1.112xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-3tb1.56xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 6,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-6tb1.112xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-6tb1.56xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"u-9tb1.112xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"vt1.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"vt1.3xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"vt1.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x1.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1.32xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.16xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.32xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.4xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.8xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x1e.xlarge": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: false,
BranchInterface: 0,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "xen",
IsBareMetal: false,
},
"x2gd.12xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 38,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 9,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.medium": {
Interface: 2,
IPv4PerInterface: 4,
IsTrunkingCompatible: true,
BranchInterface: 10,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 2,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2gd.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"x2gd.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 18,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2idn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2idn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2idn.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2idn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"x2iedn.16xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.24xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 27,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.32xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iedn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"x2iedn.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 11,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.12xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 62,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.4xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.8xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 114,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"x2iezn.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"z1d.12xlarge": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"z1d.2xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 58,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"z1d.3xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"z1d.6xlarge": {
Interface: 8,
IPv4PerInterface: 30,
IsTrunkingCompatible: true,
BranchInterface: 54,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 8,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"z1d.large": {
Interface: 3,
IPv4PerInterface: 10,
IsTrunkingCompatible: true,
BranchInterface: 13,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 3,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
"z1d.metal": {
Interface: 15,
IPv4PerInterface: 50,
IsTrunkingCompatible: true,
BranchInterface: 107,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 15,
NetworkCardIndex: 0,
},
},
Hypervisor: "",
IsBareMetal: true,
},
"z1d.xlarge": {
Interface: 4,
IPv4PerInterface: 15,
IsTrunkingCompatible: true,
BranchInterface: 28,
DefaultNetworkCardIndex: 0,
NetworkCards: []NetworkCard{
{
MaximumNetworkInterfaces: 4,
NetworkCardIndex: 0,
},
},
Hypervisor: "nitro",
IsBareMetal: false,
},
}
| 9,764 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package launchtemplate
import (
"context"
"errors"
"fmt"
"math"
"net"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/mitchellh/hashstructure/v2"
"github.com/patrickmn/go-cache"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/api/resource"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awserrors "github.com/aws/karpenter/pkg/errors"
"github.com/aws/karpenter/pkg/providers/amifamily"
"github.com/aws/karpenter/pkg/providers/securitygroup"
"github.com/aws/karpenter/pkg/providers/subnet"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/utils/pretty"
)
const (
launchTemplateNameFormat = "karpenter.k8s.aws/%s"
karpenterManagedTagKey = "karpenter.k8s.aws/cluster"
)
type Provider struct {
sync.Mutex
ec2api ec2iface.EC2API
amiFamily *amifamily.Resolver
securityGroupProvider *securitygroup.Provider
subnetProvider *subnet.Provider
cache *cache.Cache
caBundle *string
cm *pretty.ChangeMonitor
KubeDNSIP net.IP
ClusterEndpoint string
}
func NewProvider(ctx context.Context, cache *cache.Cache, ec2api ec2iface.EC2API, amiFamily *amifamily.Resolver, securityGroupProvider *securitygroup.Provider, subnetProvider *subnet.Provider, caBundle *string, startAsync <-chan struct{}, kubeDNSIP net.IP, clusterEndpoint string) *Provider {
l := &Provider{
ec2api: ec2api,
amiFamily: amiFamily,
securityGroupProvider: securityGroupProvider,
subnetProvider: subnetProvider,
cache: cache,
caBundle: caBundle,
cm: pretty.NewChangeMonitor(),
KubeDNSIP: kubeDNSIP,
ClusterEndpoint: clusterEndpoint,
}
l.cache.OnEvicted(l.cachedEvictedFunc(ctx))
go func() {
// only hydrate cache once elected leader
select {
case <-startAsync:
case <-ctx.Done():
return
}
l.hydrateCache(ctx)
}()
return l
}
func (p *Provider) EnsureAll(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, machine *v1alpha5.Machine,
instanceTypes []*cloudprovider.InstanceType, additionalLabels map[string]string, tags map[string]string) (map[string][]*cloudprovider.InstanceType, error) {
p.Lock()
defer p.Unlock()
// If Launch Template is directly specified then just use it
if nodeTemplate.Spec.LaunchTemplateName != nil {
return map[string][]*cloudprovider.InstanceType{ptr.StringValue(nodeTemplate.Spec.LaunchTemplateName): instanceTypes}, nil
}
options, err := p.createAMIOptions(ctx, nodeTemplate, lo.Assign(machine.Labels, additionalLabels), tags)
if err != nil {
return nil, err
}
resolvedLaunchTemplates, err := p.amiFamily.Resolve(ctx, nodeTemplate, machine, instanceTypes, options)
if err != nil {
return nil, err
}
launchTemplates := map[string][]*cloudprovider.InstanceType{}
for _, resolvedLaunchTemplate := range resolvedLaunchTemplates {
// Ensure the launch template exists, or create it
ec2LaunchTemplate, err := p.ensureLaunchTemplate(ctx, resolvedLaunchTemplate)
if err != nil {
return nil, err
}
launchTemplates[*ec2LaunchTemplate.LaunchTemplateName] = resolvedLaunchTemplate.InstanceTypes
}
return launchTemplates, nil
}
// Invalidate deletes a launch template from cache if it exists
func (p *Provider) Invalidate(ctx context.Context, ltName string, ltID string) {
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("launch-template-name", ltName, "launch-template-id", ltID))
p.Lock()
defer p.Unlock()
defer p.cache.OnEvicted(p.cachedEvictedFunc(ctx))
p.cache.OnEvicted(nil)
logging.FromContext(ctx).Debugf("invalidating launch template in the cache because it no longer exists")
p.cache.Delete(ltName)
}
func launchTemplateName(options *amifamily.LaunchTemplate) string {
hash, err := hashstructure.Hash(options, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
if err != nil {
panic(fmt.Sprintf("hashing launch template, %s", err))
}
return fmt.Sprintf(launchTemplateNameFormat, fmt.Sprint(hash))
}
func (p *Provider) createAMIOptions(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, labels, tags map[string]string) (*amifamily.Options, error) {
instanceProfile, err := p.getInstanceProfile(ctx, nodeTemplate)
if err != nil {
return nil, err
}
// Get constrained security groups
securityGroups, err := p.securityGroupProvider.List(ctx, nodeTemplate)
if err != nil {
return nil, err
}
if len(securityGroups) == 0 {
return nil, fmt.Errorf("no security groups exist given constraints")
}
options := &amifamily.Options{
ClusterName: settings.FromContext(ctx).ClusterName,
ClusterEndpoint: p.ClusterEndpoint,
AWSENILimitedPodDensity: settings.FromContext(ctx).EnableENILimitedPodDensity,
InstanceProfile: instanceProfile,
SecurityGroups: lo.Map(securityGroups, func(s *ec2.SecurityGroup, _ int) v1alpha1.SecurityGroup {
return v1alpha1.SecurityGroup{ID: aws.StringValue(s.GroupId), Name: aws.StringValue(s.GroupName)}
}),
Tags: tags,
Labels: labels,
CABundle: p.caBundle,
KubeDNSIP: p.KubeDNSIP,
}
if ok, err := p.subnetProvider.CheckAnyPublicIPAssociations(ctx, nodeTemplate); err != nil {
return nil, err
} else if !ok {
// If all referenced subnets do not assign public IPv4 addresses to EC2 instances therein, we explicitly set
// AssociatePublicIpAddress to 'false' in the Launch Template, generated based on this configuration struct.
// This is done to help comply with AWS account policies that require explicitly setting of that field to 'false'.
// https://github.com/aws/karpenter/issues/3815
options.AssociatePublicIPAddress = aws.Bool(false)
}
return options, nil
}
func (p *Provider) ensureLaunchTemplate(ctx context.Context, options *amifamily.LaunchTemplate) (*ec2.LaunchTemplate, error) {
var launchTemplate *ec2.LaunchTemplate
name := launchTemplateName(options)
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("launch-template-name", name))
// Read from cache
if launchTemplate, ok := p.cache.Get(name); ok {
p.cache.SetDefault(name, launchTemplate)
return launchTemplate.(*ec2.LaunchTemplate), nil
}
// Attempt to find an existing LT.
output, err := p.ec2api.DescribeLaunchTemplatesWithContext(ctx, &ec2.DescribeLaunchTemplatesInput{
LaunchTemplateNames: []*string{aws.String(name)},
})
// Create LT if one doesn't exist
if awserrors.IsNotFound(err) {
launchTemplate, err = p.createLaunchTemplate(ctx, options)
if err != nil {
return nil, fmt.Errorf("creating launch template, %w", err)
}
} else if err != nil {
return nil, fmt.Errorf("describing launch templates, %w", err)
} else if len(output.LaunchTemplates) != 1 {
return nil, fmt.Errorf("expected to find one launch template, but found %d", len(output.LaunchTemplates))
} else {
if p.cm.HasChanged("launchtemplate-"+name, name) {
logging.FromContext(ctx).Debugf("discovered launch template")
}
launchTemplate = output.LaunchTemplates[0]
}
p.cache.SetDefault(name, launchTemplate)
return launchTemplate, nil
}
func (p *Provider) createLaunchTemplate(ctx context.Context, options *amifamily.LaunchTemplate) (*ec2.LaunchTemplate, error) {
userData, err := options.UserData.Script()
if err != nil {
return nil, err
}
networkInterface := p.generateNetworkInterface(options)
output, err := p.ec2api.CreateLaunchTemplateWithContext(ctx, &ec2.CreateLaunchTemplateInput{
LaunchTemplateName: aws.String(launchTemplateName(options)),
LaunchTemplateData: &ec2.RequestLaunchTemplateData{
BlockDeviceMappings: p.blockDeviceMappings(options.BlockDeviceMappings),
IamInstanceProfile: &ec2.LaunchTemplateIamInstanceProfileSpecificationRequest{
Name: aws.String(options.InstanceProfile),
},
Monitoring: &ec2.LaunchTemplatesMonitoringRequest{
Enabled: aws.Bool(options.DetailedMonitoring),
},
// If the network interface is defined, the security groups are defined within it
SecurityGroupIds: lo.Ternary(networkInterface != nil, nil, lo.Map(options.SecurityGroups, func(s v1alpha1.SecurityGroup, _ int) *string { return aws.String(s.ID) })),
UserData: aws.String(userData),
ImageId: aws.String(options.AMIID),
MetadataOptions: &ec2.LaunchTemplateInstanceMetadataOptionsRequest{
HttpEndpoint: options.MetadataOptions.HTTPEndpoint,
HttpProtocolIpv6: options.MetadataOptions.HTTPProtocolIPv6,
HttpPutResponseHopLimit: options.MetadataOptions.HTTPPutResponseHopLimit,
HttpTokens: options.MetadataOptions.HTTPTokens,
},
NetworkInterfaces: networkInterface,
TagSpecifications: []*ec2.LaunchTemplateTagSpecificationRequest{
{ResourceType: aws.String(ec2.ResourceTypeNetworkInterface), Tags: utils.MergeTags(options.Tags)},
},
},
TagSpecifications: []*ec2.TagSpecification{
{
ResourceType: aws.String(ec2.ResourceTypeLaunchTemplate),
Tags: utils.MergeTags(options.Tags, map[string]string{karpenterManagedTagKey: options.ClusterName}),
},
},
})
if err != nil {
return nil, err
}
logging.FromContext(ctx).With("id", aws.StringValue(output.LaunchTemplate.LaunchTemplateId)).Debugf("created launch template")
return output.LaunchTemplate, nil
}
// generateNetworkInterface generates a network interface for the launch template.
// If all referenced subnets do not assign public IPv4 addresses to EC2 instances therein, we explicitly set
// AssociatePublicIpAddress to 'false' in the Launch Template, generated based on this configuration struct.
// This is done to help comply with AWS account policies that require explicitly setting that field to 'false'.
// https://github.com/aws/karpenter/issues/3815
func (p *Provider) generateNetworkInterface(options *amifamily.LaunchTemplate) []*ec2.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest {
if options.AssociatePublicIPAddress != nil {
return []*ec2.LaunchTemplateInstanceNetworkInterfaceSpecificationRequest{
{
AssociatePublicIpAddress: options.AssociatePublicIPAddress,
DeviceIndex: aws.Int64(0),
Groups: lo.Map(options.SecurityGroups, func(s v1alpha1.SecurityGroup, _ int) *string { return aws.String(s.ID) }),
},
}
}
return nil
}
func (p *Provider) blockDeviceMappings(blockDeviceMappings []*v1alpha1.BlockDeviceMapping) []*ec2.LaunchTemplateBlockDeviceMappingRequest {
if len(blockDeviceMappings) == 0 {
// The EC2 API fails with empty slices and expects nil.
return nil
}
var blockDeviceMappingsRequest []*ec2.LaunchTemplateBlockDeviceMappingRequest
for _, blockDeviceMapping := range blockDeviceMappings {
blockDeviceMappingsRequest = append(blockDeviceMappingsRequest, &ec2.LaunchTemplateBlockDeviceMappingRequest{
DeviceName: blockDeviceMapping.DeviceName,
Ebs: &ec2.LaunchTemplateEbsBlockDeviceRequest{
DeleteOnTermination: blockDeviceMapping.EBS.DeleteOnTermination,
Encrypted: blockDeviceMapping.EBS.Encrypted,
VolumeType: blockDeviceMapping.EBS.VolumeType,
Iops: blockDeviceMapping.EBS.IOPS,
Throughput: blockDeviceMapping.EBS.Throughput,
KmsKeyId: blockDeviceMapping.EBS.KMSKeyID,
SnapshotId: blockDeviceMapping.EBS.SnapshotID,
VolumeSize: p.volumeSize(blockDeviceMapping.EBS.VolumeSize),
},
})
}
return blockDeviceMappingsRequest
}
// volumeSize returns a GiB scaled value from a resource quantity or nil if the resource quantity passed in is nil
func (p *Provider) volumeSize(quantity *resource.Quantity) *int64 {
if quantity == nil {
return nil
}
// Converts the value to Gi and rounds up the value to the nearest Gi
return aws.Int64(int64(math.Ceil(quantity.AsApproximateFloat64() / math.Pow(2, 30))))
}
// hydrateCache queries for existing Launch Templates created by Karpenter for the current cluster and adds to the LT cache.
// Any error during hydration will result in a panic
func (p *Provider) hydrateCache(ctx context.Context) {
clusterName := settings.FromContext(ctx).ClusterName
ctx = logging.WithLogger(ctx, logging.FromContext(ctx).With("tag-key", karpenterManagedTagKey, "tag-value", clusterName))
if err := p.ec2api.DescribeLaunchTemplatesPagesWithContext(ctx, &ec2.DescribeLaunchTemplatesInput{
Filters: []*ec2.Filter{{Name: aws.String(fmt.Sprintf("tag:%s", karpenterManagedTagKey)), Values: []*string{aws.String(clusterName)}}},
}, func(output *ec2.DescribeLaunchTemplatesOutput, _ bool) bool {
for _, lt := range output.LaunchTemplates {
p.cache.SetDefault(*lt.LaunchTemplateName, lt)
}
return true
}); err != nil {
logging.FromContext(ctx).Errorf(fmt.Sprintf("Unable to hydrate the AWS launch template cache, %s", err))
} else {
logging.FromContext(ctx).With("count", p.cache.ItemCount()).Debugf("hydrated launch template cache")
}
}
func (p *Provider) cachedEvictedFunc(ctx context.Context) func(string, interface{}) {
return func(key string, lt interface{}) {
p.Lock()
defer p.Unlock()
if _, expiration, _ := p.cache.GetWithExpiration(key); expiration.After(time.Now()) {
return
}
launchTemplate := lt.(*ec2.LaunchTemplate)
if _, err := p.ec2api.DeleteLaunchTemplate(&ec2.DeleteLaunchTemplateInput{LaunchTemplateId: launchTemplate.LaunchTemplateId}); err != nil {
logging.FromContext(ctx).With("launch-template", launchTemplate.LaunchTemplateName).Errorf("failed to delete launch template, %v", err)
return
}
logging.FromContext(ctx).With(
"id", aws.StringValue(launchTemplate.LaunchTemplateId),
"name", aws.StringValue(launchTemplate.LaunchTemplateName),
).Debugf("deleted launch template")
}
}
func (p *Provider) getInstanceProfile(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) (string, error) {
if nodeTemplate.Spec.InstanceProfile != nil {
return aws.StringValue(nodeTemplate.Spec.InstanceProfile), nil
}
defaultProfile := settings.FromContext(ctx).DefaultInstanceProfile
if defaultProfile == "" {
return "", errors.New("neither spec.provider.instanceProfile nor --aws-default-instance-profile is specified")
}
return defaultProfile, nil
}
| 356 |
karpenter | aws | Go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package launchtemplate_test
import (
"context"
"encoding/base64"
"fmt"
"net"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/record"
clock "k8s.io/utils/clock/testing"
. "knative.dev/pkg/logging/testing"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/cloudprovider"
"github.com/aws/karpenter/pkg/fake"
"github.com/aws/karpenter/pkg/providers/amifamily/bootstrap"
"github.com/aws/karpenter/pkg/providers/instancetype"
"github.com/aws/karpenter/pkg/test"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/controllers/provisioning"
"github.com/aws/karpenter-core/pkg/controllers/state"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/operator/options"
"github.com/aws/karpenter-core/pkg/operator/scheme"
coretest "github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
)
var ctx context.Context
var stop context.CancelFunc
var opts options.Options
var env *coretest.Environment
var awsEnv *test.Environment
var fakeClock *clock.FakeClock
var prov *provisioning.Provisioner
var provisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
var cluster *state.Cluster
var cloudProvider *cloudprovider.CloudProvider
func TestAWS(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Provider/AWS")
}
var _ = BeforeSuite(func() {
env = coretest.NewEnvironment(scheme.Scheme, coretest.WithCRDs(apis.CRDs...))
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
ctx, stop = context.WithCancel(ctx)
awsEnv = test.NewEnvironment(ctx, env)
fakeClock = &clock.FakeClock{}
cloudProvider = cloudprovider.New(awsEnv.InstanceTypesProvider, awsEnv.InstanceProvider, env.Client, awsEnv.AMIProvider, awsEnv.SecurityGroupProvider, awsEnv.SubnetProvider)
cluster = state.NewCluster(fakeClock, env.Client, cloudProvider)
prov = provisioning.NewProvisioner(env.Client, env.KubernetesInterface.CoreV1(), events.NewRecorder(&record.FakeRecorder{}), cloudProvider, cluster)
})
var _ = AfterSuite(func() {
stop()
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = BeforeEach(func() {
ctx = injection.WithOptions(ctx, opts)
ctx = coresettings.ToContext(ctx, coretest.Settings())
ctx = settings.ToContext(ctx, test.Settings())
nodeTemplate = &v1alpha1.AWSNodeTemplate{
ObjectMeta: metav1.ObjectMeta{
Name: coretest.RandomName(),
},
Spec: v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: aws.String(v1alpha1.AMIFamilyAL2),
SubnetSelector: map[string]string{"*": "*"},
SecurityGroupSelector: map[string]string{"*": "*"},
},
},
}
nodeTemplate.SetGroupVersionKind(schema.GroupVersionKind{
Group: v1alpha1.SchemeGroupVersion.Group,
Version: v1alpha1.SchemeGroupVersion.Version,
Kind: "AWSNodeTemplate",
})
provisioner = test.Provisioner(coretest.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
}},
ProviderRef: &v1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
cluster.Reset()
awsEnv.Reset()
awsEnv.LaunchTemplateProvider.KubeDNSIP = net.ParseIP("10.0.100.10")
awsEnv.LaunchTemplateProvider.ClusterEndpoint = "https://test-cluster"
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("LaunchTemplates", func() {
It("should default to a generated launch template", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(BeNumerically("==", 1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(len(createFleetInput.LaunchTemplateConfigs)).To(BeNumerically("==", awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()))
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
launchTemplate, ok := lo.Find(createFleetInput.LaunchTemplateConfigs, func(ltConfig *ec2.FleetLaunchTemplateConfigRequest) bool {
return *ltConfig.LaunchTemplateSpecification.LaunchTemplateName == *ltInput.LaunchTemplateName
})
Expect(ok).To(BeTrue())
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Encrypted).To(Equal(aws.Bool(true)))
Expect(*launchTemplate.LaunchTemplateSpecification.Version).To(Equal("$Latest"))
})
})
Context("LaunchTemplateName", func() {
It("should allow a launch template to be specified", func() {
nodeTemplate.Spec.LaunchTemplateName = aws.String("test-launch-template")
nodeTemplate.Spec.SecurityGroupSelector = nil
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
input := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(input.LaunchTemplateConfigs).To(HaveLen(1))
launchTemplate := input.LaunchTemplateConfigs[0].LaunchTemplateSpecification
Expect(*launchTemplate.LaunchTemplateName).To(Equal("test-launch-template"))
Expect(*launchTemplate.Version).To(Equal("$Latest"))
})
})
Context("Cache", func() {
It("should use same launch template for equivalent constraints", func() {
t1 := v1.Toleration{
Key: "Abacus",
Operator: "Equal",
Value: "Zebra",
Effect: "NoSchedule",
}
t2 := v1.Toleration{
Key: "Zebra",
Operator: "Equal",
Value: "Abacus",
Effect: "NoSchedule",
}
t3 := v1.Toleration{
Key: "Boar",
Operator: "Equal",
Value: "Abacus",
Effect: "NoSchedule",
}
// constrain the packer to a single launch template type
rr := v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("24"),
v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1"),
},
Limits: v1.ResourceList{v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1")},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod1 := coretest.UnschedulablePod(coretest.PodOptions{
Tolerations: []v1.Toleration{t1, t2, t3},
ResourceRequirements: rr,
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod1)
ExpectScheduled(ctx, env.Client, pod1)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
lts1 := sets.NewString()
for _, ltConfig := range createFleetInput.LaunchTemplateConfigs {
lts1.Insert(*ltConfig.LaunchTemplateSpecification.LaunchTemplateName)
}
pod2 := coretest.UnschedulablePod(coretest.PodOptions{
Tolerations: []v1.Toleration{t2, t3, t1},
ResourceRequirements: rr,
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod2)
ExpectScheduled(ctx, env.Client, pod2)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput = awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
lts2 := sets.NewString()
for _, ltConfig := range createFleetInput.LaunchTemplateConfigs {
lts2.Insert(*ltConfig.LaunchTemplateSpecification.LaunchTemplateName)
}
Expect(lts1.Equal(lts2)).To(BeTrue())
})
It("should recover from an out-of-sync launch template cache", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{MaxPods: aws.Int32(1)}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
ltName := aws.StringValue(ltInput.LaunchTemplateName)
lt, ok := awsEnv.LaunchTemplateCache.Get(ltName)
Expect(ok).To(Equal(true))
// Remove expiration from cached LT
awsEnv.LaunchTemplateCache.Set(ltName, lt, -1)
})
awsEnv.EC2API.CreateFleetBehavior.Error.Set(awserr.New("InvalidLaunchTemplateName.NotFoundException", "", nil), fake.MaxCalls(1))
pod = coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
// should call fleet twice. Once will fail on invalid LT and the next will succeed
Expect(awsEnv.EC2API.CreateFleetBehavior.FailedCalls()).To(BeNumerically("==", 1))
Expect(awsEnv.EC2API.CreateFleetBehavior.SuccessfulCalls()).To(BeNumerically("==", 2))
})
})
Context("Labels", func() {
It("should apply labels to the node", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
node := ExpectScheduled(ctx, env.Client, pod)
Expect(node.Labels).To(HaveKey(v1.LabelOSStable))
Expect(node.Labels).To(HaveKey(v1.LabelArchStable))
Expect(node.Labels).To(HaveKey(v1.LabelInstanceTypeStable))
})
It("should apply provider labels to the node", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2022-08-15T12:00:00Z"),
},
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-456"),
Architecture: aws.String("arm64"),
CreationDate: aws.String("2022-08-10T12:00:00Z"),
},
}})
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
Expect(env.Client.Get(ctx, client.ObjectKeyFromObject(newProvisioner), newProvisioner)).To(Succeed())
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
})
Context("Tags", func() {
It("should tag with provisioner name", func() {
provisionerName := "the-provisioner"
provisioner.Name = provisionerName
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.TagSpecifications).To(HaveLen(3))
tags := map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisionerName,
"Name": fmt.Sprintf("%s/%s", v1alpha5.ProvisionerNameLabelKey, provisionerName),
}
// tags should be included in instance, volume, and fleet tag specification
Expect(*createFleetInput.TagSpecifications[0].ResourceType).To(Equal(ec2.ResourceTypeInstance))
ExpectTags(createFleetInput.TagSpecifications[0].Tags, tags)
Expect(*createFleetInput.TagSpecifications[1].ResourceType).To(Equal(ec2.ResourceTypeVolume))
ExpectTags(createFleetInput.TagSpecifications[1].Tags, tags)
Expect(*createFleetInput.TagSpecifications[2].ResourceType).To(Equal(ec2.ResourceTypeFleet))
ExpectTags(createFleetInput.TagSpecifications[2].Tags, tags)
})
It("should request that tags be applied to both instances and volumes", func() {
nodeTemplate.Spec.Tags = map[string]string{
"tag1": "tag1value",
"tag2": "tag2value",
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.TagSpecifications).To(HaveLen(3))
// tags should be included in instance, volume, and fleet tag specification
Expect(*createFleetInput.TagSpecifications[0].ResourceType).To(Equal(ec2.ResourceTypeInstance))
ExpectTags(createFleetInput.TagSpecifications[0].Tags, nodeTemplate.Spec.Tags)
Expect(*createFleetInput.TagSpecifications[1].ResourceType).To(Equal(ec2.ResourceTypeVolume))
ExpectTags(createFleetInput.TagSpecifications[1].Tags, nodeTemplate.Spec.Tags)
Expect(*createFleetInput.TagSpecifications[2].ResourceType).To(Equal(ec2.ResourceTypeFleet))
ExpectTags(createFleetInput.TagSpecifications[2].Tags, nodeTemplate.Spec.Tags)
})
It("should override default tag names", func() {
// these tags are defaulted, so ensure users can override them
nodeTemplate.Spec.Tags = map[string]string{
"Name": "myname",
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.TagSpecifications).To(HaveLen(3))
// tags should be included in instance, volume, and fleet tag specification
Expect(*createFleetInput.TagSpecifications[0].ResourceType).To(Equal(ec2.ResourceTypeInstance))
ExpectTags(createFleetInput.TagSpecifications[0].Tags, nodeTemplate.Spec.Tags)
Expect(*createFleetInput.TagSpecifications[1].ResourceType).To(Equal(ec2.ResourceTypeVolume))
ExpectTags(createFleetInput.TagSpecifications[1].Tags, nodeTemplate.Spec.Tags)
Expect(*createFleetInput.TagSpecifications[2].ResourceType).To(Equal(ec2.ResourceTypeFleet))
ExpectTags(createFleetInput.TagSpecifications[2].Tags, nodeTemplate.Spec.Tags)
})
It("should merge global tags into launch template and volume tags", func() {
nodeTemplate.Spec.Tags = map[string]string{
"tag1": "tag1value",
"tag2": "tag2value",
}
settingsTags := map[string]string{
"customTag1": "value1",
"customTag2": "value2",
}
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
Tags: settingsTags,
}))
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.TagSpecifications).To(HaveLen(3))
// tags should be included in instance, volume, and fleet tag specification
Expect(*createFleetInput.TagSpecifications[0].ResourceType).To(Equal(ec2.ResourceTypeInstance))
ExpectTags(createFleetInput.TagSpecifications[0].Tags, settingsTags)
Expect(*createFleetInput.TagSpecifications[1].ResourceType).To(Equal(ec2.ResourceTypeVolume))
ExpectTags(createFleetInput.TagSpecifications[1].Tags, settingsTags)
Expect(*createFleetInput.TagSpecifications[2].ResourceType).To(Equal(ec2.ResourceTypeFleet))
ExpectTags(createFleetInput.TagSpecifications[2].Tags, settingsTags)
})
It("should override global tags with provider tags", func() {
nodeTemplate.Spec.Tags = map[string]string{
"tag1": "tag1value",
"tag2": "tag2value",
}
settingsTags := map[string]string{
"tag1": "custom1",
"tag2": "custom2",
}
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
Tags: settingsTags,
}))
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Len()).To(Equal(1))
createFleetInput := awsEnv.EC2API.CreateFleetBehavior.CalledWithInput.Pop()
Expect(createFleetInput.TagSpecifications).To(HaveLen(3))
// tags should be included in instance, volume, and fleet tag specification
Expect(*createFleetInput.TagSpecifications[0].ResourceType).To(Equal(ec2.ResourceTypeInstance))
ExpectTags(createFleetInput.TagSpecifications[0].Tags, nodeTemplate.Spec.Tags)
ExpectTagsNotFound(createFleetInput.TagSpecifications[0].Tags, settingsTags)
Expect(*createFleetInput.TagSpecifications[1].ResourceType).To(Equal(ec2.ResourceTypeVolume))
ExpectTags(createFleetInput.TagSpecifications[1].Tags, nodeTemplate.Spec.Tags)
ExpectTagsNotFound(createFleetInput.TagSpecifications[0].Tags, settingsTags)
Expect(*createFleetInput.TagSpecifications[2].ResourceType).To(Equal(ec2.ResourceTypeFleet))
ExpectTags(createFleetInput.TagSpecifications[2].Tags, nodeTemplate.Spec.Tags)
ExpectTagsNotFound(createFleetInput.TagSpecifications[0].Tags, settingsTags)
})
})
Context("Block Device Mappings", func() {
It("should default AL2 block device mappings", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(len(ltInput.LaunchTemplateData.BlockDeviceMappings)).To(Equal(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeSize).To(Equal(int64(20)))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeType).To(Equal("gp3"))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Iops).To(BeNil())
})
})
It("should use custom block device mapping", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
VolumeType: aws.String("io2"),
VolumeSize: lo.ToPtr(resource.MustParse("200G")),
IOPS: aws.Int64(10_000),
KMSKeyID: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
},
},
{
DeviceName: aws.String("/dev/xvdb"),
EBS: &v1alpha1.BlockDevice{
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
VolumeType: aws.String("io2"),
VolumeSize: lo.ToPtr(resource.MustParse("200Gi")),
IOPS: aws.Int64(10_000),
KMSKeyID: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs).To(Equal(&ec2.LaunchTemplateEbsBlockDeviceRequest{
VolumeSize: aws.Int64(187),
VolumeType: aws.String("io2"),
Iops: aws.Int64(10_000),
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
KmsKeyId: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
}))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[1].Ebs).To(Equal(&ec2.LaunchTemplateEbsBlockDeviceRequest{
VolumeSize: aws.Int64(200),
VolumeType: aws.String("io2"),
Iops: aws.Int64(10_000),
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
KmsKeyId: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
}))
})
})
It("should round up for custom block device mappings when specified in gigabytes", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
VolumeType: aws.String("io2"),
VolumeSize: lo.ToPtr(resource.MustParse("4G")),
IOPS: aws.Int64(10_000),
KMSKeyID: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
},
},
{
DeviceName: aws.String("/dev/xvdb"),
EBS: &v1alpha1.BlockDevice{
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
VolumeType: aws.String("io2"),
VolumeSize: lo.ToPtr(resource.MustParse("2G")),
IOPS: aws.Int64(10_000),
KMSKeyID: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
// Both of these values are rounded up when converting to Gibibytes
Expect(aws.Int64Value(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeSize)).To(BeNumerically("==", 4))
Expect(aws.Int64Value(ltInput.LaunchTemplateData.BlockDeviceMappings[1].Ebs.VolumeSize)).To(BeNumerically("==", 2))
})
})
It("should default bottlerocket second volume with root volume size", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(len(ltInput.LaunchTemplateData.BlockDeviceMappings)).To(Equal(2))
// Bottlerocket control volume
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeSize).To(Equal(int64(4)))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeType).To(Equal("gp3"))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Iops).To(BeNil())
// Bottlerocket user volume
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[1].Ebs.VolumeSize).To(Equal(int64(20)))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[1].Ebs.VolumeType).To(Equal("gp3"))
Expect(ltInput.LaunchTemplateData.BlockDeviceMappings[1].Ebs.Iops).To(BeNil())
})
})
It("should not default block device mappings for custom AMIFamilies", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
nodeTemplate.Spec.AMISelector = map[string]string{"*": "*"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(len(ltInput.LaunchTemplateData.BlockDeviceMappings)).To(Equal(0))
})
})
It("should use custom block device mapping for custom AMIFamilies", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
nodeTemplate.Spec.AMISelector = map[string]string{"*": "*"}
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
DeleteOnTermination: aws.Bool(true),
Encrypted: aws.Bool(true),
VolumeType: aws.String("io2"),
VolumeSize: lo.ToPtr(resource.MustParse("40Gi")),
IOPS: aws.Int64(10_000),
KMSKeyID: aws.String("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"),
},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(len(ltInput.LaunchTemplateData.BlockDeviceMappings)).To(Equal(1))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeSize).To(Equal(int64(40)))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.VolumeType).To(Equal("io2"))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Iops).To(Equal(int64(10_000)))
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.DeleteOnTermination).To(BeTrue())
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.Encrypted).To(BeTrue())
Expect(*ltInput.LaunchTemplateData.BlockDeviceMappings[0].Ebs.KmsKeyId).To(Equal("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"))
})
})
})
Context("Ephemeral Storage", func() {
It("should pack pods when a daemonset has an ephemeral-storage request", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate, coretest.DaemonSet(
coretest.DaemonSetOptions{PodOptions: coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1"),
v1.ResourceMemory: resource.MustParse("1Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi")}},
}},
))
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should pack pods with any ephemeral-storage request", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("1G"),
}}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should pack pods with large ephemeral-storage request", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
}}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
})
It("should not pack pods if the sum of pod ephemeral-storage and overhead exceeds node capacity", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("19Gi"),
}}})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should launch multiple nodes if sum of pod ephemeral-storage requests exceeds a single nodes capacity", func() {
var nodes []*v1.Node
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
}),
coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
for _, pod := range pods {
nodes = append(nodes, ExpectScheduled(ctx, env.Client, pod))
}
Expect(nodes).To(HaveLen(2))
})
It("should only pack pods with ephemeral-storage requests that will fit on an available node", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pods := []*v1.Pod{
coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
}),
coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("150Gi"),
},
},
}),
}
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pods...)
ExpectScheduled(ctx, env.Client, pods[0])
ExpectNotScheduled(ctx, env.Client, pods[1])
})
It("should not pack pod if no available instance types have enough storage", func() {
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("150Gi"),
},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should pack pods using the blockdevicemappings from the provider spec when defined", func() {
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(50, resource.Giga),
},
}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceEphemeralStorage: resource.MustParse("25Gi"),
},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// capacity isn't recorded on the node any longer, but we know the pod should schedule
ExpectScheduled(ctx, env.Client, pod)
})
It("should pack pods using blockdevicemappings for Custom AMIFamily", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
nodeTemplate.Spec.AMISelector = map[string]string{"*": "*"}
nodeTemplate.Spec.BlockDeviceMappings = []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(20, resource.Giga),
},
},
{
DeviceName: aws.String("/dev/xvdb"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resource.NewScaledQuantity(40, resource.Giga),
},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
// this pod can only be satisfied if `/dev/xvdb` will house all the pods.
v1.ResourceEphemeralStorage: resource.MustParse("25Gi"),
},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// capacity isn't recorded on the node any longer, but we know the pod should schedule
ExpectScheduled(ctx, env.Client, pod)
})
})
Context("AL2", func() {
var info *ec2.InstanceTypeInfo
BeforeEach(func() {
var ok bool
var instanceInfo []*ec2.InstanceTypeInfo
err := awsEnv.EC2API.DescribeInstanceTypesPagesWithContext(ctx, &ec2.DescribeInstanceTypesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("supported-virtualization-type"),
Values: []*string{aws.String("hvm")},
},
{
Name: aws.String("processor-info.supported-architecture"),
Values: aws.StringSlice([]string{"x86_64", "arm64"}),
},
},
}, func(page *ec2.DescribeInstanceTypesOutput, lastPage bool) bool {
instanceInfo = append(instanceInfo, page.InstanceTypes...)
return true
})
Expect(err).To(BeNil())
info, ok = lo.Find(instanceInfo, func(i *ec2.InstanceTypeInfo) bool {
return aws.StringValue(i.InstanceType) == "m5.xlarge"
})
Expect(ok).To(BeTrue())
})
It("should calculate memory overhead based on eni limited pods when ENI limited", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
VMMemoryOverheadPercent: lo.ToPtr[float64](0),
}))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
overhead := it.Overhead.Total()
Expect(overhead.Memory().String()).To(Equal("993Mi"))
})
It("should calculate memory overhead based on eni limited pods when not ENI limited", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
VMMemoryOverheadPercent: lo.ToPtr[float64](0),
}))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
overhead := it.Overhead.Total()
Expect(overhead.Memory().String()).To(Equal("993Mi"))
})
})
Context("Bottlerocket", func() {
var info *ec2.InstanceTypeInfo
BeforeEach(func() {
var ok bool
var instanceInfo []*ec2.InstanceTypeInfo
err := awsEnv.EC2API.DescribeInstanceTypesPagesWithContext(ctx, &ec2.DescribeInstanceTypesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("supported-virtualization-type"),
Values: []*string{aws.String("hvm")},
},
{
Name: aws.String("processor-info.supported-architecture"),
Values: aws.StringSlice([]string{"x86_64", "arm64"}),
},
},
}, func(page *ec2.DescribeInstanceTypesOutput, lastPage bool) bool {
instanceInfo = append(instanceInfo, page.InstanceTypes...)
return true
})
Expect(err).To(BeNil())
info, ok = lo.Find(instanceInfo, func(i *ec2.InstanceTypeInfo) bool {
return aws.StringValue(i.InstanceType) == "m5.xlarge"
})
Expect(ok).To(BeTrue())
})
It("should calculate memory overhead based on eni limited pods when ENI limited", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(true),
VMMemoryOverheadPercent: lo.ToPtr[float64](0),
}))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
overhead := it.Overhead.Total()
Expect(overhead.Memory().String()).To(Equal("993Mi"))
})
It("should calculate memory overhead based on max pods when not ENI limited", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
VMMemoryOverheadPercent: lo.ToPtr[float64](0),
}))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
it := instancetype.NewInstanceType(ctx, info, provisioner.Spec.KubeletConfiguration, "", nodeTemplate, nil)
overhead := it.Overhead.Total()
Expect(overhead.Memory().String()).To(Equal("1565Mi"))
})
})
Context("User Data", func() {
It("should specify --use-max-pods=false when using ENI-based pod density", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--use-max-pods false")
})
It("should specify --use-max-pods=false when not using ENI-based pod density", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--use-max-pods false", "--max-pods=110")
})
It("should specify --use-max-pods=false and --max-pods user value when user specifies maxPods in Provisioner", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{MaxPods: aws.Int32(10)}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--use-max-pods false", "--max-pods=10")
})
It("should specify --system-reserved when overriding system reserved values", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("500m"),
v1.ResourceMemory: resource.MustParse("1Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("2Gi"),
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Check whether the arguments are there for --system-reserved
arg := "--system-reserved="
i := strings.Index(string(userData), arg)
rem := string(userData)[(i + len(arg)):]
i = strings.Index(rem, "'")
for k, v := range provisioner.Spec.KubeletConfiguration.SystemReserved {
Expect(rem[:i]).To(ContainSubstring(fmt.Sprintf("%v=%v", k.String(), v.String())))
}
})
})
It("should specify --kube-reserved when overriding system reserved values", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("500m"),
v1.ResourceMemory: resource.MustParse("1Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("2Gi"),
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Check whether the arguments are there for --kube-reserved
arg := "--kube-reserved="
i := strings.Index(string(userData), arg)
rem := string(userData)[(i + len(arg)):]
i = strings.Index(rem, "'")
for k, v := range provisioner.Spec.KubeletConfiguration.KubeReserved {
Expect(rem[:i]).To(ContainSubstring(fmt.Sprintf("%v=%v", k.String(), v.String())))
}
})
})
It("should pass eviction hard threshold values when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "10%",
"nodefs.available": "15%",
"nodefs.inodesFree": "5%",
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Check whether the arguments are there for --kube-reserved
arg := "--eviction-hard="
i := strings.Index(string(userData), arg)
rem := string(userData)[(i + len(arg)):]
i = strings.Index(rem, "'")
for k, v := range provisioner.Spec.KubeletConfiguration.EvictionHard {
Expect(rem[:i]).To(ContainSubstring(fmt.Sprintf("%v<%v", k, v)))
}
})
})
It("should pass eviction soft threshold values when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "10%",
"nodefs.available": "15%",
"nodefs.inodesFree": "5%",
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Check whether the arguments are there for --kube-reserved
arg := "--eviction-soft="
i := strings.Index(string(userData), arg)
rem := string(userData)[(i + len(arg)):]
i = strings.Index(rem, "'")
for k, v := range provisioner.Spec.KubeletConfiguration.EvictionSoft {
Expect(rem[:i]).To(ContainSubstring(fmt.Sprintf("%v<%v", k, v)))
}
})
})
It("should pass eviction soft grace period values when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
"nodefs.available": {Duration: time.Second * 180},
"nodefs.inodesFree": {Duration: time.Minute * 5},
},
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Check whether the arguments are there for --kube-reserved
arg := "--eviction-soft-grace-period="
i := strings.Index(string(userData), arg)
rem := string(userData)[(i + len(arg)):]
i = strings.Index(rem, "'")
for k, v := range provisioner.Spec.KubeletConfiguration.EvictionSoftGracePeriod {
Expect(rem[:i]).To(ContainSubstring(fmt.Sprintf("%v=%v", k, v.Duration.String())))
}
})
})
It("should pass eviction max pod grace period when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
EvictionMaxPodGracePeriod: aws.Int32(300),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining(fmt.Sprintf("--eviction-max-pod-grace-period=%d", 300))
})
It("should specify --pods-per-core", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
PodsPerCore: aws.Int32(2),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining(fmt.Sprintf("--pods-per-core=%d", 2))
})
It("should specify --pods-per-core with --max-pods enabled", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
PodsPerCore: aws.Int32(2),
MaxPods: aws.Int32(100),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining(fmt.Sprintf("--pods-per-core=%d", 2), fmt.Sprintf("--max-pods=%d", 100))
})
It("should specify --container-runtime containerd by default", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--container-runtime containerd")
})
It("should specify dockerd if specified in the provisionerSpec", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{ContainerRuntime: aws.String("dockerd")}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--container-runtime dockerd")
})
It("should specify --container-runtime containerd when using Neuron GPUs", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{{Key: v1alpha1.LabelInstanceCategory, Operator: v1.NodeSelectorOpExists}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("1"),
v1alpha1.ResourceAWSNeuron: resource.MustParse("1"),
},
Limits: map[v1.ResourceName]resource.Quantity{
v1alpha1.ResourceAWSNeuron: resource.MustParse("1"),
},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--container-runtime containerd")
})
It("should specify --container-runtime containerd when using Nvidia GPUs", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{{Key: v1alpha1.LabelInstanceCategory, Operator: v1.NodeSelectorOpExists}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod(coretest.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("1"),
v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1"),
},
Limits: map[v1.ResourceName]resource.Quantity{
v1alpha1.ResourceNVIDIAGPU: resource.MustParse("1"),
},
},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--container-runtime containerd")
})
It("should specify --dns-cluster-ip and --ip-family when running in an ipv6 cluster", func() {
awsEnv.LaunchTemplateProvider.KubeDNSIP = net.ParseIP("fd4b:121b:812b::a")
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--dns-cluster-ip 'fd4b:121b:812b::a'")
ExpectLaunchTemplatesCreatedWithUserDataContaining("--ip-family ipv6")
})
It("should specify --dns-cluster-ip when running in an ipv4 cluster", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--dns-cluster-ip '10.0.100.10'")
})
It("should pass ImageGCHighThresholdPercent when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
ImageGCHighThresholdPercent: aws.Int32(50),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--image-gc-high-threshold=50")
})
It("should pass ImageGCLowThresholdPercent when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
ImageGCLowThresholdPercent: aws.Int32(50),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--image-gc-low-threshold=50")
})
It("should pass --cpu-fs-quota when specified", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
CPUCFSQuota: aws.Bool(false),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--cpu-cfs-quota=false")
})
Context("Bottlerocket", func() {
It("should merge in custom user data", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
content, err := os.ReadFile("testdata/br_userdata_input.golden")
Expect(err).To(BeNil())
nodeTemplate.Spec.UserData = aws.String(string(content))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner.Spec.Taints = []v1.Taint{{Key: "foo", Value: "bar", Effect: v1.TaintEffectNoExecute}}
provisioner.Spec.StartupTaints = []v1.Taint{{Key: "baz", Value: "bin", Effect: v1.TaintEffectNoExecute}}
ExpectApplied(ctx, env.Client, nodeTemplate, provisioner)
Expect(env.Client.Get(ctx, client.ObjectKeyFromObject(provisioner), provisioner)).To(Succeed())
pod := coretest.UnschedulablePod(coretest.PodOptions{
Tolerations: []v1.Toleration{{Operator: v1.TolerationOpExists}},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
content, err = os.ReadFile("testdata/br_userdata_merged.golden")
Expect(err).To(BeNil())
ExpectLaunchTemplatesCreatedWithUserData(fmt.Sprintf(string(content), provisioner.Name))
})
It("should bootstrap when custom user data is empty", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner.Spec.Taints = []v1.Taint{{Key: "foo", Value: "bar", Effect: v1.TaintEffectNoExecute}}
provisioner.Spec.StartupTaints = []v1.Taint{{Key: "baz", Value: "bin", Effect: v1.TaintEffectNoExecute}}
ExpectApplied(ctx, env.Client, nodeTemplate, provisioner)
Expect(env.Client.Get(ctx, client.ObjectKeyFromObject(provisioner), provisioner)).To(Succeed())
pod := coretest.UnschedulablePod(coretest.PodOptions{
Tolerations: []v1.Toleration{{Operator: v1.TolerationOpExists}},
})
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
content, err := os.ReadFile("testdata/br_userdata_unmerged.golden")
Expect(err).To(BeNil())
ExpectLaunchTemplatesCreatedWithUserData(fmt.Sprintf(string(content), provisioner.Name))
})
It("should not bootstrap when provider ref points to a non-existent resource", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: "doesnotexist"}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// This will not be scheduled since we were pointed to a non-existent awsnodetemplate resource.
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should not bootstrap on invalid toml user data", func() {
nodeTemplate.Spec.UserData = aws.String("#/bin/bash\n ./not-toml.sh")
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
// This will not be scheduled since userData cannot be generated for the prospective node.
ExpectNotScheduled(ctx, env.Client, pod)
})
It("should override system reserved values in user data", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, nodeTemplate)
provisioner = test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Kubelet: &v1alpha5.KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("3Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(len(config.Settings.Kubernetes.SystemReserved)).To(Equal(3))
Expect(config.Settings.Kubernetes.SystemReserved[v1.ResourceCPU.String()]).To(Equal("2"))
Expect(config.Settings.Kubernetes.SystemReserved[v1.ResourceMemory.String()]).To(Equal("3Gi"))
Expect(config.Settings.Kubernetes.SystemReserved[v1.ResourceEphemeralStorage.String()]).To(Equal("10Gi"))
})
})
It("should override kube reserved values in user data", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, nodeTemplate)
provisioner = test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Kubelet: &v1alpha5.KubeletConfiguration{
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("3Gi"),
v1.ResourceEphemeralStorage: resource.MustParse("10Gi"),
},
},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(len(config.Settings.Kubernetes.KubeReserved)).To(Equal(3))
Expect(config.Settings.Kubernetes.KubeReserved[v1.ResourceCPU.String()]).To(Equal("2"))
Expect(config.Settings.Kubernetes.KubeReserved[v1.ResourceMemory.String()]).To(Equal("3Gi"))
Expect(config.Settings.Kubernetes.KubeReserved[v1.ResourceEphemeralStorage.String()]).To(Equal("10Gi"))
})
})
It("should override kube reserved values in user data", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, nodeTemplate)
provisioner = test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Kubelet: &v1alpha5.KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "10%",
"nodefs.available": "15%",
"nodefs.inodesFree": "5%",
},
},
})
ExpectApplied(ctx, env.Client, provisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(len(config.Settings.Kubernetes.EvictionHard)).To(Equal(3))
Expect(config.Settings.Kubernetes.EvictionHard["memory.available"]).To(Equal("10%"))
Expect(config.Settings.Kubernetes.EvictionHard["nodefs.available"]).To(Equal("15%"))
Expect(config.Settings.Kubernetes.EvictionHard["nodefs.inodesFree"]).To(Equal("5%"))
})
})
It("should specify max pods value when passing maxPods in configuration", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner = test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Kubelet: &v1alpha5.KubeletConfiguration{
MaxPods: aws.Int32(10),
},
})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(config.Settings.Kubernetes.MaxPods).ToNot(BeNil())
Expect(*config.Settings.Kubernetes.MaxPods).To(BeNumerically("==", 10))
})
})
It("should pass ImageGCHighThresholdPercent when specified", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
ImageGCHighThresholdPercent: aws.Int32(50),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(config.Settings.Kubernetes.ImageGCHighThresholdPercent).ToNot(BeNil())
percent, err := strconv.Atoi(*config.Settings.Kubernetes.ImageGCHighThresholdPercent)
Expect(err).ToNot(HaveOccurred())
Expect(percent).To(BeNumerically("==", 50))
})
})
It("should pass ImageGCLowThresholdPercent when specified", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
ImageGCLowThresholdPercent: aws.Int32(50),
}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(config.Settings.Kubernetes.ImageGCLowThresholdPercent).ToNot(BeNil())
percent, err := strconv.Atoi(*config.Settings.Kubernetes.ImageGCLowThresholdPercent)
Expect(err).ToNot(HaveOccurred())
Expect(percent).To(BeNumerically("==", 50))
})
})
It("should pass ClusterDNSIP when discovered", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*ltInput.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
config := &bootstrap.BottlerocketConfig{}
Expect(config.UnmarshalTOML(userData)).To(Succeed())
Expect(config.Settings.Kubernetes.ClusterDNSIP).ToNot(BeNil())
Expect(*config.Settings.Kubernetes.ClusterDNSIP).To(Equal("10.0.100.10"))
})
})
})
Context("AL2 Custom UserData", func() {
It("should merge in custom user data", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
content, err := os.ReadFile("testdata/al2_userdata_input.golden")
Expect(err).To(BeNil())
nodeTemplate.Spec.UserData = aws.String(string(content))
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
content, err = os.ReadFile("testdata/al2_userdata_merged.golden")
Expect(err).To(BeNil())
expectedUserData := fmt.Sprintf(string(content), newProvisioner.Name)
ExpectLaunchTemplatesCreatedWithUserData(expectedUserData)
})
It("should merge in custom user data not in multi-part mime format", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
content, err := os.ReadFile("testdata/al2_no_mime_userdata_input.golden")
Expect(err).To(BeNil())
nodeTemplate.Spec.UserData = aws.String(string(content))
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
content, err = os.ReadFile("testdata/al2_userdata_merged.golden")
Expect(err).To(BeNil())
expectedUserData := fmt.Sprintf(string(content), newProvisioner.Name)
ExpectLaunchTemplatesCreatedWithUserData(expectedUserData)
})
It("should handle empty custom user data", func() {
ctx = settings.ToContext(ctx, test.Settings(test.SettingOptions{
EnableENILimitedPodDensity: lo.ToPtr(false),
}))
nodeTemplate.Spec.UserData = nil
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
content, err := os.ReadFile("testdata/al2_userdata_unmerged.golden")
Expect(err).To(BeNil())
expectedUserData := fmt.Sprintf(string(content), newProvisioner.Name)
ExpectLaunchTemplatesCreatedWithUserData(expectedUserData)
})
})
Context("Custom AMI Selector", func() {
It("should use ami selector specified in AWSNodeTemplate", func() {
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2022-08-15T12:00:00Z")},
}})
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect("ami-123").To(Equal(*ltInput.LaunchTemplateData.ImageId))
})
})
It("should copy over userData untouched when AMIFamily is Custom", func() {
nodeTemplate.Spec.UserData = aws.String("special user data")
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2022-08-15T12:00:00Z")},
}})
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserData("special user data")
})
It("should correctly use ami selector with specific IDs in AWSNodeTemplate", func() {
nodeTemplate.Spec.AMISelector = map[string]string{"aws-ids": "ami-123,ami-456"}
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{{Key: aws.String(v1.LabelInstanceTypeStable), Value: aws.String("m5.large")}},
CreationDate: aws.String("2022-08-15T12:00:00Z"),
},
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-456"),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{{Key: aws.String(v1.LabelInstanceTypeStable), Value: aws.String("m5.xlarge")}},
CreationDate: aws.String("2022-08-15T12:00:00Z"),
},
}})
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 2))
actualFilter := awsEnv.EC2API.CalledWithDescribeImagesInput.Pop().Filters
expectedFilter := []*ec2.Filter{
{
Name: aws.String("image-id"),
Values: aws.StringSlice([]string{"ami-123", "ami-456"}),
},
}
Expect(actualFilter).To(Equal(expectedFilter))
})
It("should create multiple launch templates when multiple amis are discovered with non-equivalent requirements", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{{Key: aws.String(v1.LabelInstanceTypeStable), Value: aws.String("m5.large")}},
CreationDate: aws.String("2022-08-15T12:00:00Z"),
},
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-456"),
Architecture: aws.String("x86_64"),
Tags: []*ec2.Tag{{Key: aws.String(v1.LabelInstanceTypeStable), Value: aws.String("m5.xlarge")}},
CreationDate: aws.String("2022-08-10T12:00:00Z"),
},
}})
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 2))
expectedImageIds := sets.NewString("ami-123", "ami-456")
actualImageIds := sets.NewString(
*awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Pop().LaunchTemplateData.ImageId,
*awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Pop().LaunchTemplateData.ImageId,
)
Expect(expectedImageIds.Equal(actualImageIds)).To(BeTrue())
})
It("should create a launch template with the newest compatible AMI when multiple amis are discovered", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-123"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2020-01-01T12:00:00Z"),
},
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-456"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2021-01-01T12:00:00Z"),
},
{
// Incompatible because required ARM64
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("ami-789"),
Architecture: aws.String("arm64"),
CreationDate: aws.String("2022-01-01T12:00:00Z"),
},
}})
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureAmd64},
},
},
})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect("ami-456").To(Equal(*ltInput.LaunchTemplateData.ImageId))
})
})
It("should fail if no amis match selector.", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{}})
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(Equal(0))
})
It("should fail if no instanceType matches ami requirements.", func() {
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{Name: aws.String(coretest.RandomName()), ImageId: aws.String("ami-123"), Architecture: aws.String("newnew"), CreationDate: aws.String("2022-01-01T12:00:00Z")}}})
nodeTemplate.Spec.AMISelector = map[string]string{"karpenter.sh/discovery": "my-cluster"}
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectNotScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(Equal(0))
})
It("should choose amis from SSM if no selector specified in AWSNodeTemplate", func() {
version := lo.Must(awsEnv.AMIProvider.KubeServerVersion(ctx))
awsEnv.SSMAPI.Parameters = map[string]string{
fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", version): "test-ami-123",
}
awsEnv.EC2API.DescribeImagesOutput.Set(&ec2.DescribeImagesOutput{Images: []*ec2.Image{
{
Name: aws.String(coretest.RandomName()),
ImageId: aws.String("test-ami-123"),
Architecture: aws.String("x86_64"),
CreationDate: aws.String("2022-08-15T12:00:00Z"),
},
}})
ExpectApplied(ctx, env.Client, nodeTemplate)
newProvisioner := test.Provisioner(coretest.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name}})
ExpectApplied(ctx, env.Client, newProvisioner)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
input := awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Pop()
Expect(*input.LaunchTemplateData.ImageId).To(ContainSubstring("test-ami"))
})
})
Context("Subnet-based Launch Template Configration", func() {
It("should explicitly set 'AssignPublicIPv4' to false in the Launch Template", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-1,test-subnet-3"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
input := awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Pop()
Expect(*input.LaunchTemplateData.NetworkInterfaces[0].AssociatePublicIpAddress).To(BeFalse())
})
It("should not explicitly set 'AssignPublicIPv4' when the subnets are configured to assign public IPv4 addresses", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
input := awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Pop()
Expect(len(input.LaunchTemplateData.NetworkInterfaces)).To(BeNumerically("==", 0))
})
})
Context("Kubelet Args", func() {
It("should specify the --dns-cluster-ip flag when clusterDNSIP is set", func() {
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{ClusterDNS: []string{"10.0.10.100"}}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
ExpectLaunchTemplatesCreatedWithUserDataContaining("--dns-cluster-ip '10.0.10.100'")
})
})
Context("Instance Profile", func() {
It("should use the default instance profile if none specified on the Provisioner", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(*ltInput.LaunchTemplateData.IamInstanceProfile.Name).To(Equal("test-instance-profile"))
})
})
It("should use the instance profile on the Provisioner when specified", func() {
nodeTemplate.Spec.InstanceProfile = aws.String("overridden-profile")
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(*ltInput.LaunchTemplateData.IamInstanceProfile.Name).To(Equal("overridden-profile"))
})
})
})
})
Context("Detailed Monitoring", func() {
It("should default detailed monitoring to off", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(aws.BoolValue(ltInput.LaunchTemplateData.Monitoring.Enabled)).To(BeFalse())
})
})
It("should pass detailed monitoring setting to the launch template at creation", func() {
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyAL2
nodeTemplate.Spec.DetailedMonitoring = aws.Bool(true)
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
pod := coretest.UnschedulablePod()
ExpectProvisioned(ctx, env.Client, cluster, cloudProvider, prov, pod)
ExpectScheduled(ctx, env.Client, pod)
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(ltInput *ec2.CreateLaunchTemplateInput) {
Expect(aws.BoolValue(ltInput.LaunchTemplateData.Monitoring.Enabled)).To(BeTrue())
})
})
})
})
// ExpectTags verifies that the expected tags are a subset of the tags found
func ExpectTags(tags []*ec2.Tag, expected map[string]string) {
existingTags := lo.SliceToMap(tags, func(t *ec2.Tag) (string, string) { return *t.Key, *t.Value })
for expKey, expValue := range expected {
foundValue, ok := existingTags[expKey]
ExpectWithOffset(1, ok).To(BeTrue(), fmt.Sprintf("expected to find tag %s in %s", expKey, existingTags))
ExpectWithOffset(1, foundValue).To(Equal(expValue))
}
}
func ExpectTagsNotFound(tags []*ec2.Tag, expectNotFound map[string]string) {
existingTags := lo.SliceToMap(tags, func(t *ec2.Tag) (string, string) { return *t.Key, *t.Value })
for k, v := range expectNotFound {
elem, ok := existingTags[k]
ExpectWithOffset(1, !ok || v != elem).To(BeTrue())
}
}
func ExpectLaunchTemplatesCreatedWithUserDataContaining(substrings ...string) {
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(input *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*input.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
for _, substring := range substrings {
Expect(string(userData)).To(ContainSubstring(substring))
}
})
}
func ExpectLaunchTemplatesCreatedWithUserData(expected string) {
Expect(awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.Len()).To(BeNumerically(">=", 1))
awsEnv.EC2API.CalledWithCreateLaunchTemplateInput.ForEach(func(input *ec2.CreateLaunchTemplateInput) {
userData, err := base64.StdEncoding.DecodeString(*input.LaunchTemplateData.UserData)
Expect(err).To(BeNil())
// Newlines are always added for missing TOML fields, so strip them out before comparisons.
actualUserData := strings.Replace(string(userData), "\n", "", -1)
expectedUserData := strings.Replace(expected, "\n", "", -1)
Expect(expectedUserData).To(Equal(actualUserData))
})
}
| 1,748 |
Subsets and Splits