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 pricing
import (
"context"
"time"
lop "github.com/samber/lo/parallel"
"go.uber.org/multierr"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
)
type Controller struct {
pricingProvider *Provider
}
func NewController(pricingProvider *Provider) *Controller {
return &Controller{
pricingProvider: pricingProvider,
}
}
func (c *Controller) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
return reconcile.Result{RequeueAfter: 12 * time.Hour}, c.updatePricing(ctx)
}
func (c *Controller) Name() string {
return "pricing"
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.NewSingletonManagedBy(m)
}
func (c *Controller) updatePricing(ctx context.Context) error {
work := []func(ctx context.Context) error{
c.pricingProvider.UpdateOnDemandPricing,
c.pricingProvider.UpdateSpotPricing,
}
errs := make([]error, len(work))
lop.ForEach(work, func(f func(ctx context.Context) error, i int) {
if err := f(ctx); err != nil {
errs[i] = err
}
})
return multierr.Combine(errs...)
}
| 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 pricing
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"
CapacityTypeLabel = "capacity_type"
RegionLabel = "region"
TopologyLabel = "zone"
InstancePriceEstimate = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: metrics.Namespace,
Subsystem: cloudProviderSubsystem,
Name: "instance_type_price_estimate",
Help: "Estimated hourly price used when making informed decisions on node cost calculation. This is updated once on startup and then every 12 hours.",
},
[]string{
InstanceTypeLabel,
CapacityTypeLabel,
RegionLabel,
TopologyLabel,
})
)
func init() {
crmetrics.Registry.MustRegister(InstancePriceEstimate)
}
| 51 |
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 pricing
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"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/pricing"
"github.com/aws/aws-sdk-go/service/pricing/pricingiface"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"go.uber.org/multierr"
"knative.dev/pkg/logging"
"github.com/aws/karpenter-core/pkg/utils/pretty"
)
// Provider provides actual pricing data to the AWS cloud provider to allow it to make more informed decisions
// regarding which instances to launch. This is initialized at startup with a periodically updated static price list to
// support running in locations where pricing data is unavailable. In those cases the static pricing data provides a
// relative ordering that is still more accurate than our previous pricing model. In the event that a pricing update
// fails, the previous pricing information is retained and used which may be the static initial pricing data if pricing
// updates never succeed.
type Provider struct {
ec2 ec2iface.EC2API
pricing pricingiface.PricingAPI
region string
cm *pretty.ChangeMonitor
mu sync.RWMutex
onDemandUpdateTime time.Time
onDemandPrices map[string]float64
spotUpdateTime time.Time
spotPrices map[string]zonal
}
// zonalPricing is used to capture the per-zone price
// for spot data as well as the default price
// based on on-demand price when the provisioningController first
// comes up
type zonal struct {
defaultPrice float64 // Used until we get the spot pricing data
prices map[string]float64
}
type Err struct {
error
lastUpdateTime time.Time
}
func newZonalPricing(defaultPrice float64) zonal {
z := zonal{
prices: map[string]float64{},
}
z.defaultPrice = defaultPrice
return z
}
// NewPricingAPI returns a pricing API configured based on a particular region
func NewAPI(sess *session.Session, region string) pricingiface.PricingAPI {
if sess == nil {
return nil
}
// pricing API doesn't have an endpoint in all regions
pricingAPIRegion := "us-east-1"
if strings.HasPrefix(region, "ap-") || strings.HasPrefix(region, "cn-") {
pricingAPIRegion = "ap-south-1"
}
return pricing.New(sess, &aws.Config{Region: aws.String(pricingAPIRegion)})
}
func NewProvider(_ context.Context, pricing pricingiface.PricingAPI, ec2Api ec2iface.EC2API, region string) *Provider {
p := &Provider{
region: region,
ec2: ec2Api,
pricing: pricing,
cm: pretty.NewChangeMonitor(),
}
// sets the pricing data from the static default state for the provider
p.Reset()
return p
}
// InstanceTypes returns the list of all instance types for which either a spot or on-demand price is known.
func (p *Provider) InstanceTypes() []string {
p.mu.RLock()
defer p.mu.RUnlock()
return lo.Union(lo.Keys(p.onDemandPrices), lo.Keys(p.spotPrices))
}
// OnDemandLastUpdated returns the time that the on-demand pricing was last updated
func (p *Provider) OnDemandLastUpdated() time.Time {
p.mu.RLock()
defer p.mu.RUnlock()
return p.onDemandUpdateTime
}
// SpotLastUpdated returns the time that the spot pricing was last updated
func (p *Provider) SpotLastUpdated() time.Time {
p.mu.RLock()
defer p.mu.RUnlock()
return p.spotUpdateTime
}
// OnDemandPrice returns the last known on-demand price for a given instance type, returning an error if there is no
// known on-demand pricing for the instance type.
func (p *Provider) OnDemandPrice(instanceType string) (float64, bool) {
p.mu.RLock()
defer p.mu.RUnlock()
price, ok := p.onDemandPrices[instanceType]
if !ok {
return 0.0, false
}
return price, true
}
// SpotPrice returns the last known spot price for a given instance type and zone, returning an error
// if there is no known spot pricing for that instance type or zone
func (p *Provider) SpotPrice(instanceType string, zone string) (float64, bool) {
p.mu.RLock()
defer p.mu.RUnlock()
if val, ok := p.spotPrices[instanceType]; ok {
if p.spotUpdateTime.Equal(initialPriceUpdate) {
return val.defaultPrice, true
}
if price, ok := p.spotPrices[instanceType].prices[zone]; ok {
return price, true
}
return 0.0, false
}
return 0.0, false
}
func (p *Provider) UpdateOnDemandPricing(ctx context.Context) error {
// standard on-demand instances
var wg sync.WaitGroup
var onDemandPrices, onDemandMetalPrices map[string]float64
var onDemandErr, onDemandMetalErr error
wg.Add(1)
go func() {
defer wg.Done()
onDemandPrices, onDemandErr = p.fetchOnDemandPricing(ctx,
&pricing.Filter{
Field: aws.String("tenancy"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Shared"),
},
&pricing.Filter{
Field: aws.String("productFamily"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Compute Instance"),
})
}()
// bare metal on-demand prices
wg.Add(1)
go func() {
defer wg.Done()
onDemandMetalPrices, onDemandMetalErr = p.fetchOnDemandPricing(ctx,
&pricing.Filter{
Field: aws.String("tenancy"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Dedicated"),
},
&pricing.Filter{
Field: aws.String("productFamily"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Compute Instance (bare metal)"),
})
}()
wg.Wait()
p.mu.Lock()
defer p.mu.Unlock()
err := multierr.Append(onDemandErr, onDemandMetalErr)
if err != nil {
return &Err{error: err, lastUpdateTime: p.onDemandUpdateTime}
}
if len(onDemandPrices) == 0 || len(onDemandMetalPrices) == 0 {
return &Err{error: errors.New("no on-demand pricing found"), lastUpdateTime: p.onDemandUpdateTime}
}
p.onDemandPrices = lo.Assign(onDemandPrices, onDemandMetalPrices)
p.onDemandUpdateTime = time.Now()
for instanceType, price := range p.onDemandPrices {
InstancePriceEstimate.With(prometheus.Labels{
InstanceTypeLabel: instanceType,
CapacityTypeLabel: ec2.UsageClassTypeOnDemand,
RegionLabel: p.region,
TopologyLabel: "",
}).Set(price)
}
if p.cm.HasChanged("on-demand-prices", p.onDemandPrices) {
logging.FromContext(ctx).With("instance-type-count", len(p.onDemandPrices)).Infof("updated on-demand pricing")
}
return nil
}
func (p *Provider) fetchOnDemandPricing(ctx context.Context, additionalFilters ...*pricing.Filter) (map[string]float64, error) {
prices := map[string]float64{}
filters := append([]*pricing.Filter{
{
Field: aws.String("regionCode"),
Type: aws.String("TERM_MATCH"),
Value: aws.String(p.region),
},
{
Field: aws.String("serviceCode"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("AmazonEC2"),
},
{
Field: aws.String("preInstalledSw"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("NA"),
},
{
Field: aws.String("operatingSystem"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Linux"),
},
{
Field: aws.String("capacitystatus"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("Used"),
},
{
Field: aws.String("marketoption"),
Type: aws.String("TERM_MATCH"),
Value: aws.String("OnDemand"),
}},
additionalFilters...)
if err := p.pricing.GetProductsPagesWithContext(ctx, &pricing.GetProductsInput{
Filters: filters,
ServiceCode: aws.String("AmazonEC2")}, p.onDemandPage(prices)); err != nil {
return nil, err
}
return prices, nil
}
// turning off cyclo here, it measures as a 12 due to all of the type checks of the pricing data which returns a deeply
// nested map[string]interface{}
// nolint: gocyclo
func (p *Provider) onDemandPage(prices map[string]float64) func(output *pricing.GetProductsOutput, b bool) bool {
// this isn't the full pricing struct, just the portions we care about
type priceItem struct {
Product struct {
Attributes struct {
InstanceType string
}
}
Terms struct {
OnDemand map[string]struct {
PriceDimensions map[string]struct {
PricePerUnit map[string]string
}
}
}
}
return func(output *pricing.GetProductsOutput, b bool) bool {
currency := "USD"
if p.region == "cn-north-1" {
currency = "CNY"
}
for _, outer := range output.PriceList {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
if err := enc.Encode(outer); err != nil {
logging.FromContext(context.Background()).Errorf("encoding %s", err)
}
dec := json.NewDecoder(&buf)
var pItem priceItem
if err := dec.Decode(&pItem); err != nil {
logging.FromContext(context.Background()).Errorf("decoding %s", err)
}
if pItem.Product.Attributes.InstanceType == "" {
continue
}
for _, term := range pItem.Terms.OnDemand {
for _, v := range term.PriceDimensions {
price, err := strconv.ParseFloat(v.PricePerUnit[currency], 64)
if err != nil || price == 0 {
continue
}
prices[pItem.Product.Attributes.InstanceType] = price
}
}
}
return true
}
}
// nolint: gocyclo
func (p *Provider) UpdateSpotPricing(ctx context.Context) error {
totalOfferings := 0
prices := map[string]map[string]float64{}
err := p.ec2.DescribeSpotPriceHistoryPagesWithContext(ctx, &ec2.DescribeSpotPriceHistoryInput{
ProductDescriptions: []*string{aws.String("Linux/UNIX"), aws.String("Linux/UNIX (Amazon VPC)")},
// get the latest spot price for each instance type
StartTime: aws.Time(time.Now()),
}, func(output *ec2.DescribeSpotPriceHistoryOutput, b bool) bool {
for _, sph := range output.SpotPriceHistory {
spotPriceStr := aws.StringValue(sph.SpotPrice)
spotPrice, err := strconv.ParseFloat(spotPriceStr, 64)
// these errors shouldn't occur, but if pricing API does have an error, we ignore the record
if err != nil {
logging.FromContext(ctx).Debugf("unable to parse price record %#v", sph)
continue
}
if sph.Timestamp == nil {
continue
}
instanceType := aws.StringValue(sph.InstanceType)
az := aws.StringValue(sph.AvailabilityZone)
_, ok := prices[instanceType]
if !ok {
prices[instanceType] = map[string]float64{}
}
prices[instanceType][az] = spotPrice
InstancePriceEstimate.With(prometheus.Labels{
InstanceTypeLabel: instanceType,
CapacityTypeLabel: ec2.UsageClassTypeSpot,
RegionLabel: p.region,
TopologyLabel: az,
}).Set(spotPrice)
}
return true
})
p.mu.Lock()
defer p.mu.Unlock()
if err != nil {
return &Err{error: err, lastUpdateTime: p.spotUpdateTime}
}
if len(prices) == 0 {
return &Err{error: errors.New("no spot pricing found"), lastUpdateTime: p.spotUpdateTime}
}
for it, zoneData := range prices {
if _, ok := p.spotPrices[it]; !ok {
p.spotPrices[it] = newZonalPricing(0)
}
for zone, price := range zoneData {
p.spotPrices[it].prices[zone] = price
}
totalOfferings += len(zoneData)
}
p.spotUpdateTime = time.Now()
if p.cm.HasChanged("spot-prices", p.spotPrices) {
logging.FromContext(ctx).With(
"instance-type-count", len(p.onDemandPrices),
"offering-count", totalOfferings).Infof("updated spot pricing with instance types and offerings")
}
return nil
}
func (p *Provider) LivenessProbe(_ *http.Request) error {
// ensure we don't deadlock and nolint for the empty critical section
p.mu.Lock()
//nolint: staticcheck
p.mu.Unlock()
return nil
}
func populateInitialSpotPricing(pricing map[string]float64) map[string]zonal {
m := map[string]zonal{}
for it, price := range pricing {
m[it] = newZonalPricing(price)
}
return m
}
func (p *Provider) Reset() {
// see if we've got region specific pricing data
staticPricing, ok := initialOnDemandPrices[p.region]
if !ok {
// and if not, fall back to the always available us-east-1
staticPricing = initialOnDemandPrices["us-east-1"]
}
p.onDemandPrices = staticPricing
// default our spot pricing to the same as the on-demand pricing until a price update
p.spotPrices = populateInitialSpotPricing(staticPricing)
p.onDemandUpdateTime = initialPriceUpdate
p.spotUpdateTime = initialPriceUpdate
}
| 417 |
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 pricing_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
awspricing "github.com/aws/aws-sdk-go/service/pricing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/types"
. "knative.dev/pkg/logging/testing"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
"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/test/expectations"
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/fake"
"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 controller *pricing.Controller
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)
controller = pricing.NewController(awsEnv.PricingProvider)
})
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())
awsEnv.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("Pricing", func() {
It("should return static on-demand data if pricing API fails", func() {
awsEnv.PricingAPI.NextError.Set(fmt.Errorf("failed"))
ExpectReconcileFailed(ctx, controller, types.NamespacedName{})
price, ok := awsEnv.PricingProvider.OnDemandPrice("c5.large")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically(">", 0))
})
It("should return static spot data if EC2 describeSpotPriceHistory API fails", func() {
awsEnv.PricingAPI.NextError.Set(fmt.Errorf("failed"))
ExpectReconcileFailed(ctx, controller, types.NamespacedName{})
price, ok := awsEnv.PricingProvider.SpotPrice("c5.large", "test-zone-1a")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically(">", 0))
})
It("should update on-demand pricing with response from the pricing API", func() {
// modify our API before creating the pricing provider as it performs an initial update on creation. The pricing
// API provides on-demand prices, the ec2 API provides spot prices
awsEnv.PricingAPI.GetProductsOutput.Set(&awspricing.GetProductsOutput{
PriceList: []aws.JSONValue{
fake.NewOnDemandPrice("c98.large", 1.20),
fake.NewOnDemandPrice("c99.large", 1.23),
},
})
updateStart := time.Now()
ExpectReconcileFailed(ctx, controller, types.NamespacedName{})
Eventually(func() bool { return awsEnv.PricingProvider.OnDemandLastUpdated().After(updateStart) }).Should(BeTrue())
price, ok := awsEnv.PricingProvider.OnDemandPrice("c98.large")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically("==", 1.20))
Expect(getPricingEstimateMetricValue("c98.large", ec2.UsageClassTypeOnDemand, "")).To(BeNumerically("==", 1.20))
price, ok = awsEnv.PricingProvider.OnDemandPrice("c99.large")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically("==", 1.23))
Expect(getPricingEstimateMetricValue("c99.large", ec2.UsageClassTypeOnDemand, "")).To(BeNumerically("==", 1.23))
})
It("should update spot pricing with response from the pricing API", func() {
now := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c99.large"),
SpotPrice: aws.String("1.23"),
Timestamp: &now,
},
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c98.large"),
SpotPrice: aws.String("1.20"),
Timestamp: &now,
},
{
AvailabilityZone: aws.String("test-zone-1b"),
InstanceType: aws.String("c99.large"),
SpotPrice: aws.String("1.50"),
Timestamp: &now,
},
{
AvailabilityZone: aws.String("test-zone-1b"),
InstanceType: aws.String("c98.large"),
SpotPrice: aws.String("1.10"),
Timestamp: &now,
},
},
})
awsEnv.PricingAPI.GetProductsOutput.Set(&awspricing.GetProductsOutput{
PriceList: []aws.JSONValue{
fake.NewOnDemandPrice("c98.large", 1.20),
fake.NewOnDemandPrice("c99.large", 1.23),
},
})
updateStart := time.Now()
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(updateStart) }).Should(BeTrue())
price, ok := awsEnv.PricingProvider.SpotPrice("c98.large", "test-zone-1b")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically("==", 1.10))
Expect(getPricingEstimateMetricValue("c98.large", ec2.UsageClassTypeSpot, "test-zone-1b")).To(BeNumerically("==", 1.10))
price, ok = awsEnv.PricingProvider.SpotPrice("c99.large", "test-zone-1a")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically("==", 1.23))
Expect(getPricingEstimateMetricValue("c99.large", ec2.UsageClassTypeSpot, "test-zone-1a")).To(BeNumerically("==", 1.23))
})
It("should update zonal pricing with data from the spot pricing API", func() {
now := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c99.large"),
SpotPrice: aws.String("1.23"),
Timestamp: &now,
},
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c98.large"),
SpotPrice: aws.String("1.20"),
Timestamp: &now,
},
},
})
awsEnv.PricingAPI.GetProductsOutput.Set(&awspricing.GetProductsOutput{
PriceList: []aws.JSONValue{
fake.NewOnDemandPrice("c98.large", 1.20),
fake.NewOnDemandPrice("c99.large", 1.23),
},
})
updateStart := time.Now()
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(updateStart) }).Should(BeTrue())
price, ok := awsEnv.PricingProvider.SpotPrice("c98.large", "test-zone-1a")
Expect(ok).To(BeTrue())
Expect(price).To(BeNumerically("==", 1.20))
Expect(getPricingEstimateMetricValue("c98.large", ec2.UsageClassTypeSpot, "test-zone-1a")).To(BeNumerically("==", 1.20))
_, ok = awsEnv.PricingProvider.SpotPrice("c98.large", "test-zone-1b")
Expect(ok).ToNot(BeTrue())
})
It("should respond with false if price doesn't exist in zone", func() {
now := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c99.large"),
SpotPrice: aws.String("1.23"),
Timestamp: &now,
},
},
})
awsEnv.PricingAPI.GetProductsOutput.Set(&awspricing.GetProductsOutput{
PriceList: []aws.JSONValue{
fake.NewOnDemandPrice("c98.large", 1.20),
fake.NewOnDemandPrice("c99.large", 1.23),
},
})
updateStart := time.Now()
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(updateStart) }).Should(BeTrue())
_, ok := awsEnv.PricingProvider.SpotPrice("c99.large", "test-zone-1b")
Expect(ok).To(BeFalse())
})
It("should query for both `Linux/UNIX` and `Linux/UNIX (Amazon VPC)`", func() {
// If an account supports EC2 classic, then the non-classic instance types have a product
// description of Linux/UNIX (Amazon VPC)
// If it doesn't, they have a product description of Linux/UNIX. To work in both cases, we
// need to search for both values.
updateStart := time.Now()
awsEnv.EC2API.DescribeSpotPriceHistoryOutput.Set(&ec2.DescribeSpotPriceHistoryOutput{
SpotPriceHistory: []*ec2.SpotPrice{
{
AvailabilityZone: aws.String("test-zone-1a"),
InstanceType: aws.String("c99.large"),
SpotPrice: aws.String("1.23"),
Timestamp: &updateStart,
},
},
})
awsEnv.PricingAPI.GetProductsOutput.Set(&awspricing.GetProductsOutput{
PriceList: []aws.JSONValue{
fake.NewOnDemandPrice("c98.large", 1.20),
fake.NewOnDemandPrice("c99.large", 1.23),
},
})
ExpectReconcileSucceeded(ctx, controller, types.NamespacedName{})
Eventually(func() bool { return awsEnv.PricingProvider.SpotLastUpdated().After(updateStart) }, 5*time.Second).Should(BeTrue())
inp := awsEnv.EC2API.DescribeSpotPriceHistoryInput.Clone()
Expect(lo.Map(inp.ProductDescriptions, func(x *string, _ int) string { return *x })).
To(ContainElements("Linux/UNIX", "Linux/UNIX (Amazon VPC)"))
})
})
func getPricingEstimateMetricValue(instanceType string, capacityType string, zone string) float64 {
var value *float64
metric, ok := FindMetricWithLabelValues("karpenter_cloudprovider_instance_type_price_estimate", map[string]string{
pricing.InstanceTypeLabel: instanceType,
pricing.CapacityTypeLabel: capacityType,
pricing.RegionLabel: "",
pricing.TopologyLabel: zone,
})
Expect(ok).To(BeTrue())
value = metric.GetGauge().Value
Expect(value).To(Not(BeNil()))
return *value
}
| 277 |
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 pricing
import "time"
// generated at 2023-06-26T13:09:51Z for us-east-1
var initialPriceUpdate, _ = time.Parse(time.RFC3339, "2023-06-26T13:09:51Z")
var initialOnDemandPrices = map[string]map[string]float64{}
func init() {
// us-east-1
initialOnDemandPrices["us-east-1"] = map[string]float64{
// a1 family
"a1.2xlarge": 0.204000, "a1.4xlarge": 0.408000, "a1.large": 0.051000, "a1.medium": 0.025500,
"a1.metal": 0.408000, "a1.xlarge": 0.102000,
// c1 family
"c1.medium": 0.130000, "c1.xlarge": 0.520000,
// c3 family
"c3.2xlarge": 0.420000, "c3.4xlarge": 0.840000, "c3.8xlarge": 1.680000, "c3.large": 0.105000,
"c3.xlarge": 0.210000,
// c4 family
"c4.2xlarge": 0.398000, "c4.4xlarge": 0.796000, "c4.8xlarge": 1.591000, "c4.large": 0.100000,
"c4.xlarge": 0.199000,
// c5 family
"c5.12xlarge": 2.040000, "c5.18xlarge": 3.060000, "c5.24xlarge": 4.080000, "c5.2xlarge": 0.340000,
"c5.4xlarge": 0.680000, "c5.9xlarge": 1.530000, "c5.large": 0.085000, "c5.metal": 4.080000,
"c5.xlarge": 0.170000,
// c5a family
"c5a.12xlarge": 1.848000, "c5a.16xlarge": 2.464000, "c5a.24xlarge": 3.696000, "c5a.2xlarge": 0.308000,
"c5a.4xlarge": 0.616000, "c5a.8xlarge": 1.232000, "c5a.large": 0.077000, "c5a.xlarge": 0.154000,
// c5ad family
"c5ad.12xlarge": 2.064000, "c5ad.16xlarge": 2.752000, "c5ad.24xlarge": 4.128000, "c5ad.2xlarge": 0.344000,
"c5ad.4xlarge": 0.688000, "c5ad.8xlarge": 1.376000, "c5ad.large": 0.086000, "c5ad.xlarge": 0.172000,
// c5d family
"c5d.12xlarge": 2.304000, "c5d.18xlarge": 3.456000, "c5d.24xlarge": 4.608000, "c5d.2xlarge": 0.384000,
"c5d.4xlarge": 0.768000, "c5d.9xlarge": 1.728000, "c5d.large": 0.096000, "c5d.metal": 4.608000,
"c5d.xlarge": 0.192000,
// c5n family
"c5n.18xlarge": 3.888000, "c5n.2xlarge": 0.432000, "c5n.4xlarge": 0.864000, "c5n.9xlarge": 1.944000,
"c5n.large": 0.108000, "c5n.metal": 3.888000, "c5n.xlarge": 0.216000,
// c6a family
"c6a.12xlarge": 1.836000, "c6a.16xlarge": 2.448000, "c6a.24xlarge": 3.672000, "c6a.2xlarge": 0.306000,
"c6a.32xlarge": 4.896000, "c6a.48xlarge": 7.344000, "c6a.4xlarge": 0.612000, "c6a.8xlarge": 1.224000,
"c6a.large": 0.076500, "c6a.metal": 7.344000, "c6a.xlarge": 0.153000,
// c6g family
"c6g.12xlarge": 1.632000, "c6g.16xlarge": 2.176000, "c6g.2xlarge": 0.272000, "c6g.4xlarge": 0.544000,
"c6g.8xlarge": 1.088000, "c6g.large": 0.068000, "c6g.medium": 0.034000, "c6g.metal": 2.306600,
"c6g.xlarge": 0.136000,
// c6gd family
"c6gd.12xlarge": 1.843200, "c6gd.16xlarge": 2.457600, "c6gd.2xlarge": 0.307200, "c6gd.4xlarge": 0.614400,
"c6gd.8xlarge": 1.228800, "c6gd.large": 0.076800, "c6gd.medium": 0.038400, "c6gd.metal": 2.605100,
"c6gd.xlarge": 0.153600,
// c6gn family
"c6gn.12xlarge": 2.073600, "c6gn.16xlarge": 2.764800, "c6gn.2xlarge": 0.345600, "c6gn.4xlarge": 0.691200,
"c6gn.8xlarge": 1.382400, "c6gn.large": 0.086400, "c6gn.medium": 0.043200, "c6gn.xlarge": 0.172800,
// c6i family
"c6i.12xlarge": 2.040000, "c6i.16xlarge": 2.720000, "c6i.24xlarge": 4.080000, "c6i.2xlarge": 0.340000,
"c6i.32xlarge": 5.440000, "c6i.4xlarge": 0.680000, "c6i.8xlarge": 1.360000, "c6i.large": 0.085000,
"c6i.metal": 5.440000, "c6i.xlarge": 0.170000,
// c6id family
"c6id.12xlarge": 2.419200, "c6id.16xlarge": 3.225600, "c6id.24xlarge": 4.838400, "c6id.2xlarge": 0.403200,
"c6id.32xlarge": 6.451200, "c6id.4xlarge": 0.806400, "c6id.8xlarge": 1.612800, "c6id.large": 0.100800,
"c6id.metal": 6.451200, "c6id.xlarge": 0.201600,
// c6in family
"c6in.12xlarge": 2.721600, "c6in.16xlarge": 3.628800, "c6in.24xlarge": 5.443200, "c6in.2xlarge": 0.453600,
"c6in.32xlarge": 7.257600, "c6in.4xlarge": 0.907200, "c6in.8xlarge": 1.814400, "c6in.large": 0.113400,
"c6in.metal": 7.257600, "c6in.xlarge": 0.226800,
// c7g family
"c7g.12xlarge": 1.740000, "c7g.16xlarge": 2.320000, "c7g.2xlarge": 0.290000, "c7g.4xlarge": 0.580000,
"c7g.8xlarge": 1.160000, "c7g.large": 0.072500, "c7g.medium": 0.036300, "c7g.metal": 2.320000,
"c7g.xlarge": 0.145000,
// c7gn family
"c7gn.12xlarge": 2.995200, "c7gn.16xlarge": 3.993600, "c7gn.2xlarge": 0.499200, "c7gn.4xlarge": 0.998400,
"c7gn.8xlarge": 1.996800, "c7gn.large": 0.124800, "c7gn.medium": 0.062400, "c7gn.xlarge": 0.249600,
// cc2 family
"cc2.8xlarge": 2.000000,
// cr1 family
"cr1.8xlarge": 3.500000,
// d2 family
"d2.2xlarge": 1.380000, "d2.4xlarge": 2.760000, "d2.8xlarge": 5.520000, "d2.xlarge": 0.690000,
// d3 family
"d3.2xlarge": 0.999000, "d3.4xlarge": 1.998000, "d3.8xlarge": 3.995520, "d3.xlarge": 0.499000,
// d3en family
"d3en.12xlarge": 6.308640, "d3en.2xlarge": 1.051000, "d3en.4xlarge": 2.103000, "d3en.6xlarge": 3.154000,
"d3en.8xlarge": 4.205760, "d3en.xlarge": 0.526000,
// dl1 family
"dl1.24xlarge": 13.109040,
// f1 family
"f1.16xlarge": 13.200000, "f1.2xlarge": 1.650000, "f1.4xlarge": 3.300000,
// g2 family
"g2.2xlarge": 0.650000, "g2.8xlarge": 2.600000,
// g3 family
"g3.16xlarge": 4.560000, "g3.4xlarge": 1.140000, "g3.8xlarge": 2.280000,
// g3s family
"g3s.xlarge": 0.750000,
// g4ad family
"g4ad.16xlarge": 3.468000, "g4ad.2xlarge": 0.541170, "g4ad.4xlarge": 0.867000, "g4ad.8xlarge": 1.734000,
"g4ad.xlarge": 0.378530,
// g4dn family
"g4dn.12xlarge": 3.912000, "g4dn.16xlarge": 4.352000, "g4dn.2xlarge": 0.752000, "g4dn.4xlarge": 1.204000,
"g4dn.8xlarge": 2.176000, "g4dn.metal": 7.824000, "g4dn.xlarge": 0.526000,
// g5 family
"g5.12xlarge": 5.672000, "g5.16xlarge": 4.096000, "g5.24xlarge": 8.144000, "g5.2xlarge": 1.212000,
"g5.48xlarge": 16.288000, "g5.4xlarge": 1.624000, "g5.8xlarge": 2.448000, "g5.xlarge": 1.006000,
// g5g family
"g5g.16xlarge": 2.744000, "g5g.2xlarge": 0.556000, "g5g.4xlarge": 0.828000, "g5g.8xlarge": 1.372000,
"g5g.metal": 2.744000, "g5g.xlarge": 0.420000,
// h1 family
"h1.16xlarge": 3.744000, "h1.2xlarge": 0.468000, "h1.4xlarge": 0.936000, "h1.8xlarge": 1.872000,
// hpc7g family
"hpc7g.16xlarge": 1.683200, "hpc7g.4xlarge": 1.683200, "hpc7g.8xlarge": 1.683200,
// hs1 family
"hs1.8xlarge": 4.600000,
// i2 family
"i2.2xlarge": 1.705000, "i2.4xlarge": 3.410000, "i2.8xlarge": 6.820000, "i2.xlarge": 0.853000,
// i3 family
"i3.16xlarge": 4.992000, "i3.2xlarge": 0.624000, "i3.4xlarge": 1.248000, "i3.8xlarge": 2.496000,
"i3.large": 0.156000, "i3.metal": 4.992000, "i3.xlarge": 0.312000,
// i3en family
"i3en.12xlarge": 5.424000, "i3en.24xlarge": 10.848000, "i3en.2xlarge": 0.904000, "i3en.3xlarge": 1.356000,
"i3en.6xlarge": 2.712000, "i3en.large": 0.226000, "i3en.metal": 10.848000, "i3en.xlarge": 0.452000,
// i4g family
"i4g.16xlarge": 4.942080, "i4g.2xlarge": 0.617760, "i4g.4xlarge": 1.235520, "i4g.8xlarge": 2.471040,
"i4g.large": 0.154440, "i4g.xlarge": 0.308880,
// i4i family
"i4i.16xlarge": 5.491000, "i4i.2xlarge": 0.686000, "i4i.32xlarge": 10.982400, "i4i.4xlarge": 1.373000,
"i4i.8xlarge": 2.746000, "i4i.large": 0.172000, "i4i.metal": 10.982000, "i4i.xlarge": 0.343000,
// im4gn family
"im4gn.16xlarge": 5.820670, "im4gn.2xlarge": 0.727580, "im4gn.4xlarge": 1.455170, "im4gn.8xlarge": 2.910340,
"im4gn.large": 0.181900, "im4gn.xlarge": 0.363790,
// inf1 family
"inf1.24xlarge": 4.721000, "inf1.2xlarge": 0.362000, "inf1.6xlarge": 1.180000, "inf1.xlarge": 0.228000,
// inf2 family
"inf2.24xlarge": 6.490630, "inf2.48xlarge": 12.981270, "inf2.8xlarge": 1.967860, "inf2.xlarge": 0.758200,
// is4gen family
"is4gen.2xlarge": 1.152600, "is4gen.4xlarge": 2.305200, "is4gen.8xlarge": 4.610400,
"is4gen.large": 0.288150, "is4gen.medium": 0.144080, "is4gen.xlarge": 0.576300,
// m1 family
"m1.large": 0.175000, "m1.medium": 0.087000, "m1.small": 0.044000, "m1.xlarge": 0.350000,
// m2 family
"m2.2xlarge": 0.490000, "m2.4xlarge": 0.980000, "m2.xlarge": 0.245000,
// m3 family
"m3.2xlarge": 0.532000, "m3.large": 0.133000, "m3.medium": 0.067000, "m3.xlarge": 0.266000,
// m4 family
"m4.10xlarge": 2.000000, "m4.16xlarge": 3.200000, "m4.2xlarge": 0.400000, "m4.4xlarge": 0.800000,
"m4.large": 0.100000, "m4.xlarge": 0.200000,
// m5 family
"m5.12xlarge": 2.304000, "m5.16xlarge": 3.072000, "m5.24xlarge": 4.608000, "m5.2xlarge": 0.384000,
"m5.4xlarge": 0.768000, "m5.8xlarge": 1.536000, "m5.large": 0.096000, "m5.metal": 4.608000,
"m5.xlarge": 0.192000,
// m5a family
"m5a.12xlarge": 2.064000, "m5a.16xlarge": 2.752000, "m5a.24xlarge": 4.128000, "m5a.2xlarge": 0.344000,
"m5a.4xlarge": 0.688000, "m5a.8xlarge": 1.376000, "m5a.large": 0.086000, "m5a.xlarge": 0.172000,
// m5ad family
"m5ad.12xlarge": 2.472000, "m5ad.16xlarge": 3.296000, "m5ad.24xlarge": 4.944000, "m5ad.2xlarge": 0.412000,
"m5ad.4xlarge": 0.824000, "m5ad.8xlarge": 1.648000, "m5ad.large": 0.103000, "m5ad.xlarge": 0.206000,
// m5d family
"m5d.12xlarge": 2.712000, "m5d.16xlarge": 3.616000, "m5d.24xlarge": 5.424000, "m5d.2xlarge": 0.452000,
"m5d.4xlarge": 0.904000, "m5d.8xlarge": 1.808000, "m5d.large": 0.113000, "m5d.metal": 5.424000,
"m5d.xlarge": 0.226000,
// m5dn family
"m5dn.12xlarge": 3.264000, "m5dn.16xlarge": 4.352000, "m5dn.24xlarge": 6.528000, "m5dn.2xlarge": 0.544000,
"m5dn.4xlarge": 1.088000, "m5dn.8xlarge": 2.176000, "m5dn.large": 0.136000, "m5dn.metal": 6.528000,
"m5dn.xlarge": 0.272000,
// m5n family
"m5n.12xlarge": 2.856000, "m5n.16xlarge": 3.808000, "m5n.24xlarge": 5.712000, "m5n.2xlarge": 0.476000,
"m5n.4xlarge": 0.952000, "m5n.8xlarge": 1.904000, "m5n.large": 0.119000, "m5n.metal": 5.712000,
"m5n.xlarge": 0.238000,
// m5zn family
"m5zn.12xlarge": 3.964100, "m5zn.2xlarge": 0.660700, "m5zn.3xlarge": 0.991000, "m5zn.6xlarge": 1.982000,
"m5zn.large": 0.165200, "m5zn.metal": 4.360500, "m5zn.xlarge": 0.330300,
// m6a family
"m6a.12xlarge": 2.073600, "m6a.16xlarge": 2.764800, "m6a.24xlarge": 4.147200, "m6a.2xlarge": 0.345600,
"m6a.32xlarge": 5.529600, "m6a.48xlarge": 8.294400, "m6a.4xlarge": 0.691200, "m6a.8xlarge": 1.382400,
"m6a.large": 0.086400, "m6a.metal": 8.294400, "m6a.xlarge": 0.172800,
// m6g family
"m6g.12xlarge": 1.848000, "m6g.16xlarge": 2.464000, "m6g.2xlarge": 0.308000, "m6g.4xlarge": 0.616000,
"m6g.8xlarge": 1.232000, "m6g.large": 0.077000, "m6g.medium": 0.038500, "m6g.metal": 2.611200,
"m6g.xlarge": 0.154000,
// m6gd family
"m6gd.12xlarge": 2.169600, "m6gd.16xlarge": 2.892800, "m6gd.2xlarge": 0.361600, "m6gd.4xlarge": 0.723200,
"m6gd.8xlarge": 1.446400, "m6gd.large": 0.090400, "m6gd.medium": 0.045200, "m6gd.metal": 3.066400,
"m6gd.xlarge": 0.180800,
// m6i family
"m6i.12xlarge": 2.304000, "m6i.16xlarge": 3.072000, "m6i.24xlarge": 4.608000, "m6i.2xlarge": 0.384000,
"m6i.32xlarge": 6.144000, "m6i.4xlarge": 0.768000, "m6i.8xlarge": 1.536000, "m6i.large": 0.096000,
"m6i.metal": 6.144000, "m6i.xlarge": 0.192000,
// m6id family
"m6id.12xlarge": 2.847600, "m6id.16xlarge": 3.796800, "m6id.24xlarge": 5.695200, "m6id.2xlarge": 0.474600,
"m6id.32xlarge": 7.593600, "m6id.4xlarge": 0.949200, "m6id.8xlarge": 1.898400, "m6id.large": 0.118650,
"m6id.metal": 7.593600, "m6id.xlarge": 0.237300,
// m6idn family
"m6idn.12xlarge": 3.818880, "m6idn.16xlarge": 5.091840, "m6idn.24xlarge": 7.637760,
"m6idn.2xlarge": 0.636480, "m6idn.32xlarge": 10.183680, "m6idn.4xlarge": 1.272960, "m6idn.8xlarge": 2.545920,
"m6idn.large": 0.159120, "m6idn.metal": 10.183680, "m6idn.xlarge": 0.318240,
// m6in family
"m6in.12xlarge": 3.341520, "m6in.16xlarge": 4.455360, "m6in.24xlarge": 6.683040, "m6in.2xlarge": 0.556920,
"m6in.32xlarge": 8.910720, "m6in.4xlarge": 1.113840, "m6in.8xlarge": 2.227680, "m6in.large": 0.139230,
"m6in.metal": 8.910720, "m6in.xlarge": 0.278460,
// m7g family
"m7g.12xlarge": 1.958400, "m7g.16xlarge": 2.611200, "m7g.2xlarge": 0.326400, "m7g.4xlarge": 0.652800,
"m7g.8xlarge": 1.305600, "m7g.large": 0.081600, "m7g.medium": 0.040800, "m7g.metal": 2.611200,
"m7g.xlarge": 0.163200,
// p2 family
"p2.16xlarge": 14.400000, "p2.8xlarge": 7.200000, "p2.xlarge": 0.900000,
// p3 family
"p3.16xlarge": 24.480000, "p3.2xlarge": 3.060000, "p3.8xlarge": 12.240000,
// p3dn family
"p3dn.24xlarge": 31.212000,
// p4d family
"p4d.24xlarge": 32.772600,
// p4de family
"p4de.24xlarge": 40.965750,
// r3 family
"r3.2xlarge": 0.665000, "r3.4xlarge": 1.330000, "r3.8xlarge": 2.660000, "r3.large": 0.166000,
"r3.xlarge": 0.333000,
// r4 family
"r4.16xlarge": 4.256000, "r4.2xlarge": 0.532000, "r4.4xlarge": 1.064000, "r4.8xlarge": 2.128000,
"r4.large": 0.133000, "r4.xlarge": 0.266000,
// r5 family
"r5.12xlarge": 3.024000, "r5.16xlarge": 4.032000, "r5.24xlarge": 6.048000, "r5.2xlarge": 0.504000,
"r5.4xlarge": 1.008000, "r5.8xlarge": 2.016000, "r5.large": 0.126000, "r5.metal": 6.048000,
"r5.xlarge": 0.252000,
// r5a family
"r5a.12xlarge": 2.712000, "r5a.16xlarge": 3.616000, "r5a.24xlarge": 5.424000, "r5a.2xlarge": 0.452000,
"r5a.4xlarge": 0.904000, "r5a.8xlarge": 1.808000, "r5a.large": 0.113000, "r5a.xlarge": 0.226000,
// r5ad family
"r5ad.12xlarge": 3.144000, "r5ad.16xlarge": 4.192000, "r5ad.24xlarge": 6.288000, "r5ad.2xlarge": 0.524000,
"r5ad.4xlarge": 1.048000, "r5ad.8xlarge": 2.096000, "r5ad.large": 0.131000, "r5ad.xlarge": 0.262000,
// r5b family
"r5b.12xlarge": 3.576000, "r5b.16xlarge": 4.768000, "r5b.24xlarge": 7.152000, "r5b.2xlarge": 0.596000,
"r5b.4xlarge": 1.192000, "r5b.8xlarge": 2.384000, "r5b.large": 0.149000, "r5b.metal": 7.867200,
"r5b.xlarge": 0.298000,
// r5d family
"r5d.12xlarge": 3.456000, "r5d.16xlarge": 4.608000, "r5d.24xlarge": 6.912000, "r5d.2xlarge": 0.576000,
"r5d.4xlarge": 1.152000, "r5d.8xlarge": 2.304000, "r5d.large": 0.144000, "r5d.metal": 6.912000,
"r5d.xlarge": 0.288000,
// r5dn family
"r5dn.12xlarge": 4.008000, "r5dn.16xlarge": 5.344000, "r5dn.24xlarge": 8.016000, "r5dn.2xlarge": 0.668000,
"r5dn.4xlarge": 1.336000, "r5dn.8xlarge": 2.672000, "r5dn.large": 0.167000, "r5dn.metal": 8.016000,
"r5dn.xlarge": 0.334000,
// r5n family
"r5n.12xlarge": 3.576000, "r5n.16xlarge": 4.768000, "r5n.24xlarge": 7.152000, "r5n.2xlarge": 0.596000,
"r5n.4xlarge": 1.192000, "r5n.8xlarge": 2.384000, "r5n.large": 0.149000, "r5n.metal": 7.152000,
"r5n.xlarge": 0.298000,
// r6a family
"r6a.12xlarge": 2.721600, "r6a.16xlarge": 3.628800, "r6a.24xlarge": 5.443200, "r6a.2xlarge": 0.453600,
"r6a.32xlarge": 7.257600, "r6a.48xlarge": 10.886400, "r6a.4xlarge": 0.907200, "r6a.8xlarge": 1.814400,
"r6a.large": 0.113400, "r6a.metal": 10.886400, "r6a.xlarge": 0.226800,
// r6g family
"r6g.12xlarge": 2.419200, "r6g.16xlarge": 3.225600, "r6g.2xlarge": 0.403200, "r6g.4xlarge": 0.806400,
"r6g.8xlarge": 1.612800, "r6g.large": 0.100800, "r6g.medium": 0.050400, "r6g.metal": 3.419100,
"r6g.xlarge": 0.201600,
// r6gd family
"r6gd.12xlarge": 2.764800, "r6gd.16xlarge": 3.686400, "r6gd.2xlarge": 0.460800, "r6gd.4xlarge": 0.921600,
"r6gd.8xlarge": 1.843200, "r6gd.large": 0.115200, "r6gd.medium": 0.057600, "r6gd.metal": 3.907600,
"r6gd.xlarge": 0.230400,
// r6i family
"r6i.12xlarge": 3.024000, "r6i.16xlarge": 4.032000, "r6i.24xlarge": 6.048000, "r6i.2xlarge": 0.504000,
"r6i.32xlarge": 8.064000, "r6i.4xlarge": 1.008000, "r6i.8xlarge": 2.016000, "r6i.large": 0.126000,
"r6i.metal": 8.064000, "r6i.xlarge": 0.252000,
// r6id family
"r6id.12xlarge": 3.628800, "r6id.16xlarge": 4.838400, "r6id.24xlarge": 7.257600, "r6id.2xlarge": 0.604800,
"r6id.32xlarge": 9.676800, "r6id.4xlarge": 1.209600, "r6id.8xlarge": 2.419200, "r6id.large": 0.151200,
"r6id.metal": 9.676800, "r6id.xlarge": 0.302400,
// r6idn family
"r6idn.12xlarge": 4.689360, "r6idn.16xlarge": 6.252480, "r6idn.24xlarge": 9.378720,
"r6idn.2xlarge": 0.781560, "r6idn.32xlarge": 12.504960, "r6idn.4xlarge": 1.563120, "r6idn.8xlarge": 3.126240,
"r6idn.large": 0.195390, "r6idn.metal": 12.504960, "r6idn.xlarge": 0.390780,
// r6in family
"r6in.12xlarge": 4.183920, "r6in.16xlarge": 5.578560, "r6in.24xlarge": 8.367840, "r6in.2xlarge": 0.697320,
"r6in.32xlarge": 11.157120, "r6in.4xlarge": 1.394640, "r6in.8xlarge": 2.789280, "r6in.large": 0.174330,
"r6in.metal": 11.157120, "r6in.xlarge": 0.348660,
// r7g family
"r7g.12xlarge": 2.570400, "r7g.16xlarge": 3.427200, "r7g.2xlarge": 0.428400, "r7g.4xlarge": 0.856800,
"r7g.8xlarge": 1.713600, "r7g.large": 0.107100, "r7g.medium": 0.053600, "r7g.metal": 3.427200,
"r7g.xlarge": 0.214200,
// t1 family
"t1.micro": 0.020000,
// t2 family
"t2.2xlarge": 0.371200, "t2.large": 0.092800, "t2.medium": 0.046400, "t2.micro": 0.011600,
"t2.nano": 0.005800, "t2.small": 0.023000, "t2.xlarge": 0.185600,
// t3 family
"t3.2xlarge": 0.332800, "t3.large": 0.083200, "t3.medium": 0.041600, "t3.micro": 0.010400,
"t3.nano": 0.005200, "t3.small": 0.020800, "t3.xlarge": 0.166400,
// t3a family
"t3a.2xlarge": 0.300800, "t3a.large": 0.075200, "t3a.medium": 0.037600, "t3a.micro": 0.009400,
"t3a.nano": 0.004700, "t3a.small": 0.018800, "t3a.xlarge": 0.150400,
// t4g family
"t4g.2xlarge": 0.268800, "t4g.large": 0.067200, "t4g.medium": 0.033600, "t4g.micro": 0.008400,
"t4g.nano": 0.004200, "t4g.small": 0.016800, "t4g.xlarge": 0.134400,
// trn1 family
"trn1.2xlarge": 1.343750, "trn1.32xlarge": 21.500000,
// trn1n family
"trn1n.32xlarge": 24.780000,
// u-12tb1 family
"u-12tb1.112xlarge": 109.200000,
// u-18tb1 family
"u-18tb1.112xlarge": 163.800000,
// u-24tb1 family
"u-24tb1.112xlarge": 218.400000,
// u-3tb1 family
"u-3tb1.56xlarge": 27.300000,
// u-6tb1 family
"u-6tb1.112xlarge": 54.600000, "u-6tb1.56xlarge": 46.403910,
// u-9tb1 family
"u-9tb1.112xlarge": 81.900000,
// vt1 family
"vt1.24xlarge": 5.200000, "vt1.3xlarge": 0.650000, "vt1.6xlarge": 1.300000,
// x1 family
"x1.16xlarge": 6.669000, "x1.32xlarge": 13.338000,
// x1e family
"x1e.16xlarge": 13.344000, "x1e.2xlarge": 1.668000, "x1e.32xlarge": 26.688000, "x1e.4xlarge": 3.336000,
"x1e.8xlarge": 6.672000, "x1e.xlarge": 0.834000,
// x2gd family
"x2gd.12xlarge": 4.008000, "x2gd.16xlarge": 5.344000, "x2gd.2xlarge": 0.668000, "x2gd.4xlarge": 1.336000,
"x2gd.8xlarge": 2.672000, "x2gd.large": 0.167000, "x2gd.medium": 0.083500, "x2gd.metal": 5.878400,
"x2gd.xlarge": 0.334000,
// x2idn family
"x2idn.16xlarge": 6.669000, "x2idn.24xlarge": 10.003500, "x2idn.32xlarge": 13.338000,
"x2idn.metal": 13.338000,
// x2iedn family
"x2iedn.16xlarge": 13.338000, "x2iedn.24xlarge": 20.007000, "x2iedn.2xlarge": 1.667250,
"x2iedn.32xlarge": 26.676000, "x2iedn.4xlarge": 3.334500, "x2iedn.8xlarge": 6.669000,
"x2iedn.metal": 26.676000, "x2iedn.xlarge": 0.833630,
// x2iezn family
"x2iezn.12xlarge": 10.008000, "x2iezn.2xlarge": 1.668000, "x2iezn.4xlarge": 3.336000,
"x2iezn.6xlarge": 5.004000, "x2iezn.8xlarge": 6.672000, "x2iezn.metal": 10.008000,
// z1d family
"z1d.12xlarge": 4.464000, "z1d.2xlarge": 0.744000, "z1d.3xlarge": 1.116000, "z1d.6xlarge": 2.232000,
"z1d.large": 0.186000, "z1d.metal": 4.464000, "z1d.xlarge": 0.372000,
}
// us-gov-west-1
initialOnDemandPrices["us-gov-west-1"] = map[string]float64{
// c1 family
"c1.medium": 0.157000, "c1.xlarge": 0.628000,
// c3 family
"c3.2xlarge": 0.504000, "c3.4xlarge": 1.008000, "c3.8xlarge": 2.016000, "c3.large": 0.126000,
"c3.xlarge": 0.252000,
// c4 family
"c4.2xlarge": 0.479000, "c4.4xlarge": 0.958000, "c4.8xlarge": 1.915000, "c4.large": 0.120000,
"c4.xlarge": 0.239000,
// c5 family
"c5.12xlarge": 2.448000, "c5.18xlarge": 3.672000, "c5.24xlarge": 4.896000, "c5.2xlarge": 0.408000,
"c5.4xlarge": 0.816000, "c5.9xlarge": 1.836000, "c5.large": 0.102000, "c5.metal": 4.896000,
"c5.xlarge": 0.204000,
// c5a family
"c5a.12xlarge": 2.208000, "c5a.16xlarge": 2.944000, "c5a.24xlarge": 4.416000, "c5a.2xlarge": 0.368000,
"c5a.4xlarge": 0.736000, "c5a.8xlarge": 1.472000, "c5a.large": 0.092000, "c5a.xlarge": 0.184000,
// c5d family
"c5d.12xlarge": 2.784000, "c5d.18xlarge": 4.176000, "c5d.24xlarge": 5.568000, "c5d.2xlarge": 0.464000,
"c5d.4xlarge": 0.928000, "c5d.9xlarge": 2.088000, "c5d.large": 0.116000, "c5d.metal": 5.568000,
"c5d.xlarge": 0.232000,
// c5n family
"c5n.18xlarge": 4.680000, "c5n.2xlarge": 0.520000, "c5n.4xlarge": 1.040000, "c5n.9xlarge": 2.340000,
"c5n.large": 0.130000, "c5n.metal": 4.680000, "c5n.xlarge": 0.260000,
// c6g family
"c6g.12xlarge": 1.958400, "c6g.16xlarge": 2.611200, "c6g.2xlarge": 0.326400, "c6g.4xlarge": 0.652800,
"c6g.8xlarge": 1.305600, "c6g.large": 0.081600, "c6g.medium": 0.040800, "c6g.metal": 2.767900,
"c6g.xlarge": 0.163200,
// c6i family
"c6i.12xlarge": 2.448000, "c6i.16xlarge": 3.264000, "c6i.24xlarge": 4.896000, "c6i.2xlarge": 0.408000,
"c6i.32xlarge": 6.528000, "c6i.4xlarge": 0.816000, "c6i.8xlarge": 1.632000, "c6i.large": 0.102000,
"c6i.metal": 6.528000, "c6i.xlarge": 0.204000,
// c6id family
"c6id.12xlarge": 2.923200, "c6id.16xlarge": 3.897600, "c6id.24xlarge": 5.846400, "c6id.2xlarge": 0.487200,
"c6id.32xlarge": 7.795200, "c6id.4xlarge": 0.974400, "c6id.8xlarge": 1.948800, "c6id.large": 0.121800,
"c6id.metal": 7.795200, "c6id.xlarge": 0.243600,
// c6in family
"c6in.12xlarge": 3.276000, "c6in.16xlarge": 4.368000, "c6in.24xlarge": 6.552000, "c6in.2xlarge": 0.546000,
"c6in.32xlarge": 8.736000, "c6in.4xlarge": 1.092000, "c6in.8xlarge": 2.184000, "c6in.large": 0.136500,
"c6in.metal": 8.736000, "c6in.xlarge": 0.273000,
// cc2 family
"cc2.8xlarge": 2.250000,
// d2 family
"d2.2xlarge": 1.656000, "d2.4xlarge": 3.312000, "d2.8xlarge": 6.624000, "d2.xlarge": 0.828000,
// d3 family
"d3.2xlarge": 1.197000, "d3.4xlarge": 2.394000, "d3.8xlarge": 4.787760, "d3.xlarge": 0.598000,
// f1 family
"f1.16xlarge": 15.840000, "f1.2xlarge": 1.980000, "f1.4xlarge": 3.960000,
// g3 family
"g3.16xlarge": 5.280000, "g3.4xlarge": 1.320000, "g3.8xlarge": 2.640000,
// g3s family
"g3s.xlarge": 0.868000,
// g4dn family
"g4dn.12xlarge": 4.931000, "g4dn.16xlarge": 5.486000, "g4dn.2xlarge": 0.948000, "g4dn.4xlarge": 1.518000,
"g4dn.8xlarge": 2.743000, "g4dn.metal": 9.862000, "g4dn.xlarge": 0.663000,
// hpc6a family
"hpc6a.48xlarge": 3.467000,
// hpc6id family
"hpc6id.32xlarge": 6.854400,
// hs1 family
"hs1.8xlarge": 5.520000,
// i2 family
"i2.2xlarge": 2.046000, "i2.4xlarge": 4.092000, "i2.8xlarge": 8.184000, "i2.xlarge": 1.023000,
// i3 family
"i3.16xlarge": 6.016000, "i3.2xlarge": 0.752000, "i3.4xlarge": 1.504000, "i3.8xlarge": 3.008000,
"i3.large": 0.188000, "i3.metal": 6.016000, "i3.xlarge": 0.376000,
// i3en family
"i3en.12xlarge": 6.552000, "i3en.24xlarge": 13.104000, "i3en.2xlarge": 1.092000, "i3en.3xlarge": 1.638000,
"i3en.6xlarge": 3.276000, "i3en.large": 0.273000, "i3en.metal": 13.104000, "i3en.xlarge": 0.546000,
// i3p family
"i3p.16xlarge": 6.016000,
// i4i family
"i4i.16xlarge": 6.618000, "i4i.2xlarge": 0.827000, "i4i.32xlarge": 13.235200, "i4i.4xlarge": 1.654000,
"i4i.8xlarge": 3.309000, "i4i.large": 0.207000, "i4i.metal": 13.235000, "i4i.xlarge": 0.414000,
// inf1 family
"inf1.24xlarge": 5.953000, "inf1.2xlarge": 0.456000, "inf1.6xlarge": 1.488000, "inf1.xlarge": 0.288000,
// m1 family
"m1.large": 0.211000, "m1.medium": 0.106000, "m1.small": 0.053000, "m1.xlarge": 0.423000,
// m2 family
"m2.2xlarge": 0.586000, "m2.4xlarge": 1.171000, "m2.xlarge": 0.293000,
// m3 family
"m3.2xlarge": 0.672000, "m3.large": 0.168000, "m3.medium": 0.084000, "m3.xlarge": 0.336000,
// m4 family
"m4.10xlarge": 2.520000, "m4.16xlarge": 4.032000, "m4.2xlarge": 0.504000, "m4.4xlarge": 1.008000,
"m4.large": 0.126000, "m4.xlarge": 0.252000,
// m5 family
"m5.12xlarge": 2.904000, "m5.16xlarge": 3.872000, "m5.24xlarge": 5.808000, "m5.2xlarge": 0.484000,
"m5.4xlarge": 0.968000, "m5.8xlarge": 1.936000, "m5.large": 0.121000, "m5.metal": 5.808000,
"m5.xlarge": 0.242000,
// m5a family
"m5a.12xlarge": 2.616000, "m5a.16xlarge": 3.488000, "m5a.24xlarge": 5.232000, "m5a.2xlarge": 0.436000,
"m5a.4xlarge": 0.872000, "m5a.8xlarge": 1.744000, "m5a.large": 0.109000, "m5a.xlarge": 0.218000,
// m5ad family
"m5ad.12xlarge": 3.144000, "m5ad.16xlarge": 4.192000, "m5ad.24xlarge": 6.288000, "m5ad.2xlarge": 0.524000,
"m5ad.4xlarge": 1.048000, "m5ad.8xlarge": 2.096000, "m5ad.large": 0.131000, "m5ad.xlarge": 0.262000,
// m5d family
"m5d.12xlarge": 3.432000, "m5d.16xlarge": 4.576000, "m5d.24xlarge": 6.864000, "m5d.2xlarge": 0.572000,
"m5d.4xlarge": 1.144000, "m5d.8xlarge": 2.288000, "m5d.large": 0.143000, "m5d.metal": 6.864000,
"m5d.xlarge": 0.286000,
// m5dn family
"m5dn.12xlarge": 4.104000, "m5dn.16xlarge": 5.472000, "m5dn.24xlarge": 8.208000, "m5dn.2xlarge": 0.684000,
"m5dn.4xlarge": 1.368000, "m5dn.8xlarge": 2.736000, "m5dn.large": 0.171000, "m5dn.metal": 8.208000,
"m5dn.xlarge": 0.342000,
// m5n family
"m5n.12xlarge": 3.576000, "m5n.16xlarge": 4.768000, "m5n.24xlarge": 7.152000, "m5n.2xlarge": 0.596000,
"m5n.4xlarge": 1.192000, "m5n.8xlarge": 2.384000, "m5n.large": 0.149000, "m5n.metal": 7.152000,
"m5n.xlarge": 0.298000,
// m6g family
"m6g.12xlarge": 2.323200, "m6g.16xlarge": 3.097600, "m6g.2xlarge": 0.387200, "m6g.4xlarge": 0.774400,
"m6g.8xlarge": 1.548800, "m6g.large": 0.096800, "m6g.medium": 0.048400, "m6g.metal": 3.283500,
"m6g.xlarge": 0.193600,
// m6i family
"m6i.12xlarge": 2.904000, "m6i.16xlarge": 3.872000, "m6i.24xlarge": 5.808000, "m6i.2xlarge": 0.484000,
"m6i.32xlarge": 7.744000, "m6i.4xlarge": 0.968000, "m6i.8xlarge": 1.936000, "m6i.large": 0.121000,
"m6i.metal": 7.744000, "m6i.xlarge": 0.242000,
// m6id family
"m6id.12xlarge": 3.604800, "m6id.16xlarge": 4.806400, "m6id.24xlarge": 7.209600, "m6id.2xlarge": 0.600800,
"m6id.32xlarge": 9.612800, "m6id.4xlarge": 1.201600, "m6id.8xlarge": 2.403200, "m6id.large": 0.150200,
"m6id.metal": 9.612800, "m6id.xlarge": 0.300400,
// m6idn family
"m6idn.12xlarge": 4.801680, "m6idn.16xlarge": 6.402240, "m6idn.24xlarge": 9.603360,
"m6idn.2xlarge": 0.800280, "m6idn.32xlarge": 12.804480, "m6idn.4xlarge": 1.600560, "m6idn.8xlarge": 3.201120,
"m6idn.large": 0.200070, "m6idn.metal": 12.804480, "m6idn.xlarge": 0.400140,
// m6in family
"m6in.12xlarge": 4.183920, "m6in.16xlarge": 5.578560, "m6in.24xlarge": 8.367840, "m6in.2xlarge": 0.697320,
"m6in.32xlarge": 11.157120, "m6in.4xlarge": 1.394640, "m6in.8xlarge": 2.789280, "m6in.large": 0.174330,
"m6in.metal": 11.157120, "m6in.xlarge": 0.348660,
// p2 family
"p2.16xlarge": 17.280000, "p2.8xlarge": 8.640000, "p2.xlarge": 1.080000,
// p3 family
"p3.16xlarge": 29.376000, "p3.2xlarge": 3.672000, "p3.8xlarge": 14.688000,
// p3dn family
"p3dn.24xlarge": 37.454000,
// p4d family
"p4d.24xlarge": 39.330000,
// r3 family
"r3.2xlarge": 0.798000, "r3.4xlarge": 1.596000, "r3.8xlarge": 3.192000, "r3.large": 0.200000,
"r3.xlarge": 0.399000,
// r4 family
"r4.16xlarge": 5.107200, "r4.2xlarge": 0.638400, "r4.4xlarge": 1.276800, "r4.8xlarge": 2.553600,
"r4.large": 0.159600, "r4.xlarge": 0.319200,
// r5 family
"r5.12xlarge": 3.624000, "r5.16xlarge": 4.832000, "r5.24xlarge": 7.248000, "r5.2xlarge": 0.604000,
"r5.4xlarge": 1.208000, "r5.8xlarge": 2.416000, "r5.large": 0.151000, "r5.metal": 7.248000,
"r5.xlarge": 0.302000,
// r5a family
"r5a.12xlarge": 3.264000, "r5a.16xlarge": 4.352000, "r5a.24xlarge": 6.528000, "r5a.2xlarge": 0.544000,
"r5a.4xlarge": 1.088000, "r5a.8xlarge": 2.176000, "r5a.large": 0.136000, "r5a.xlarge": 0.272000,
// r5ad family
"r5ad.12xlarge": 3.792000, "r5ad.16xlarge": 5.056000, "r5ad.24xlarge": 7.584000, "r5ad.2xlarge": 0.632000,
"r5ad.4xlarge": 1.264000, "r5ad.8xlarge": 2.528000, "r5ad.large": 0.158000, "r5ad.xlarge": 0.316000,
// r5d family
"r5d.12xlarge": 4.152000, "r5d.16xlarge": 5.536000, "r5d.24xlarge": 8.304000, "r5d.2xlarge": 0.692000,
"r5d.4xlarge": 1.384000, "r5d.8xlarge": 2.768000, "r5d.large": 0.173000, "r5d.metal": 8.304000,
"r5d.xlarge": 0.346000,
// r5dn family
"r5dn.12xlarge": 4.824000, "r5dn.16xlarge": 6.432000, "r5dn.24xlarge": 9.648000, "r5dn.2xlarge": 0.804000,
"r5dn.4xlarge": 1.608000, "r5dn.8xlarge": 3.216000, "r5dn.large": 0.201000, "r5dn.metal": 9.648000,
"r5dn.xlarge": 0.402000,
// r5n family
"r5n.12xlarge": 4.296000, "r5n.16xlarge": 5.728000, "r5n.24xlarge": 8.592000, "r5n.2xlarge": 0.716000,
"r5n.4xlarge": 1.432000, "r5n.8xlarge": 2.864000, "r5n.large": 0.179000, "r5n.metal": 8.592000,
"r5n.xlarge": 0.358000,
// r6g family
"r6g.12xlarge": 2.899200, "r6g.16xlarge": 3.865600, "r6g.2xlarge": 0.483200, "r6g.4xlarge": 0.966400,
"r6g.8xlarge": 1.932800, "r6g.large": 0.120800, "r6g.medium": 0.060400, "r6g.metal": 4.097500,
"r6g.xlarge": 0.241600,
// r6i family
"r6i.12xlarge": 3.624000, "r6i.16xlarge": 4.832000, "r6i.24xlarge": 7.248000, "r6i.2xlarge": 0.604000,
"r6i.32xlarge": 9.664000, "r6i.4xlarge": 1.208000, "r6i.8xlarge": 2.416000, "r6i.large": 0.151000,
"r6i.metal": 9.664000, "r6i.xlarge": 0.302000,
// r6id family
"r6id.12xlarge": 4.360800, "r6id.16xlarge": 5.814400, "r6id.24xlarge": 8.721600, "r6id.2xlarge": 0.726800,
"r6id.32xlarge": 11.628800, "r6id.4xlarge": 1.453600, "r6id.8xlarge": 2.907200, "r6id.large": 0.181700,
"r6id.metal": 11.628800, "r6id.xlarge": 0.363400,
// r6idn family
"r6idn.12xlarge": 5.644080, "r6idn.16xlarge": 7.525440, "r6idn.24xlarge": 11.288160,
"r6idn.2xlarge": 0.940680, "r6idn.32xlarge": 15.050880, "r6idn.4xlarge": 1.881360, "r6idn.8xlarge": 3.762720,
"r6idn.large": 0.235170, "r6idn.metal": 15.050880, "r6idn.xlarge": 0.470340,
// r6in family
"r6in.12xlarge": 5.026320, "r6in.16xlarge": 6.701760, "r6in.24xlarge": 10.052640, "r6in.2xlarge": 0.837720,
"r6in.32xlarge": 13.403520, "r6in.4xlarge": 1.675440, "r6in.8xlarge": 3.350880, "r6in.large": 0.209430,
"r6in.metal": 13.403520, "r6in.xlarge": 0.418860,
// t1 family
"t1.micro": 0.024000,
// t2 family
"t2.2xlarge": 0.435200, "t2.large": 0.108800, "t2.medium": 0.054400, "t2.micro": 0.013600,
"t2.nano": 0.006800, "t2.small": 0.027200, "t2.xlarge": 0.217600,
// t3 family
"t3.2xlarge": 0.390400, "t3.large": 0.097600, "t3.medium": 0.048800, "t3.micro": 0.012200,
"t3.nano": 0.006100, "t3.small": 0.024400, "t3.xlarge": 0.195200,
// t3a family
"t3a.2xlarge": 0.351400, "t3a.large": 0.087800, "t3a.medium": 0.043900, "t3a.micro": 0.011000,
"t3a.nano": 0.005500, "t3a.small": 0.022000, "t3a.xlarge": 0.175700,
// t4g family
"t4g.2xlarge": 0.313600, "t4g.large": 0.078400, "t4g.medium": 0.039200, "t4g.micro": 0.009800,
"t4g.nano": 0.004900, "t4g.small": 0.019600, "t4g.xlarge": 0.156800,
// u-12tb1 family
"u-12tb1.112xlarge": 130.867000,
// u-24tb1 family
"u-24tb1.112xlarge": 261.730000,
// u-3tb1 family
"u-3tb1.56xlarge": 32.716500,
// u-6tb1 family
"u-6tb1.112xlarge": 65.433000, "u-6tb1.56xlarge": 55.610750,
// u-9tb1 family
"u-9tb1.112xlarge": 98.150000,
// x1 family
"x1.16xlarge": 8.003000, "x1.32xlarge": 16.006000,
// x1e family
"x1e.16xlarge": 16.000000, "x1e.2xlarge": 2.000000, "x1e.32xlarge": 32.000000, "x1e.4xlarge": 4.000000,
"x1e.8xlarge": 8.000000, "x1e.xlarge": 1.000000,
// x2idn family
"x2idn.16xlarge": 8.003000, "x2idn.24xlarge": 12.004500, "x2idn.32xlarge": 16.006000,
"x2idn.metal": 16.006000,
// x2iedn family
"x2iedn.16xlarge": 16.006000, "x2iedn.24xlarge": 24.009000, "x2iedn.2xlarge": 2.000750,
"x2iedn.32xlarge": 32.012000, "x2iedn.4xlarge": 4.001500, "x2iedn.8xlarge": 8.003000,
"x2iedn.metal": 32.012000, "x2iedn.xlarge": 1.000380,
}
// us-gov-east-1
initialOnDemandPrices["us-gov-east-1"] = map[string]float64{
// c5 family
"c5.12xlarge": 2.448000, "c5.18xlarge": 3.672000, "c5.24xlarge": 4.896000, "c5.2xlarge": 0.408000,
"c5.4xlarge": 0.816000, "c5.9xlarge": 1.836000, "c5.large": 0.102000, "c5.metal": 4.896000,
"c5.xlarge": 0.204000,
// c5a family
"c5a.12xlarge": 2.208000, "c5a.16xlarge": 2.944000, "c5a.24xlarge": 4.416000, "c5a.2xlarge": 0.368000,
"c5a.4xlarge": 0.736000, "c5a.8xlarge": 1.472000, "c5a.large": 0.092000, "c5a.xlarge": 0.184000,
// c5d family
"c5d.18xlarge": 4.176000, "c5d.2xlarge": 0.464000, "c5d.4xlarge": 0.928000, "c5d.9xlarge": 2.088000,
"c5d.large": 0.116000, "c5d.xlarge": 0.232000,
// c5n family
"c5n.18xlarge": 4.680000, "c5n.2xlarge": 0.520000, "c5n.4xlarge": 1.040000, "c5n.9xlarge": 2.340000,
"c5n.large": 0.130000, "c5n.metal": 4.680000, "c5n.xlarge": 0.260000,
// c6g family
"c6g.12xlarge": 1.958400, "c6g.16xlarge": 2.611200, "c6g.2xlarge": 0.326400, "c6g.4xlarge": 0.652800,
"c6g.8xlarge": 1.305600, "c6g.large": 0.081600, "c6g.medium": 0.040800, "c6g.metal": 2.767900,
"c6g.xlarge": 0.163200,
// c6i family
"c6i.12xlarge": 2.448000, "c6i.16xlarge": 3.264000, "c6i.24xlarge": 4.896000, "c6i.2xlarge": 0.408000,
"c6i.32xlarge": 6.528000, "c6i.4xlarge": 0.816000, "c6i.8xlarge": 1.632000, "c6i.large": 0.102000,
"c6i.metal": 6.528000, "c6i.xlarge": 0.204000,
// c6in family
"c6in.12xlarge": 3.276000, "c6in.16xlarge": 4.368000, "c6in.24xlarge": 6.552000, "c6in.2xlarge": 0.546000,
"c6in.32xlarge": 8.736000, "c6in.4xlarge": 1.092000, "c6in.8xlarge": 2.184000, "c6in.large": 0.136500,
"c6in.metal": 8.736000, "c6in.xlarge": 0.273000,
// d2 family
"d2.2xlarge": 1.656000, "d2.4xlarge": 3.312000, "d2.8xlarge": 6.624000, "d2.xlarge": 0.828000,
// g4dn family
"g4dn.12xlarge": 4.931000, "g4dn.16xlarge": 5.486000, "g4dn.2xlarge": 0.948000, "g4dn.4xlarge": 1.518000,
"g4dn.8xlarge": 2.743000, "g4dn.xlarge": 0.663000,
// hpc6a family
"hpc6a.48xlarge": 3.467000,
// i3 family
"i3.16xlarge": 6.016000, "i3.2xlarge": 0.752000, "i3.4xlarge": 1.504000, "i3.8xlarge": 3.008000,
"i3.large": 0.188000, "i3.metal": 6.016000, "i3.xlarge": 0.376000,
// i3en family
"i3en.12xlarge": 6.552000, "i3en.24xlarge": 13.104000, "i3en.2xlarge": 1.092000, "i3en.3xlarge": 1.638000,
"i3en.6xlarge": 3.276000, "i3en.large": 0.273000, "i3en.metal": 13.104000, "i3en.xlarge": 0.546000,
// i4i family
"i4i.16xlarge": 6.618000, "i4i.2xlarge": 0.827000, "i4i.32xlarge": 13.235200, "i4i.4xlarge": 1.654000,
"i4i.8xlarge": 3.309000, "i4i.large": 0.207000, "i4i.metal": 13.235000, "i4i.xlarge": 0.414000,
// inf1 family
"inf1.24xlarge": 5.953000, "inf1.2xlarge": 0.456000, "inf1.6xlarge": 1.488000, "inf1.xlarge": 0.288000,
// m5 family
"m5.12xlarge": 2.904000, "m5.16xlarge": 3.872000, "m5.24xlarge": 5.808000, "m5.2xlarge": 0.484000,
"m5.4xlarge": 0.968000, "m5.8xlarge": 1.936000, "m5.large": 0.121000, "m5.metal": 5.808000,
"m5.xlarge": 0.242000,
// m5a family
"m5a.12xlarge": 2.616000, "m5a.16xlarge": 3.488000, "m5a.24xlarge": 5.232000, "m5a.2xlarge": 0.436000,
"m5a.4xlarge": 0.872000, "m5a.8xlarge": 1.744000, "m5a.large": 0.109000, "m5a.xlarge": 0.218000,
// m5d family
"m5d.12xlarge": 3.432000, "m5d.16xlarge": 4.576000, "m5d.24xlarge": 6.864000, "m5d.2xlarge": 0.572000,
"m5d.4xlarge": 1.144000, "m5d.8xlarge": 2.288000, "m5d.large": 0.143000, "m5d.metal": 6.864000,
"m5d.xlarge": 0.286000,
// m5dn family
"m5dn.12xlarge": 4.104000, "m5dn.16xlarge": 5.472000, "m5dn.24xlarge": 8.208000, "m5dn.2xlarge": 0.684000,
"m5dn.4xlarge": 1.368000, "m5dn.8xlarge": 2.736000, "m5dn.large": 0.171000, "m5dn.metal": 8.208000,
"m5dn.xlarge": 0.342000,
// m5n family
"m5n.12xlarge": 3.576000, "m5n.16xlarge": 4.768000, "m5n.24xlarge": 7.152000, "m5n.2xlarge": 0.596000,
"m5n.4xlarge": 1.192000, "m5n.8xlarge": 2.384000, "m5n.large": 0.149000, "m5n.metal": 7.152000,
"m5n.xlarge": 0.298000,
// m6g family
"m6g.12xlarge": 2.323200, "m6g.16xlarge": 3.097600, "m6g.2xlarge": 0.387200, "m6g.4xlarge": 0.774400,
"m6g.8xlarge": 1.548800, "m6g.large": 0.096800, "m6g.medium": 0.048400, "m6g.metal": 3.283500,
"m6g.xlarge": 0.193600,
// m6i family
"m6i.12xlarge": 2.904000, "m6i.16xlarge": 3.872000, "m6i.24xlarge": 5.808000, "m6i.2xlarge": 0.484000,
"m6i.32xlarge": 7.744000, "m6i.4xlarge": 0.968000, "m6i.8xlarge": 1.936000, "m6i.large": 0.121000,
"m6i.metal": 7.744000, "m6i.xlarge": 0.242000,
// p3dn family
"p3dn.24xlarge": 37.454000,
// r5 family
"r5.12xlarge": 3.624000, "r5.16xlarge": 4.832000, "r5.24xlarge": 7.248000, "r5.2xlarge": 0.604000,
"r5.4xlarge": 1.208000, "r5.8xlarge": 2.416000, "r5.large": 0.151000, "r5.metal": 7.248000,
"r5.xlarge": 0.302000,
// r5a family
"r5a.12xlarge": 3.264000, "r5a.16xlarge": 4.352000, "r5a.24xlarge": 6.528000, "r5a.2xlarge": 0.544000,
"r5a.4xlarge": 1.088000, "r5a.8xlarge": 2.176000, "r5a.large": 0.136000, "r5a.xlarge": 0.272000,
// r5d family
"r5d.12xlarge": 4.152000, "r5d.16xlarge": 5.536000, "r5d.24xlarge": 8.304000, "r5d.2xlarge": 0.692000,
"r5d.4xlarge": 1.384000, "r5d.8xlarge": 2.768000, "r5d.large": 0.173000, "r5d.metal": 8.304000,
"r5d.xlarge": 0.346000,
// r5dn family
"r5dn.12xlarge": 4.824000, "r5dn.16xlarge": 6.432000, "r5dn.24xlarge": 9.648000, "r5dn.2xlarge": 0.804000,
"r5dn.4xlarge": 1.608000, "r5dn.8xlarge": 3.216000, "r5dn.large": 0.201000, "r5dn.metal": 9.648000,
"r5dn.xlarge": 0.402000,
// r5n family
"r5n.12xlarge": 4.296000, "r5n.16xlarge": 5.728000, "r5n.24xlarge": 8.592000, "r5n.2xlarge": 0.716000,
"r5n.4xlarge": 1.432000, "r5n.8xlarge": 2.864000, "r5n.large": 0.179000, "r5n.metal": 8.592000,
"r5n.xlarge": 0.358000,
// r6g family
"r6g.12xlarge": 2.899200, "r6g.16xlarge": 3.865600, "r6g.2xlarge": 0.483200, "r6g.4xlarge": 0.966400,
"r6g.8xlarge": 1.932800, "r6g.large": 0.120800, "r6g.medium": 0.060400, "r6g.metal": 4.097500,
"r6g.xlarge": 0.241600,
// r6i family
"r6i.12xlarge": 3.624000, "r6i.16xlarge": 4.832000, "r6i.24xlarge": 7.248000, "r6i.2xlarge": 0.604000,
"r6i.32xlarge": 9.664000, "r6i.4xlarge": 1.208000, "r6i.8xlarge": 2.416000, "r6i.large": 0.151000,
"r6i.metal": 9.664000, "r6i.xlarge": 0.302000,
// t3 family
"t3.2xlarge": 0.390400, "t3.large": 0.097600, "t3.medium": 0.048800, "t3.micro": 0.012200,
"t3.nano": 0.006100, "t3.small": 0.024400, "t3.xlarge": 0.195200,
// t3a family
"t3a.2xlarge": 0.351400, "t3a.large": 0.087800, "t3a.medium": 0.043900, "t3a.micro": 0.011000,
"t3a.nano": 0.005500, "t3a.small": 0.022000, "t3a.xlarge": 0.175700,
// t4g family
"t4g.2xlarge": 0.313600, "t4g.large": 0.078400, "t4g.medium": 0.039200, "t4g.micro": 0.009800,
"t4g.nano": 0.004900, "t4g.small": 0.019600, "t4g.xlarge": 0.156800,
// u-12tb1 family
"u-12tb1.112xlarge": 130.867000,
// u-24tb1 family
"u-24tb1.112xlarge": 261.730000,
// u-6tb1 family
"u-6tb1.112xlarge": 65.433000, "u-6tb1.56xlarge": 55.610750,
// u-9tb1 family
"u-9tb1.112xlarge": 98.150000,
// x1 family
"x1.16xlarge": 8.003000, "x1.32xlarge": 16.006000,
// x1e family
"x1e.16xlarge": 16.000000, "x1e.2xlarge": 2.000000, "x1e.32xlarge": 32.000000, "x1e.4xlarge": 4.000000,
"x1e.8xlarge": 8.000000, "x1e.xlarge": 1.000000,
// x2idn family
"x2idn.16xlarge": 8.003000, "x2idn.24xlarge": 12.004500, "x2idn.32xlarge": 16.006000,
"x2idn.metal": 16.006000,
// x2iedn family
"x2iedn.16xlarge": 16.006000, "x2iedn.24xlarge": 24.009000, "x2iedn.2xlarge": 2.000750,
"x2iedn.32xlarge": 32.012000, "x2iedn.4xlarge": 4.001500, "x2iedn.8xlarge": 8.003000,
"x2iedn.metal": 32.012000, "x2iedn.xlarge": 1.000380,
}
// cn-north-1
initialOnDemandPrices["cn-north-1"] = map[string]float64{
// c3 family
"c3.2xlarge": 4.217000, "c3.4xlarge": 8.434000, "c3.8xlarge": 16.869000, "c3.large": 1.054000,
"c3.xlarge": 2.109000,
// c4 family
"c4.2xlarge": 4.535000, "c4.4xlarge": 9.071000, "c4.8xlarge": 18.141000, "c4.large": 1.134000,
"c4.xlarge": 2.268000,
// c5 family
"c5.12xlarge": 17.745000, "c5.18xlarge": 26.617000, "c5.24xlarge": 35.490000, "c5.2xlarge": 2.957000,
"c5.4xlarge": 5.915000, "c5.9xlarge": 13.309000, "c5.large": 0.739000, "c5.metal": 35.490000,
"c5.xlarge": 1.479000,
// c5a family
"c5a.12xlarge": 15.937000, "c5a.16xlarge": 21.250000, "c5a.24xlarge": 31.875000, "c5a.2xlarge": 2.656000,
"c5a.4xlarge": 5.312000, "c5a.8xlarge": 10.625000, "c5a.large": 0.664000, "c5a.xlarge": 1.328000,
// c5d family
"c5d.12xlarge": 21.852000, "c5d.18xlarge": 32.779000, "c5d.24xlarge": 43.705000, "c5d.2xlarge": 3.642000,
"c5d.4xlarge": 7.284000, "c5d.9xlarge": 16.389000, "c5d.large": 0.911000, "c5d.metal": 43.705000,
"c5d.xlarge": 1.821000,
// c6g family
"c6g.12xlarge": 14.064400, "c6g.16xlarge": 18.752600, "c6g.2xlarge": 2.344100, "c6g.4xlarge": 4.688100,
"c6g.8xlarge": 9.376300, "c6g.large": 0.586000, "c6g.medium": 0.293000, "c6g.metal": 19.390900,
"c6g.xlarge": 1.172000,
// c6i family
"c6i.12xlarge": 17.744830, "c6i.16xlarge": 23.659780, "c6i.24xlarge": 35.489660, "c6i.2xlarge": 2.957470,
"c6i.32xlarge": 47.319550, "c6i.4xlarge": 5.914940, "c6i.8xlarge": 11.829890, "c6i.large": 0.739370,
"c6i.metal": 47.319550, "c6i.xlarge": 1.478740,
// d2 family
"d2.2xlarge": 13.345000, "d2.4xlarge": 26.690000, "d2.8xlarge": 53.380000, "d2.xlarge": 6.673000,
// g3 family
"g3.16xlarge": 64.817900, "g3.4xlarge": 16.204500, "g3.8xlarge": 32.409000,
// g3s family
"g3s.xlarge": 11.282000,
// g4dn family
"g4dn.12xlarge": 38.849000, "g4dn.16xlarge": 43.218000, "g4dn.2xlarge": 7.468000, "g4dn.4xlarge": 11.956000,
"g4dn.8xlarge": 21.609000, "g4dn.xlarge": 5.223000,
// i2 family
"i2.2xlarge": 20.407000, "i2.4xlarge": 40.815000, "i2.8xlarge": 81.630000, "i2.xlarge": 10.204000,
// i3 family
"i3.16xlarge": 49.948000, "i3.2xlarge": 6.244000, "i3.4xlarge": 12.487000, "i3.8xlarge": 24.974000,
"i3.large": 1.561000, "i3.xlarge": 3.122000,
// i3en family
"i3en.12xlarge": 54.302000, "i3en.24xlarge": 108.605000, "i3en.2xlarge": 9.050000, "i3en.3xlarge": 13.576000,
"i3en.6xlarge": 27.151000, "i3en.large": 2.263000, "i3en.xlarge": 4.525000,
// inf1 family
"inf1.24xlarge": 47.342000, "inf1.2xlarge": 3.630000, "inf1.6xlarge": 11.835000, "inf1.xlarge": 2.288000,
// m1 family
"m1.small": 0.442000,
// m3 family
"m3.2xlarge": 6.942000, "m3.large": 1.735000, "m3.medium": 0.868000, "m3.xlarge": 3.471000,
// m4 family
"m4.10xlarge": 28.121000, "m4.16xlarge": 44.995000, "m4.2xlarge": 5.624000, "m4.4xlarge": 11.248000,
"m4.large": 1.405000, "m4.xlarge": 2.815000,
// m5 family
"m5.12xlarge": 24.317000, "m5.16xlarge": 32.423000, "m5.24xlarge": 48.634000, "m5.2xlarge": 4.053000,
"m5.4xlarge": 8.106000, "m5.8xlarge": 16.211000, "m5.large": 1.013000, "m5.metal": 48.634000,
"m5.xlarge": 2.026000,
// m5a family
"m5a.12xlarge": 21.852000, "m5a.16xlarge": 29.137000, "m5a.24xlarge": 43.705000, "m5a.2xlarge": 3.642000,
"m5a.4xlarge": 7.284000, "m5a.8xlarge": 14.568000, "m5a.large": 0.911000, "m5a.xlarge": 1.821000,
// m5d family
"m5d.12xlarge": 30.561000, "m5d.16xlarge": 40.747000, "m5d.24xlarge": 61.121000, "m5d.2xlarge": 5.093000,
"m5d.4xlarge": 10.187000, "m5d.8xlarge": 20.374000, "m5d.large": 1.273000, "m5d.metal": 61.121000,
"m5d.xlarge": 2.547000,
// m6g family
"m6g.12xlarge": 19.289300, "m6g.16xlarge": 25.719100, "m6g.2xlarge": 3.214900, "m6g.4xlarge": 6.429800,
"m6g.8xlarge": 12.859500, "m6g.large": 0.803700, "m6g.medium": 0.401900, "m6g.metal": 26.486300,
"m6g.xlarge": 1.607400,
// m6i family
"m6i.12xlarge": 24.316990, "m6i.16xlarge": 32.422660, "m6i.24xlarge": 48.633980, "m6i.2xlarge": 4.052830,
"m6i.32xlarge": 64.845310, "m6i.4xlarge": 8.105660, "m6i.8xlarge": 16.211330, "m6i.large": 1.013210,
"m6i.metal": 64.845310, "m6i.xlarge": 2.026420,
// p2 family
"p2.16xlarge": 169.792000, "p2.8xlarge": 84.896000, "p2.xlarge": 10.612000,
// p3 family
"p3.16xlarge": 288.627000, "p3.2xlarge": 36.078000, "p3.8xlarge": 144.314000,
// r3 family
"r3.2xlarge": 9.803600, "r3.4xlarge": 19.607300, "r3.8xlarge": 39.214700, "r3.large": 2.450900,
"r3.xlarge": 4.901800,
// r4 family
"r4.16xlarge": 62.746000, "r4.2xlarge": 7.842000, "r4.4xlarge": 15.683000, "r4.8xlarge": 31.373000,
"r4.large": 1.959000, "r4.xlarge": 3.924000,
// r5 family
"r5.12xlarge": 29.246000, "r5.16xlarge": 38.995000, "r5.24xlarge": 58.492000, "r5.2xlarge": 4.874000,
"r5.4xlarge": 9.749000, "r5.8xlarge": 19.497000, "r5.large": 1.219000, "r5.metal": 58.492000,
"r5.xlarge": 2.437000,
// r5a family
"r5a.12xlarge": 26.322000, "r5a.16xlarge": 35.095000, "r5a.24xlarge": 52.643000, "r5a.2xlarge": 4.387000,
"r5a.4xlarge": 8.774000, "r5a.8xlarge": 17.548000, "r5a.large": 1.097000, "r5a.xlarge": 2.193000,
// r5d family
"r5d.12xlarge": 35.490000, "r5d.16xlarge": 47.320000, "r5d.24xlarge": 70.979000, "r5d.2xlarge": 5.915000,
"r5d.4xlarge": 11.830000, "r5d.8xlarge": 23.660000, "r5d.large": 1.479000, "r5d.metal": 70.979000,
"r5d.xlarge": 2.957000,
// r6g family
"r6g.12xlarge": 23.199700, "r6g.16xlarge": 30.933000, "r6g.2xlarge": 3.866600, "r6g.4xlarge": 7.733200,
"r6g.8xlarge": 15.466500, "r6g.large": 0.966700, "r6g.medium": 0.483300, "r6g.metal": 31.847000,
"r6g.xlarge": 1.933300,
// r6gd family
"r6gd.12xlarge": 28.096000, "r6gd.16xlarge": 37.461300, "r6gd.2xlarge": 4.682700, "r6gd.4xlarge": 9.365300,
"r6gd.8xlarge": 18.730700, "r6gd.large": 1.170700, "r6gd.medium": 0.585300, "r6gd.metal": 37.461300,
"r6gd.xlarge": 2.341300,
// r6i family
"r6i.12xlarge": 29.246110, "r6i.16xlarge": 38.994820, "r6i.24xlarge": 58.492220, "r6i.2xlarge": 4.874350,
"r6i.32xlarge": 77.989630, "r6i.4xlarge": 9.748700, "r6i.8xlarge": 19.497410, "r6i.large": 1.218590,
"r6i.metal": 77.989630, "r6i.xlarge": 2.437180,
// t2 family
"t2.2xlarge": 3.392000, "t2.large": 0.851000, "t2.medium": 0.426000, "t2.micro": 0.106000,
"t2.nano": 0.060600, "t2.small": 0.212000, "t2.xlarge": 1.696000,
// t3 family
"t3.2xlarge": 2.103100, "t3.large": 0.525800, "t3.medium": 0.262900, "t3.micro": 0.065700,
"t3.nano": 0.032900, "t3.small": 0.131400, "t3.xlarge": 1.051500,
// t3a family
"t3a.2xlarge": 1.892800, "t3a.large": 0.473200, "t3a.medium": 0.236600, "t3a.micro": 0.059100,
"t3a.nano": 0.029600, "t3a.small": 0.118300, "t3a.xlarge": 0.946400,
// t4g family
"t4g.2xlarge": 1.621100, "t4g.large": 0.405300, "t4g.medium": 0.202600, "t4g.micro": 0.050700,
"t4g.nano": 0.025300, "t4g.small": 0.101300, "t4g.xlarge": 0.810600,
// u-12tb1 family
"u-12tb1.112xlarge": 1074.685080,
// u-6tb1 family
"u-6tb1.112xlarge": 537.342540, "u-6tb1.56xlarge": 456.681190,
// u-9tb1 family
"u-9tb1.112xlarge": 805.979580,
// x1 family
"x1.16xlarge": 68.876000, "x1.32xlarge": 137.752000,
// x2idn family
"x2idn.16xlarge": 68.870760, "x2idn.24xlarge": 103.306140, "x2idn.32xlarge": 137.741520,
"x2idn.metal": 137.741520,
// x2iedn family
"x2iedn.16xlarge": 137.741520, "x2iedn.24xlarge": 206.612280, "x2iedn.2xlarge": 17.217690,
"x2iedn.32xlarge": 275.483040, "x2iedn.4xlarge": 34.435380, "x2iedn.8xlarge": 68.870760,
"x2iedn.metal": 275.483040, "x2iedn.xlarge": 8.608850,
}
}
| 838 |
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 securitygroup
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/patrickmn/go-cache"
"github.com/samber/lo"
"knative.dev/pkg/logging"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/pretty"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
type Provider struct {
sync.Mutex
ec2api ec2iface.EC2API
cache *cache.Cache
cm *pretty.ChangeMonitor
}
const TTL = 5 * time.Minute
func NewProvider(ec2api ec2iface.EC2API, cache *cache.Cache) *Provider {
return &Provider{
ec2api: ec2api,
cm: pretty.NewChangeMonitor(),
// TODO: Remove cache for v1beta1, utilize resolved security groups from the AWSNodeTemplate.status
cache: cache,
}
}
func (p *Provider) List(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) ([]*ec2.SecurityGroup, error) {
p.Lock()
defer p.Unlock()
// Get SecurityGroups
// TODO: When removing custom launchTemplates for v1beta1, security groups will be required.
// The check will not be necessary
filters := p.getFilters(nodeTemplate)
if len(filters) == 0 {
return []*ec2.SecurityGroup{}, nil
}
securityGroups, err := p.getSecurityGroups(ctx, filters)
if err != nil {
return nil, err
}
if p.cm.HasChanged(fmt.Sprintf("security-groups/%s", nodeTemplate.Name), securityGroups) {
logging.FromContext(ctx).
With("security-groups", lo.Map(securityGroups, func(s *ec2.SecurityGroup, _ int) string {
return aws.StringValue(s.GroupId)
})).
Debugf("discovered security groups")
}
return securityGroups, nil
}
func (p *Provider) getFilters(nodeTemplate *v1alpha1.AWSNodeTemplate) []*ec2.Filter {
var filters []*ec2.Filter
for key, value := range nodeTemplate.Spec.SecurityGroupSelector {
if key == "aws-ids" {
filters = append(filters, &ec2.Filter{
Name: aws.String("group-id"),
Values: aws.StringSlice(functional.SplitCommaSeparatedString(value)),
})
} else if value == "*" {
filters = append(filters, &ec2.Filter{
Name: aws.String("tag-key"),
Values: []*string{aws.String(key)},
})
} else {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: aws.StringSlice(functional.SplitCommaSeparatedString(value)),
})
}
}
return filters
}
func (p *Provider) getSecurityGroups(ctx context.Context, filters []*ec2.Filter) ([]*ec2.SecurityGroup, error) {
hash, err := hashstructure.Hash(filters, hashstructure.FormatV2, nil)
if err != nil {
return nil, err
}
if securityGroups, ok := p.cache.Get(fmt.Sprint(hash)); ok {
return securityGroups.([]*ec2.SecurityGroup), nil
}
output, err := p.ec2api.DescribeSecurityGroupsWithContext(ctx, &ec2.DescribeSecurityGroupsInput{Filters: filters})
if err != nil {
return nil, fmt.Errorf("describing security groups %+v, %w", filters, err)
}
p.cache.SetDefault(fmt.Sprint(hash), output.SecurityGroups)
return output.SecurityGroups, nil
}
| 116 |
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 securitygroup_test
import (
"context"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
. "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"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
corev1alpha5 "github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"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 provisioner *corev1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
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)
})
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: &corev1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
awsEnv.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("Security Group Provider", func() {
It("should default to the clusters security groups", func() {
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*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"),
}},
},
}))
})
It("should discover security groups by tag", func() {
awsEnv.EC2API.DescribeSecurityGroupsOutput.Set(&ec2.DescribeSecurityGroupsOutput{SecurityGroups: []*ec2.SecurityGroup{
{GroupName: aws.String("test-sgName-1"), GroupId: aws.String("test-sg-1"), Tags: []*ec2.Tag{{Key: aws.String("kubernetes.io/cluster/test-cluster"), Value: aws.String("test-sg-1")}}},
{GroupName: aws.String("test-sgName-2"), GroupId: aws.String("test-sg-2"), Tags: []*ec2.Tag{{Key: aws.String("kubernetes.io/cluster/test-cluster"), Value: aws.String("test-sg-2")}}},
}})
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*ec2.SecurityGroup{
{
GroupName: aws.String("test-sgName-1"),
GroupId: aws.String("test-sg-1"),
Tags: []*ec2.Tag{{
Key: aws.String("kubernetes.io/cluster/test-cluster"),
Value: aws.String("test-sg-1"),
}},
},
{
GroupName: aws.String("test-sgName-2"),
GroupId: aws.String("test-sg-2"),
Tags: []*ec2.Tag{{
Key: aws.String("kubernetes.io/cluster/test-cluster"),
Value: aws.String("test-sg-2"),
}},
},
}))
})
It("should discover security groups by multiple tag values", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{"Name": "test-security-group-1,test-security-group-2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*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"),
}},
},
}))
})
It("should discover security groups by ID", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{"aws-ids": "sg-test1"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*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"),
}},
},
}))
})
It("should discover security groups by IDs", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{"aws-ids": "sg-test1,sg-test2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*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"),
}},
},
}))
})
It("should discover security groups by IDs and tags", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{"aws-ids": "sg-test1,sg-test2", "foo": "bar"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*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"),
}},
},
}))
})
It("should discover security groups by IDs intersected with tags", func() {
nodeTemplate.Spec.SecurityGroupSelector = map[string]string{"aws-ids": "sg-test2", "foo": "bar"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
securityGroups, err := awsEnv.SecurityGroupProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(securityGroups).To(Equal([]*ec2.SecurityGroup{
{
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"),
}},
},
}))
})
})
| 312 |
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 subnet
import (
"context"
"fmt"
"net/http"
"sort"
"sync"
"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"
"knative.dev/pkg/logging"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/pretty"
)
type Provider struct {
sync.RWMutex
ec2api ec2iface.EC2API
cache *cache.Cache
cm *pretty.ChangeMonitor
inflightIPs map[string]int64
}
func NewProvider(ec2api ec2iface.EC2API, cache *cache.Cache) *Provider {
return &Provider{
ec2api: ec2api,
cm: pretty.NewChangeMonitor(),
// TODO: Remove cache for v1beta1, utilize resolved subnet from the AWSNodeTemplate.status
// Subnets are sorted on AvailableIpAddressCount, descending order
cache: cache,
// inflightIPs is used to track IPs from known launched instances
inflightIPs: map[string]int64{},
}
}
func (p *Provider) List(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) ([]*ec2.Subnet, error) {
p.Lock()
defer p.Unlock()
filters := getFilters(nodeTemplate)
if len(filters) == 0 {
return []*ec2.Subnet{}, nil
}
hash, err := hashstructure.Hash(filters, hashstructure.FormatV2, &hashstructure.HashOptions{SlicesAsSets: true})
if err != nil {
return nil, err
}
if subnets, ok := p.cache.Get(fmt.Sprint(hash)); ok {
return subnets.([]*ec2.Subnet), nil
}
output, err := p.ec2api.DescribeSubnetsWithContext(ctx, &ec2.DescribeSubnetsInput{Filters: filters})
if err != nil {
return nil, fmt.Errorf("describing subnets %s, %w", pretty.Concise(filters), err)
}
p.cache.SetDefault(fmt.Sprint(hash), output.Subnets)
// remove any previously tracked IP addresses since we just refreshed from EC2
for _, subnet := range output.Subnets {
delete(p.inflightIPs, *subnet.SubnetId)
}
if p.cm.HasChanged(fmt.Sprintf("subnets/%s", nodeTemplate.Name), output.Subnets) {
logging.FromContext(ctx).
With("subnets", lo.Map(output.Subnets, func(s *ec2.Subnet, _ int) string {
return fmt.Sprintf("%s (%s)", aws.StringValue(s.SubnetId), aws.StringValue(s.AvailabilityZone))
})).
Debugf("discovered subnets")
}
return output.Subnets, nil
}
// CheckAnyPublicIPAssociations returns a bool indicating whether all referenced subnets assign public IPv4 addresses to EC2 instances created therein
func (p *Provider) CheckAnyPublicIPAssociations(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate) (bool, error) {
subnets, err := p.List(ctx, nodeTemplate)
if err != nil {
return false, err
}
_, ok := lo.Find(subnets, func(s *ec2.Subnet) bool {
return aws.BoolValue(s.MapPublicIpOnLaunch)
})
return ok, nil
}
// ZonalSubnetsForLaunch returns a mapping of zone to the subnet with the most available IP addresses and deducts the passed ips from the available count
func (p *Provider) ZonalSubnetsForLaunch(ctx context.Context, nodeTemplate *v1alpha1.AWSNodeTemplate, instanceTypes []*cloudprovider.InstanceType, capacityType string) (map[string]*ec2.Subnet, error) {
subnets, err := p.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)
}
p.Lock()
defer p.Unlock()
// sort subnets in ascending order of available IP addresses and populate map with most available subnet per AZ
zonalSubnets := map[string]*ec2.Subnet{}
sort.Slice(subnets, func(i, j int) bool {
iIPs := aws.Int64Value(subnets[i].AvailableIpAddressCount)
jIPs := aws.Int64Value(subnets[j].AvailableIpAddressCount)
// override ip count from ec2.Subnet if we've tracked launches
if ips, ok := p.inflightIPs[*subnets[i].SubnetId]; ok {
iIPs = ips
}
if ips, ok := p.inflightIPs[*subnets[j].SubnetId]; ok {
jIPs = ips
}
return iIPs < jIPs
})
for _, subnet := range subnets {
zonalSubnets[*subnet.AvailabilityZone] = subnet
}
for _, subnet := range zonalSubnets {
predictedIPsUsed := p.minPods(instanceTypes, *subnet.AvailabilityZone, capacityType)
prevIPs := *subnet.AvailableIpAddressCount
if trackedIPs, ok := p.inflightIPs[*subnet.SubnetId]; ok {
prevIPs = trackedIPs
}
p.inflightIPs[*subnet.SubnetId] = prevIPs - predictedIPsUsed
}
return zonalSubnets, nil
}
// UpdateInflightIPs is used to refresh the in-memory IP usage by adding back unused IPs after a CreateFleet response is returned
func (p *Provider) UpdateInflightIPs(createFleetInput *ec2.CreateFleetInput, createFleetOutput *ec2.CreateFleetOutput, instanceTypes []*cloudprovider.InstanceType,
subnets []*ec2.Subnet, capacityType string) {
p.Lock()
defer p.Unlock()
// Process the CreateFleetInput to pull out all the requested subnetIDs
fleetInputSubnets := lo.Compact(lo.Uniq(lo.FlatMap(createFleetInput.LaunchTemplateConfigs, func(req *ec2.FleetLaunchTemplateConfigRequest, _ int) []string {
return lo.Map(req.Overrides, func(override *ec2.FleetLaunchTemplateOverridesRequest, _ int) string {
if override == nil {
return ""
}
return lo.FromPtr(override.SubnetId)
})
})))
// Process the CreateFleetOutput to pull out all the fulfilled subnetIDs
var fleetOutputSubnets []string
if createFleetOutput != nil {
fleetOutputSubnets = lo.Compact(lo.Uniq(lo.Map(createFleetOutput.Instances, func(fleetInstance *ec2.CreateFleetInstance, _ int) string {
if fleetInstance == nil || fleetInstance.LaunchTemplateAndOverrides == nil || fleetInstance.LaunchTemplateAndOverrides.Overrides == nil {
return ""
}
return lo.FromPtr(fleetInstance.LaunchTemplateAndOverrides.Overrides.SubnetId)
})))
}
// Find the subnets that were included in the input but not chosen by Fleet, so we need to add the inflight IPs back to them
subnetIDsToAddBackIPs, _ := lo.Difference(fleetInputSubnets, fleetOutputSubnets)
// Aggregate all the cached subnets
cachedSubnets := lo.UniqBy(lo.Flatten(lo.MapToSlice(p.cache.Items(), func(_ string, item cache.Item) []*ec2.Subnet {
return item.Object.([]*ec2.Subnet)
})), func(subnet *ec2.Subnet) string { return *subnet.SubnetId })
// Update the inflight IP tracking of subnets stored in the cache that have not be synchronized since the initial
// deduction of IP addresses before the instance launch
for _, cachedSubnet := range cachedSubnets {
if !lo.Contains(subnetIDsToAddBackIPs, *cachedSubnet.SubnetId) {
continue
}
originalSubnet, ok := lo.Find(subnets, func(subnet *ec2.Subnet) bool {
return *subnet.SubnetId == *cachedSubnet.SubnetId
})
if !ok {
continue
}
// If the cached subnet IP address count hasn't changed from the original subnet used to
// launch the instance, then we need to update the tracked IPs
if *originalSubnet.AvailableIpAddressCount == *cachedSubnet.AvailableIpAddressCount {
// other IPs deducted were opportunistic and need to be readded since Fleet didn't pick those subnets to launch into
if ips, ok := p.inflightIPs[*originalSubnet.SubnetId]; ok {
minPods := p.minPods(instanceTypes, *originalSubnet.AvailabilityZone, capacityType)
p.inflightIPs[*originalSubnet.SubnetId] = ips + minPods
}
}
}
}
func (p *Provider) LivenessProbe(_ *http.Request) error {
p.Lock()
//nolint: staticcheck
p.Unlock()
return nil
}
func (p *Provider) minPods(instanceTypes []*cloudprovider.InstanceType, zone string, capacityType string) int64 {
// filter for instance types available in the zone and capacity type being requested
filteredInstanceTypes := lo.Filter(instanceTypes, func(it *cloudprovider.InstanceType, _ int) bool {
offering, ok := it.Offerings.Get(capacityType, zone)
if !ok {
return false
}
return offering.Available
})
if len(filteredInstanceTypes) == 0 {
return 0
}
// Get minimum pods to use when selecting a subnet and deducting what will be launched
pods, _ := lo.MinBy(filteredInstanceTypes, func(i *cloudprovider.InstanceType, j *cloudprovider.InstanceType) bool {
return i.Capacity.Pods().Cmp(*j.Capacity.Pods()) < 0
}).Capacity.Pods().AsInt64()
return pods
}
func getFilters(nodeTemplate *v1alpha1.AWSNodeTemplate) []*ec2.Filter {
filters := []*ec2.Filter{}
// Filter by subnet
for key, value := range nodeTemplate.Spec.SubnetSelector {
if key == "aws-ids" {
filters = append(filters, &ec2.Filter{
Name: aws.String("subnet-id"),
Values: aws.StringSlice(functional.SplitCommaSeparatedString(value)),
})
} else if value == "*" {
filters = append(filters, &ec2.Filter{
Name: aws.String("tag-key"),
Values: []*string{aws.String(key)},
})
} else {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: aws.StringSlice(functional.SplitCommaSeparatedString(value)),
})
}
}
return filters
}
| 251 |
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 subnet_test
import (
"context"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
. "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"
coresettings "github.com/aws/karpenter-core/pkg/apis/settings"
corev1alpha5 "github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"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 provisioner *corev1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
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)
})
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: &corev1alpha5.MachineTemplateRef{
APIVersion: nodeTemplate.APIVersion,
Kind: nodeTemplate.Kind,
Name: nodeTemplate.Name,
},
})
awsEnv.Reset()
})
var _ = AfterEach(func() {
ExpectCleanedUp(ctx, env.Client)
})
var _ = Describe("Subnet Provider", func() {
It("should discover subnet by ID", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"aws-ids": "subnet-test1"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(1))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test1"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1a"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should discover subnets by IDs", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"aws-ids": "subnet-test1,subnet-test2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(2))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test1"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1a"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
Expect(aws.StringValue(subnets[1].SubnetId)).To(Equal("subnet-test2"))
Expect(aws.StringValue(subnets[1].AvailabilityZone)).To(Equal("test-zone-1b"))
Expect(aws.Int64Value(subnets[1].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should discover subnets by IDs and tags", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"aws-ids": "subnet-test1,subnet-test2", "foo": "bar"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(2))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test1"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1a"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
Expect(aws.StringValue(subnets[1].SubnetId)).To(Equal("subnet-test2"))
Expect(aws.StringValue(subnets[1].AvailabilityZone)).To(Equal("test-zone-1b"))
Expect(aws.Int64Value(subnets[1].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should discover subnets by a single tag", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-1"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(1))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test1"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1a"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should discover subnets by multiple tag values", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-1,test-subnet-2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(2))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test1"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1a"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
Expect(aws.StringValue(subnets[1].SubnetId)).To(Equal("subnet-test2"))
Expect(aws.StringValue(subnets[1].AvailabilityZone)).To(Equal("test-zone-1b"))
Expect(aws.Int64Value(subnets[1].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should discover subnets by IDs intersected with tags", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"aws-ids": "subnet-test2", "foo": "bar"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
subnets, err := awsEnv.SubnetProvider.List(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(subnets).To(HaveLen(1))
Expect(aws.StringValue(subnets[0].SubnetId)).To(Equal("subnet-test2"))
Expect(aws.StringValue(subnets[0].AvailabilityZone)).To(Equal("test-zone-1b"))
Expect(aws.Int64Value(subnets[0].AvailableIpAddressCount)).To(BeNumerically("==", 100))
})
It("should note that no subnets assign a public IPv4 address to EC2 instances on launch", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"Name": "test-subnet-1,test-subnet-3"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
onlyPrivate, err := awsEnv.SubnetProvider.CheckAnyPublicIPAssociations(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(onlyPrivate).To(BeFalse())
})
It("should note that at least one subnet assigns a public IPv4 address to EC2instances on launch", func() {
nodeTemplate.Spec.SubnetSelector = map[string]string{"aws-ids": "subnet-test2"}
ExpectApplied(ctx, env.Client, provisioner, nodeTemplate)
onlyPrivate, err := awsEnv.SubnetProvider.CheckAnyPublicIPAssociations(ctx, nodeTemplate)
Expect(err).To(BeNil())
Expect(onlyPrivate).To(BeTrue())
})
})
| 202 |
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 test
import (
"fmt"
"github.com/imdario/mergo"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
func AWSNodeTemplate(overrides ...v1alpha1.AWSNodeTemplateSpec) *v1alpha1.AWSNodeTemplate {
options := v1alpha1.AWSNodeTemplateSpec{}
for _, override := range overrides {
if err := mergo.Merge(&options, override, mergo.WithOverride); err != nil {
panic(fmt.Sprintf("Failed to merge settings: %s", err))
}
}
if options.AWS.SecurityGroupSelector == nil {
options.AWS.SecurityGroupSelector = map[string]string{"*": "*"}
}
if options.AWS.SubnetSelector == nil {
options.AWS.SubnetSelector = map[string]string{"*": "*"}
}
return &v1alpha1.AWSNodeTemplate{
ObjectMeta: test.ObjectMeta(),
Spec: options,
}
}
| 47 |
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 test
import (
"context"
"net"
"k8s.io/client-go/tools/record"
"knative.dev/pkg/ptr"
"github.com/patrickmn/go-cache"
awscache "github.com/aws/karpenter/pkg/cache"
"github.com/aws/karpenter/pkg/fake"
"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-core/pkg/events"
coretest "github.com/aws/karpenter-core/pkg/test"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
)
type Environment struct {
// API
EC2API *fake.EC2API
SSMAPI *fake.SSMAPI
PricingAPI *fake.PricingAPI
// Cache
SSMCache *cache.Cache
EC2Cache *cache.Cache
KubernetesVersionCache *cache.Cache
InstanceTypeCache *cache.Cache
UnavailableOfferingsCache *awscache.UnavailableOfferings
LaunchTemplateCache *cache.Cache
SubnetCache *cache.Cache
SecurityGroupCache *cache.Cache
// Providers
InstanceTypesProvider *instancetype.Provider
InstanceProvider *instance.Provider
SubnetProvider *subnet.Provider
SecurityGroupProvider *securitygroup.Provider
PricingProvider *pricing.Provider
AMIProvider *amifamily.Provider
AMIResolver *amifamily.Resolver
LaunchTemplateProvider *launchtemplate.Provider
}
func NewEnvironment(ctx context.Context, env *coretest.Environment) *Environment {
// API
ec2api := &fake.EC2API{}
ssmapi := &fake.SSMAPI{}
// cache
ssmCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
ec2Cache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
kubernetesVersionCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
instanceTypeCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
unavailableOfferingsCache := awscache.NewUnavailableOfferings(events.NewRecorder(&record.FakeRecorder{}))
launchTemplateCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
subnetCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
securityGroupCache := cache.New(awscache.DefaultTTL, awscache.DefaultCleanupInterval)
fakePricingAPI := &fake.PricingAPI{}
// Providers
pricingProvider := pricing.NewProvider(ctx, fakePricingAPI, ec2api, "")
subnetProvider := subnet.NewProvider(ec2api, subnetCache)
securityGroupProvider := securitygroup.NewProvider(ec2api, securityGroupCache)
amiProvider := amifamily.NewProvider(env.Client, env.KubernetesInterface, ssmapi, ec2api, ssmCache, ec2Cache, kubernetesVersionCache)
amiResolver := amifamily.New(amiProvider)
instanceTypesProvider := instancetype.NewProvider("", instanceTypeCache, ec2api, subnetProvider, unavailableOfferingsCache, pricingProvider)
launchTemplateProvider :=
launchtemplate.NewProvider(
ctx,
launchTemplateCache,
ec2api,
amiResolver,
securityGroupProvider,
subnetProvider,
ptr.String("ca-bundle"),
make(chan struct{}),
net.ParseIP("10.0.100.10"),
"https://test-cluster",
)
instanceProvider :=
instance.NewProvider(ctx,
"",
ec2api,
unavailableOfferingsCache,
instanceTypesProvider,
subnetProvider,
launchTemplateProvider,
)
return &Environment{
EC2API: ec2api,
SSMAPI: ssmapi,
PricingAPI: fakePricingAPI,
SSMCache: ssmCache,
EC2Cache: ec2Cache,
KubernetesVersionCache: kubernetesVersionCache,
InstanceTypeCache: instanceTypeCache,
LaunchTemplateCache: launchTemplateCache,
SubnetCache: subnetCache,
SecurityGroupCache: securityGroupCache,
UnavailableOfferingsCache: unavailableOfferingsCache,
InstanceTypesProvider: instanceTypesProvider,
InstanceProvider: instanceProvider,
SubnetProvider: subnetProvider,
SecurityGroupProvider: securityGroupProvider,
PricingProvider: pricingProvider,
AMIProvider: amiProvider,
AMIResolver: amiResolver,
LaunchTemplateProvider: launchTemplateProvider,
}
}
func (env *Environment) Reset() {
env.EC2API.Reset()
env.SSMAPI.Reset()
env.PricingAPI.Reset()
env.PricingProvider.Reset()
env.SSMCache.Flush()
env.EC2Cache.Flush()
env.KubernetesVersionCache.Flush()
env.InstanceTypeCache.Flush()
env.UnavailableOfferingsCache.Flush()
env.LaunchTemplateCache.Flush()
env.SubnetCache.Flush()
env.SecurityGroupCache.Flush()
mfs, err := crmetrics.Registry.Gather()
if err != nil {
for _, mf := range mfs {
for _, metric := range mf.GetMetric() {
if metric != nil {
metric.Reset()
}
}
}
}
}
| 166 |
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 test
import (
"context"
"github.com/samber/lo"
corev1alpha5 "github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha5"
)
func Provisioner(options test.ProvisionerOptions) *corev1alpha5.Provisioner {
provisioner := v1alpha5.Provisioner(lo.FromPtr(test.Provisioner(options)))
provisioner.SetDefaults(context.Background())
return lo.ToPtr(corev1alpha5.Provisioner(provisioner))
}
| 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 test
import (
"fmt"
"github.com/imdario/mergo"
"github.com/samber/lo"
awssettings "github.com/aws/karpenter/pkg/apis/settings"
)
type SettingOptions struct {
ClusterName *string
ClusterEndpoint *string
DefaultInstanceProfile *string
EnablePodENI *bool
EnableENILimitedPodDensity *bool
IsolatedVPC *bool
VMMemoryOverheadPercent *float64
InterruptionQueueName *string
Tags map[string]string
ReservedENIs *int
}
func Settings(overrides ...SettingOptions) *awssettings.Settings {
options := SettingOptions{}
for _, override := range overrides {
if err := mergo.Merge(&options, override, mergo.WithOverride); err != nil {
panic(fmt.Sprintf("Failed to merge settings: %s", err))
}
}
return &awssettings.Settings{
ClusterName: lo.FromPtrOr(options.ClusterName, "test-cluster"),
ClusterEndpoint: lo.FromPtrOr(options.ClusterEndpoint, "https://test-cluster"),
DefaultInstanceProfile: lo.FromPtrOr(options.DefaultInstanceProfile, "test-instance-profile"),
EnablePodENI: lo.FromPtrOr(options.EnablePodENI, true),
EnableENILimitedPodDensity: lo.FromPtrOr(options.EnableENILimitedPodDensity, true),
IsolatedVPC: lo.FromPtrOr(options.IsolatedVPC, false),
VMMemoryOverheadPercent: lo.FromPtrOr(options.VMMemoryOverheadPercent, 0.075),
InterruptionQueueName: lo.FromPtrOr(options.InterruptionQueueName, ""),
Tags: options.Tags,
ReservedENIs: lo.FromPtrOr(options.ReservedENIs, 0),
}
}
| 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 utils
import (
"fmt"
"regexp"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
)
var (
instanceIDRegex = regexp.MustCompile(`aws:///(?P<AZ>.*)/(?P<InstanceID>.*)`)
)
// ParseInstanceID parses the provider ID stored on the node to get the instance ID
// associated with a node
func ParseInstanceID(providerID string) (string, error) {
matches := instanceIDRegex.FindStringSubmatch(providerID)
if matches == nil {
return "", fmt.Errorf("parsing instance id %s", providerID)
}
for i, name := range instanceIDRegex.SubexpNames() {
if name == "InstanceID" {
return matches[i], nil
}
}
return "", fmt.Errorf("parsing instance id %s", providerID)
}
// MergeTags takes a variadic list of maps and merges them together into a list of
// EC2 tags to be passed into EC2 API calls
func MergeTags(tags ...map[string]string) []*ec2.Tag {
return lo.MapToSlice(lo.Assign(tags...), func(k, v string) *ec2.Tag {
return &ec2.Tag{Key: aws.String(k), Value: aws.String(v)}
})
}
| 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.
*/
package project
// Version is the karpenter app version injected during compilation
// when using the Makefile
var Version = "unspecified"
| 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 webhooks
import (
"context"
"k8s.io/apimachinery/pkg/runtime/schema"
"knative.dev/pkg/configmap"
"knative.dev/pkg/controller"
knativeinjection "knative.dev/pkg/injection"
"knative.dev/pkg/webhook/resourcesemantics"
"knative.dev/pkg/webhook/resourcesemantics/defaulting"
"knative.dev/pkg/webhook/resourcesemantics/validation"
corev1alpha5 "github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/apis/v1alpha5"
)
func NewWebhooks() []knativeinjection.ControllerConstructor {
return []knativeinjection.ControllerConstructor{
NewCRDDefaultingWebhook,
NewCRDValidationWebhook,
}
}
func NewCRDDefaultingWebhook(ctx context.Context, _ configmap.Watcher) *controller.Impl {
return defaulting.NewAdmissionController(ctx,
"defaulting.webhook.karpenter.k8s.aws",
"/default/karpenter.k8s.aws",
Resources,
func(ctx context.Context) context.Context { return ctx },
true,
)
}
func NewCRDValidationWebhook(ctx context.Context, _ configmap.Watcher) *controller.Impl {
return validation.NewAdmissionController(ctx,
"validation.webhook.karpenter.k8s.aws",
"/validate/karpenter.k8s.aws",
Resources,
func(ctx context.Context) context.Context { return ctx },
true,
)
}
var Resources = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{
v1alpha1.SchemeGroupVersion.WithKind("AWSNodeTemplate"): &v1alpha1.AWSNodeTemplate{},
corev1alpha5.SchemeGroupVersion.WithKind("Provisioner"): &v1alpha5.Provisioner{},
}
| 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 main
import (
"context"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cloudformation"
cloudformationtypes "github.com/aws/aws-sdk-go-v2/service/cloudformation/types"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
cloudwatchtypes "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/samber/lo"
"go.uber.org/zap"
)
const (
expirationTTL = time.Hour * 12
karpenterMetricNamespace = "testing.karpenter.sh/cleanup"
karpenterProvisionerNameTag = "karpenter.sh/provisioner-name"
karpenterLaunchTemplateTag = "karpenter.k8s.aws/cluster"
githubRunURLTag = "github.com/run-url"
)
func main() {
ctx := context.Background()
cfg := lo.Must(config.LoadDefaultConfig(ctx))
logger := lo.Must(zap.NewProduction()).Sugar()
expirationTime := time.Now().Add(-expirationTTL)
logger.With("expiration-time", expirationTime.String()).Infof("resolved expiration time for all resources")
ec2Client := ec2.NewFromConfig(cfg)
cloudFormationClient := cloudformation.NewFromConfig(cfg)
cloudWatchClient := cloudwatch.NewFromConfig(cfg)
// Terminate any old instances that were provisioned by Karpenter as part of testing
// We execute these in serial since we will most likely get rate limited if we try to delete these too aggressively
ids := getOldInstances(ctx, ec2Client, expirationTime)
logger.With("ids", ids, "count", len(ids)).Infof("discovered test instances to delete")
if len(ids) > 0 {
if _, err := ec2Client.TerminateInstances(ctx, &ec2.TerminateInstancesInput{
InstanceIds: ids,
}); err != nil {
logger.With("ids", ids, "count", len(ids)).Errorf("terminating test instances, %v", err)
} else {
logger.With("ids", ids, "count", len(ids)).Infof("terminated test instances")
if err = fireMetric(ctx, cloudWatchClient, "InstancesDeleted", float64(len(ids))); err != nil {
logger.With("name", "InstancesDeleted").Errorf("firing metric, %v", err)
}
}
}
// Terminate any old stacks that were provisioned as part of testing
// We execute these in serial since we will most likely get rate limited if we try to delete these too aggressively
names := getOldStacks(ctx, cloudFormationClient, expirationTime)
logger.With("names", names, "count", len(names)).Infof("discovered test stacks to delete")
deleted := 0
for i := range names {
if _, err := cloudFormationClient.DeleteStack(ctx, &cloudformation.DeleteStackInput{
StackName: lo.ToPtr(names[i]),
}); err != nil {
logger.With("name", names[i]).Errorf("deleting test stack, %v", err)
} else {
logger.With("name", names[i]).Infof("deleted test stack")
deleted++
}
}
if err := fireMetric(ctx, cloudWatchClient, "StacksDeleted", float64(deleted)); err != nil {
logger.With("name", "StacksDeleted").Errorf("firing metric, %v", err)
}
// Terminate any old launch templates that were managed by Karpenter and were provisioned as part of testing
names = getOldLaunchTemplates(ctx, ec2Client, expirationTime)
logger.With("names", names, "count", len(names)).Infof("discovered test launch templates to delete")
deleted = 0
for i := range names {
if _, err := ec2Client.DeleteLaunchTemplate(ctx, &ec2.DeleteLaunchTemplateInput{
LaunchTemplateName: lo.ToPtr(names[i]),
}); err != nil {
logger.With("name", names[i]).Errorf("deleting test launch template, %v", err)
} else {
logger.With("name", names[i]).Infof("deleted test launch template")
deleted++
}
}
if err := fireMetric(ctx, cloudWatchClient, "LaunchTemplatesDeleted", float64(deleted)); err != nil {
logger.With("name", "LaunchTemplatesDeleted").Errorf("firing metric, %v", err)
}
}
func fireMetric(ctx context.Context, cloudWatchClient *cloudwatch.Client, name string, value float64) error {
_, err := cloudWatchClient.PutMetricData(ctx, &cloudwatch.PutMetricDataInput{
Namespace: lo.ToPtr(karpenterMetricNamespace),
MetricData: []cloudwatchtypes.MetricDatum{
{
MetricName: lo.ToPtr(name),
Value: lo.ToPtr(value),
},
},
})
return err
}
func getOldInstances(ctx context.Context, ec2Client *ec2.Client, expirationTime time.Time) (ids []string) {
var nextToken *string
for {
out := lo.Must(ec2Client.DescribeInstances(ctx, &ec2.DescribeInstancesInput{
Filters: []ec2types.Filter{
{
Name: lo.ToPtr("instance-state-name"),
Values: []string{string(ec2types.InstanceStateNameRunning)},
},
{
Name: lo.ToPtr("tag-key"),
Values: []string{karpenterProvisionerNameTag},
},
},
NextToken: nextToken,
}))
for _, res := range out.Reservations {
for _, instance := range res.Instances {
if _, found := lo.Find(instance.Tags, func(t ec2types.Tag) bool {
return lo.FromPtr(t.Key) == "kubernetes.io/cluster/KITInfrastructure"
}); !found && lo.FromPtr(instance.LaunchTime).Before(expirationTime) {
ids = append(ids, lo.FromPtr(instance.InstanceId))
}
}
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return ids
}
func getOldStacks(ctx context.Context, cloudFormationClient *cloudformation.Client, expirationTime time.Time) (names []string) {
var nextToken *string
for {
out := lo.Must(cloudFormationClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
NextToken: nextToken,
}))
stacks := lo.Reject(out.Stacks, func(s cloudformationtypes.Stack, _ int) bool {
return s.StackStatus == cloudformationtypes.StackStatusDeleteComplete ||
s.StackStatus == cloudformationtypes.StackStatusDeleteInProgress
})
for _, stack := range stacks {
if _, found := lo.Find(stack.Tags, func(t cloudformationtypes.Tag) bool {
return lo.FromPtr(t.Key) == githubRunURLTag
}); found && lo.FromPtr(stack.CreationTime).Before(expirationTime) {
names = append(names, lo.FromPtr(stack.StackName))
}
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return names
}
func getOldLaunchTemplates(ctx context.Context, ec2Client *ec2.Client, expirationTime time.Time) (names []string) {
var nextToken *string
for {
out := lo.Must(ec2Client.DescribeLaunchTemplates(ctx, &ec2.DescribeLaunchTemplatesInput{
Filters: []ec2types.Filter{
{
Name: lo.ToPtr("tag-key"),
Values: []string{karpenterLaunchTemplateTag},
},
},
NextToken: nextToken,
}))
for _, launchTemplate := range out.LaunchTemplates {
if lo.FromPtr(launchTemplate.CreateTime).Before(expirationTime) {
names = append(names, lo.FromPtr(launchTemplate.LaunchTemplateName))
}
}
nextToken = out.NextToken
if nextToken == nil {
break
}
}
return names
}
| 211 |
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 debug
import (
"context"
"fmt"
"strings"
"time"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type EventClient struct {
start time.Time
kubeClient client.Client
}
func NewEventClient(kubeClient client.Client) *EventClient {
return &EventClient{
start: time.Now(),
kubeClient: kubeClient,
}
}
func (c *EventClient) DumpEvents(ctx context.Context) error {
return multierr.Combine(
c.dumpKarpenterEvents(ctx),
c.dumpPodEvents(ctx),
c.dumpNodeEvents(ctx),
)
}
func (c *EventClient) dumpKarpenterEvents(ctx context.Context) error {
el := &v1.EventList{}
if err := c.kubeClient.List(ctx, el, client.InNamespace("karpenter")); err != nil {
return err
}
for k, v := range coallateEvents(filterTestEvents(el.Items, c.start)) {
fmt.Print(getEventInformation(k, v))
}
return nil
}
func (c *EventClient) dumpPodEvents(ctx context.Context) error {
el := &v1.EventList{}
if err := c.kubeClient.List(ctx, el, &client.ListOptions{
FieldSelector: fields.SelectorFromSet(map[string]string{"involvedObject.kind": "Pod"}),
}); err != nil {
return err
}
events := lo.Filter(filterTestEvents(el.Items, c.start), func(e v1.Event, _ int) bool {
return e.InvolvedObject.Namespace != "kube-system"
})
for k, v := range coallateEvents(events) {
fmt.Print(getEventInformation(k, v))
}
return nil
}
func (c *EventClient) dumpNodeEvents(ctx context.Context) error {
el := &v1.EventList{}
if err := c.kubeClient.List(ctx, el, &client.ListOptions{
FieldSelector: fields.SelectorFromSet(map[string]string{"involvedObject.kind": "Node"}),
}); err != nil {
return err
}
for k, v := range coallateEvents(filterTestEvents(el.Items, c.start)) {
fmt.Print(getEventInformation(k, v))
}
return nil
}
func filterTestEvents(events []v1.Event, startTime time.Time) []v1.Event {
return lo.Filter(events, func(e v1.Event, _ int) bool {
if !e.EventTime.IsZero() {
if e.EventTime.BeforeTime(&metav1.Time{Time: startTime}) {
return false
}
} else if e.FirstTimestamp.Before(&metav1.Time{Time: startTime}) {
return false
}
return true
})
}
func coallateEvents(events []v1.Event) map[v1.ObjectReference]*v1.EventList {
eventMap := map[v1.ObjectReference]*v1.EventList{}
for i := range events {
elem := events[i]
objectKey := v1.ObjectReference{Kind: elem.InvolvedObject.Kind, Namespace: elem.InvolvedObject.Namespace, Name: elem.InvolvedObject.Name}
if _, ok := eventMap[objectKey]; !ok {
eventMap[objectKey] = &v1.EventList{}
}
eventMap[objectKey].Items = append(eventMap[objectKey].Items, elem)
}
return eventMap
}
// Partially copied from
// https://github.com/kubernetes/kubernetes/blob/04ee339c7a4d36b4037ce3635993e2a9e395ebf3/staging/src/k8s.io/kubectl/pkg/describe/describe.go#L4232
func getEventInformation(o v1.ObjectReference, el *v1.EventList) string {
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("------- %s/%s%s EVENTS -------\n",
strings.ToLower(o.Kind), lo.Ternary(o.Namespace != "", o.Namespace+"/", ""), o.Name))
if len(el.Items) == 0 {
return sb.String()
}
for _, e := range el.Items {
source := e.Source.Component
if source == "" {
source = e.ReportingController
}
eventTime := e.EventTime
if eventTime.IsZero() {
eventTime = metav1.NewMicroTime(e.FirstTimestamp.Time)
}
sb.WriteString(fmt.Sprintf("time=%s type=%s reason=%s from=%s message=%s\n",
eventTime.Format(time.RFC3339),
e.Type,
e.Reason,
source,
strings.TrimSpace(e.Message)),
)
}
return sb.String()
}
| 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 debug
import (
"context"
"fmt"
"time"
"k8s.io/apimachinery/pkg/api/errors"
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/event"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
)
type MachineController struct {
kubeClient client.Client
}
func NewMachineController(kubeClient client.Client) *MachineController {
return &MachineController{
kubeClient: kubeClient,
}
}
func (c *MachineController) Name() string {
return "machine"
}
func (c *MachineController) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
m := &v1alpha5.Machine{}
if err := c.kubeClient.Get(ctx, req.NamespacedName, m); err != nil {
if errors.IsNotFound(err) {
fmt.Printf("[DELETED %s] MACHINE %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.String())
}
return reconcile.Result{}, client.IgnoreNotFound(err)
}
fmt.Printf("[CREATED/UPDATED %s] MACHINE %s %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.Name, c.GetInfo(m))
return reconcile.Result{}, nil
}
func (c *MachineController) GetInfo(m *v1alpha5.Machine) string {
return fmt.Sprintf("ready=%t launched=%t registered=%t initialized=%t",
m.StatusConditions().IsHappy(),
m.StatusConditions().GetCondition(v1alpha5.MachineLaunched).IsTrue(),
m.StatusConditions().GetCondition(v1alpha5.MachineRegistered).IsTrue(),
m.StatusConditions().GetCondition(v1alpha5.MachineInitialized).IsTrue(),
)
}
func (c *MachineController) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1alpha5.Machine{}).
WithEventFilter(predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldMachine := e.ObjectOld.(*v1alpha5.Machine)
newMachine := e.ObjectNew.(*v1alpha5.Machine)
return c.GetInfo(oldMachine) != c.GetInfo(newMachine)
},
}).
WithOptions(controller.Options{MaxConcurrentReconciles: 10}))
}
| 83 |
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 debug
import (
"context"
"sync"
"github.com/samber/lo"
"k8s.io/client-go/rest"
"knative.dev/pkg/logging"
controllerruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/operator/scheme"
)
type Monitor struct {
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
mgr manager.Manager
}
func New(ctx context.Context, config *rest.Config, kubeClient client.Client) *Monitor {
logger := logging.FromContext(ctx)
mgr := lo.Must(controllerruntime.NewManager(config, controllerruntime.Options{
Scheme: scheme.Scheme,
BaseContext: func() context.Context {
ctx := context.Background()
ctx = logging.WithLogger(ctx, logger)
logger.WithOptions()
return ctx
},
MetricsBindAddress: "0",
}))
for _, c := range newControllers(kubeClient) {
lo.Must0(c.Builder(ctx, mgr).Complete(c), "failed to register controller")
}
ctx, cancel := context.WithCancel(ctx) // this context is only meant for monitor start/stop
return &Monitor{
ctx: ctx,
cancel: cancel,
mgr: mgr,
}
}
// MustStart starts the debug monitor
func (m *Monitor) MustStart() {
m.wg.Add(1)
go func() {
defer m.wg.Done()
lo.Must0(m.mgr.Start(m.ctx))
}()
}
// Stop stops the monitor
func (m *Monitor) Stop() {
m.cancel()
m.wg.Wait()
}
func newControllers(kubeClient client.Client) []controller.Controller {
return []controller.Controller{
NewMachineController(kubeClient),
NewNodeController(kubeClient),
NewPodController(kubeClient),
}
}
| 84 |
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 debug
import (
"context"
"fmt"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
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/event"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
nodeutils "github.com/aws/karpenter-core/pkg/utils/node"
)
type NodeController struct {
kubeClient client.Client
}
func NewNodeController(kubeClient client.Client) *NodeController {
return &NodeController{
kubeClient: kubeClient,
}
}
func (c *NodeController) Name() string {
return "node"
}
func (c *NodeController) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
n := &v1.Node{}
if err := c.kubeClient.Get(ctx, req.NamespacedName, n); err != nil {
if errors.IsNotFound(err) {
fmt.Printf("[DELETED %s] NODE %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.String())
}
return reconcile.Result{}, client.IgnoreNotFound(err)
}
fmt.Printf("[CREATED/UPDATED %s] NODE %s %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.Name, c.GetInfo(ctx, n))
return reconcile.Result{}, nil
}
func (c *NodeController) GetInfo(ctx context.Context, n *v1.Node) string {
pods, _ := nodeutils.GetNodePods(ctx, c.kubeClient, n)
return fmt.Sprintf("ready=%s schedulable=%t initialized=%s pods=%d taints=%v", nodeutils.GetCondition(n, v1.NodeReady).Status, !n.Spec.Unschedulable, n.Labels[v1alpha5.LabelNodeInitialized], len(pods), n.Spec.Taints)
}
func (c *NodeController) Builder(ctx context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1.Node{}).
WithEventFilter(predicate.And(
predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldNode := e.ObjectOld.(*v1.Node)
newNode := e.ObjectNew.(*v1.Node)
return c.GetInfo(ctx, oldNode) != c.GetInfo(ctx, newNode)
},
},
predicate.NewPredicateFuncs(func(o client.Object) bool {
return o.GetLabels()[v1alpha5.ProvisionerNameLabelKey] != ""
}),
)).
WithOptions(controller.Options{MaxConcurrentReconciles: 10}))
}
| 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 debug
import (
"context"
"fmt"
"strings"
"time"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
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/event"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/utils/pod"
)
type PodController struct {
kubeClient client.Client
}
func NewPodController(kubeClient client.Client) *PodController {
return &PodController{
kubeClient: kubeClient,
}
}
func (c *PodController) Name() string {
return "pod"
}
func (c *PodController) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
p := &v1.Pod{}
if err := c.kubeClient.Get(ctx, req.NamespacedName, p); err != nil {
if errors.IsNotFound(err) {
fmt.Printf("[DELETED %s] POD %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.String())
}
return reconcile.Result{}, client.IgnoreNotFound(err)
}
fmt.Printf("[CREATED/UPDATED %s] POD %s %s\n", time.Now().Format(time.RFC3339), req.NamespacedName.String(), c.GetInfo(p))
return reconcile.Result{}, nil
}
func (c *PodController) GetInfo(p *v1.Pod) string {
var containerInfo strings.Builder
for _, c := range p.Status.ContainerStatuses {
if containerInfo.Len() > 0 {
_ = lo.Must(fmt.Fprintf(&containerInfo, ", "))
}
_ = lo.Must(fmt.Fprintf(&containerInfo, "%s restarts=%d", c.Name, c.RestartCount))
}
return fmt.Sprintf("provisionable=%v phase=%s nodename=%s owner=%#v [%s]",
pod.IsProvisionable(p), p.Status.Phase, p.Spec.NodeName, p.OwnerReferences, containerInfo.String())
}
func (c *PodController) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1.Pod{}).
WithEventFilter(predicate.And(
predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
oldPod := e.ObjectOld.(*v1.Pod)
newPod := e.ObjectNew.(*v1.Pod)
return c.GetInfo(oldPod) != c.GetInfo(newPod)
},
},
predicate.NewPredicateFuncs(func(o client.Object) bool {
return o.GetNamespace() != "kube-system" && o.GetNamespace() != "karpenter"
}),
)).
WithOptions(controller.Options{MaxConcurrentReconciles: 10}))
}
| 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 debug
import (
"context"
"github.com/onsi/ginkgo/v2"
"github.com/samber/lo"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
. "github.com/onsi/gomega" //nolint:revive,stylecheck
)
const (
NoWatch = "NoWatch"
NoEvents = "NoEvents"
)
var m *Monitor
var e *EventClient
func BeforeEach(ctx context.Context, config *rest.Config, kubeClient client.Client) {
// If the test is labeled as NoWatch, then the node/pod monitor will just list at the beginning
// of the test rather than perform a watch during it
if !lo.Contains(ginkgo.CurrentSpecReport().Labels(), NoWatch) {
m = New(ctx, config, kubeClient)
m.MustStart()
}
if !lo.Contains(ginkgo.CurrentSpecReport().Labels(), NoEvents) {
e = NewEventClient(kubeClient)
}
}
func AfterEach(ctx context.Context) {
if !lo.Contains(ginkgo.CurrentSpecReport().Labels(), NoWatch) {
m.Stop()
}
if !lo.Contains(ginkgo.CurrentSpecReport().Labels(), NoEvents) {
Expect(e.DumpEvents(ctx)).To(Succeed())
}
}
| 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 aws
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"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/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/fis"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/samber/lo"
"k8s.io/utils/env"
. "github.com/onsi/ginkgo/v2" //nolint:revive,stylecheck
"github.com/aws/karpenter/pkg/controllers/interruption"
"github.com/aws/karpenter/test/pkg/environment/common"
)
const WindowsDefaultImage = "mcr.microsoft.com/oss/kubernetes/pause:3.9"
type Environment struct {
*common.Environment
Region string
STSAPI *sts.STS
EC2API *ec2.EC2
SSMAPI *ssm.SSM
IAMAPI *iam.IAM
FISAPI *fis.FIS
EKSAPI *eks.EKS
CloudwatchAPI cloudwatchiface.CloudWatchAPI
SQSProvider *interruption.SQSProvider
}
func NewEnvironment(t *testing.T) *Environment {
env := common.NewEnvironment(t)
session := session.Must(session.NewSessionWithOptions(
session.Options{
Config: *request.WithRetryer(
&aws.Config{STSRegionalEndpoint: endpoints.RegionalSTSEndpoint},
client.DefaultRetryer{NumMaxRetries: 10},
),
SharedConfigState: session.SharedConfigEnable,
},
))
return &Environment{
Region: *session.Config.Region,
Environment: env,
STSAPI: sts.New(session),
EC2API: ec2.New(session),
SSMAPI: ssm.New(session),
IAMAPI: iam.New(session),
FISAPI: fis.New(session),
EKSAPI: eks.New(session),
CloudwatchAPI: GetCloudWatchAPI(session),
SQSProvider: interruption.NewSQSProvider(sqs.New(session)),
}
}
func GetCloudWatchAPI(session *session.Session) cloudwatchiface.CloudWatchAPI {
if lo.Must(env.GetBool("ENABLE_CLOUDWATCH", false)) {
By("enabling cloudwatch metrics firing for this suite")
return cloudwatch.New(session)
}
return &NoOpCloudwatchAPI{}
}
| 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 aws
import (
"fmt"
"net"
"strconv"
"strings"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/fis"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/aws-sdk-go/service/sts"
. "github.com/onsi/ginkgo/v2" //nolint:revive,stylecheck
. "github.com/onsi/gomega" //nolint:revive,stylecheck
"github.com/samber/lo"
"go.uber.org/multierr"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
// Spot Interruption experiment details partially copied from
// https://github.com/aws/amazon-ec2-spot-interrupter/blob/main/pkg/itn/itn.go
const (
fisRoleName = "FISInterruptionRole"
fisTargetLimit = 5
spotITNAction = "aws:ec2:send-spot-instance-interruptions"
)
func (env *Environment) ExpectWindowsIPAMEnabled() {
GinkgoHelper()
env.ExpectConfigMapDataOverridden(types.NamespacedName{Namespace: "kube-system", Name: "amazon-vpc-cni"}, map[string]string{
"enable-windows-ipam": "true",
})
}
func (env *Environment) ExpectWindowsIPAMDisabled() {
GinkgoHelper()
env.ExpectConfigMapDataOverridden(types.NamespacedName{Namespace: "kube-system", Name: "amazon-vpc-cni"}, map[string]string{
"enable-windows-ipam": "false",
})
}
func (env *Environment) ExpectInstance(nodeName string) Assertion {
return Expect(env.GetInstance(nodeName))
}
func (env *Environment) ExpectIPv6ClusterDNS() string {
dnsService, err := env.Environment.KubeClient.CoreV1().Services("kube-system").Get(env.Context, "kube-dns", metav1.GetOptions{})
Expect(err).ToNot(HaveOccurred())
kubeDNSIP := net.ParseIP(dnsService.Spec.ClusterIP)
Expect(kubeDNSIP.To4()).To(BeNil())
return kubeDNSIP.String()
}
func (env *Environment) ExpectSpotInterruptionExperiment(instanceIDs ...string) *fis.Experiment {
GinkgoHelper()
template := &fis.CreateExperimentTemplateInput{
Actions: map[string]*fis.CreateExperimentTemplateActionInput{},
Targets: map[string]*fis.CreateExperimentTemplateTargetInput{},
StopConditions: []*fis.CreateExperimentTemplateStopConditionInput{{Source: aws.String("none")}},
RoleArn: env.ExpectSpotInterruptionRole().Arn,
Description: aws.String(fmt.Sprintf("trigger spot ITN for instances %v", instanceIDs)),
}
for j, ids := range lo.Chunk(instanceIDs, fisTargetLimit) {
key := fmt.Sprintf("itn%d", j)
template.Actions[key] = &fis.CreateExperimentTemplateActionInput{
ActionId: aws.String(spotITNAction),
Parameters: map[string]*string{
// durationBeforeInterruption is the time before the instance is terminated, so we add 2 minutes
"durationBeforeInterruption": aws.String("PT120S"),
},
Targets: map[string]*string{"SpotInstances": aws.String(key)},
}
template.Targets[key] = &fis.CreateExperimentTemplateTargetInput{
ResourceType: aws.String("aws:ec2:spot-instance"),
SelectionMode: aws.String("ALL"),
ResourceArns: aws.StringSlice(lo.Map(ids, func(id string, _ int) string {
return fmt.Sprintf("arn:aws:ec2:%s:%s:instance/%s", env.Region, env.ExpectAccountID(), id)
})),
}
}
experimentTemplate, err := env.FISAPI.CreateExperimentTemplateWithContext(env.Context, template)
Expect(err).ToNot(HaveOccurred())
experiment, err := env.FISAPI.StartExperimentWithContext(env.Context, &fis.StartExperimentInput{ExperimentTemplateId: experimentTemplate.ExperimentTemplate.Id})
Expect(err).ToNot(HaveOccurred())
return experiment.Experiment
}
func (env *Environment) ExpectExperimentTemplateDeleted(id string) {
GinkgoHelper()
_, err := env.FISAPI.DeleteExperimentTemplateWithContext(env.Context, &fis.DeleteExperimentTemplateInput{
Id: aws.String(id),
})
Expect(err).ToNot(HaveOccurred())
}
func (env *Environment) GetInstance(nodeName string) ec2.Instance {
node := env.Environment.GetNode(nodeName)
return env.GetInstanceByIDWithOffset(1, env.ExpectParsedProviderID(node.Spec.ProviderID))
}
func (env *Environment) ExpectInstanceStopped(nodeName string) {
node := env.Environment.GetNode(nodeName)
_, err := env.EC2API.StopInstances(&ec2.StopInstancesInput{
Force: aws.Bool(true),
InstanceIds: aws.StringSlice([]string{env.ExpectParsedProviderID(node.Spec.ProviderID)}),
})
ExpectWithOffset(1, err).To(Succeed())
}
func (env *Environment) ExpectInstanceTerminated(nodeName string) {
node := env.Environment.GetNode(nodeName)
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: aws.StringSlice([]string{env.ExpectParsedProviderID(node.Spec.ProviderID)}),
})
ExpectWithOffset(1, err).To(Succeed())
}
func (env *Environment) GetInstanceByID(instanceID string) ec2.Instance {
return env.GetInstanceByIDWithOffset(1, instanceID)
}
func (env *Environment) GetInstanceByIDWithOffset(offset int, instanceID string) ec2.Instance {
instance, err := env.EC2API.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: aws.StringSlice([]string{instanceID}),
})
ExpectWithOffset(offset+1, err).ToNot(HaveOccurred())
ExpectWithOffset(offset+1, instance.Reservations).To(HaveLen(1))
ExpectWithOffset(offset+1, instance.Reservations[0].Instances).To(HaveLen(1))
return *instance.Reservations[0].Instances[0]
}
func (env *Environment) GetVolume(volumeID *string) ec2.Volume {
dvo, err := env.EC2API.DescribeVolumes(&ec2.DescribeVolumesInput{VolumeIds: []*string{volumeID}})
ExpectWithOffset(1, err).ToNot(HaveOccurred())
ExpectWithOffset(1, len(dvo.Volumes)).To(Equal(1))
return *dvo.Volumes[0]
}
// GetSubnets returns all subnets matching the label selector
// mapped from AZ -> {subnet-ids...}
func (env *Environment) GetSubnets(tags map[string]string) map[string][]string {
var filters []*ec2.Filter
for key, val := range tags {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(val)},
})
}
subnets := map[string][]string{}
err := env.EC2API.DescribeSubnetsPages(&ec2.DescribeSubnetsInput{Filters: filters}, func(dso *ec2.DescribeSubnetsOutput, _ bool) bool {
for _, subnet := range dso.Subnets {
subnets[*subnet.AvailabilityZone] = append(subnets[*subnet.AvailabilityZone], *subnet.SubnetId)
}
return true
})
Expect(err).To(BeNil())
return subnets
}
// SubnetInfo is a simple struct for testing
type SubnetInfo struct {
Name string
ID string
}
// GetSubnetNameAndIds returns all subnets matching the label selector
func (env *Environment) GetSubnetNameAndIds(tags map[string]string) []SubnetInfo {
var filters []*ec2.Filter
for key, val := range tags {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(val)},
})
}
var subnetInfo []SubnetInfo
err := env.EC2API.DescribeSubnetsPages(&ec2.DescribeSubnetsInput{Filters: filters}, func(dso *ec2.DescribeSubnetsOutput, _ bool) bool {
subnetInfo = lo.Map(dso.Subnets, func(s *ec2.Subnet, _ int) SubnetInfo {
elem := SubnetInfo{ID: aws.StringValue(s.SubnetId)}
if tag, ok := lo.Find(s.Tags, func(t *ec2.Tag) bool { return aws.StringValue(t.Key) == "Name" }); ok {
elem.Name = aws.StringValue(tag.Value)
}
return elem
})
return true
})
Expect(err).To(BeNil())
return subnetInfo
}
type SecurityGroup struct {
ec2.GroupIdentifier
Tags []*ec2.Tag
}
// GetSecurityGroups returns all getSecurityGroups matching the label selector
func (env *Environment) GetSecurityGroups(tags map[string]string) []SecurityGroup {
var filters []*ec2.Filter
for key, val := range tags {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(val)},
})
}
var securityGroups []SecurityGroup
err := env.EC2API.DescribeSecurityGroupsPages(&ec2.DescribeSecurityGroupsInput{Filters: filters}, func(dso *ec2.DescribeSecurityGroupsOutput, _ bool) bool {
for _, sg := range dso.SecurityGroups {
securityGroups = append(securityGroups, SecurityGroup{
Tags: sg.Tags,
GroupIdentifier: ec2.GroupIdentifier{GroupId: sg.GroupId, GroupName: sg.GroupName},
})
}
return true
})
Expect(err).To(BeNil())
return securityGroups
}
func (env *Environment) ExpectQueueExists() {
exists, err := env.SQSProvider.QueueExists(env.Context)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
ExpectWithOffset(1, exists).To(BeTrue())
}
func (env *Environment) ExpectMessagesCreated(msgs ...interface{}) {
wg := &sync.WaitGroup{}
mu := &sync.Mutex{}
var err error
for _, msg := range msgs {
wg.Add(1)
go func(m interface{}) {
defer wg.Done()
defer GinkgoRecover()
_, e := env.SQSProvider.SendMessage(env.Environment.Context, m)
if e != nil {
mu.Lock()
err = multierr.Append(err, e)
mu.Unlock()
}
}(msg)
}
wg.Wait()
ExpectWithOffset(1, err).To(Succeed())
}
func (env *Environment) ExpectParsedProviderID(providerID string) string {
providerIDSplit := strings.Split(providerID, "/")
ExpectWithOffset(1, len(providerIDSplit)).ToNot(Equal(0))
return providerIDSplit[len(providerIDSplit)-1]
}
func (env *Environment) GetCustomAMI(amiPath string, versionOffset int) string {
serverVersion, err := env.KubeClient.Discovery().ServerVersion()
Expect(err).To(BeNil())
minorVersion, err := strconv.Atoi(strings.TrimSuffix(serverVersion.Minor, "+"))
Expect(err).To(BeNil())
// Choose a minor version one lesser than the server's minor version. This ensures that we choose an AMI for
// this test that wouldn't be selected as Karpenter's SSM default (therefore avoiding false positives), and also
// ensures that we aren't violating version skew.
version := fmt.Sprintf("%s.%d", serverVersion.Major, minorVersion-versionOffset)
parameter, err := env.SSMAPI.GetParameter(&ssm.GetParameterInput{
Name: aws.String(fmt.Sprintf(amiPath, version)),
})
Expect(err).To(BeNil())
return *parameter.Parameter.Value
}
func (env *Environment) ExpectRunInstances(instanceInput *ec2.RunInstancesInput) *ec2.Reservation {
GinkgoHelper()
// implement IMDSv2
instanceInput.MetadataOptions = &ec2.InstanceMetadataOptionsRequest{
HttpEndpoint: aws.String("enabled"),
HttpTokens: aws.String("required"),
}
out, err := env.EC2API.RunInstances(instanceInput)
Expect(err).ToNot(HaveOccurred())
return out
}
func (env *Environment) ExpectSpotInterruptionRole() *iam.Role {
GinkgoHelper()
out, err := env.IAMAPI.GetRoleWithContext(env.Context, &iam.GetRoleInput{
RoleName: aws.String(fisRoleName),
})
Expect(err).ToNot(HaveOccurred())
return out.Role
}
func (env *Environment) ExpectAccountID() string {
GinkgoHelper()
identity, err := env.STSAPI.GetCallerIdentityWithContext(env.Context, &sts.GetCallerIdentityInput{})
Expect(err).ToNot(HaveOccurred())
return aws.StringValue(identity.Account)
}
| 315 |
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 aws
import (
"strconv"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface"
. "github.com/onsi/ginkgo/v2" //nolint:revive,stylecheck
. "github.com/onsi/gomega" //nolint:revive,stylecheck
"github.com/samber/lo"
"github.com/aws/karpenter/test/pkg/environment/common"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
)
var _ cloudwatchiface.CloudWatchAPI = (*NoOpCloudwatchAPI)(nil)
type NoOpCloudwatchAPI struct {
cloudwatch.CloudWatch
}
func (o NoOpCloudwatchAPI) PutMetricData(_ *cloudwatch.PutMetricDataInput) (*cloudwatch.PutMetricDataOutput, error) {
return nil, nil
}
type EventType string
const (
ProvisioningEventType EventType = "provisioning"
DeprovisioningEventType EventType = "deprovisioning"
)
const (
scaleTestingMetricNamespace = v1alpha5.TestingGroup + "/scale"
TestEventTypeDimension = "eventType"
TestSubEventTypeDimension = "subEventType"
TestGroupDimension = "group"
TestNameDimension = "name"
GitRefDimension = "gitRef"
DeprovisionedNodeCountDimension = "deprovisionedNodeCount"
ProvisionedNodeCountDimension = "provisionedNodeCount"
PodDensityDimension = "podDensity"
)
// MeasureDurationFor observes the duration between the beginning of the function f() and the end of the function f()
func (env *Environment) MeasureDurationFor(f func(), eventType EventType, group, name string, additionalLabels map[string]string) {
GinkgoHelper()
start := time.Now()
f()
gitRef := "n/a"
if env.Context.Value(common.GitRefContextKey) != nil {
gitRef = env.Value(common.GitRefContextKey).(string)
}
env.ExpectEventDurationMetric(time.Since(start), lo.Assign(map[string]string{
TestEventTypeDimension: string(eventType),
TestGroupDimension: group,
TestNameDimension: name,
GitRefDimension: gitRef,
}, additionalLabels))
}
func (env *Environment) ExpectEventDurationMetric(d time.Duration, labels map[string]string) {
GinkgoHelper()
env.ExpectMetric("eventDuration", cloudwatch.StandardUnitSeconds, d.Seconds(), labels)
}
func (env *Environment) ExpectMetric(name string, unit string, value float64, labels map[string]string) {
GinkgoHelper()
_, err := env.CloudwatchAPI.PutMetricData(&cloudwatch.PutMetricDataInput{
Namespace: aws.String(scaleTestingMetricNamespace),
MetricData: []*cloudwatch.MetricDatum{
{
MetricName: aws.String(name),
Dimensions: lo.MapToSlice(labels, func(k, v string) *cloudwatch.Dimension {
return &cloudwatch.Dimension{
Name: aws.String(k),
Value: aws.String(v),
}
}),
Unit: aws.String(unit),
Value: aws.Float64(value),
Timestamp: aws.Time(time.Now()),
},
},
})
Expect(err).ToNot(HaveOccurred())
}
func GenerateTestDimensions(provisionedNodeCount, deprovisionedNodeCount, podDensity int) map[string]string {
return map[string]string{
DeprovisionedNodeCountDimension: strconv.Itoa(deprovisionedNodeCount),
ProvisionedNodeCountDimension: strconv.Itoa(provisionedNodeCount),
PodDensityDimension: strconv.Itoa(podDensity),
}
}
| 113 |
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 aws
import (
//nolint:revive,stylecheck
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var persistedSettings *v1.ConfigMap
var (
CleanableObjects = []functional.Pair[client.Object, client.ObjectList]{
{First: &v1alpha1.AWSNodeTemplate{}, Second: &v1alpha1.AWSNodeTemplateList{}},
}
)
func (env *Environment) BeforeEach() {
persistedSettings = env.ExpectSettings()
env.Environment.BeforeEach()
}
func (env *Environment) Cleanup() {
env.Environment.CleanupObjects(CleanableObjects...)
env.Environment.Cleanup()
}
func (env *Environment) AfterEach() {
env.Environment.AfterEach()
// Ensure we reset settings after collecting the controller logs
env.ExpectSettingsReplaced(persistedSettings.Data)
}
| 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 common
import (
"context"
"fmt"
"os"
"testing"
"time"
"github.com/onsi/gomega"
"github.com/samber/lo"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
loggingtesting "knative.dev/pkg/logging/testing"
"knative.dev/pkg/system"
controllerruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
coreapis "github.com/aws/karpenter-core/pkg/apis"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter/pkg/apis"
"github.com/aws/karpenter/pkg/utils/project"
)
type ContextKey string
const (
GitRefContextKey = ContextKey("gitRef")
)
type Environment struct {
context.Context
Client client.Client
Config *rest.Config
KubeClient kubernetes.Interface
Monitor *Monitor
StartingNodeCount int
}
func NewEnvironment(t *testing.T) *Environment {
ctx := loggingtesting.TestContextWithLogger(t)
config := NewConfig()
client := lo.Must(NewClient(config))
lo.Must0(os.Setenv(system.NamespaceEnvKey, "karpenter"))
kubernetesInterface := kubernetes.NewForConfigOrDie(config)
ctx = injection.WithSettingsOrDie(ctx, kubernetesInterface, apis.Settings...)
if val, ok := os.LookupEnv("GIT_REF"); ok {
ctx = context.WithValue(ctx, GitRefContextKey, val)
}
gomega.SetDefaultEventuallyTimeout(5 * time.Minute)
gomega.SetDefaultEventuallyPollingInterval(1 * time.Second)
return &Environment{
Context: ctx,
Config: config,
Client: client,
KubeClient: kubernetes.NewForConfigOrDie(config),
Monitor: NewMonitor(ctx, client),
}
}
func NewConfig() *rest.Config {
config := controllerruntime.GetConfigOrDie()
config.UserAgent = fmt.Sprintf("testing.karpenter.sh-%s", project.Version)
return config
}
func NewClient(config *rest.Config) (client.Client, error) {
scheme := runtime.NewScheme()
if err := clientgoscheme.AddToScheme(scheme); err != nil {
return nil, err
}
if err := apis.AddToScheme(scheme); err != nil {
return nil, err
}
if err := coreapis.AddToScheme(scheme); err != nil {
return nil, err
}
return client.New(config, client.Options{Scheme: scheme})
}
| 100 |
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 common
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"strings"
"time"
. "github.com/onsi/ginkgo/v2" //nolint:revive,stylecheck
. "github.com/onsi/gomega" //nolint:revive,stylecheck
"github.com/samber/lo"
appsv1 "k8s.io/api/apps/v1"
coordinationv1 "k8s.io/api/coordination/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/transport"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
pscheduling "github.com/aws/karpenter-core/pkg/controllers/provisioning/scheduling"
"github.com/aws/karpenter-core/pkg/scheduling"
"github.com/aws/karpenter-core/pkg/test"
)
func (env *Environment) ExpectCreatedWithOffset(offset int, objects ...client.Object) {
for _, object := range objects {
object.SetLabels(lo.Assign(object.GetLabels(), map[string]string{
test.DiscoveryLabel: "unspecified",
}))
ExpectWithOffset(offset+1, env.Client.Create(env, object)).To(Succeed())
}
}
func (env *Environment) ExpectCreated(objects ...client.Object) {
env.ExpectCreatedWithOffset(1, objects...)
}
func (env *Environment) ExpectDeletedWithOffset(offset int, objects ...client.Object) {
for _, object := range objects {
ExpectWithOffset(offset+1, env.Client.Delete(env, object, client.PropagationPolicy(metav1.DeletePropagationForeground), &client.DeleteOptions{GracePeriodSeconds: ptr.Int64(0)})).To(Succeed())
}
}
func (env *Environment) ExpectDeleted(objects ...client.Object) {
env.ExpectDeletedWithOffset(1, objects...)
}
func (env *Environment) ExpectUpdatedWithOffset(offset int, objects ...client.Object) {
for _, o := range objects {
current := o.DeepCopyObject().(client.Object)
ExpectWithOffset(offset+1, env.Client.Get(env.Context, client.ObjectKeyFromObject(current), current)).To(Succeed())
o.SetResourceVersion(current.GetResourceVersion())
ExpectWithOffset(offset+1, env.Client.Update(env.Context, o)).To(Succeed())
}
}
func (env *Environment) ExpectUpdated(objects ...client.Object) {
env.ExpectUpdatedWithOffset(1, objects...)
}
func (env *Environment) ExpectCreatedOrUpdated(objects ...client.Object) {
for _, o := range objects {
current := o.DeepCopyObject().(client.Object)
err := env.Client.Get(env, client.ObjectKeyFromObject(current), current)
if err != nil {
if errors.IsNotFound(err) {
env.ExpectCreatedWithOffset(1, o)
} else {
Fail(fmt.Sprintf("Getting object %s, %v", client.ObjectKeyFromObject(o), err))
}
} else {
env.ExpectUpdatedWithOffset(1, o)
}
}
}
// ExpectSettings gets the karpenter-global-settings ConfigMap
func (env *Environment) ExpectSettings() *v1.ConfigMap {
GinkgoHelper()
return env.ExpectConfigMapExists(types.NamespacedName{Namespace: "karpenter", Name: "karpenter-global-settings"})
}
// ExpectSettingsReplaced performs a full replace of the settings, replacing the existing data
// with the data passed through
func (env *Environment) ExpectSettingsReplaced(data ...map[string]string) {
GinkgoHelper()
if env.ExpectConfigMapDataReplaced(types.NamespacedName{Namespace: "karpenter", Name: "karpenter-global-settings"}, data...) {
env.EventuallyExpectKarpenterRestarted()
}
}
// ExpectSettingsOverridden overrides specific values specified through data. It only overrides
// or inserts the specific values specified and does not upsert any of the existing data
func (env *Environment) ExpectSettingsOverridden(data ...map[string]string) {
GinkgoHelper()
if env.ExpectConfigMapDataOverridden(types.NamespacedName{Namespace: "karpenter", Name: "karpenter-global-settings"}, data...) {
env.EventuallyExpectKarpenterRestarted()
}
}
func (env *Environment) ExpectConfigMapExists(key types.NamespacedName) *v1.ConfigMap {
GinkgoHelper()
cm := &v1.ConfigMap{}
Expect(env.Client.Get(env, key, cm)).To(Succeed())
return cm
}
func (env *Environment) ExpectConfigMapDataReplaced(key types.NamespacedName, data ...map[string]string) (changed bool) {
GinkgoHelper()
cm := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
}
err := env.Client.Get(env, key, cm)
Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred())
stored := cm.DeepCopy()
cm.Data = lo.Assign(data...) // Completely replace the data
// If the data hasn't changed, we can just return and not update anything
if equality.Semantic.DeepEqual(stored, cm) {
return false
}
// Update the configMap to update the settings
env.ExpectCreatedOrUpdated(cm)
return true
}
func (env *Environment) ExpectConfigMapDataOverridden(key types.NamespacedName, data ...map[string]string) (changed bool) {
GinkgoHelper()
cm := &v1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: key.Name,
Namespace: key.Namespace,
},
}
err := env.Client.Get(env, key, cm)
Expect(client.IgnoreNotFound(err)).ToNot(HaveOccurred())
stored := cm.DeepCopy()
cm.Data = lo.Assign(append([]map[string]string{cm.Data}, data...)...)
// If the data hasn't changed, we can just return and not update anything
if equality.Semantic.DeepEqual(stored, cm) {
return false
}
// Update the configMap to update the settings
env.ExpectCreatedOrUpdated(cm)
return true
}
func (env *Environment) ExpectPodENIEnabled() {
env.ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(1, types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_POD_ENI", "true")
}
func (env *Environment) ExpectPodENIDisabled() {
env.ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(1, types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_POD_ENI", "false")
}
func (env *Environment) ExpectPrefixDelegationEnabled() {
env.ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(1, types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_PREFIX_DELEGATION", "true")
}
func (env *Environment) ExpectPrefixDelegationDisabled() {
env.ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(1, types.NamespacedName{Namespace: "kube-system", Name: "aws-node"},
"ENABLE_PREFIX_DELEGATION", "false")
}
func (env *Environment) ExpectExists(obj client.Object) {
ExpectWithOffset(1, env.Client.Get(env, client.ObjectKeyFromObject(obj), obj)).To(Succeed())
}
func (env *Environment) EventuallyExpectHealthy(pods ...*v1.Pod) {
GinkgoHelper()
env.EventuallyExpectHealthyWithTimeout(-1, pods...)
}
func (env *Environment) EventuallyExpectHealthyWithTimeout(timeout time.Duration, pods ...*v1.Pod) {
GinkgoHelper()
for _, pod := range pods {
Eventually(func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(pod), pod)).To(Succeed())
g.Expect(pod.Status.Conditions).To(ContainElement(And(
HaveField("Type", Equal(v1.PodReady)),
HaveField("Status", Equal(v1.ConditionTrue)),
)))
}).WithTimeout(timeout).Should(Succeed())
}
}
func (env *Environment) EventuallyExpectKarpenterRestarted() {
GinkgoHelper()
By("rolling out the new karpenter deployment")
env.EventuallyExpectRollout("karpenter", "karpenter")
By("waiting for a new karpenter pod to hold the lease")
pods := env.ExpectKarpenterPods()
Eventually(func(g Gomega) {
name := env.ExpectActiveKarpenterPodName()
g.Expect(lo.ContainsBy(pods, func(p *v1.Pod) bool {
return p.Name == name
})).To(BeTrue())
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectRollout(name, namespace string) {
GinkgoHelper()
By("restarting the deployment")
deploy := &appsv1.Deployment{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: name, Namespace: namespace}, deploy)).To(Succeed())
stored := deploy.DeepCopy()
restartedAtAnnotation := map[string]string{
"kubectl.kubernetes.io/restartedAt": time.Now().Format(time.RFC3339),
}
deploy.Spec.Template.Annotations = lo.Assign(deploy.Spec.Template.Annotations, restartedAtAnnotation)
Expect(env.Client.Patch(env.Context, deploy, client.MergeFrom(stored))).To(Succeed())
By("waiting for the newly generated deployment to rollout")
Eventually(func(g Gomega) {
podList := &v1.PodList{}
g.Expect(env.Client.List(env.Context, podList, client.InNamespace(namespace))).To(Succeed())
pods := lo.Filter(podList.Items, func(p v1.Pod, _ int) bool {
return p.Annotations["kubectl.kubernetes.io/restartedAt"] == restartedAtAnnotation["kubectl.kubernetes.io/restartedAt"]
})
g.Expect(len(pods)).To(BeNumerically("==", lo.FromPtr(deploy.Spec.Replicas)))
for _, pod := range pods {
g.Expect(pod.Status.Conditions).To(ContainElement(And(
HaveField("Type", Equal(v1.PodReady)),
HaveField("Status", Equal(v1.ConditionTrue)),
)))
g.Expect(pod.Status.Phase).To(Equal(v1.PodRunning))
}
}).Should(Succeed())
}
func (env *Environment) ExpectKarpenterPods() []*v1.Pod {
GinkgoHelper()
podList := &v1.PodList{}
Expect(env.Client.List(env.Context, podList, client.MatchingLabels{
"app.kubernetes.io/instance": "karpenter",
})).To(Succeed())
return lo.Map(podList.Items, func(p v1.Pod, _ int) *v1.Pod { return &p })
}
func (env *Environment) ExpectActiveKarpenterPodName() string {
GinkgoHelper()
lease := &coordinationv1.Lease{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: "karpenter-leader-election", Namespace: "karpenter"}, lease)).To(Succeed())
// Holder identity for lease is always in the format "<pod-name>_<pseudo-random-value>
holderArr := strings.Split(lo.FromPtr(lease.Spec.HolderIdentity), "_")
Expect(len(holderArr)).To(BeNumerically(">", 0))
return holderArr[0]
}
func (env *Environment) ExpectActiveKarpenterPod() *v1.Pod {
GinkgoHelper()
podName := env.ExpectActiveKarpenterPodName()
pod := &v1.Pod{}
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: podName, Namespace: "karpenter"}, pod)).To(Succeed())
return pod
}
func (env *Environment) EventuallyExpectPendingPodCount(selector labels.Selector, numPods int) {
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Monitor.PendingPodsCount(selector)).To(Equal(numPods))
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectHealthyPodCount(selector labels.Selector, numPods int) {
By(fmt.Sprintf("waiting for %d pods matching selector %s to be ready", numPods, selector.String()))
GinkgoHelper()
env.EventuallyExpectHealthyPodCountWithTimeout(-1, selector, numPods)
}
func (env *Environment) EventuallyExpectHealthyPodCountWithTimeout(timeout time.Duration, selector labels.Selector, numPods int) {
GinkgoHelper()
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Monitor.RunningPodsCount(selector)).To(Equal(numPods))
}).WithTimeout(timeout).Should(Succeed())
}
func (env *Environment) ExpectUniqueNodeNames(selector labels.Selector, uniqueNames int) {
pods := env.Monitor.RunningPods(selector)
nodeNames := sets.NewString()
for _, pod := range pods {
nodeNames.Insert(pod.Spec.NodeName)
}
ExpectWithOffset(1, len(nodeNames)).To(BeNumerically("==", uniqueNames))
}
func (env *Environment) eventuallyExpectScaleDown() {
EventuallyWithOffset(1, func(g Gomega) {
// expect the current node count to be what it was when the test started
g.Expect(env.Monitor.NodeCount()).To(Equal(env.StartingNodeCount))
}).Should(Succeed(), fmt.Sprintf("expected scale down to %d nodes, had %d", env.StartingNodeCount, env.Monitor.NodeCount()))
}
func (env *Environment) EventuallyExpectNotFound(objects ...client.Object) {
env.EventuallyExpectNotFoundWithOffset(1, objects...)
}
func (env *Environment) EventuallyExpectNotFoundWithOffset(offset int, objects ...client.Object) {
env.EventuallyExpectNotFoundAssertionWithOffset(offset+1, objects...).Should(Succeed())
}
func (env *Environment) EventuallyExpectNotFoundAssertion(objects ...client.Object) AsyncAssertion {
return env.EventuallyExpectNotFoundAssertionWithOffset(1, objects...)
}
func (env *Environment) EventuallyExpectNotFoundAssertionWithOffset(offset int, objects ...client.Object) AsyncAssertion {
return EventuallyWithOffset(offset, func(g Gomega) {
for _, object := range objects {
err := env.Client.Get(env, client.ObjectKeyFromObject(object), object)
g.Expect(errors.IsNotFound(err)).To(BeTrue())
}
})
}
func (env *Environment) ExpectCreatedNodeCount(comparator string, count int) []*v1.Node {
createdNodes := env.Monitor.CreatedNodes()
ExpectWithOffset(1, len(createdNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d created nodes, had %d (%v)", count, len(createdNodes), NodeNames(createdNodes)))
return createdNodes
}
func NodeNames(nodes []*v1.Node) []string {
return lo.Map(nodes, func(n *v1.Node, index int) string {
return n.Name
})
}
func (env *Environment) EventuallyExpectNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for nodes to be %s to %d", comparator, count))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodes, had %d (%v)", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) EventuallyExpectNodeCountWithSelector(comparator string, count int, selector labels.Selector) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for nodes with selector %v to be %s to %d", selector, comparator, count))
nodeList := &v1.NodeList{}
Eventually(func(g Gomega) {
g.Expect(env.Client.List(env, nodeList, client.HasLabels{test.DiscoveryLabel}, client.MatchingLabelsSelector{Selector: selector})).To(Succeed())
g.Expect(len(nodeList.Items)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d nodes, had %d (%v)", count, len(nodeList.Items), NodeNames(lo.ToSlicePtr(nodeList.Items))))
}).Should(Succeed())
return lo.ToSlicePtr(nodeList.Items)
}
func (env *Environment) EventuallyExpectCreatedNodeCount(comparator string, count int) []*v1.Node {
By(fmt.Sprintf("waiting for created nodes to be %s to %d", comparator, count))
var createdNodes []*v1.Node
EventuallyWithOffset(1, func(g Gomega) {
createdNodes = env.Monitor.CreatedNodes()
g.Expect(len(createdNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d created nodes, had %d (%v)", count, len(createdNodes), NodeNames(createdNodes)))
}).Should(Succeed())
return createdNodes
}
func (env *Environment) EventuallyExpectDeletedNodeCount(comparator string, count int) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for deleted nodes to be %s to %d", comparator, count))
var deletedNodes []*v1.Node
Eventually(func(g Gomega) {
deletedNodes = env.Monitor.DeletedNodes()
g.Expect(len(deletedNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d deleted nodes, had %d (%v)", count, len(deletedNodes), NodeNames(deletedNodes)))
}).Should(Succeed())
return deletedNodes
}
func (env *Environment) EventuallyExpectDeletedNodeCountWithSelector(comparator string, count int, selector labels.Selector) []*v1.Node {
GinkgoHelper()
By(fmt.Sprintf("waiting for deleted nodes with selector %v to be %s to %d", selector, comparator, count))
var deletedNodes []*v1.Node
Eventually(func(g Gomega) {
deletedNodes = env.Monitor.DeletedNodes()
deletedNodes = lo.Filter(deletedNodes, func(n *v1.Node, _ int) bool {
return selector.Matches(labels.Set(n.Labels))
})
g.Expect(len(deletedNodes)).To(BeNumerically(comparator, count),
fmt.Sprintf("expected %d deleted nodes, had %d (%v)", count, len(deletedNodes), NodeNames(deletedNodes)))
}).Should(Succeed())
return deletedNodes
}
func (env *Environment) EventuallyExpectInitializedNodeCount(comparator string, count int) []*v1.Node {
By(fmt.Sprintf("waiting for initialized nodes to be %s to %d", comparator, count))
var nodes []*v1.Node
EventuallyWithOffset(1, func(g Gomega) {
nodes = env.Monitor.CreatedNodes()
nodes = lo.Filter(nodes, func(n *v1.Node, _ int) bool {
return n.Labels[v1alpha5.LabelNodeInitialized] == "true"
})
g.Expect(len(nodes)).To(BeNumerically(comparator, count))
}).Should(Succeed())
return nodes
}
func (env *Environment) EventuallyExpectCreatedMachineCount(comparator string, count int) []*v1alpha5.Machine {
By(fmt.Sprintf("waiting for created machines to be %s to %d", comparator, count))
machineList := &v1alpha5.MachineList{}
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Client.List(env.Context, machineList)).To(Succeed())
g.Expect(len(machineList.Items)).To(BeNumerically(comparator, count))
}).Should(Succeed())
return lo.Map(machineList.Items, func(m v1alpha5.Machine, _ int) *v1alpha5.Machine {
return &m
})
}
func (env *Environment) EventuallyExpectMachinesReady(machines ...*v1alpha5.Machine) {
Eventually(func(g Gomega) {
for _, machine := range machines {
temp := &v1alpha5.Machine{}
g.Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(machine), temp)).Should(Succeed())
g.Expect(temp.StatusConditions().IsHappy()).To(BeTrue())
}
}).Should(Succeed())
}
func (env *Environment) GetNode(nodeName string) v1.Node {
var node v1.Node
ExpectWithOffset(1, env.Client.Get(env.Context, types.NamespacedName{Name: nodeName}, &node)).To(Succeed())
return node
}
func (env *Environment) ExpectNoCrashes() {
_, crashed := lo.Find(lo.Values(env.Monitor.RestartCount()), func(restartCount int) bool {
return restartCount > 0
})
ExpectWithOffset(1, crashed).To(BeFalse(), "expected karpenter containers to not crash")
}
var (
lastLogged = metav1.Now()
)
func (env *Environment) printControllerLogs(options *v1.PodLogOptions) {
fmt.Println("------- START CONTROLLER LOGS -------")
defer fmt.Println("------- END CONTROLLER LOGS -------")
if options.SinceTime == nil {
options.SinceTime = lastLogged.DeepCopy()
lastLogged = metav1.Now()
}
pods := env.ExpectKarpenterPods()
for _, pod := range pods {
temp := options.DeepCopy() // local version of the log options
fmt.Printf("------- pod/%s -------\n", pod.Name)
if pod.Status.ContainerStatuses[0].RestartCount > 0 {
fmt.Printf("[PREVIOUS CONTAINER LOGS]\n")
temp.Previous = true
}
stream, err := env.KubeClient.CoreV1().Pods("karpenter").GetLogs(pod.Name, temp).Stream(env.Context)
if err != nil {
logging.FromContext(env.Context).Errorf("fetching controller logs: %s", err)
return
}
log := &bytes.Buffer{}
_, err = io.Copy(log, stream)
Expect(err).ToNot(HaveOccurred())
logging.FromContext(env.Context).Info(log)
}
}
func (env *Environment) EventuallyExpectMinUtilization(resource v1.ResourceName, comparator string, value float64) {
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Monitor.MinUtilization(resource)).To(BeNumerically(comparator, value))
}).Should(Succeed())
}
func (env *Environment) EventuallyExpectAvgUtilization(resource v1.ResourceName, comparator string, value float64) {
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Monitor.AvgUtilization(resource)).To(BeNumerically(comparator, value))
}, 10*time.Minute).Should(Succeed())
}
func (env *Environment) ExpectDaemonSetEnvironmentVariableUpdated(obj client.ObjectKey, name, value string) {
env.ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(1, obj, name, value)
}
func (env *Environment) ExpectDaemonSetEnvironmentVariableUpdatedWithOffset(offset int, obj client.ObjectKey, name, value string) {
ds := &appsv1.DaemonSet{}
ExpectWithOffset(offset+1, env.Client.Get(env.Context, obj, ds)).To(Succeed())
ExpectWithOffset(offset+1, len(ds.Spec.Template.Spec.Containers)).To(BeNumerically("==", 1))
patch := client.MergeFrom(ds.DeepCopy())
// If the value is found, update it. Else, create it
found := false
for i, v := range ds.Spec.Template.Spec.Containers[0].Env {
if v.Name == name {
ds.Spec.Template.Spec.Containers[0].Env[i].Value = value
found = true
}
}
if !found {
ds.Spec.Template.Spec.Containers[0].Env = append(ds.Spec.Template.Spec.Containers[0].Env, v1.EnvVar{
Name: name,
Value: value,
})
}
ExpectWithOffset(offset+1, env.Client.Patch(env.Context, ds, patch)).To(Succeed())
}
func (env *Environment) ExpectCABundle() string {
// 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 := env.Config.TransportConfig()
ExpectWithOffset(1, err).ToNot(HaveOccurred())
_, err = transport.TLSConfigFor(transportConfig) // fills in CAData!
ExpectWithOffset(1, err).ToNot(HaveOccurred())
logging.FromContext(env.Context).Debugf("Discovered caBundle, length %d", len(transportConfig.TLS.CAData))
return base64.StdEncoding.EncodeToString(transportConfig.TLS.CAData)
}
func (env *Environment) GetDaemonSetCount(prov *v1alpha5.Provisioner) int {
// Performs the same logic as the scheduler to get the number of daemonset
// pods that we estimate we will need to schedule as overhead to each node
daemonSetList := &appsv1.DaemonSetList{}
Expect(env.Client.List(env.Context, daemonSetList)).To(Succeed())
return lo.CountBy(daemonSetList.Items, func(d appsv1.DaemonSet) bool {
p := &v1.Pod{Spec: d.Spec.Template.Spec}
nodeTemplate := pscheduling.NewMachineTemplate(prov)
if err := nodeTemplate.Taints.Tolerates(p); err != nil {
return false
}
if err := nodeTemplate.Requirements.Compatible(scheduling.NewPodRequirements(p)); err != nil {
return false
}
return true
})
}
| 577 |
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 common
import (
"context"
"fmt"
"math"
"sync"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/utils/resources"
)
// Monitor is used to monitor the cluster state during a running test
type Monitor struct {
ctx context.Context
kubeClient client.Client
mu sync.RWMutex
nodesAtReset map[string]*v1.Node
}
type state struct {
pods v1.PodList
nodes map[string]*v1.Node // node name -> node
nodePods map[string][]*v1.Pod // node name -> pods bound to the node
nodeRequests map[string]v1.ResourceList // node name -> sum of pod resource requests
}
func NewMonitor(ctx context.Context, kubeClient client.Client) *Monitor {
m := &Monitor{
ctx: ctx,
kubeClient: kubeClient,
nodesAtReset: map[string]*v1.Node{},
}
m.Reset()
return m
}
// Reset resets the cluster monitor prior to running a test.
func (m *Monitor) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
st := m.poll()
m.nodesAtReset = deepCopyMap(st.nodes)
}
// RestartCount returns the containers and number of restarts for that container for all containers in the pods in the
// given namespace
func (m *Monitor) RestartCount() map[string]int {
st := m.poll()
m.mu.RLock()
defer m.mu.RUnlock()
restarts := map[string]int{}
for _, pod := range st.pods.Items {
if pod.Namespace != "karpenter" {
continue
}
for _, cs := range pod.Status.ContainerStatuses {
name := fmt.Sprintf("%s/%s", pod.Name, cs.Name)
restarts[name] = int(cs.RestartCount)
}
}
return restarts
}
// NodeCount returns the current number of nodes
func (m *Monitor) NodeCount() int {
return len(m.poll().nodes)
}
// NodeCountAtReset returns the number of nodes that were running when the monitor was last reset, typically at the
// beginning of a test
func (m *Monitor) NodeCountAtReset() int {
return len(m.NodesAtReset())
}
// CreatedNodeCount returns the number of nodes created since the last reset
func (m *Monitor) CreatedNodeCount() int {
return m.NodeCount() - m.NodeCountAtReset()
}
// NodesAtReset returns a slice of nodes that the monitor saw at the last reset
func (m *Monitor) NodesAtReset() []*v1.Node {
m.mu.RLock()
defer m.mu.RUnlock()
return deepCopySlice(lo.Values(m.nodesAtReset))
}
// Nodes returns all the nodes on the cluster
func (m *Monitor) Nodes() []*v1.Node {
st := m.poll()
return lo.Values(st.nodes)
}
// CreatedNodes returns the nodes that have been created since the last reset (essentially Nodes - NodesAtReset)
func (m *Monitor) CreatedNodes() []*v1.Node {
resetNodeNames := sets.NewString(lo.Map(m.NodesAtReset(), func(n *v1.Node, _ int) string { return n.Name })...)
return lo.Filter(m.Nodes(), func(n *v1.Node, _ int) bool { return !resetNodeNames.Has(n.Name) })
}
// DeletedNodes returns the nodes that have been deleted since the last reset (essentially NodesAtReset - Nodes)
func (m *Monitor) DeletedNodes() []*v1.Node {
currentNodeNames := sets.NewString(lo.Map(m.Nodes(), func(n *v1.Node, _ int) string { return n.Name })...)
return lo.Filter(m.NodesAtReset(), func(n *v1.Node, _ int) bool { return !currentNodeNames.Has(n.Name) })
}
// PendingPods returns the number of pending pods matching the given selector
func (m *Monitor) PendingPods(selector labels.Selector) []*v1.Pod {
var pods []*v1.Pod
for _, pod := range m.poll().pods.Items {
pod := pod
if pod.Status.Phase != v1.PodPending {
continue
}
if selector.Matches(labels.Set(pod.Labels)) {
pods = append(pods, &pod)
}
}
return pods
}
func (m *Monitor) PendingPodsCount(selector labels.Selector) int {
return len(m.PendingPods(selector))
}
// RunningPods returns the number of running pods matching the given selector
func (m *Monitor) RunningPods(selector labels.Selector) []*v1.Pod {
var pods []*v1.Pod
for _, pod := range m.poll().pods.Items {
pod := pod
if pod.Status.Phase != v1.PodRunning {
continue
}
if selector.Matches(labels.Set(pod.Labels)) {
pods = append(pods, &pod)
}
}
return pods
}
func (m *Monitor) RunningPodsCount(selector labels.Selector) int {
return len(m.RunningPods(selector))
}
func (m *Monitor) poll() state {
var nodes v1.NodeList
if err := m.kubeClient.List(m.ctx, &nodes); err != nil {
logging.FromContext(m.ctx).Errorf("listing nodes, %s", err)
}
var pods v1.PodList
if err := m.kubeClient.List(m.ctx, &pods); err != nil {
logging.FromContext(m.ctx).Errorf("listing pods, %s", err)
}
st := state{
nodes: map[string]*v1.Node{},
pods: pods,
nodePods: map[string][]*v1.Pod{},
nodeRequests: map[string]v1.ResourceList{},
}
for i := range nodes.Items {
st.nodes[nodes.Items[i].Name] = &nodes.Items[i]
}
// collect pods per node
for i := range pods.Items {
pod := &pods.Items[i]
if pod.Spec.NodeName == "" {
continue
}
st.nodePods[pod.Spec.NodeName] = append(st.nodePods[pod.Spec.NodeName], pod)
}
for _, n := range nodes.Items {
st.nodeRequests[n.Name] = resources.RequestsForPods(st.nodePods[n.Name]...)
}
return st
}
func (m *Monitor) AvgUtilization(resource v1.ResourceName) float64 {
utilization := m.nodeUtilization(resource)
sum := 0.0
for _, v := range utilization {
sum += v
}
return sum / float64(len(utilization))
}
func (m *Monitor) MinUtilization(resource v1.ResourceName) float64 {
min := math.MaxFloat64
for _, v := range m.nodeUtilization(resource) {
min = math.Min(v, min)
}
return min
}
func (m *Monitor) nodeUtilization(resource v1.ResourceName) []float64 {
st := m.poll()
var utilization []float64
for nodeName, requests := range st.nodeRequests {
allocatable := st.nodes[nodeName].Status.Allocatable[resource]
// skip any nodes we didn't launch
if _, ok := st.nodes[nodeName].Labels[v1alpha5.ProvisionerNameLabelKey]; !ok {
continue
}
if allocatable.IsZero() {
continue
}
requested := requests[resource]
utilization = append(utilization, requested.AsApproximateFloat64()/allocatable.AsApproximateFloat64())
}
return utilization
}
type copyable[T any] interface {
DeepCopy() T
}
func deepCopyMap[K comparable, V copyable[V]](m map[K]V) map[K]V {
ret := map[K]V{}
for k, v := range m {
ret[k] = v.DeepCopy()
}
return ret
}
func deepCopySlice[T copyable[T]](s []T) []T {
var ret []T
for _, elem := range s {
ret = append(ret, elem.DeepCopy())
}
return ret
}
| 257 |
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 common
import (
"fmt"
"sync"
. "github.com/onsi/ginkgo/v2" //nolint:revive,stylecheck
. "github.com/onsi/gomega" //nolint:revive,stylecheck
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/pod"
"github.com/aws/karpenter/test/pkg/debug"
)
var (
CleanableObjects = []functional.Pair[client.Object, client.ObjectList]{
{First: &v1.Pod{}, Second: &v1.PodList{}},
{First: &appsv1.Deployment{}, Second: &appsv1.DeploymentList{}},
{First: &appsv1.DaemonSet{}, Second: &appsv1.DaemonSetList{}},
{First: &policyv1.PodDisruptionBudget{}, Second: &policyv1.PodDisruptionBudgetList{}},
{First: &v1.PersistentVolumeClaim{}, Second: &v1.PersistentVolumeClaimList{}},
{First: &v1.PersistentVolume{}, Second: &v1.PersistentVolumeList{}},
{First: &storagev1.StorageClass{}, Second: &storagev1.StorageClassList{}},
{First: &v1alpha5.Provisioner{}, Second: &v1alpha5.ProvisionerList{}},
{First: &v1.LimitRange{}, Second: &v1.LimitRangeList{}},
{First: &schedulingv1.PriorityClass{}, Second: &schedulingv1.PriorityClassList{}},
}
// Delete objects with Karpenter finalizers separately. Executing delete calls on all of these objects at once
// may be grouped as DeleteCollection requests, which have a lower timeout than individual delete calls (before k8s 1.27).
// Separating them out diminishes the chance of running into timeouts when doing cleanup for tests of high scale.
// https://github.com/kubernetes/kubernetes/pull/115341
FinalizableObjects = []functional.Pair[client.Object, client.ObjectList]{
{First: &v1.Node{}, Second: &v1.NodeList{}},
{First: &v1alpha5.Machine{}, Second: &v1alpha5.MachineList{}},
}
)
// nolint:gocyclo
func (env *Environment) BeforeEach() {
debug.BeforeEach(env.Context, env.Config, env.Client)
env.Context = injection.WithSettingsOrDie(env.Context, env.KubeClient, apis.Settings...)
// Expect this cluster to be clean for test runs to execute successfully
env.ExpectCleanCluster()
var provisioners v1alpha5.ProvisionerList
Expect(env.Client.List(env.Context, &provisioners)).To(Succeed())
Expect(provisioners.Items).To(HaveLen(0), "expected no provisioners to exist")
env.Monitor.Reset()
env.StartingNodeCount = env.Monitor.NodeCountAtReset()
}
func (env *Environment) ExpectCleanCluster() {
var nodes v1.NodeList
Expect(env.Client.List(env.Context, &nodes)).To(Succeed())
for _, node := range nodes.Items {
if len(node.Spec.Taints) == 0 && !node.Spec.Unschedulable {
Fail(fmt.Sprintf("expected system pool node %s to be tainted", node.Name))
}
}
var pods v1.PodList
Expect(env.Client.List(env.Context, &pods)).To(Succeed())
for i := range pods.Items {
Expect(pod.IsProvisionable(&pods.Items[i])).To(BeFalse(),
fmt.Sprintf("expected to have no provisionable pods, found %s/%s", pods.Items[i].Namespace, pods.Items[i].Name))
Expect(pods.Items[i].Namespace).ToNot(Equal("default"),
fmt.Sprintf("expected no pods in the `default` namespace, found %s/%s", pods.Items[i].Namespace, pods.Items[i].Name))
}
}
func (env *Environment) Cleanup() {
env.CleanupObjects(CleanableObjects...)
env.CleanupObjects(FinalizableObjects...)
env.eventuallyExpectScaleDown()
env.ExpectNoCrashes()
}
func (env *Environment) AfterEach() {
debug.AfterEach(env.Context)
env.printControllerLogs(&v1.PodLogOptions{Container: "controller"})
}
func (env *Environment) CleanupObjects(cleanableObjects ...functional.Pair[client.Object, client.ObjectList]) {
namespaces := &v1.NamespaceList{}
Expect(env.Client.List(env, namespaces)).To(Succeed())
wg := sync.WaitGroup{}
for _, p := range cleanableObjects {
for _, namespace := range namespaces.Items {
wg.Add(1)
go func(obj client.Object, objList client.ObjectList, namespace string) {
defer wg.Done()
defer GinkgoRecover()
Expect(env.Client.DeleteAllOf(env, obj,
client.InNamespace(namespace),
client.HasLabels([]string{test.DiscoveryLabel}),
client.PropagationPolicy(metav1.DeletePropagationForeground),
)).To(Succeed())
Eventually(func(g Gomega) {
stored := objList.DeepCopyObject().(client.ObjectList)
g.Expect(env.Client.List(env, stored,
client.InNamespace(namespace),
client.HasLabels([]string{test.DiscoveryLabel}))).To(Succeed())
items, err := meta.ExtractList(stored)
g.Expect(err).To(Succeed())
g.Expect(len(items)).To(BeZero())
}).Should(Succeed())
}(p.First, p.Second, namespace.Name)
}
}
wg.Wait()
}
| 138 |
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 chaos
import (
"context"
"fmt"
"sync/atomic"
"testing"
"time"
. "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/client-go/informers"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
controllerruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
nodeutils "github.com/aws/karpenter-core/pkg/utils/node"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/debug"
"github.com/aws/karpenter/test/pkg/environment/common"
)
var env *common.Environment
func TestChaos(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = common.NewEnvironment(t)
})
RunSpecs(t, "Chaos")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("Chaos", func() {
Describe("Runaway Scale-Up", func() {
It("should not produce a runaway scale-up when consolidation is enabled", Label(debug.NoWatch), Label(debug.NoEvents), func() {
ctx, cancel := context.WithCancel(env.Context)
defer cancel()
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeSpot},
},
},
Consolidation: &v1alpha5.Consolidation{
Enabled: lo.ToPtr(true),
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: lo.ToPtr[int64](0),
},
})
// Start a controller that adds taints to nodes after creation
Expect(startTaintAdder(ctx, env.Config)).To(Succeed())
startNodeCountMonitor(ctx, env.Client)
// Create a deployment with a single pod
env.ExpectCreated(provider, provisioner, dep)
// Expect that we never get over a high number of nodes
Consistently(func(g Gomega) {
list := &v1.NodeList{}
g.Expect(env.Client.List(env.Context, list, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(list.Items)).To(BeNumerically("<", 35))
}, time.Minute*5).Should(Succeed())
})
It("should not produce a runaway scale-up when ttlSecondsAfterEmpty is enabled", Label(debug.NoWatch), Label(debug.NoEvents), func() {
ctx, cancel := context.WithCancel(env.Context)
defer cancel()
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeSpot},
},
},
TTLSecondsAfterEmpty: lo.ToPtr[int64](30),
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: lo.ToPtr[int64](0),
},
})
// Start a controller that adds taints to nodes after creation
Expect(startTaintAdder(ctx, env.Config)).To(Succeed())
startNodeCountMonitor(ctx, env.Client)
// Create a deployment with a single pod
env.ExpectCreated(provider, provisioner, dep)
// Expect that we never get over a high number of nodes
Consistently(func(g Gomega) {
list := &v1.NodeList{}
g.Expect(env.Client.List(env.Context, list, client.HasLabels{test.DiscoveryLabel})).To(Succeed())
g.Expect(len(list.Items)).To(BeNumerically("<", 35))
}, time.Minute*5).Should(Succeed())
})
})
})
type taintAdder struct {
kubeClient client.Client
}
func (t *taintAdder) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
node := &v1.Node{}
if err := t.kubeClient.Get(ctx, req.NamespacedName, node); err != nil {
return reconcile.Result{}, client.IgnoreNotFound(err)
}
mergeFrom := client.MergeFrom(node.DeepCopy())
taint := v1.Taint{
Key: "test",
Value: "true",
Effect: v1.TaintEffectNoExecute,
}
if !lo.Contains(node.Spec.Taints, taint) {
node.Spec.Taints = append(node.Spec.Taints, taint)
if err := t.kubeClient.Patch(ctx, node, mergeFrom); err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
func (t *taintAdder) Builder(mgr manager.Manager) *controllerruntime.Builder {
return controllerruntime.NewControllerManagedBy(mgr).
For(&v1.Node{}).
WithEventFilter(predicate.NewPredicateFuncs(func(obj client.Object) bool {
node := obj.(*v1.Node)
if _, ok := node.Labels[test.DiscoveryLabel]; !ok {
return false
}
return true
}))
}
func startTaintAdder(ctx context.Context, config *rest.Config) error {
mgr, err := controllerruntime.NewManager(config, controllerruntime.Options{})
if err != nil {
return err
}
adder := &taintAdder{kubeClient: mgr.GetClient()}
if err = adder.Builder(mgr).Complete(adder); err != nil {
return err
}
go func() {
Expect(mgr.Start(ctx)).To(Succeed())
}()
return nil
}
func startNodeCountMonitor(ctx context.Context, kubeClient client.Client) {
createdNodes := atomic.Int64{}
deletedNodes := atomic.Int64{}
factory := informers.NewSharedInformerFactoryWithOptions(env.KubeClient, time.Second*30,
informers.WithTweakListOptions(func(l *metav1.ListOptions) { l.LabelSelector = v1alpha5.ProvisionerNameLabelKey }))
nodeInformer := factory.Core().V1().Nodes().Informer()
nodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(_ interface{}) {
createdNodes.Add(1)
},
DeleteFunc: func(_ interface{}) {
deletedNodes.Add(1)
},
})
factory.Start(ctx.Done())
go func() {
for {
list := &v1.NodeList{}
if err := kubeClient.List(ctx, list, client.HasLabels{test.DiscoveryLabel}); err == nil {
readyCount := lo.CountBy(list.Items, func(n v1.Node) bool {
return nodeutils.GetCondition(&n, v1.NodeReady).Status == v1.ConditionTrue
})
fmt.Printf("[NODE COUNT] CURRENT: %d | READY: %d | CREATED: %d | DELETED: %d\n", len(list.Items), readyCount, createdNodes.Load(), deletedNodes.Load())
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second * 5):
}
}
}()
}
| 239 |
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 consolidation
import (
"fmt"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/test/pkg/debug"
awstest "github.com/aws/karpenter/pkg/test"
environmentaws "github.com/aws/karpenter/test/pkg/environment/aws"
"github.com/aws/karpenter/test/pkg/environment/common"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var env *environmentaws.Environment
func TestConsolidation(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = environmentaws.NewEnvironment(t)
})
RunSpecs(t, "Consolidation")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("Consolidation", func() {
It("should consolidate nodes (delete)", Label(debug.NoWatch), Label(debug.NoEvents), func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
// we don't replace spot nodes, so this forces us to only delete nodes
Values: []string{"spot"},
},
{
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"medium", "large", "xlarge"},
},
{
Key: v1alpha1.LabelInstanceFamily,
Operator: v1.NodeSelectorOpNotIn,
// remove some cheap burstable and the odd c1 instance types so we have
// more control over what gets provisioned
Values: []string{"t2", "t3", "c1", "t3a", "t4g"},
},
},
// prevent emptiness from deleting the nodes
TTLSecondsAfterEmpty: aws.Int64(99999),
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
var numPods int32 = 100
dep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1")},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreatedNodeCount("==", 0)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, int(numPods))
// reduce the number of pods by 60%
dep.Spec.Replicas = aws.Int32(40)
env.ExpectUpdated(dep)
env.EventuallyExpectAvgUtilization(v1.ResourceCPU, "<", 0.5)
provisioner.Spec.TTLSecondsAfterEmpty = nil
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{
Enabled: aws.Bool(true),
}
env.ExpectUpdated(provisioner)
// With consolidation enabled, we now must delete nodes
env.EventuallyExpectAvgUtilization(v1.ResourceCPU, ">", 0.6)
env.ExpectDeleted(dep)
})
It("should consolidate on-demand nodes (replace)", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"on-demand"},
},
{
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"large", "2xlarge"},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
var numPods int32 = 3
largeDep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
TopologySpreadConstraints: []v1.TopologySpreadConstraint{
{
MaxSkew: 1,
TopologyKey: v1.LabelHostname,
WhenUnsatisfiable: v1.DoNotSchedule,
LabelSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "large-app",
},
},
},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("4")},
},
},
})
smallDep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "small-app"},
},
TopologySpreadConstraints: []v1.TopologySpreadConstraint{
{
MaxSkew: 1,
TopologyKey: v1.LabelHostname,
WhenUnsatisfiable: v1.DoNotSchedule,
LabelSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "small-app",
},
},
},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1.5")},
},
},
})
selector := labels.SelectorFromSet(largeDep.Spec.Selector.MatchLabels)
env.ExpectCreatedNodeCount("==", 0)
env.ExpectCreated(provisioner, provider, largeDep, smallDep)
env.EventuallyExpectHealthyPodCount(selector, int(numPods))
// 3 nodes due to the anti-affinity rules
env.ExpectCreatedNodeCount("==", 3)
// scaling down the large deployment leaves only small pods on each node
largeDep.Spec.Replicas = aws.Int32(0)
env.ExpectUpdated(largeDep)
env.EventuallyExpectAvgUtilization(v1.ResourceCPU, "<", 0.5)
provisioner.Spec.TTLSecondsAfterEmpty = nil
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{
Enabled: aws.Bool(true),
}
env.ExpectUpdated(provisioner)
// With consolidation enabled, we now must replace each node in turn to consolidate due to the anti-affinity
// rules on the smaller deployment. The 2xl nodes should go to a large
env.EventuallyExpectAvgUtilization(v1.ResourceCPU, ">", 0.8)
var nodes v1.NodeList
Expect(env.Client.List(env.Context, &nodes)).To(Succeed())
numLargeNodes := 0
numOtherNodes := 0
for _, n := range nodes.Items {
// only count the nodes created by the provisoiner
if n.Labels[v1alpha5.ProvisionerNameLabelKey] != provisioner.Name {
continue
}
if strings.HasSuffix(n.Labels[v1.LabelInstanceTypeStable], ".large") {
numLargeNodes++
} else {
numOtherNodes++
}
}
// all of the 2xlarge nodes should have been replaced with large instance types
Expect(numLargeNodes).To(Equal(3))
// and we should have no other nodes
Expect(numOtherNodes).To(Equal(0))
env.ExpectDeleted(largeDep, smallDep)
})
It("should consolidate on-demand nodes to spot (replace)", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"on-demand"},
},
{
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"large"},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
var numPods int32 = 2
smallDep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "small-app"},
},
TopologySpreadConstraints: []v1.TopologySpreadConstraint{
{
MaxSkew: 1,
TopologyKey: v1.LabelHostname,
WhenUnsatisfiable: v1.DoNotSchedule,
LabelSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "small-app",
},
},
},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1.5")},
},
},
})
selector := labels.SelectorFromSet(smallDep.Spec.Selector.MatchLabels)
env.ExpectCreatedNodeCount("==", 0)
env.ExpectCreated(provisioner, provider, smallDep)
env.EventuallyExpectHealthyPodCount(selector, int(numPods))
env.ExpectCreatedNodeCount("==", int(numPods))
// Enable spot capacity type after the on-demand node is provisioned
// Expect the node to consolidate to a spot instance as it will be a cheaper
// instance than on-demand
provisioner.Spec.TTLSecondsAfterEmpty = nil
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{
Enabled: aws.Bool(true),
}
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"on-demand", "spot"},
},
{
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"large"},
},
}
env.ExpectUpdated(provisioner)
// Eventually expect the on-demand nodes to be consolidated into
// spot nodes after some time
Eventually(func(g Gomega) {
var nodes v1.NodeList
Expect(env.Client.List(env.Context, &nodes)).To(Succeed())
var spotNodes []*v1.Node
var otherNodes []*v1.Node
for i, n := range nodes.Items {
// only count the nodes created by the provisioner
if n.Labels[v1alpha5.ProvisionerNameLabelKey] != provisioner.Name {
continue
}
if n.Labels[v1alpha5.LabelCapacityType] == v1alpha5.CapacityTypeSpot {
spotNodes = append(spotNodes, &nodes.Items[i])
} else {
otherNodes = append(otherNodes, &nodes.Items[i])
}
}
// all the on-demand nodes should have been replaced with spot nodes
msg := fmt.Sprintf("node names, spot= %v, other = %v", common.NodeNames(spotNodes), common.NodeNames(otherNodes))
g.Expect(len(spotNodes)).To(BeNumerically("==", numPods), msg)
// and we should have no other nodes
g.Expect(len(otherNodes)).To(BeNumerically("==", 0), msg)
}, time.Minute*10).Should(Succeed())
env.ExpectDeleted(smallDep)
})
})
| 342 |
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 drift
import (
"fmt"
"strings"
"testing"
"time"
. "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"
"sigs.k8s.io/controller-runtime/pkg/client"
awssdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
var customAMI string
func TestDrift(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "Drift")
}
var _ = BeforeEach(func() {
env.BeforeEach()
})
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("Drift", Label("AWS"), func() {
BeforeEach(func() {
customAMI = env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
env.ExpectSettingsOverridden(map[string]string{
"featureGates.driftEnabled": "true",
})
})
It("should deprovision nodes that have drifted due to AMIs", func() {
// choose an old static image
parameter, err := env.SSMAPI.GetParameter(&ssm.GetParameterInput{
Name: awssdk.String("/aws/service/eks/optimized-ami/1.23/amazon-linux-2/amazon-eks-node-1.23-v20230322/image_id"),
})
Expect(err).To(BeNil())
oldCustomAMI := *parameter.Parameter.Value
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws-ids": oldCustomAMI},
UserData: awssdk.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
// Add a do-not-evict pod so that we can check node metadata before we deprovision
pod := test.Pod(test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.DoNotEvictPodAnnotationKey: "true",
},
},
})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
provider.Spec.AMISelector = map[string]string{"aws-ids": customAMI}
env.ExpectCreatedOrUpdated(provider)
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(node), node)).To(Succeed())
g.Expect(node.Annotations).To(HaveKeyWithValue(v1alpha5.VoluntaryDisruptionAnnotationKey, v1alpha5.VoluntaryDisruptionDriftedAnnotationValue))
}).Should(Succeed())
delete(pod.Annotations, v1alpha5.DoNotEvictPodAnnotationKey)
env.ExpectUpdated(pod)
env.EventuallyExpectNotFound(pod, node)
})
It("should not deprovision nodes that have drifted without the featureGate enabled", func() {
env.ExpectSettingsOverridden(map[string]string{
"featureGates.driftEnabled": "false",
})
// choose an old static image
parameter, err := env.SSMAPI.GetParameter(&ssm.GetParameterInput{
Name: awssdk.String("/aws/service/eks/optimized-ami/1.23/amazon-linux-2/amazon-eks-node-1.23-v20230322/image_id"),
})
Expect(err).To(BeNil())
oldCustomAMI := *parameter.Parameter.Value
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws-ids": oldCustomAMI},
UserData: awssdk.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
// Add a do-not-evict pod so that we can check node metadata before we deprovision
pod := test.Pod(test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.DoNotEvictPodAnnotationKey: "true",
},
},
})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
provider.Spec.AMISelector = map[string]string{"aws-ids": customAMI}
env.ExpectUpdated(provider)
// We should consistently get the same node existing for a minute
Consistently(func(g Gomega) {
g.Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(node), &v1.Node{})).To(Succeed())
}).WithTimeout(time.Minute).Should(Succeed())
})
It("should deprovision nodes that have drifted due to securitygroup", func() {
By("getting the cluster vpc id")
output, err := env.EKSAPI.DescribeCluster(&eks.DescribeClusterInput{Name: awssdk.String(settings.FromContext(env.Context).ClusterName)})
Expect(err).To(BeNil())
By("creating new security group")
createSecurityGroup := &ec2.CreateSecurityGroupInput{
GroupName: awssdk.String("security-group-drift"),
Description: awssdk.String("End-to-end Drift Test, should delete after drift test is completed"),
VpcId: output.Cluster.ResourcesVpcConfig.VpcId,
TagSpecifications: []*ec2.TagSpecification{
{
ResourceType: awssdk.String("security-group"),
Tags: []*ec2.Tag{
{
Key: awssdk.String("karpenter.sh/discovery"),
Value: awssdk.String(settings.FromContext(env.Context).ClusterName),
},
},
},
},
}
_, _ = env.EC2API.CreateSecurityGroup(createSecurityGroup)
By("looking for security groups")
var securitygroups []aws.SecurityGroup
var testSecurityGroup aws.SecurityGroup
Eventually(func(g Gomega) {
securitygroups = env.GetSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
testSecurityGroup, _ = lo.Find(securitygroups, func(sg aws.SecurityGroup) bool {
return awssdk.StringValue(sg.GroupName) == "security-group-drift"
})
g.Expect(testSecurityGroup).ToNot(BeNil())
}).Should(Succeed())
By("creating a new provider with the new securitygroup")
awsIDs := lo.Map(securitygroups, func(sg aws.SecurityGroup, _ int) string {
if awssdk.StringValue(sg.GroupId) != awssdk.StringValue(testSecurityGroup.GroupId) {
return awssdk.StringValue(sg.GroupId)
}
return ""
})
clusterSecurityGroupIDs := strings.Join(lo.WithoutEmpty(awsIDs), ",")
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"aws-ids": fmt.Sprintf("%s,%s", clusterSecurityGroupIDs, awssdk.StringValue(testSecurityGroup.GroupId))},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
// Add a do-not-evict pod so that we can check node metadata before we deprovision
pod := test.Pod(test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.DoNotEvictPodAnnotationKey: "true",
},
},
})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
By("updating the provider securitygroup")
node := env.Monitor.CreatedNodes()[0]
provider.Spec.SecurityGroupSelector = map[string]string{"aws-ids": clusterSecurityGroupIDs}
env.ExpectCreatedOrUpdated(provider)
By("checking the node metadata")
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(node), node)).To(Succeed())
g.Expect(node.Annotations).To(HaveKeyWithValue(v1alpha5.VoluntaryDisruptionAnnotationKey, v1alpha5.VoluntaryDisruptionDriftedAnnotationValue))
}).Should(Succeed())
delete(pod.Annotations, v1alpha5.DoNotEvictPodAnnotationKey)
env.ExpectUpdated(pod)
env.EventuallyExpectNotFound(pod, node)
})
It("should deprovision nodes that have drifted due to subnets", func() {
subnets := env.GetSubnetNameAndIds(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).To(BeNumerically(">", 1))
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"aws-ids": subnets[0].ID},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
// Add a do-not-evict pod so that we can check node metadata before we deprovision
pod := test.Pod(test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.DoNotEvictPodAnnotationKey: "true",
},
},
})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
provider.Spec.SubnetSelector = map[string]string{"aws-ids": subnets[1].ID}
env.ExpectCreatedOrUpdated(provider)
EventuallyWithOffset(1, func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(node), node)).To(Succeed())
g.Expect(node.Annotations).To(HaveKeyWithValue(v1alpha5.VoluntaryDisruptionAnnotationKey, v1alpha5.VoluntaryDisruptionDriftedAnnotationValue))
}).Should(Succeed())
delete(pod.Annotations, v1alpha5.DoNotEvictPodAnnotationKey)
env.ExpectUpdated(pod)
env.EventuallyExpectNotFound(pod, node)
})
})
| 268 |
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 integration_test
import (
"encoding/base64"
"fmt"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"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"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("AMI", func() {
var customAMI string
BeforeEach(func() {
customAMI = env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
})
It("should use the AMI defined by the AMI Selector", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
AMISelector: map[string]string{"aws-ids": customAMI},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("ImageId", HaveValue(Equal(customAMI))))
})
It("should use the most recent AMI when discovering multiple", func() {
// choose an old static image
parameter, err := env.SSMAPI.GetParameter(&ssm.GetParameterInput{
Name: aws.String("/aws/service/eks/optimized-ami/1.23/amazon-linux-2/amazon-eks-node-1.23-v20230322/image_id"),
})
Expect(err).To(BeNil())
oldCustomAMI := *parameter.Parameter.Value
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws-ids": fmt.Sprintf("%s,%s", customAMI, oldCustomAMI)},
UserData: aws.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("ImageId", HaveValue(Equal(customAMI))))
})
It("should support ami selector aws::name but fail with incorrect owners", func() {
output, err := env.EC2API.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{aws.String(customAMI)},
})
Expect(err).To(BeNil())
Expect(output.Images).To(HaveLen(1))
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws::name": *output.Images[0].Name, "aws::owners": "fakeOwnerValue"},
UserData: aws.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.ExpectCreatedNodeCount("==", 0)
Expect(pod.Spec.NodeName).To(Equal(""))
})
It("should support ami selector aws::name with default owners", func() {
output, err := env.EC2API.DescribeImages(&ec2.DescribeImagesInput{
ImageIds: []*string{aws.String(customAMI)},
})
Expect(err).To(BeNil())
Expect(output.Images).To(HaveLen(1))
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws::name": *output.Images[0].Name},
UserData: aws.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("ImageId", HaveValue(Equal(customAMI))))
})
It("should support ami selector aws::ids", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws::ids": customAMI},
UserData: aws.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("ImageId", HaveValue(Equal(customAMI))))
})
Context("AMIFamily", func() {
It("should provision a node using the AL2 family", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
pod := test.Pod()
env.ExpectCreated(provider, provisioner, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
})
It("should provision a node using the Bottlerocket family", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
pod := test.Pod()
env.ExpectCreated(provider, provisioner, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
})
It("should provision a node using the Ubuntu family", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyUbuntu,
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
pod := test.Pod()
env.ExpectCreated(provider, provisioner, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
})
It("should support Custom AMIFamily with AMI Selectors", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyCustom,
},
AMISelector: map[string]string{"aws-ids": customAMI},
UserData: aws.String(fmt.Sprintf("#!/bin/bash\n/etc/eks/bootstrap.sh '%s'", settings.FromContext(env.Context).ClusterName)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("ImageId", HaveValue(Equal(customAMI))))
})
It("should have the AWSNodeTemplateStatus for AMIs using wildcard", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{"aws::name": "*"},
})
env.ExpectCreated(provider)
ant := EventuallyExpectAMIsToExist(provider)
Expect(len(ant.Status.AMIs)).To(BeNumerically("<", 10))
})
It("should have the AWSNodeTemplateStatus for AMIs using tags", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{"aws-ids": customAMI},
})
env.ExpectCreated(provider)
ant := EventuallyExpectAMIsToExist(provider)
Expect(len(ant.Status.AMIs)).To(BeNumerically("==", 1))
Expect(ant.Status.AMIs[0].ID).To(Equal(customAMI))
})
})
Context("UserData", func() {
It("should merge UserData contents for AL2 AMIFamily", func() {
content, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
UserData: aws.String(string(content)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Taints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoExecute"}},
StartupTaints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoSchedule"}},
})
pod := test.Pod(test.PodOptions{Tolerations: []v1.Toleration{{Key: "example.com", Operator: v1.TolerationOpExists}}})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
Expect(env.GetNode(pod.Spec.NodeName).Spec.Taints).To(ContainElements(
v1.Taint{Key: "example.com", Value: "value", Effect: "NoExecute"},
v1.Taint{Key: "example.com", Value: "value", Effect: "NoSchedule"},
))
actualUserData, err := base64.StdEncoding.DecodeString(*getInstanceAttribute(pod.Spec.NodeName, "userData").UserData.Value)
Expect(err).ToNot(HaveOccurred())
// Since the node has joined the cluster, we know our bootstrapping was correct.
// Just verify if the UserData contains our custom content too, rather than doing a byte-wise comparison.
Expect(string(actualUserData)).To(ContainSubstring("Running custom user data script"))
})
It("should merge non-MIME UserData contents for AL2 AMIFamily", func() {
content, err := os.ReadFile("testdata/al2_no_mime_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
UserData: aws.String(string(content)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Taints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoExecute"}},
StartupTaints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoSchedule"}},
})
pod := test.Pod(test.PodOptions{Tolerations: []v1.Toleration{{Key: "example.com", Operator: v1.TolerationOpExists}}})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
Expect(env.GetNode(pod.Spec.NodeName).Spec.Taints).To(ContainElements(
v1.Taint{Key: "example.com", Value: "value", Effect: "NoExecute"},
v1.Taint{Key: "example.com", Value: "value", Effect: "NoSchedule"},
))
actualUserData, err := base64.StdEncoding.DecodeString(*getInstanceAttribute(pod.Spec.NodeName, "userData").UserData.Value)
Expect(err).ToNot(HaveOccurred())
// Since the node has joined the cluster, we know our bootstrapping was correct.
// Just verify if the UserData contains our custom content too, rather than doing a byte-wise comparison.
Expect(string(actualUserData)).To(ContainSubstring("Running custom user data script"))
})
It("should merge UserData contents for Bottlerocket AMIFamily", func() {
content, err := os.ReadFile("testdata/br_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
},
UserData: aws.String(string(content)),
})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Taints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoExecute"}},
StartupTaints: []v1.Taint{{Key: "example.com", Value: "value", Effect: "NoSchedule"}},
})
pod := test.Pod(test.PodOptions{Tolerations: []v1.Toleration{{Key: "example.com", Operator: v1.TolerationOpExists}}})
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
Expect(env.GetNode(pod.Spec.NodeName).Spec.Taints).To(ContainElements(
v1.Taint{Key: "example.com", Value: "value", Effect: "NoExecute"},
v1.Taint{Key: "example.com", Value: "value", Effect: "NoSchedule"},
))
actualUserData, err := base64.StdEncoding.DecodeString(*getInstanceAttribute(pod.Spec.NodeName, "userData").UserData.Value)
Expect(err).ToNot(HaveOccurred())
Expect(string(actualUserData)).To(ContainSubstring("kube-api-qps = 30"))
})
})
})
func getInstanceAttribute(nodeName string, attribute string) *ec2.DescribeInstanceAttributeOutput {
var node v1.Node
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: nodeName}, &node)).To(Succeed())
providerIDSplit := strings.Split(node.Spec.ProviderID, "/")
instanceID := providerIDSplit[len(providerIDSplit)-1]
instanceAttribute, err := env.EC2API.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
InstanceId: aws.String(instanceID),
Attribute: aws.String(attribute),
})
Expect(err).ToNot(HaveOccurred())
return instanceAttribute
}
func EventuallyExpectAMIsToExist(provider *v1alpha1.AWSNodeTemplate) v1alpha1.AWSNodeTemplate {
var ant v1alpha1.AWSNodeTemplate
Eventually(func(g Gomega) {
g.Expect(env.Client.Get(env, client.ObjectKeyFromObject(provider), &ant)).To(Succeed())
g.Expect(ant.Status.AMIs).ToNot(BeNil())
}).WithTimeout(30 * time.Second).Should(Succeed())
return ant
}
| 357 |
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 integration_test
import (
"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/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("MetadataOptions", func() {
It("should use specified metadata options", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
LaunchTemplate: v1alpha1.LaunchTemplate{
MetadataOptions: &v1alpha1.MetadataOptions{
HTTPEndpoint: aws.String("enabled"),
HTTPProtocolIPv6: aws.String("enabled"),
HTTPPutResponseHopLimit: aws.Int64(1),
HTTPTokens: aws.String("required"),
},
},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("MetadataOptions", HaveValue(Equal(ec2.InstanceMetadataOptionsResponse{
State: aws.String(ec2.InstanceMetadataOptionsStateApplied),
HttpEndpoint: aws.String("enabled"),
HttpProtocolIpv6: aws.String("enabled"),
HttpPutResponseHopLimit: aws.Int64(1),
HttpTokens: aws.String("required"),
InstanceMetadataTags: aws.String("disabled"),
}))))
})
})
| 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 integration_test
import (
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var _ = Describe("BackwardsCompatability", func() {
It("should succeed to launch a node by specifying a provider in the Provisioner", func() {
provisioner := test.Provisioner(
test.ProvisionerOptions{
Provider: &v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{
"custom-tag": "custom-value",
"custom-tag2": "custom-value2",
},
},
},
)
pod := test.Pod()
env.ExpectCreated(pod, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
nodes := env.Monitor.CreatedNodes()
Expect(nodes).To(HaveLen(1))
Expect(env.GetInstance(nodes[0].Name).Tags).To(ContainElements(
&ec2.Tag{Key: lo.ToPtr("custom-tag"), Value: lo.ToPtr("custom-value")},
&ec2.Tag{Key: lo.ToPtr("custom-tag2"), Value: lo.ToPtr("custom-value2")},
))
})
})
| 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 integration_test
import (
"github.com/aws/aws-sdk-go/aws"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("BlockDeviceMappings", func() {
It("should use specified block device mappings", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
LaunchTemplate: v1alpha1.LaunchTemplate{
BlockDeviceMappings: []*v1alpha1.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
EBS: &v1alpha1.BlockDevice{
VolumeSize: resources.Quantity("10G"),
VolumeType: aws.String("io2"),
IOPS: aws.Int64(1000),
Encrypted: aws.Bool(true),
DeleteOnTermination: aws.Bool(true),
},
},
},
},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
instance := env.GetInstance(pod.Spec.NodeName)
Expect(len(instance.BlockDeviceMappings)).To(Equal(1))
Expect(instance.BlockDeviceMappings[0]).ToNot(BeNil())
Expect(instance.BlockDeviceMappings[0]).To(HaveField("DeviceName", HaveValue(Equal("/dev/xvda"))))
Expect(instance.BlockDeviceMappings[0].Ebs).To(HaveField("DeleteOnTermination", HaveValue(BeTrue())))
volume := env.GetVolume(instance.BlockDeviceMappings[0].Ebs.VolumeId)
Expect(volume).To(HaveField("Encrypted", HaveValue(BeTrue())))
Expect(volume).To(HaveField("Size", HaveValue(Equal(int64(10))))) // Convert G -> Gib (rounded up)
Expect(volume).To(HaveField("Iops", HaveValue(Equal(int64(1000)))))
Expect(volume).To(HaveField("VolumeType", HaveValue(Equal("io2"))))
})
})
| 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 integration_test
import (
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("CNITests", func() {
It("should set max pods to 110 when AWSENILimited when AWS_ENI_LIMITED_POD_DENSITY is false", func() {
env.ExpectSettingsOverridden(map[string]string{
"aws.enableENILimitedPodDensity": "false",
})
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
var node corev1.Node
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: pod.Spec.NodeName}, &node)).To(Succeed())
allocatablePods, _ := node.Status.Allocatable.Pods().AsInt64()
Expect(allocatablePods).To(Equal(int64(110)))
})
It("should set eni-limited maxPods when AWSENILimited when AWS_ENI_LIMITED_POD_DENSITY is true", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
var node corev1.Node
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: pod.Spec.NodeName}, &node)).To(Succeed())
allocatablePods, _ := node.Status.Allocatable.Pods().AsInt64()
Expect(allocatablePods).To(Equal(eniLimitedPodsFor(node.Labels["node.kubernetes.io/instance-type"])))
})
It("should set maxPods when reservedENIs is set", func() {
env.ExpectSettingsOverridden(map[string]string{
"aws.reservedENIs": "1",
})
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyAL2,
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
var node corev1.Node
Expect(env.Client.Get(env.Context, types.NamespacedName{Name: pod.Spec.NodeName}, &node)).To(Succeed())
allocatablePods, _ := node.Status.Allocatable.Pods().AsInt64()
Expect(allocatablePods).To(Equal(reservedENIsFor(node.Labels["node.kubernetes.io/instance-type"])))
})
})
func eniLimitedPodsFor(instanceType string) int64 {
instance, err := env.EC2API.DescribeInstanceTypes(&ec2.DescribeInstanceTypesInput{
InstanceTypes: aws.StringSlice([]string{instanceType}),
})
Expect(err).ToNot(HaveOccurred())
networkInfo := *instance.InstanceTypes[0].NetworkInfo
return *networkInfo.MaximumNetworkInterfaces*(*networkInfo.Ipv4AddressesPerInterface-1) + 2
}
func reservedENIsFor(instanceType string) int64 {
instance, err := env.EC2API.DescribeInstanceTypes(&ec2.DescribeInstanceTypesInput{
InstanceTypes: aws.StringSlice([]string{instanceType}),
})
Expect(err).ToNot(HaveOccurred())
networkInfo := *instance.InstanceTypes[0].NetworkInfo
reservedENIs := 0
reservedENIsStr, ok := env.ExpectSettings().Data["aws.reservedENIs"]
if ok {
reservedENIs, err = strconv.Atoi(reservedENIsStr)
Expect(err).ToNot(HaveOccurred())
}
return (*networkInfo.MaximumNetworkInterfaces-int64(reservedENIs))*(*networkInfo.Ipv4AddressesPerInterface-1) + 2
}
| 122 |
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 integration_test
import (
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var _ = Describe("DaemonSet", func() {
var provider *v1alpha1.AWSNodeTemplate
var provisioner *v1alpha5.Provisioner
var limitrange *v1.LimitRange
var priorityclass *schedulingv1.PriorityClass
var daemonset *appsv1.DaemonSet
var dep *appsv1.Deployment
BeforeEach(func() {
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner = test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Consolidation: &v1alpha5.Consolidation{
Enabled: lo.ToPtr(true),
},
})
priorityclass = &schedulingv1.PriorityClass{
ObjectMeta: metav1.ObjectMeta{
Name: "high-priority-daemonsets",
},
Value: int32(10000000),
GlobalDefault: false,
Description: "This priority class should be used for daemonsets.",
}
limitrange = &v1.LimitRange{
ObjectMeta: metav1.ObjectMeta{
Name: "limitrange",
Namespace: "default",
},
}
daemonset = test.DaemonSet(test.DaemonSetOptions{
PodOptions: test.PodOptions{
ResourceRequirements: v1.ResourceRequirements{Limits: v1.ResourceList{v1.ResourceMemory: resource.MustParse("1Gi")}},
PriorityClassName: "high-priority-daemonsets",
},
})
numPods := 1
dep = test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceMemory: resource.MustParse("4")},
},
},
})
})
It("should account for LimitRange Default on daemonSet pods for resources", func() {
limitrange.Spec.Limits = []v1.LimitRangeItem{
{
Type: v1.LimitTypeContainer,
Default: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("1Gi"),
},
},
}
podSelector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
daemonSetSelector := labels.SelectorFromSet(daemonset.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, limitrange, priorityclass, daemonset, dep)
// Eventually expect a single node to exist and both the deployment pod and the daemonset pod to schedule to it
Eventually(func(g Gomega) {
nodeList := &v1.NodeList{}
g.Expect(env.Client.List(env, nodeList, client.HasLabels{"testing.karpenter.sh/test-id"})).To(Succeed())
g.Expect(nodeList.Items).To(HaveLen(1))
deploymentPods := env.Monitor.RunningPods(podSelector)
g.Expect(deploymentPods).To(HaveLen(1))
daemonSetPods := env.Monitor.RunningPods(daemonSetSelector)
g.Expect(daemonSetPods).To(HaveLen(1))
g.Expect(deploymentPods[0].Spec.NodeName).To(Equal(nodeList.Items[0].Name))
g.Expect(daemonSetPods[0].Spec.NodeName).To(Equal(nodeList.Items[0].Name))
}).Should(Succeed())
})
It("should account for LimitRange DefaultRequest on daemonSet pods for resources", func() {
limitrange.Spec.Limits = []v1.LimitRangeItem{
{
Type: v1.LimitTypeContainer,
DefaultRequest: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("1Gi"),
},
},
}
podSelector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
daemonSetSelector := labels.SelectorFromSet(daemonset.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, limitrange, priorityclass, daemonset, dep)
// Eventually expect a single node to exist and both the deployment pod and the daemonset pod to schedule to it
Eventually(func(g Gomega) {
nodeList := &v1.NodeList{}
g.Expect(env.Client.List(env, nodeList, client.HasLabels{"testing.karpenter.sh/test-id"})).To(Succeed())
g.Expect(nodeList.Items).To(HaveLen(1))
deploymentPods := env.Monitor.RunningPods(podSelector)
g.Expect(deploymentPods).To(HaveLen(1))
daemonSetPods := env.Monitor.RunningPods(daemonSetSelector)
g.Expect(daemonSetPods).To(HaveLen(1))
g.Expect(deploymentPods[0].Spec.NodeName).To(Equal(nodeList.Items[0].Name))
g.Expect(daemonSetPods[0].Spec.NodeName).To(Equal(nodeList.Items[0].Name))
}).Should(Succeed())
})
})
| 153 |
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 integration_test
import (
"k8s.io/apimachinery/pkg/labels"
"knative.dev/pkg/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Emptiness", func() {
It("should terminate an empty node", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
TTLSecondsAfterEmpty: ptr.Int64(0),
})
const numPods = 1
deployment := test.Deployment(test.DeploymentOptions{Replicas: numPods})
env.ExpectCreated(provider, provisioner, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), numPods)
env.ExpectCreatedNodeCount("==", 1)
persisted := deployment.DeepCopy()
deployment.Spec.Replicas = ptr.Int32(0)
Expect(env.Client.Patch(env, deployment, client.MergeFrom(persisted))).To(Succeed())
nodes := env.Monitor.CreatedNodes()
for i := range nodes {
env.EventuallyExpectNotFound(nodes[i])
}
})
})
| 61 |
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 integration_test
import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter/pkg/apis/settings"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var _ = Describe("Expiration", func() {
It("should expire the node after the TTLSecondsUntilExpired is reached", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
TTLSecondsUntilExpired: ptr.Int64(30),
})
var numPods int32 = 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
},
})
env.ExpectCreatedNodeCount("==", 0)
env.ExpectCreated(provisioner, provider, dep)
// We don't care if the pod goes healthy, just if the node is expired
env.EventuallyExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
env.Monitor.Reset()
// Eventually the node will be set as unschedulable, which means its actively being deprovisioned
Eventually(func(g Gomega) {
n := &v1.Node{}
g.Expect(env.Client.Get(env.Context, types.NamespacedName{Name: node.Name}, n)).Should(Succeed())
g.Expect(n.Spec.Unschedulable).Should(BeTrue())
}).Should(Succeed())
// Remove the TTLSecondsUntilExpired to make sure new node isn't deleted
// This is CRITICAL since it prevents nodes that are immediately spun up from immediately being expired and
// racing at the end of the E2E test, leaking node resources into subsequent tests
provisioner.Spec.TTLSecondsUntilExpired = nil
env.ExpectUpdated(provisioner)
// After the deletion timestamp is set and all pods are drained
// the node should be gone
env.EventuallyExpectNotFound(node)
env.EventuallyExpectCreatedNodeCount("==", 1)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(dep.Spec.Selector.MatchLabels), 1)
})
It("should replace expired node with a single node and schedule all pods", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
var numPods int32 = 5
// We should setup a PDB that will only allow a minimum of 1 pod to be pending at a time
minAvailable := intstr.FromInt(int(numPods) - 1)
pdb := test.PodDisruptionBudget(test.PDBOptions{
Labels: map[string]string{
"app": "large-app",
},
MinAvailable: &minAvailable,
})
dep := test.Deployment(test.DeploymentOptions{
Replicas: numPods,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreatedNodeCount("==", 0)
env.ExpectCreated(provisioner, provider, pdb, dep)
env.EventuallyExpectHealthyPodCount(selector, int(numPods))
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
// Reset the monitor so that we can expect a single node to be spun up after expiration
env.Monitor.Reset()
// Set the TTLSecondsUntilExpired to get the node deleted
provisioner.Spec.TTLSecondsUntilExpired = ptr.Int64(60)
env.ExpectUpdated(provisioner)
// Eventually the node will be set as unschedulable, which means its actively being deprovisioned
Eventually(func(g Gomega) {
n := &v1.Node{}
g.Expect(env.Client.Get(env.Context, types.NamespacedName{Name: node.Name}, n)).Should(Succeed())
g.Expect(n.Spec.Unschedulable).Should(BeTrue())
}).Should(Succeed())
// Remove the TTLSecondsUntilExpired to make sure new node isn't deleted
// This is CRITICAL since it prevents nodes that are immediately spun up from immediately being expired and
// racing at the end of the E2E test, leaking node resources into subsequent tests
provisioner.Spec.TTLSecondsUntilExpired = nil
env.ExpectUpdated(provisioner)
// After the deletion timestamp is set and all pods are drained
// the node should be gone
env.EventuallyExpectNotFound(node)
env.EventuallyExpectHealthyPodCount(selector, int(numPods))
env.ExpectCreatedNodeCount("==", 1)
})
})
| 148 |
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 integration_test
import (
"fmt"
"os"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Extended Resources", func() {
It("should provision nodes for a deployment that requests nvidia.com/gpu", func() {
ExpectNvidiaDevicePluginCreated()
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
},
},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
"nvidia.com/gpu": resource.MustParse("1"),
},
Limits: v1.ResourceList{
"nvidia.com/gpu": resource.MustParse("1"),
},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
env.EventuallyExpectInitializedNodeCount("==", 1)
})
It("should provision nodes for a deployment that requests nvidia.com/gpu (Bottlerocket)", func() {
// For Bottlerocket, we are testing that resources are initialized without needing a device plugin
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
},
},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
"nvidia.com/gpu": resource.MustParse("1"),
},
Limits: v1.ResourceList{
"nvidia.com/gpu": resource.MustParse("1"),
},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
env.EventuallyExpectInitializedNodeCount("==", 1)
})
It("should provision nodes for a deployment that requests vpc.amazonaws.com/pod-eni (security groups for pods)", func() {
env.ExpectPodENIEnabled()
DeferCleanup(func() {
env.ExpectPodENIDisabled()
})
env.ExpectSettingsOverridden(map[string]string{
"aws.enablePodENI": "true",
})
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
},
},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
"vpc.amazonaws.com/pod-eni": resource.MustParse("1"),
},
Limits: v1.ResourceList{
"vpc.amazonaws.com/pod-eni": resource.MustParse("1"),
},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
env.EventuallyExpectInitializedNodeCount("==", 1)
})
It("should provision nodes for a deployment that requests amd.com/gpu", func() {
Skip("skipping test on AMD instance types")
ExpectAMDDevicePluginCreated()
customAMI := env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 0)
// We create custom userData that installs the AMD Radeon driver and then performs the EKS bootstrap script
// We use a Custom AMI so that we can reboot after we start the kubelet service
rawContent, err := os.ReadFile("testdata/amd_driver_input.sh")
Expect(err).ToNot(HaveOccurred())
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyCustom,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{
"aws-ids": customAMI,
},
},
)
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpExists,
},
},
})
provider.Spec.UserData = lo.ToPtr(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle(), provisioner.Name))
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
"amd.com/gpu": resource.MustParse("1"),
},
Limits: v1.ResourceList{
"amd.com/gpu": resource.MustParse("1"),
},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
Eventually(func(g Gomega) {
g.Expect(env.Monitor.RunningPodsCount(selector)).To(Equal(numPods))
}).WithTimeout(15 * time.Minute).Should(Succeed()) // The node needs additional time to install the AMD GPU driver
env.ExpectCreatedNodeCount("==", 1)
env.EventuallyExpectInitializedNodeCount("==", 1)
})
// Need to subscribe to the AMI to run the test successfully
// https://aws.amazon.com/marketplace/pp/prodview-st5jc2rk3phr2?sr=0-2&ref_=beagle&applicationId=AWSMPContessa
It("should provision nodes for a deployment that requests habana.ai/gaudi", func() {
Skip("skipping test on an exotic instance type")
ExpectHabanaDevicePluginCreated()
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{"aws-ids": "ami-0fae925f94979981f"},
})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeOnDemand},
},
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c", "m", "r", "p", "g", "dl"},
},
},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
"habana.ai/gaudi": resource.MustParse("1"),
},
Limits: v1.ResourceList{
"habana.ai/gaudi": resource.MustParse("1"),
},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
env.EventuallyExpectInitializedNodeCount("==", 1)
})
})
func ExpectNvidiaDevicePluginCreated() {
env.ExpectCreatedWithOffset(1, &appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "nvidia-device-plugin-daemonset",
Namespace: "kube-system",
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"name": "nvidia-device-plugin-ds",
},
},
UpdateStrategy: appsv1.DaemonSetUpdateStrategy{
Type: appsv1.RollingUpdateDaemonSetStrategyType,
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"name": "nvidia-device-plugin-ds",
},
},
Spec: v1.PodSpec{
Tolerations: []v1.Toleration{
{
Key: "nvidia.com/gpu",
Operator: v1.TolerationOpExists,
Effect: v1.TaintEffectNoSchedule,
},
},
PriorityClassName: "system-node-critical",
Containers: []v1.Container{
{
Name: "nvidia-device-plugin-ctr",
Image: "nvcr.io/nvidia/k8s-device-plugin:v0.12.3",
Env: []v1.EnvVar{
{
Name: "FAIL_ON_INIT_ERROR",
Value: "false",
},
},
SecurityContext: &v1.SecurityContext{
AllowPrivilegeEscalation: lo.ToPtr(false),
Capabilities: &v1.Capabilities{
Drop: []v1.Capability{"ALL"},
},
},
VolumeMounts: []v1.VolumeMount{
{
Name: "device-plugin",
MountPath: "/var/lib/kubelet/device-plugins",
},
},
},
},
Volumes: []v1.Volume{
{
Name: "device-plugin",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/var/lib/kubelet/device-plugins",
},
},
},
},
},
},
},
})
}
func ExpectAMDDevicePluginCreated() {
env.ExpectCreatedWithOffset(1, &appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "amdgpu-device-plugin-daemonset",
Namespace: "kube-system",
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"name": "amdgpu-dp-ds",
},
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"name": "amdgpu-dp-ds",
},
},
Spec: v1.PodSpec{
PriorityClassName: "system-node-critical",
Tolerations: []v1.Toleration{
{
Key: "amd.com/gpu",
Operator: v1.TolerationOpExists,
Effect: v1.TaintEffectNoSchedule,
},
},
Containers: []v1.Container{
{
Name: "amdgpu-dp-cntr",
Image: "rocm/k8s-device-plugin",
SecurityContext: &v1.SecurityContext{
AllowPrivilegeEscalation: lo.ToPtr(false),
Capabilities: &v1.Capabilities{
Drop: []v1.Capability{"ALL"},
},
},
VolumeMounts: []v1.VolumeMount{
{
Name: "dp",
MountPath: "/var/lib/kubelet/device-plugins",
},
{
Name: "sys",
MountPath: "/sys",
},
},
},
},
Volumes: []v1.Volume{
{
Name: "dp",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/var/lib/kubelet/device-plugins",
},
},
},
{
Name: "sys",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/sys",
},
},
},
},
},
},
},
})
}
func ExpectHabanaDevicePluginCreated() {
env.ExpectCreatedWithOffset(1, &v1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "habana-system",
},
})
env.ExpectCreatedWithOffset(1, &appsv1.DaemonSet{
ObjectMeta: metav1.ObjectMeta{
Name: "habanalabs-device-plugin-daemonset",
Namespace: "habana-system",
},
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"name": "habanalabs-device-plugin-ds",
},
},
UpdateStrategy: appsv1.DaemonSetUpdateStrategy{
Type: appsv1.RollingUpdateDaemonSetStrategyType,
},
Template: v1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"scheduler.alpha.kubernetes.io/critical-pod": "",
},
Labels: map[string]string{
"name": "habanalabs-device-plugin-ds",
},
},
Spec: v1.PodSpec{
Tolerations: []v1.Toleration{
{
Key: "habana.ai/gaudi",
Operator: v1.TolerationOpExists,
Effect: v1.TaintEffectNoSchedule,
},
},
PriorityClassName: "system-node-critical",
Containers: []v1.Container{
{
Name: "habanalabs-device-plugin-ctr",
Image: "vault.habana.ai/docker-k8s-device-plugin/docker-k8s-device-plugin:latest",
SecurityContext: &v1.SecurityContext{
Privileged: lo.ToPtr(true),
},
VolumeMounts: []v1.VolumeMount{
{
Name: "device-plugin",
MountPath: "/var/lib/kubelet/device-plugins",
},
},
},
},
Volumes: []v1.Volume{
{
Name: "device-plugin",
VolumeSource: v1.VolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/var/lib/kubelet/device-plugins",
},
},
},
},
},
},
},
})
}
| 485 |
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 integration_test
import (
"math"
"time"
. "github.com/onsi/ginkgo/v2"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter/pkg/apis/settings"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/environment/aws"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
)
var _ = Describe("KubeletConfiguration Overrides", func() {
Context("All kubelet configuration set", func() {
var nodeTemplate *v1alpha1.AWSNodeTemplate
var provisioner *v1alpha5.Provisioner
BeforeEach(func() {
nodeTemplate = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
// MaxPods needs to account for the daemonsets that will run on the nodes
provisioner = test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: nodeTemplate.Name},
Kubelet: &v1alpha5.KubeletConfiguration{
ContainerRuntime: ptr.String("containerd"),
MaxPods: ptr.Int32(110),
PodsPerCore: ptr.Int32(10),
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("200m"),
v1.ResourceMemory: resource.MustParse("200Mi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("200m"),
v1.ResourceMemory: resource.MustParse("200Mi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
EvictionHard: map[string]string{
"memory.available": "5%",
"nodefs.available": "5%",
"nodefs.inodesFree": "5%",
"imagefs.available": "5%",
"imagefs.inodesFree": "5%",
"pid.available": "3%",
},
EvictionSoft: map[string]string{
"memory.available": "10%",
"nodefs.available": "10%",
"nodefs.inodesFree": "10%",
"imagefs.available": "10%",
"imagefs.inodesFree": "10%",
"pid.available": "6%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute * 2},
"nodefs.available": {Duration: time.Minute * 2},
"nodefs.inodesFree": {Duration: time.Minute * 2},
"imagefs.available": {Duration: time.Minute * 2},
"imagefs.inodesFree": {Duration: time.Minute * 2},
"pid.available": {Duration: time.Minute * 2},
},
EvictionMaxPodGracePeriod: ptr.Int32(120),
ImageGCHighThresholdPercent: ptr.Int32(50),
ImageGCLowThresholdPercent: ptr.Int32(10),
CPUCFSQuota: ptr.Bool(false),
},
})
})
DescribeTable("Linux AMIFamilies",
func(amiFamily *string) {
nodeTemplate.Spec.AMIFamily = amiFamily
// Need to enable provisioner-level OS-scoping for now since DS evaluation is done off of the provisioner
// requirements, not off of the instance type options so scheduling can fail if provisioners aren't
// properly scoped
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
})
pod := test.Pod(test.PodOptions{
NodeSelector: map[string]string{
v1.LabelOSStable: string(v1.Linux),
v1.LabelArchStable: "amd64",
},
})
env.ExpectCreated(provisioner, nodeTemplate, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
},
Entry("when the AMIFamily is AL2", &v1alpha1.AMIFamilyAL2),
Entry("when the AMIFamily is Ubuntu", &v1alpha1.AMIFamilyUbuntu),
Entry("when the AMIFamily is Bottlerocket", &v1alpha1.AMIFamilyBottlerocket),
)
DescribeTable("Windows AMIFamilies",
func(amiFamily *string) {
env.ExpectWindowsIPAMEnabled()
DeferCleanup(func() {
env.ExpectWindowsIPAMDisabled()
})
nodeTemplate.Spec.AMIFamily = amiFamily
// Need to enable provisioner-level OS-scoping for now since DS evaluation is done off of the provisioner
// requirements, not off of the instance type options so scheduling can fail if provisioners aren't
// properly scoped
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Windows)},
})
pod := test.Pod(test.PodOptions{
Image: aws.WindowsDefaultImage,
NodeSelector: map[string]string{
v1.LabelOSStable: string(v1.Windows),
v1.LabelArchStable: "amd64",
},
})
env.ExpectCreated(provisioner, nodeTemplate, pod)
env.EventuallyExpectHealthyWithTimeout(time.Minute*15, pod)
env.ExpectCreatedNodeCount("==", 1)
},
Entry("when the AMIFamily is Windows2019", &v1alpha1.AMIFamilyWindows2019),
Entry("when the AMIFamily is Windows2022", &v1alpha1.AMIFamilyWindows2022),
)
})
It("should schedule pods onto separate nodes when maxPods is set", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
// MaxPods needs to account for the daemonsets that will run on the nodes
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
},
},
})
// Get the DS pod count and use it to calculate the DS pod overhead
dsCount := env.GetDaemonSetCount(provisioner)
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: ptr.Int32(1 + int32(dsCount)),
}
numPods := 3
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("100m")},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 3)
env.ExpectUniqueNodeNames(selector, 3)
})
It("should schedule pods onto separate nodes when podsPerCore is set", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
// PodsPerCore needs to account for the daemonsets that will run on the nodes
// This will have 4 pods available on each node (2 taken by daemonset pods)
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCPU,
Operator: v1.NodeSelectorOpIn,
Values: []string{"2"},
},
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
},
},
})
numPods := 4
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("100m")},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
// Get the DS pod count and use it to calculate the DS pod overhead
// We calculate podsPerCore to split the test pods and the DS pods between two nodes:
// 1. If # of DS pods is odd, we will have i.e. ceil((3+2)/2) = 3
// Since we restrict node to two cores, we will allow 6 pods. One node will have 3
// DS pods and 3 test pods. Other node will have 1 test pod and 3 DS pods
// 2. If # of DS pods is even, we will have i.e. ceil((4+2)/2) = 3
// Since we restrict node to two cores, we will allow 6 pods. Both nodes will have
// 4 DS pods and 2 test pods.
dsCount := env.GetDaemonSetCount(provisioner)
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
PodsPerCore: ptr.Int32(int32(math.Ceil(float64(2+dsCount) / 2))),
}
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 2)
env.ExpectUniqueNodeNames(selector, 2)
})
It("should ignore podsPerCore value when Bottlerocket is used", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
AMIFamily: &v1alpha1.AMIFamilyBottlerocket,
}})
// All pods should schedule to a single node since we are ignoring podsPerCore value
// This would normally schedule to 3 nodes if not using Bottlerocket
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Kubelet: &v1alpha5.KubeletConfiguration{
PodsPerCore: ptr.Int32(1),
},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCPU,
Operator: v1.NodeSelectorOpIn,
Values: []string{"2"},
},
},
})
numPods := 6
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "large-app"},
},
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("100m")},
},
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provisioner, provider, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectUniqueNodeNames(selector, 1)
})
})
| 290 |
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 integration_test
import (
"fmt"
"time"
. "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/labels"
"k8s.io/apimachinery/pkg/util/sets"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/test/pkg/debug"
"github.com/aws/karpenter/test/pkg/environment/aws"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Scheduling", Ordered, ContinueOnFailure, func() {
var provider *v1alpha1.AWSNodeTemplate
var provisioner *v1alpha5.Provisioner
var selectors sets.String
BeforeEach(func() {
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner = test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{Key: v1alpha1.LabelInstanceCategory, Operator: v1.NodeSelectorOpExists},
{Key: v1alpha5.LabelCapacityType, Operator: v1.NodeSelectorOpExists},
},
})
})
BeforeAll(func() {
selectors = sets.NewString()
})
AfterAll(func() {
// Ensure that we're exercising all well known labels
Expect(lo.Keys(selectors)).To(ContainElements(append(v1alpha5.WellKnownLabels.UnsortedList(), lo.Keys(v1alpha5.NormalizedLabels)...)))
})
It("should apply annotations to the node", func() {
provisioner.Spec.Annotations = map[string]string{
"foo": "bar",
v1alpha5.DoNotConsolidateNodeAnnotationKey: "true",
}
pod := test.Pod()
env.ExpectCreated(provisioner, provider, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
Expect(env.GetNode(pod.Spec.NodeName).Annotations).To(And(HaveKeyWithValue("foo", "bar"), HaveKeyWithValue(v1alpha5.DoNotConsolidateNodeAnnotationKey, "true")))
})
It("should support well-known labels for instance type selection", func() {
nodeSelector := map[string]string{
// Well Known
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: "c5.large",
// Well Known to AWS
v1alpha1.LabelInstanceHypervisor: "nitro",
v1alpha1.LabelInstanceCategory: "c",
v1alpha1.LabelInstanceGeneration: "5",
v1alpha1.LabelInstanceFamily: "c5",
v1alpha1.LabelInstanceSize: "large",
v1alpha1.LabelInstanceCPU: "2",
v1alpha1.LabelInstanceMemory: "4096",
v1alpha1.LabelInstanceNetworkBandwidth: "750",
v1alpha1.LabelInstancePods: "29",
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for local NVME storage", func() {
selectors.Insert(v1alpha1.LabelInstanceLocalNVME) // Add node selector keys to selectors used in testing to ensure we test all labels
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodePreferences: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceLocalNVME,
Operator: v1.NodeSelectorOpGt,
Values: []string{"0"},
},
},
NodeRequirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceLocalNVME,
Operator: v1.NodeSelectorOpGt,
Values: []string{"0"},
},
},
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for encryption in transit", func() {
selectors.Insert(v1alpha1.LabelInstanceEncryptionInTransitSupported) // Add node selector keys to selectors used in testing to ensure we test all labels
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodePreferences: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceEncryptionInTransitSupported,
Operator: v1.NodeSelectorOpIn,
Values: []string{"true"},
},
},
NodeRequirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceEncryptionInTransitSupported,
Operator: v1.NodeSelectorOpIn,
Values: []string{"true"},
},
},
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known deprecated labels", func() {
nodeSelector := map[string]string{
// Deprecated Labels
v1.LabelFailureDomainBetaRegion: env.Region,
v1.LabelFailureDomainBetaZone: fmt.Sprintf("%sa", env.Region),
"beta.kubernetes.io/arch": "amd64",
"beta.kubernetes.io/os": "linux",
v1.LabelInstanceType: "c5.large",
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for topology and architecture", func() {
nodeSelector := map[string]string{
// Well Known
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelTopologyRegion: env.Region,
v1.LabelTopologyZone: fmt.Sprintf("%sa", env.Region),
v1.LabelOSStable: "linux",
v1.LabelArchStable: "amd64",
v1alpha5.LabelCapacityType: "on-demand",
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for a gpu (nvidia)", func() {
nodeSelector := map[string]string{
v1alpha1.LabelInstanceGPUName: "t4",
v1alpha1.LabelInstanceGPUMemory: "16384",
v1alpha1.LabelInstanceGPUManufacturer: "nvidia",
v1alpha1.LabelInstanceGPUCount: "1",
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for an accelerator (inferentia)", func() {
nodeSelector := map[string]string{
v1alpha1.LabelInstanceAcceleratorName: "inferentia",
v1alpha1.LabelInstanceAcceleratorManufacturer: "aws",
v1alpha1.LabelInstanceAcceleratorCount: "1",
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should support well-known labels for windows-build version", func() {
env.ExpectWindowsIPAMEnabled()
DeferCleanup(func() {
env.ExpectWindowsIPAMDisabled()
})
nodeSelector := map[string]string{
// Well Known
v1.LabelWindowsBuild: v1alpha1.Windows2022Build,
v1.LabelOSStable: string(v1.Windows), // Specify the OS to enable vpc-resource-controller to inject the PrivateIPv4Address resource
}
selectors.Insert(lo.Keys(nodeSelector)...) // Add node selector keys to selectors used in testing to ensure we test all labels
requirements := lo.MapToSlice(nodeSelector, func(key string, value string) v1.NodeSelectorRequirement {
return v1.NodeSelectorRequirement{Key: key, Operator: v1.NodeSelectorOpIn, Values: []string{value}}
})
deployment := test.Deployment(test.DeploymentOptions{Replicas: 1, PodOptions: test.PodOptions{
NodeSelector: nodeSelector,
NodePreferences: requirements,
NodeRequirements: requirements,
Image: aws.WindowsDefaultImage,
}})
provider.Spec.AMIFamily = &v1alpha1.AMIFamilyWindows2022
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpExists,
})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCountWithTimeout(time.Minute*15, labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", 1)
})
It("should provision a node for naked pods", func() {
pod := test.Pod()
env.ExpectCreated(provisioner, provider, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
})
It("should provision a node for a deployment", Label(debug.NoWatch), Label(debug.NoEvents), func() {
deployment := test.Deployment(test.DeploymentOptions{Replicas: 50})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("<=", 2) // should probably all land on a single node, but at worst two depending on batching
})
It("should provision a node for a self-affinity deployment", func() {
// just two pods as they all need to land on the same node
podLabels := map[string]string{"test": "self-affinity"}
deployment := test.Deployment(test.DeploymentOptions{
Replicas: 2,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: podLabels,
},
PodRequirements: []v1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{MatchLabels: podLabels},
TopologyKey: v1.LabelHostname,
},
},
},
})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), 2)
env.ExpectCreatedNodeCount("==", 1)
})
It("should provision three nodes for a zonal topology spread", func() {
// one pod per zone
podLabels := map[string]string{"test": "zonal-spread"}
deployment := test.Deployment(test.DeploymentOptions{
Replicas: 3,
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: podLabels,
},
TopologySpreadConstraints: []v1.TopologySpreadConstraint{
{
MaxSkew: 1,
TopologyKey: v1.LabelTopologyZone,
WhenUnsatisfiable: v1.DoNotSchedule,
LabelSelector: &metav1.LabelSelector{MatchLabels: podLabels},
},
},
},
})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(podLabels), 3)
env.ExpectCreatedNodeCount("==", 3)
})
It("should provision a node using a provisioner with higher priority", func() {
provisionerLowPri := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Weight: ptr.Int32(10),
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"t3.nano"},
},
},
})
provisionerHighPri := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Weight: ptr.Int32(100),
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c4.large"},
},
},
})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisionerLowPri, provisionerHighPri)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
Expect(ptr.StringValue(env.GetInstance(pod.Spec.NodeName).InstanceType)).To(Equal("c4.large"))
Expect(env.GetNode(pod.Spec.NodeName).Labels[v1alpha5.ProvisionerNameLabelKey]).To(Equal(provisionerHighPri.Name))
})
})
| 354 |
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 integration_test
import (
"fmt"
"strings"
"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"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("SecurityGroups", func() {
It("should use the security-group-id selector", func() {
securityGroups := env.GetSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(securityGroups)).To(BeNumerically(">", 1))
ids := strings.Join([]string{*securityGroups[0].GroupId, *securityGroups[1].GroupId}, ",")
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"aws-ids": ids},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("SecurityGroups", ConsistOf(&securityGroups[0].GroupIdentifier, &securityGroups[1].GroupIdentifier)))
})
It("should use the security group selector with multiple tag values", func() {
securityGroups := env.GetSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(securityGroups)).To(BeNumerically(">", 1))
first := securityGroups[0]
last := securityGroups[len(securityGroups)-1]
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"Name": fmt.Sprintf("%s,%s",
aws.StringValue(lo.FindOrElse(first.Tags, &ec2.Tag{}, func(tag *ec2.Tag) bool { return aws.StringValue(tag.Key) == "Name" }).Value),
aws.StringValue(lo.FindOrElse(last.Tags, &ec2.Tag{}, func(tag *ec2.Tag) bool { return aws.StringValue(tag.Key) == "Name" }).Value),
)},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("SecurityGroups", ConsistOf(&first.GroupIdentifier, &last.GroupIdentifier)))
})
It("should update the AWSNodeTemplateStatus for security groups", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
env.ExpectCreated(provider)
EventuallyExpectSecurityGroups(provider)
})
})
type SecurityGroup struct {
ec2.GroupIdentifier
Tags []*ec2.Tag
}
// getSecurityGroups returns all getSecurityGroups matching the label selector
func getSecurityGroups(tags map[string]string) []SecurityGroup {
var filters []*ec2.Filter
for key, val := range tags {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(val)},
})
}
var securityGroups []SecurityGroup
err := env.EC2API.DescribeSecurityGroupsPages(&ec2.DescribeSecurityGroupsInput{Filters: filters}, func(dso *ec2.DescribeSecurityGroupsOutput, _ bool) bool {
for _, sg := range dso.SecurityGroups {
securityGroups = append(securityGroups, SecurityGroup{
Tags: sg.Tags,
GroupIdentifier: ec2.GroupIdentifier{GroupId: sg.GroupId, GroupName: sg.GroupName},
})
}
return true
})
Expect(err).To(BeNil())
return securityGroups
}
func EventuallyExpectSecurityGroups(provider *v1alpha1.AWSNodeTemplate) {
securityGroup := getSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(securityGroup)).ToNot(Equal(0))
var securityGroupID []string
for _, secGroup := range securityGroup {
securityGroupID = append(securityGroupID, *secGroup.GroupId)
}
Eventually(func(g Gomega) {
var ant v1alpha1.AWSNodeTemplate
if err := env.Client.Get(env, client.ObjectKeyFromObject(provider), &ant); err != nil {
return
}
securityGroupsInStatus := lo.Map(ant.Status.SecurityGroups, func(securitygroup v1alpha1.SecurityGroup, _ int) string {
return securitygroup.ID
})
g.Expect(securityGroupsInStatus).To(Equal(securityGroupID))
}).WithTimeout(10 * time.Second).Should(Succeed())
}
| 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 integration_test
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
. "github.com/onsi/ginkgo/v2"
)
// This test requires the EBS CSI driver to be installed
var _ = Describe("Dynamic PVC", func() {
It("should run a pod with a dynamic persistent volume", func() {
// Ensure that the EBS driver is installed, or we can't run the test.
var ds appsv1.DaemonSet
if err := env.Client.Get(env.Context, client.ObjectKey{
Namespace: "kube-system",
Name: "ebs-csi-node",
}, &ds); err != nil {
if errors.IsNotFound(err) {
Skip(fmt.Sprintf("skipping dynamic PVC test due to missing EBS driver %s", err))
} else {
Fail(fmt.Sprintf("determining EBS driver status, %s", err))
}
}
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
storageClassName := "ebs-sc-test"
bindMode := storagev1.VolumeBindingWaitForFirstConsumer
sc := test.StorageClass(test.StorageClassOptions{
ObjectMeta: metav1.ObjectMeta{
Name: storageClassName,
},
Provisioner: aws.String("ebs.csi.aws.com"),
VolumeBindingMode: &bindMode,
})
pvc := test.PersistentVolumeClaim(test.PersistentVolumeClaimOptions{
ObjectMeta: metav1.ObjectMeta{
Name: "ebs-claim",
},
StorageClassName: aws.String(storageClassName),
Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceStorage: resource.MustParse("5Gi")}},
})
pod := test.Pod(test.PodOptions{
PersistentVolumeClaims: []string{pvc.Name},
})
env.ExpectCreated(provisioner, provider, sc, pvc, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectDeleted(pod)
})
})
var _ = Describe("Static PVC", func() {
It("should run a pod with a static persistent volume", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
storageClassName := "nfs-test"
bindMode := storagev1.VolumeBindingWaitForFirstConsumer
sc := test.StorageClass(test.StorageClassOptions{
ObjectMeta: metav1.ObjectMeta{
Name: storageClassName,
},
VolumeBindingMode: &bindMode,
})
pv := test.PersistentVolume(test.PersistentVolumeOptions{
ObjectMeta: metav1.ObjectMeta{Name: "nfs-test-volume"},
StorageClassName: "nfs-test",
})
// the server here doesn't need to actually exist for the pod to start running
pv.Spec.NFS = &v1.NFSVolumeSource{
Server: "fake.server",
Path: "/some/path",
}
pv.Spec.CSI = nil
pvc := test.PersistentVolumeClaim(test.PersistentVolumeClaimOptions{
ObjectMeta: metav1.ObjectMeta{
Name: "nfs-claim",
},
StorageClassName: aws.String(storageClassName),
VolumeName: pv.Name,
Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceStorage: resource.MustParse("5Gi")}},
})
pod := test.Pod(test.PodOptions{
PersistentVolumeClaims: []string{pvc.Name},
})
env.ExpectCreated(provisioner, provider, sc, pv, pvc, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectDeleted(pod)
})
})
| 140 |
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 integration_test
import (
"fmt"
"sort"
"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/onsi/gomega/types"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Subnets", func() {
It("should use the subnet-id selector", func() {
subnets := env.GetSubnets(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).ToNot(Equal(0))
shuffledAZs := lo.Shuffle(lo.Keys(subnets))
firstSubnet := subnets[shuffledAZs[0]][0]
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"aws-ids": firstSubnet},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("SubnetId", HaveValue(Equal(firstSubnet))))
})
It("should use resource based naming as node names", func() {
subnets := env.GetSubnets(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).ToNot(Equal(0))
allSubnets := lo.Flatten(lo.Values(subnets))
ExpectResourceBasedNamingEnabled(allSubnets...)
DeferCleanup(func() {
ExpectResourceBasedNamingDisabled(allSubnets...)
})
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
ExceptNodeNameToContainInstanceID(pod.Spec.NodeName)
})
It("should use the subnet tag selector with multiple tag values", func() {
// Get all the subnets for the cluster
subnets := env.GetSubnetNameAndIds(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).To(BeNumerically(">", 1))
firstSubnet := subnets[0]
lastSubnet := subnets[len(subnets)-1]
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"Name": fmt.Sprintf("%s,%s", firstSubnet.Name, lastSubnet.Name)},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("SubnetId", HaveValue(BeElementOf(firstSubnet.ID, lastSubnet.ID))))
})
It("should use a subnet within the AZ requested", func() {
subnets := env.GetSubnets(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).ToNot(Equal(0))
shuffledAZs := lo.Shuffle(lo.Keys(subnets))
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelZoneFailureDomainStable,
Operator: "In",
Values: []string{shuffledAZs[0]},
},
},
})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
env.ExpectInstance(pod.Spec.NodeName).To(HaveField("SubnetId", Or(
lo.Map(subnets[shuffledAZs[0]], func(subnetID string, _ int) types.GomegaMatcher { return HaveValue(Equal(subnetID)) })...,
)))
})
It("should have the AWSNodeTemplateStatus for subnets", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
env.ExpectCreated(provider)
EventuallyExpectSubnets(provider)
})
})
func ExpectResourceBasedNamingEnabled(subnetIDs ...string) {
for subnetID := range subnetIDs {
_, err := env.EC2API.ModifySubnetAttribute(&ec2.ModifySubnetAttributeInput{
EnableResourceNameDnsARecordOnLaunch: &ec2.AttributeBooleanValue{
Value: aws.Bool(true),
},
SubnetId: aws.String(subnetIDs[subnetID]),
})
Expect(err).To(BeNil())
_, err = env.EC2API.ModifySubnetAttribute(&ec2.ModifySubnetAttributeInput{
PrivateDnsHostnameTypeOnLaunch: aws.String("resource-name"),
SubnetId: aws.String(subnetIDs[subnetID]),
})
Expect(err).To(BeNil())
}
}
func ExpectResourceBasedNamingDisabled(subnetIDs ...string) {
for subnetID := range subnetIDs {
_, err := env.EC2API.ModifySubnetAttribute(&ec2.ModifySubnetAttributeInput{
EnableResourceNameDnsARecordOnLaunch: &ec2.AttributeBooleanValue{
Value: aws.Bool(false),
},
SubnetId: aws.String(subnetIDs[subnetID]),
})
Expect(err).To(BeNil())
_, err = env.EC2API.ModifySubnetAttribute(&ec2.ModifySubnetAttributeInput{
PrivateDnsHostnameTypeOnLaunch: aws.String("ip-name"),
SubnetId: aws.String(subnetIDs[subnetID]),
})
Expect(err).To(BeNil())
}
}
func ExceptNodeNameToContainInstanceID(nodeName string) {
instance := env.GetInstance(nodeName)
Expect(nodeName).To(Not(Equal(aws.StringValue(instance.InstanceId))))
ContainSubstring(nodeName, aws.StringValue(instance.InstanceId))
}
// SubnetInfo is a simple struct for testing
type SubnetInfo struct {
Name string
ID string
}
func EventuallyExpectSubnets(provider *v1alpha1.AWSNodeTemplate) {
subnets := env.GetSubnets(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(len(subnets)).ToNot(Equal(0))
subnetIDs := lo.Flatten(lo.Values(subnets))
sort.Strings(subnetIDs)
Eventually(func(g Gomega) {
var ant v1alpha1.AWSNodeTemplate
if err := env.Client.Get(env, client.ObjectKeyFromObject(provider), &ant); err != nil {
return
}
subnetIDsInStatus := lo.Map(ant.Status.Subnets, func(subnet v1alpha1.Subnet, _ int) string {
return subnet.ID
})
sort.Strings(subnetIDsInStatus)
g.Expect(subnetIDsInStatus).To(Equal(subnetIDs))
}).WithTimeout(10 * time.Second).Should(Succeed())
}
| 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 integration_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
func TestIntegration(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "Integration")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
| 39 |
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 integration_test
import (
"github.com/aws/aws-sdk-go/service/ec2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Tags", func() {
It("should tag all associated resources", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{"TestTag": "TestVal"},
},
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
instance := env.GetInstance(pod.Spec.NodeName)
volumeTags := tagMap(env.GetVolume(instance.BlockDeviceMappings[0].Ebs.VolumeId).Tags)
instanceTags := tagMap(instance.Tags)
Expect(instanceTags).To(HaveKeyWithValue("TestTag", "TestVal"))
Expect(volumeTags).To(HaveKeyWithValue("TestTag", "TestVal"))
})
It("should tag all associated resources with global tags", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
env.ExpectSettingsOverridden(map[string]string{
"aws.tags": `{"TestTag": "TestVal", "example.com/tag": "custom-value"}`,
})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
instance := env.GetInstance(pod.Spec.NodeName)
volumeTags := tagMap(env.GetVolume(instance.BlockDeviceMappings[0].Ebs.VolumeId).Tags)
instanceTags := tagMap(instance.Tags)
Expect(instanceTags).To(HaveKeyWithValue("TestTag", "TestVal"))
Expect(volumeTags).To(HaveKeyWithValue("TestTag", "TestVal"))
Expect(instanceTags).To(HaveKeyWithValue("example.com/tag", "custom-value"))
Expect(volumeTags).To(HaveKeyWithValue("example.com/tag", "custom-value"))
})
})
func tagMap(tags []*ec2.Tag) map[string]string {
return lo.SliceToMap(tags, func(tag *ec2.Tag) (string, string) {
return *tag.Key, *tag.Value
})
}
| 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 integration_test
import (
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Termination", func() {
It("should terminate the node and the instance on deletion", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
pod := test.Pod()
env.ExpectCreated(provisioner, provider, pod)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
nodes := env.Monitor.CreatedNodes()
instanceID := env.ExpectParsedProviderID(nodes[0].Spec.ProviderID)
env.GetInstance(nodes[0].Name)
// Pod is deleted so that we don't re-provision after node deletion
// NOTE: We have to do this right now to deal with a race condition in provisioner ownership
// This can be removed once this race is resolved with the Machine
env.ExpectDeleted(pod)
// Node is deleted and now should be not found
env.ExpectDeleted(nodes[0])
env.EventuallyExpectNotFound(nodes[0])
Eventually(func(g Gomega) {
g.Expect(lo.FromPtr(env.GetInstanceByID(instanceID).State.Name)).To(Equal("shutting-down"))
}, time.Second*10).Should(Succeed())
})
})
| 63 |
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 integration_test
import (
"fmt"
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/ptr"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("Webhooks", func() {
Context("Provisioner", func() {
Context("Defaulting", func() {
It("should set the default requirements when none are specified", func() {
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
})
env.ExpectCreated(provisioner)
env.ExpectExists(provisioner)
Expect(len(provisioner.Spec.Requirements)).To(Equal(5))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
}))
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},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c", "m", "r"},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha1.LabelInstanceGeneration,
Operator: v1.NodeSelectorOpGt,
Values: []string{"2"},
}))
})
It("shouldn't default if requirements are set", func() {
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Windows)},
},
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeSpot},
},
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureArm64},
},
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"g"},
},
{
Key: v1alpha1.LabelInstanceGeneration,
Operator: v1.NodeSelectorOpIn,
Values: []string{"4"},
},
},
})
env.ExpectCreated(provisioner)
env.ExpectExists(provisioner)
Expect(len(provisioner.Spec.Requirements)).To(Equal(5))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Windows)},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeSpot},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.ArchitectureArm64},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"g"},
}))
Expect(provisioner.Spec.Requirements).To(ContainElement(v1.NodeSelectorRequirement{
Key: v1alpha1.LabelInstanceGeneration,
Operator: v1.NodeSelectorOpIn,
Values: []string{"4"},
}))
})
})
Context("Validation", func() {
It("should error when provider and providerRef are combined", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
Provider: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
}))).ToNot(Succeed())
})
It("should error when a restricted label is used in labels (karpenter.sh/provisioner-name)", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: "my-custom-provisioner",
},
}))).ToNot(Succeed())
})
It("should error when a restricted label is used in labels (kubernetes.io/custom-label)", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Labels: map[string]string{
"kubernetes.io/custom-label": "custom-value",
},
}))).ToNot(Succeed())
})
It("should error when a requirement references a restricted label (karpenter.sh/provisioner-name)", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.ProvisionerNameLabelKey,
Operator: v1.NodeSelectorOpIn,
Values: []string{"default"},
},
},
}))).ToNot(Succeed())
})
It("should error when a requirement uses In but has no values", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{},
},
},
}))).ToNot(Succeed())
})
It("should error when a requirement uses an unknown operator", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: "within",
Values: []string{v1alpha5.CapacityTypeSpot},
},
},
}))).ToNot(Succeed())
})
It("should error when Gt is used with multiple integer values", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceMemory,
Operator: v1.NodeSelectorOpGt,
Values: []string{"1000000", "2000000"},
},
},
}))).ToNot(Succeed())
})
It("should error when Lt is used with multiple integer values", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceMemory,
Operator: v1.NodeSelectorOpLt,
Values: []string{"1000000", "2000000"},
},
},
}))).ToNot(Succeed())
})
It("should error when ttlSecondAfterEmpty is negative", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
TTLSecondsAfterEmpty: ptr.Int64(-5),
}))).ToNot(Succeed())
})
It("should error when consolidation and ttlSecondAfterEmpty are combined", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Consolidation: &v1alpha5.Consolidation{Enabled: ptr.Bool(true)},
TTLSecondsAfterEmpty: ptr.Int64(60),
}))).ToNot(Succeed())
})
It("should error if imageGCHighThresholdPercent is less than imageGCLowThresholdPercent", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Kubelet: &v1alpha5.KubeletConfiguration{
ImageGCHighThresholdPercent: ptr.Int32(10),
ImageGCLowThresholdPercent: ptr.Int32(60),
},
}))).ToNot(Succeed())
})
It("should error if imageGCHighThresholdPercent or imageGCLowThresholdPercent is negative", func() {
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Kubelet: &v1alpha5.KubeletConfiguration{
ImageGCHighThresholdPercent: ptr.Int32(-10),
},
}))).ToNot(Succeed())
Expect(env.Client.Create(env, test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: "test"},
Kubelet: &v1alpha5.KubeletConfiguration{
ImageGCLowThresholdPercent: ptr.Int32(-10),
},
}))).ToNot(Succeed())
})
})
})
Context("AWSNodeTemplate", func() {
Context("Validation", func() {
It("should error when amiSelector is not defined for amiFamily Custom", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyCustom,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}}))).ToNot(Succeed())
})
It("should fail if both userdata and launchTemplate are set", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
LaunchTemplate: v1alpha1.LaunchTemplate{LaunchTemplateName: ptr.String("lt")},
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
UserData: ptr.String("data"),
}))).ToNot(Succeed())
})
It("should fail if both userdata and Windows2019 AMIFamily are set", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyWindows2019,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
UserData: ptr.String("data"),
}))).ToNot(Succeed())
})
It("should fail if both userdata and Windows2022 AMIFamily are set", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyWindows2022,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
UserData: ptr.String("data"),
}))).ToNot(Succeed())
})
It("should fail if both amiSelector and launchTemplate are set", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
LaunchTemplate: v1alpha1.LaunchTemplate{LaunchTemplateName: ptr.String("lt")},
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{"foo": "bar"},
}))).ToNot(Succeed())
})
It("should fail for poorly formatted aws-ids", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
AMISelector: map[string]string{"aws-ids": "must-start-with-ami"},
}))).ToNot(Succeed())
})
It("should succeed when tags don't contain restricted keys", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{"karpenter.sh/custom-key": "custom-value", "kubernetes.io/role/key": "custom-value"},
},
}))).To(Succeed())
})
It("should error when tags contains a restricted key", func() {
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{"karpenter.sh/provisioner-name": "custom-value"},
},
}))).ToNot(Succeed())
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{"karpenter.sh/managed-by": settings.FromContext(env.Context).ClusterName},
},
}))).ToNot(Succeed())
Expect(env.Client.Create(env, awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
Tags: map[string]string{fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(env.Context).ClusterName): "owned"},
},
}))).ToNot(Succeed())
})
})
})
})
| 342 |
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 (
"fmt"
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/uuid"
"knative.dev/pkg/ptr"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/scheduledchange"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
var provider *v1alpha1.AWSNodeTemplate
func TestInterruption(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "Interruption")
}
var _ = BeforeEach(func() {
env.BeforeEach()
env.ExpectQueueExists()
})
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("Interruption", Label("AWS"), func() {
It("should terminate the spot instance and spin-up a new node on spot interruption warning", func() {
By("Creating a single healthy node with a healthy deployment")
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeSpot},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: ptr.Int64(0),
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provider, provisioner, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
instanceID, err := utils.ParseInstanceID(node.Spec.ProviderID)
Expect(err).ToNot(HaveOccurred())
By("interrupting the spot instance")
exp := env.ExpectSpotInterruptionExperiment(instanceID)
DeferCleanup(func() {
env.ExpectExperimentTemplateDeleted(*exp.ExperimentTemplateId)
})
// We are expecting the node to be terminated before the termination is complete
By("waiting to receive the interruption and terminate the node")
env.EventuallyExpectNotFoundAssertion(node).WithTimeout(time.Second * 110).Should(Succeed())
env.EventuallyExpectHealthyPodCount(selector, 1)
})
It("should terminate the node at the API server when the EC2 instance is stopped", func() {
By("Creating a single healthy node with a healthy deployment")
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeOnDemand},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: ptr.Int64(0),
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provider, provisioner, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
By("Stopping the EC2 instance without the EKS cluster's knowledge")
env.ExpectInstanceStopped(node.Name) // Make a call to the EC2 api to stop the instance
env.EventuallyExpectNotFoundAssertion(node).WithTimeout(time.Minute).Should(Succeed()) // shorten the timeout since we should react faster
env.EventuallyExpectHealthyPodCount(selector, 1)
})
It("should terminate the node at the API server when the EC2 instance is terminated", func() {
By("Creating a single healthy node with a healthy deployment")
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeOnDemand},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: ptr.Int64(0),
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provider, provisioner, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
By("Terminating the EC2 instance without the EKS cluster's knowledge")
env.ExpectInstanceTerminated(node.Name) // Make a call to the EC2 api to stop the instance
env.EventuallyExpectNotFoundAssertion(node).WithTimeout(time.Minute).Should(Succeed()) // shorten the timeout since we should react faster
env.EventuallyExpectHealthyPodCount(selector, 1)
})
It("should terminate the node when receiving a scheduled change health event", func() {
By("Creating a single healthy node with a healthy deployment")
provider = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha5.CapacityTypeOnDemand},
},
},
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
numPods := 1
dep := test.Deployment(test.DeploymentOptions{
Replicas: int32(numPods),
PodOptions: test.PodOptions{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{"app": "my-app"},
},
TerminationGracePeriodSeconds: ptr.Int64(0),
},
})
selector := labels.SelectorFromSet(dep.Spec.Selector.MatchLabels)
env.ExpectCreated(provider, provisioner, dep)
env.EventuallyExpectHealthyPodCount(selector, numPods)
env.ExpectCreatedNodeCount("==", 1)
node := env.Monitor.CreatedNodes()[0]
instanceID, err := utils.ParseInstanceID(node.Spec.ProviderID)
Expect(err).ToNot(HaveOccurred())
By("Creating a scheduled change health event in the SQS message queue")
env.ExpectMessagesCreated(scheduledChangeMessage(env.Region, "000000000000", instanceID))
env.EventuallyExpectNotFoundAssertion(node).WithTimeout(time.Minute).Should(Succeed()) // shorten the timeout since we should react faster
env.EventuallyExpectHealthyPodCount(selector, 1)
})
})
func scheduledChangeMessage(region, accountID, involvedInstanceID string) scheduledchange.Message {
return scheduledchange.Message{
Metadata: messages.Metadata{
Version: "0",
Account: accountID,
DetailType: "AWS Health Event",
ID: string(uuid.NewUUID()),
Region: region,
Resources: []string{
fmt.Sprintf("arn:aws:ec2:%s:instance/%s", region, involvedInstanceID),
},
Source: "aws.health",
Time: time.Now(),
},
Detail: scheduledchange.Detail{
Service: "EC2",
EventTypeCategory: "scheduledChange",
AffectedEntities: []scheduledchange.AffectedEntity{
{
EntityValue: involvedInstanceID,
},
},
},
}
}
| 257 |
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 ipv6_test
import (
"net"
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
func TestIPv6(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "IPv6")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("IPv6", func() {
It("should provision an IPv6 node by discovering kube-dns IPv6", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}, Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"t3a.small"},
},
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"on-demand"},
},
}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
node := env.GetNode(pod.Spec.NodeName)
internalIPv6Addrs := lo.Filter(node.Status.Addresses, func(addr v1.NodeAddress, _ int) bool {
return addr.Type == v1.NodeInternalIP && net.ParseIP(addr.Address).To4() == nil
})
Expect(internalIPv6Addrs).To(HaveLen(1))
})
It("should provision an IPv6 node by discovering kubeletConfig kube-dns IP", func() {
clusterDNSAddr := env.ExpectIPv6ClusterDNS()
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{
AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}, Requirements: []v1.NodeSelectorRequirement{
{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"t3a.small"},
},
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{"on-demand"},
},
}, Kubelet: &v1alpha5.KubeletConfiguration{ClusterDNS: []string{clusterDNSAddr}}})
pod := test.Pod()
env.ExpectCreated(pod, provider, provisioner)
env.EventuallyExpectHealthy(pod)
env.ExpectCreatedNodeCount("==", 1)
node := env.GetNode(pod.Spec.NodeName)
internalIPv6Addrs := lo.Filter(node.Status.Addresses, func(addr v1.NodeAddress, _ int) bool {
return addr.Type == v1.NodeInternalIP && net.ParseIP(addr.Address).To4() == nil
})
Expect(internalIPv6Addrs).To(HaveLen(1))
})
})
| 109 |
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 machine_test
import (
"encoding/base64"
"fmt"
"os"
"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"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awserrors "github.com/aws/karpenter/pkg/errors"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/utils"
environmentaws "github.com/aws/karpenter/test/pkg/environment/aws"
)
var _ = Describe("MachineGarbageCollection", func() {
var customAMI string
var instanceInput *ec2.RunInstancesInput
var provisioner *v1alpha5.Provisioner
BeforeEach(func() {
provisioner = test.Provisioner()
securityGroups := env.GetSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
subnets := env.GetSubnetNameAndIds(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(securityGroups).ToNot(HaveLen(0))
Expect(subnets).ToNot(HaveLen(0))
customAMI = env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
instanceInput = &ec2.RunInstancesInput{
InstanceType: aws.String("c5.large"),
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(settings.FromContext(env.Context).DefaultInstanceProfile),
},
SecurityGroupIds: lo.Map(securityGroups, func(s environmentaws.SecurityGroup, _ int) *string {
return s.GroupIdentifier.GroupId
}),
SubnetId: aws.String(subnets[0].ID),
BlockDeviceMappings: []*ec2.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
Ebs: &ec2.EbsBlockDevice{
Encrypted: aws.Bool(true),
DeleteOnTermination: aws.Bool(true),
VolumeType: aws.String(ec2.VolumeTypeGp3),
VolumeSize: aws.Int64(20),
},
},
},
ImageId: aws.String(customAMI), // EKS AL2-based AMI
TagSpecifications: []*ec2.TagSpecification{
{
ResourceType: aws.String(ec2.ResourceTypeInstance),
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(env.Context).ClusterName)),
Value: aws.String("owned"),
},
{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
},
},
},
},
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
}
})
It("should succeed to garbage collect a Machine that was launched by a Machine but has no Machine mapping", func() {
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
instanceInput.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle(), provisioner.Name))))
// Create an instance manually to mock Karpenter launching an instance
out := env.ExpectRunInstances(instanceInput)
Expect(out.Instances).To(HaveLen(1))
// Always ensure that we cleanup the instance
DeferCleanup(func() {
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{out.Instances[0].InstanceId},
})
if awserrors.IsNotFound(err) {
return
}
Expect(err).ToNot(HaveOccurred())
})
// Wait for the node to register with the cluster
node := env.EventuallyExpectCreatedNodeCount("==", 1)[0]
// Update the tags to add the karpenter.sh/managed-by tag
_, err = env.EC2API.CreateTagsWithContext(env.Context, &ec2.CreateTagsInput{
Resources: []*string{out.Instances[0].InstanceId},
Tags: []*ec2.Tag{
{
Key: aws.String(v1alpha5.MachineManagedByAnnotationKey),
Value: aws.String(settings.FromContext(env.Context).ClusterName),
},
},
})
Expect(err).ToNot(HaveOccurred())
// Eventually expect the node and the instance to be removed (shutting-down)
env.EventuallyExpectNotFound(node)
Eventually(func(g Gomega) {
g.Expect(lo.FromPtr(env.GetInstanceByID(aws.StringValue(out.Instances[0].InstanceId)).State.Name)).To(Equal("shutting-down"))
}, time.Second*10).Should(Succeed())
})
It("should succeed to garbage collect a Machine that was deleted without the cluster's knowledge", func() {
// Disable the interruption queue for the garbage collection test
env.ExpectSettingsOverridden(map[string]string{
"aws.interruptionQueueName": "",
})
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
pod := test.Pod()
env.ExpectCreated(provisioner, provider, pod)
env.EventuallyExpectHealthy(pod)
node := env.ExpectCreatedNodeCount("==", 1)[0]
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: aws.StringSlice([]string{lo.Must(utils.ParseInstanceID(node.Spec.ProviderID))}),
})
Expect(err).ToNot(HaveOccurred())
// The garbage collection mechanism should eventually delete this machine and node
env.EventuallyExpectNotFound(node)
})
})
| 163 |
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 machine_test
import (
"encoding/base64"
"fmt"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/samber/lo"
"sigs.k8s.io/controller-runtime/pkg/client"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awserrors "github.com/aws/karpenter/pkg/errors"
awstest "github.com/aws/karpenter/pkg/test"
environmentaws "github.com/aws/karpenter/test/pkg/environment/aws"
)
var _ = Describe("MachineLink", func() {
var customAMI string
var instanceInput *ec2.RunInstancesInput
BeforeEach(func() {
securityGroups := env.GetSecurityGroups(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
subnets := env.GetSubnetNameAndIds(map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName})
Expect(securityGroups).ToNot(HaveLen(0))
Expect(subnets).ToNot(HaveLen(0))
customAMI = env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
instanceInput = &ec2.RunInstancesInput{
InstanceType: aws.String("c5.large"),
IamInstanceProfile: &ec2.IamInstanceProfileSpecification{
Name: aws.String(settings.FromContext(env.Context).DefaultInstanceProfile),
},
SecurityGroupIds: lo.Map(securityGroups, func(s environmentaws.SecurityGroup, _ int) *string {
return s.GroupIdentifier.GroupId
}),
SubnetId: aws.String(subnets[0].ID),
BlockDeviceMappings: []*ec2.BlockDeviceMapping{
{
DeviceName: aws.String("/dev/xvda"),
Ebs: &ec2.EbsBlockDevice{
Encrypted: aws.Bool(true),
DeleteOnTermination: aws.Bool(true),
VolumeType: aws.String(ec2.VolumeTypeGp3),
VolumeSize: aws.Int64(20),
},
},
},
ImageId: aws.String(customAMI), // EKS AL2-based AMI
TagSpecifications: []*ec2.TagSpecification{
{
ResourceType: aws.String(ec2.ResourceTypeInstance),
Tags: []*ec2.Tag{
{
Key: aws.String(fmt.Sprintf("kubernetes.io/cluster/%s", settings.FromContext(env.Context).ClusterName)),
Value: aws.String("owned"),
},
},
},
},
MinCount: aws.Int64(1),
MaxCount: aws.Int64(1),
}
})
It("should succeed to link a Machine for an existing instance launched by Karpenter", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyAL2,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
env.ExpectCreated(provisioner, provider)
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
instanceInput.TagSpecifications[0].Tags = append(instanceInput.TagSpecifications[0].Tags, &ec2.Tag{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
})
instanceInput.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle(), provisioner.Name))))
// Create an instance manually to mock Karpenter launching an instance
out := env.ExpectRunInstances(instanceInput)
Expect(out.Instances).To(HaveLen(1))
// Always ensure that we cleanup the instance
DeferCleanup(func() {
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{out.Instances[0].InstanceId},
})
if awserrors.IsNotFound(err) {
return
}
Expect(err).ToNot(HaveOccurred())
})
// Wait for the node to register with the cluster
env.EventuallyExpectCreatedNodeCount("==", 1)
// Restart Karpenter to start the linking process
env.EventuallyExpectKarpenterRestarted()
// Expect that the Machine is created when Karpenter starts up
machines := env.EventuallyExpectCreatedMachineCount("==", 1)
machine := machines[0]
// Expect the machine's fields are properly populated
Expect(machine.Spec.Requirements).To(Equal(provisioner.Spec.Requirements))
Expect(machine.Spec.MachineTemplateRef.Name).To(Equal(provider.Name))
// Expect the instance to have the karpenter.sh/managed-by tag
Eventually(func(g Gomega) {
instance := env.GetInstanceByID(aws.StringValue(out.Instances[0].InstanceId))
tag, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == v1alpha5.MachineManagedByAnnotationKey
})
g.Expect(ok).To(BeTrue())
g.Expect(aws.StringValue(tag.Value)).To(Equal(settings.FromContext(env.Context).ClusterName))
}, time.Minute, time.Second).Should(Succeed())
})
It("should succeed to link a Machine for an existing instance launched by Karpenter with provider", func() {
provisioner := test.Provisioner(test.ProvisionerOptions{
Provider: &v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyAL2,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
},
})
env.ExpectCreated(provisioner)
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
instanceInput.TagSpecifications[0].Tags = append(instanceInput.TagSpecifications[0].Tags, &ec2.Tag{
Key: aws.String(v1alpha5.ProvisionerNameLabelKey),
Value: aws.String(provisioner.Name),
})
instanceInput.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle(), provisioner.Name))))
// Create an instance manually to mock Karpenter launching an instance
out := env.ExpectRunInstances(instanceInput)
Expect(out.Instances).To(HaveLen(1))
// Always ensure that we cleanup the instance
DeferCleanup(func() {
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{out.Instances[0].InstanceId},
})
if awserrors.IsNotFound(err) {
return
}
Expect(err).ToNot(HaveOccurred())
})
// Wait for the node to register with the cluster
env.EventuallyExpectCreatedNodeCount("==", 1)
// Restart Karpenter to start the linking process
env.EventuallyExpectKarpenterRestarted()
// Expect that the Machine is created when Karpenter starts up
machines := env.EventuallyExpectCreatedMachineCount("==", 1)
machine := machines[0]
// Expect the machine's fields are properly populated
Expect(machine.Spec.Requirements).To(Equal(provisioner.Spec.Requirements))
Expect(machine.Annotations).To(HaveKeyWithValue(v1alpha5.ProviderCompatabilityAnnotationKey, v1alpha5.ProviderAnnotation(provisioner.Spec.Provider)[v1alpha5.ProviderCompatabilityAnnotationKey]))
// Expect the instance to have the karpenter.sh/managed-by tag
Eventually(func(g Gomega) {
instance := env.GetInstanceByID(aws.StringValue(out.Instances[0].InstanceId))
tag, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == v1alpha5.MachineManagedByAnnotationKey
})
g.Expect(ok).To(BeTrue())
g.Expect(aws.StringValue(tag.Value)).To(Equal(settings.FromContext(env.Context).ClusterName))
}, time.Minute, time.Second).Should(Succeed())
})
It("should succeed to link a Machine for an existing instance re-owned by Karpenter", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
AMIFamily: &v1alpha1.AMIFamilyAL2,
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name},
})
env.ExpectCreated(provisioner, provider)
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
// No tag specifications since we're mocking an instance not launched by Karpenter
instanceInput.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle(), provisioner.Name))))
// Create an instance manually to mock Karpenter launching an instance
out := env.ExpectRunInstances(instanceInput)
Expect(out.Instances).To(HaveLen(1))
// Always ensure that we cleanup the instance
DeferCleanup(func() {
_, err := env.EC2API.TerminateInstances(&ec2.TerminateInstancesInput{
InstanceIds: []*string{out.Instances[0].InstanceId},
})
if awserrors.IsNotFound(err) {
return
}
Expect(err).ToNot(HaveOccurred())
})
// Wait for the node to register with the cluster
node := env.EventuallyExpectCreatedNodeCount("==", 1)[0]
// Add the provisioner-name label to the node to re-own it
stored := node.DeepCopy()
node.Labels[v1alpha5.ProvisionerNameLabelKey] = provisioner.Name
Expect(env.Client.Patch(env.Context, node, client.MergeFrom(stored))).To(Succeed())
// Restart Karpenter to start the linking process
env.EventuallyExpectKarpenterRestarted()
// Expect that the Machine is created when Karpenter starts up
machines := env.EventuallyExpectCreatedMachineCount("==", 1)
machine := machines[0]
// Expect the machine's fields are properly populated
Expect(machine.Spec.Requirements).To(Equal(provisioner.Spec.Requirements))
Expect(machine.Spec.MachineTemplateRef.Name).To(Equal(provider.Name))
// Expect the instance to have the karpenter.sh/managed-by tag and the karpenter.sh/provisioner-name tag
Eventually(func(g Gomega) {
instance := env.GetInstanceByID(aws.StringValue(out.Instances[0].InstanceId))
tag, ok := lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == v1alpha5.MachineManagedByAnnotationKey
})
g.Expect(ok).To(BeTrue())
g.Expect(aws.StringValue(tag.Value)).To(Equal(settings.FromContext(env.Context).ClusterName))
tag, ok = lo.Find(instance.Tags, func(t *ec2.Tag) bool {
return aws.StringValue(t.Key) == v1alpha5.ProvisionerNameLabelKey
})
g.Expect(ok).To(BeTrue())
g.Expect(aws.StringValue(tag.Value)).To(Equal(provisioner.Name))
}, time.Minute, time.Second).Should(Succeed())
})
})
| 275 |
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 machine_test
import (
"encoding/base64"
"fmt"
"os"
"time"
. "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"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/resources"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
)
var _ = Describe("StandaloneMachine", func() {
var nodeTemplate *v1alpha1.AWSNodeTemplate
BeforeEach(func() {
nodeTemplate = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
})
// For standalone machines, there is no Provisioner owner, so we just list all machines and delete them all
AfterEach(func() {
env.CleanupObjects(functional.Pair[client.Object, client.ObjectList]{First: &v1alpha5.Machine{}, Second: &v1alpha5.MachineList{}})
})
It("should create a standard machine within the 'c' instance family", func() {
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c"},
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
machine = env.EventuallyExpectCreatedMachineCount("==", 1)[0]
Expect(node.Labels).To(HaveKeyWithValue(v1alpha1.LabelInstanceCategory, "c"))
env.EventuallyExpectMachinesReady(machine)
})
It("should create a standard machine based on resource requests", func() {
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Resources: v1alpha5.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("3"),
v1.ResourceMemory: resource.MustParse("64Gi"),
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
machine = env.EventuallyExpectCreatedMachineCount("==", 1)[0]
Expect(resources.Fits(machine.Spec.Resources.Requests, node.Status.Allocatable))
env.EventuallyExpectMachinesReady(machine)
})
It("should create a machine propagating all the machine spec details", func() {
machine := test.Machine(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"custom-annotation": "custom-value",
},
Labels: map[string]string{
"custom-label": "custom-value",
},
},
Spec: v1alpha5.MachineSpec{
Taints: []v1.Taint{
{
Key: "custom-taint",
Effect: v1.TaintEffectNoSchedule,
Value: "custom-value",
},
{
Key: "other-custom-taint",
Effect: v1.TaintEffectNoExecute,
Value: "other-custom-value",
},
},
Resources: v1alpha5.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("3"),
v1.ResourceMemory: resource.MustParse("16Gi"),
},
},
Kubelet: &v1alpha5.KubeletConfiguration{
ContainerRuntime: lo.ToPtr("containerd"),
MaxPods: lo.ToPtr[int32](110),
PodsPerCore: lo.ToPtr[int32](10),
SystemReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("200m"),
v1.ResourceMemory: resource.MustParse("200Mi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("200m"),
v1.ResourceMemory: resource.MustParse("200Mi"),
v1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
EvictionHard: map[string]string{
"memory.available": "5%",
"nodefs.available": "5%",
"nodefs.inodesFree": "5%",
"imagefs.available": "5%",
"imagefs.inodesFree": "5%",
"pid.available": "3%",
},
EvictionSoft: map[string]string{
"memory.available": "10%",
"nodefs.available": "10%",
"nodefs.inodesFree": "10%",
"imagefs.available": "10%",
"imagefs.inodesFree": "10%",
"pid.available": "6%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute * 2},
"nodefs.available": {Duration: time.Minute * 2},
"nodefs.inodesFree": {Duration: time.Minute * 2},
"imagefs.available": {Duration: time.Minute * 2},
"imagefs.inodesFree": {Duration: time.Minute * 2},
"pid.available": {Duration: time.Minute * 2},
},
EvictionMaxPodGracePeriod: lo.ToPtr[int32](120),
ImageGCHighThresholdPercent: lo.ToPtr[int32](50),
ImageGCLowThresholdPercent: lo.ToPtr[int32](10),
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
Expect(node.Annotations).To(HaveKeyWithValue("custom-annotation", "custom-value"))
Expect(node.Labels).To(HaveKeyWithValue("custom-label", "custom-value"))
Expect(node.Spec.Taints).To(ContainElements(
v1.Taint{
Key: "custom-taint",
Effect: v1.TaintEffectNoSchedule,
Value: "custom-value",
},
v1.Taint{
Key: "other-custom-taint",
Effect: v1.TaintEffectNoExecute,
Value: "other-custom-value",
},
))
Expect(node.OwnerReferences).To(ContainElement(
metav1.OwnerReference{
APIVersion: v1alpha5.SchemeGroupVersion.String(),
Kind: "Machine",
Name: machine.Name,
UID: machine.UID,
BlockOwnerDeletion: lo.ToPtr(true),
},
))
env.EventuallyExpectCreatedMachineCount("==", 1)
env.EventuallyExpectMachinesReady(machine)
})
It("should remove the cloudProvider machine when the cluster machine is deleted", func() {
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c"},
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
machine = env.EventuallyExpectCreatedMachineCount("==", 1)[0]
instanceID := env.ExpectParsedProviderID(node.Spec.ProviderID)
env.GetInstance(node.Name)
// Node is deleted and now should be not found
env.ExpectDeleted(machine)
env.EventuallyExpectNotFound(machine, node)
Eventually(func(g Gomega) {
g.Expect(lo.FromPtr(env.GetInstanceByID(instanceID).State.Name)).To(Equal("shutting-down"))
}, time.Second*10).Should(Succeed())
})
It("should delete a machine from the node termination finalizer", func() {
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c"},
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
machine = env.EventuallyExpectCreatedMachineCount("==", 1)[0]
instanceID := env.ExpectParsedProviderID(node.Spec.ProviderID)
env.GetInstance(node.Name)
// Delete the node and expect both the node and machine to be gone as well as the instance to be shutting-down
env.ExpectDeleted(node)
env.EventuallyExpectNotFound(machine, node)
Eventually(func(g Gomega) {
g.Expect(lo.FromPtr(env.GetInstanceByID(instanceID).State.Name)).To(Equal("shutting-down"))
}, time.Second*10).Should(Succeed())
})
It("should create a machine with custom labels passed through the userData", func() {
customAMI := env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_custom_labels_input.sh")
Expect(err).ToNot(HaveOccurred())
// Create userData that adds custom labels through the --kubelet-extra-args
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
nodeTemplate.Spec.AMISelector = map[string]string{"aws-ids": customAMI}
nodeTemplate.Spec.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), settings.FromContext(env.Context).ClusterName,
settings.FromContext(env.Context).ClusterEndpoint, env.ExpectCABundle()))))
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c"},
},
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"amd64"},
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
node := env.EventuallyExpectInitializedNodeCount("==", 1)[0]
Expect(node.Labels).To(HaveKeyWithValue("custom-label", "custom-value"))
Expect(node.Labels).To(HaveKeyWithValue("custom-label2", "custom-value2"))
env.EventuallyExpectCreatedMachineCount("==", 1)
env.EventuallyExpectMachinesReady(machine)
})
It("should delete a machine after the registration timeout when the node doesn't register", func() {
customAMI := env.GetCustomAMI("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", 1)
// Update the userData for the instance input with the correct provisionerName
rawContent, err := os.ReadFile("testdata/al2_userdata_input.sh")
Expect(err).ToNot(HaveOccurred())
// Create userData that adds custom labels through the --kubelet-extra-args
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyCustom
nodeTemplate.Spec.AMISelector = map[string]string{"aws-ids": customAMI}
// Giving bad clusterName and clusterEndpoint to the userData
nodeTemplate.Spec.UserData = lo.ToPtr(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(string(rawContent), "badName", "badEndpoint", env.ExpectCABundle()))))
machine := test.Machine(v1alpha5.Machine{
Spec: v1alpha5.MachineSpec{
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha1.LabelInstanceCategory,
Operator: v1.NodeSelectorOpIn,
Values: []string{"c"},
},
{
Key: v1.LabelArchStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"amd64"},
},
},
MachineTemplateRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
},
})
env.ExpectCreated(nodeTemplate, machine)
machine = env.EventuallyExpectCreatedMachineCount("==", 1)[0]
// Expect that the machine eventually launches and has false Registration/Initialization
Eventually(func(g Gomega) {
temp := &v1alpha5.Machine{}
g.Expect(env.Client.Get(env.Context, client.ObjectKeyFromObject(machine), temp)).To(Succeed())
g.Expect(temp.StatusConditions().GetCondition(v1alpha5.MachineLaunched).IsTrue()).To(BeTrue())
g.Expect(temp.StatusConditions().GetCondition(v1alpha5.MachineRegistered).IsFalse()).To(BeTrue())
g.Expect(temp.StatusConditions().GetCondition(v1alpha5.MachineInitialized).IsFalse()).To(BeTrue())
}).Should(Succeed())
// Expect that the machine is eventually de-provisioned due to the registration timeout
env.EventuallyExpectNotFoundAssertion(machine).WithTimeout(time.Minute * 20).Should(Succeed())
})
})
| 345 |
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 machine_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
func TestMachine(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "Machine")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
| 39 |
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 scale_test
import (
"context"
"fmt"
"sync"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/samber/lo"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/uuid"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/pkg/controllers/interruption/messages"
"github.com/aws/karpenter/pkg/controllers/interruption/messages/scheduledchange"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/pkg/utils"
"github.com/aws/karpenter/test/pkg/debug"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
const (
deprovisioningTypeKey = v1alpha5.TestingGroup + "/deprovisioning-type"
consolidationValue = "consolidation"
emptinessValue = "emptiness"
expirationValue = "expiration"
noExpirationValue = "noExpiration"
driftValue = "drift"
noDriftValue = "noDrift"
)
const (
multipleDeprovisionersTestGroup = "multipleDeprovisioners"
consolidationTestGroup = "consolidation"
emptinessTestGroup = "emptiness"
expirationTestGroup = "expiration"
driftTestGroup = "drift"
interruptionTestGroup = "interruption"
defaultTestName = "default"
)
// disableProvisioningLimits represents limits that can be applied to a provisioner if you want a provisioner
// that can deprovision nodes but cannot provision nodes
var disableProvisioningLimits = &v1alpha5.Limits{
Resources: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("0"),
v1.ResourceMemory: resource.MustParse("0Gi"),
},
}
var _ = Describe("Deprovisioning", Label(debug.NoWatch), Label(debug.NoEvents), func() {
var provisioner *v1alpha5.Provisioner
var provisionerOptions test.ProvisionerOptions
var nodeTemplate *v1alpha1.AWSNodeTemplate
var deployment *appsv1.Deployment
var deploymentOptions test.DeploymentOptions
var selector labels.Selector
var dsCount int
BeforeEach(func() {
env.ExpectSettingsOverridden(map[string]string{
"featureGates.driftEnabled": "true",
})
nodeTemplate = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisionerOptions = test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha1.CapacityTypeOnDemand},
},
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
},
{
Key: "karpenter.k8s.aws/instance-hypervisor",
Operator: v1.NodeSelectorOpIn,
Values: []string{"nitro"},
},
},
// No limits!!!
// https://tenor.com/view/chaos-gif-22919457
Limits: v1.ResourceList{},
}
provisioner = test.Provisioner(provisionerOptions)
deploymentOptions = test.DeploymentOptions{
PodOptions: test.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("10m"),
v1.ResourceMemory: resource.MustParse("50Mi"),
},
},
TerminationGracePeriodSeconds: lo.ToPtr[int64](0),
},
}
deployment = test.Deployment(deploymentOptions)
selector = labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels)
dsCount = env.GetDaemonSetCount(provisioner)
})
AfterEach(func() {
env.Cleanup()
})
Context("Multiple Deprovisioners", func() {
It("should run consolidation, emptiness, expiration, and drift simultaneously", func(_ context.Context) {
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
nodeCountPerProvisioner := 10
replicas := replicasPerNode * nodeCountPerProvisioner
deprovisioningTypes := []string{
consolidationValue,
emptinessValue,
expirationValue,
driftValue,
}
expectedNodeCount := nodeCountPerProvisioner * len(deprovisioningTypes)
deploymentMap := map[string]*appsv1.Deployment{}
// Generate all the deployments for multi-deprovisioning
for _, v := range deprovisioningTypes {
deploymentOptions.PodOptions.NodeSelector = map[string]string{
deprovisioningTypeKey: v,
}
deploymentOptions.PodOptions.Labels = map[string]string{
deprovisioningTypeKey: v,
}
deploymentOptions.PodOptions.Tolerations = []v1.Toleration{
{
Key: deprovisioningTypeKey,
Operator: v1.TolerationOpEqual,
Value: v,
Effect: v1.TaintEffectNoSchedule,
},
}
deploymentOptions.Replicas = int32(replicas)
d := test.Deployment(deploymentOptions)
deploymentMap[v] = d
}
provisionerMap := map[string]*v1alpha5.Provisioner{}
// Generate all the provisioners for multi-deprovisioning
for _, v := range deprovisioningTypes {
provisionerOptions.Taints = []v1.Taint{
{
Key: deprovisioningTypeKey,
Value: v,
Effect: v1.TaintEffectNoSchedule,
},
}
provisionerOptions.Labels = map[string]string{
deprovisioningTypeKey: v,
}
provisionerOptions.Kubelet = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
provisionerMap[v] = test.Provisioner(provisionerOptions)
}
By("waiting for the deployment to deploy all of its pods")
var wg sync.WaitGroup
for _, d := range deploymentMap {
wg.Add(1)
go func(dep *appsv1.Deployment) {
defer GinkgoRecover()
defer wg.Done()
env.ExpectCreated(dep)
env.EventuallyExpectPendingPodCount(labels.SelectorFromSet(dep.Spec.Selector.MatchLabels), int(lo.FromPtr(dep.Spec.Replicas)))
}(d)
}
wg.Wait()
// Create a separate nodeTemplate for drift so that we can change the nodeTemplate later without it affecting
// the other provisioners
driftNodeTemplate := nodeTemplate.DeepCopy()
driftNodeTemplate.Name = test.RandomName()
provisionerMap[driftValue].Spec.ProviderRef = &v1alpha5.MachineTemplateRef{
Name: driftNodeTemplate.Name,
}
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(driftNodeTemplate, nodeTemplate)
for _, p := range provisionerMap {
env.ExpectCreated(p)
}
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
// Wait for all pods across all deployments we have created to be in a healthy state
wg = sync.WaitGroup{}
for _, d := range deploymentMap {
wg.Add(1)
go func(dep *appsv1.Deployment) {
defer GinkgoRecover()
defer wg.Done()
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(dep.Spec.Selector.MatchLabels), int(lo.FromPtr(dep.Spec.Replicas)))
}(d)
}
wg.Wait()
}, aws.ProvisioningEventType, multipleDeprovisionersTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
By("scaling down replicas across deployments")
deploymentMap[consolidationValue].Spec.Replicas = lo.ToPtr[int32](int32(int(float64(replicas) * 0.2)))
deploymentMap[emptinessValue].Spec.Replicas = lo.ToPtr[int32](0)
for _, d := range deploymentMap {
env.ExpectUpdated(d)
}
var totalDeletedCount int
var totalCreatedCount int
env.MeasureDurationFor(func() {
By("enabling deprovisioning across provisioners")
// Create a provisioner for expiration so that expiration can do replacement
provisionerMap[noExpirationValue] = test.Provisioner()
provisionerMap[noExpirationValue].Spec = provisionerMap[expirationValue].Spec
provisionerMap[consolidationValue].Spec.Consolidation = &v1alpha5.Consolidation{Enabled: lo.ToPtr(true)}
provisionerMap[emptinessValue].Spec.TTLSecondsAfterEmpty = lo.ToPtr[int64](0)
provisionerMap[expirationValue].Spec.TTLSecondsUntilExpired = lo.ToPtr[int64](0)
provisionerMap[expirationValue].Spec.Limits = disableProvisioningLimits
for _, p := range provisionerMap {
env.ExpectCreatedOrUpdated(p)
}
driftNodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
env.ExpectUpdated(driftNodeTemplate)
By("waiting for the nodes across all deprovisioners to get deleted")
type testAssertions struct {
deletedCount int
deletedNodeCountSelector labels.Selector
nodeCount int
nodeCountSelector labels.Selector
createdCount int
}
assertionMap := map[string]testAssertions{
consolidationValue: {
deletedCount: int(float64(nodeCountPerProvisioner) * 0.8),
nodeCount: int(float64(nodeCountPerProvisioner) * 0.2),
createdCount: 0,
},
emptinessValue: {
deletedCount: nodeCountPerProvisioner,
nodeCount: 0,
createdCount: 0,
},
expirationValue: {
deletedCount: nodeCountPerProvisioner,
nodeCount: nodeCountPerProvisioner,
nodeCountSelector: labels.SelectorFromSet(map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisionerMap[noExpirationValue].Name,
}),
createdCount: nodeCountPerProvisioner,
},
driftValue: {
deletedCount: nodeCountPerProvisioner,
nodeCount: nodeCountPerProvisioner,
createdCount: nodeCountPerProvisioner,
},
}
totalDeletedCount = lo.Reduce(lo.Values(assertionMap), func(agg int, assertion testAssertions, _ int) int {
return agg + assertion.deletedCount
}, 0)
totalCreatedCount = lo.Reduce(lo.Values(assertionMap), func(agg int, assertion testAssertions, _ int) int {
return agg + assertion.createdCount
}, 0)
wg = sync.WaitGroup{}
for k, v := range assertionMap {
wg.Add(1)
go func(d string, assertions testAssertions) {
defer GinkgoRecover()
defer wg.Done()
env.MeasureDurationFor(func() {
// Provide a default selector based on the original provisioner name if one isn't specified
selector = assertions.deletedNodeCountSelector
if selector == nil {
selector = labels.SelectorFromSet(map[string]string{v1alpha5.ProvisionerNameLabelKey: provisionerMap[d].Name})
}
env.EventuallyExpectDeletedNodeCountWithSelector("==", assertions.deletedCount, selector)
// Provide a default selector based on the original provisioner name if one isn't specified
selector = assertions.nodeCountSelector
if selector == nil {
selector = labels.SelectorFromSet(map[string]string{v1alpha5.ProvisionerNameLabelKey: provisionerMap[d].Name})
}
env.EventuallyExpectNodeCountWithSelector("==", assertions.nodeCount, selector)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deploymentMap[d].Spec.Selector.MatchLabels), int(lo.FromPtr(deploymentMap[d].Spec.Replicas)))
}, aws.DeprovisioningEventType, multipleDeprovisionersTestGroup, defaultTestName,
lo.Assign(map[string]string{aws.TestSubEventTypeDimension: d}, aws.GenerateTestDimensions(assertions.createdCount, assertions.deletedCount, replicasPerNode)))
}(k, v)
}
wg.Wait()
}, aws.DeprovisioningEventType, multipleDeprovisionersTestGroup, defaultTestName, aws.GenerateTestDimensions(totalCreatedCount, totalDeletedCount, replicasPerNode))
}, SpecTimeout(time.Hour))
})
Context("Consolidation", func() {
It("should delete all empty nodes with consolidation", func(_ context.Context) {
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 200
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, consolidationTestGroup, "empty/delete", aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
// Delete deployment to make nodes empty
env.ExpectDeleted(deployment)
env.EventuallyExpectHealthyPodCount(selector, 0)
env.MeasureDurationFor(func() {
By("kicking off deprovisioning by setting the consolidation enabled value on the provisioner")
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{Enabled: lo.ToPtr(true)}
env.ExpectUpdated(provisioner)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount)
env.EventuallyExpectNodeCount("==", 0)
}, aws.DeprovisioningEventType, consolidationTestGroup, "empty/delete", aws.GenerateTestDimensions(0, expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Minute*30))
It("should consolidate nodes to get a higher utilization (multi-consolidation delete)", func(_ context.Context) {
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 200
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, consolidationTestGroup, "delete", aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
replicas = int(float64(replicas) * 0.2)
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
env.ExpectUpdated(deployment)
env.EventuallyExpectHealthyPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off deprovisioning by setting the consolidation enabled value on the provisioner")
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{Enabled: lo.ToPtr(true)}
env.ExpectUpdated(provisioner)
env.EventuallyExpectDeletedNodeCount("==", int(float64(expectedNodeCount)*0.8))
env.EventuallyExpectNodeCount("==", int(float64(expectedNodeCount)*0.2))
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.DeprovisioningEventType, consolidationTestGroup, "delete", aws.GenerateTestDimensions(env.Monitor.CreatedNodeCount(), int(float64(expectedNodeCount)*0.8), replicasPerNode))
}, SpecTimeout(time.Minute*30))
It("should consolidate nodes to get a higher utilization (single consolidation replace)", func(_ context.Context) {
replicasPerNode := 1
expectedNodeCount := 20 // we're currently doing around 1 node/2 mins so this test should run deprovisioning in about 45m
replicas := replicasPerNode * expectedNodeCount
// Add in a instance type size requirement that's larger than the smallest that fits the pods.
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements, v1.NodeSelectorRequirement{
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"2xlarge"},
})
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
// Hostname anti-affinity to require one pod on each node
deployment.Spec.Template.Spec.Affinity = &v1.Affinity{
PodAntiAffinity: &v1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
{
LabelSelector: deployment.Spec.Selector,
TopologyKey: v1.LabelHostname,
},
},
},
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, consolidationTestGroup, "replace", aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
env.MeasureDurationFor(func() {
By("kicking off deprovisioning by setting the consolidation enabled value on the provisioner")
// The provisioner defaults to a larger instance type than we need so enabling consolidation and making
// the requirements wide-open should cause deletes and increase our utilization on the cluster
provisioner.Spec.Consolidation = &v1alpha5.Consolidation{Enabled: lo.ToPtr(true)}
provisioner.Spec.Requirements = lo.Reject(provisioner.Spec.Requirements, func(r v1.NodeSelectorRequirement, _ int) bool {
return r.Key == v1alpha1.LabelInstanceSize
})
env.ExpectUpdated(provisioner)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount) // every node should delete due to replacement
env.EventuallyExpectNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.DeprovisioningEventType, consolidationTestGroup, "replace", aws.GenerateTestDimensions(env.Monitor.CreatedNodeCount(), expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Hour))
})
Context("Emptiness", func() {
It("should deprovision all nodes when empty", func(_ context.Context) {
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 200
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, emptinessTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
By("waiting for all deployment pods to be deleted")
// Delete deployment to make nodes empty
env.ExpectDeleted(deployment)
env.EventuallyExpectHealthyPodCount(selector, 0)
env.MeasureDurationFor(func() {
By("kicking off deprovisioning emptiness by setting the ttlSecondsAfterEmpty value on the provisioner")
provisioner.Spec.TTLSecondsAfterEmpty = lo.ToPtr[int64](0)
env.ExpectCreatedOrUpdated(provisioner)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount)
env.EventuallyExpectNodeCount("==", 0)
}, aws.DeprovisioningEventType, emptinessTestGroup, defaultTestName, aws.GenerateTestDimensions(0, expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Minute*30))
})
Context("Expiration", func() {
It("should expire all nodes", func(_ context.Context) {
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 20 // we're currently doing around 1 node/2 mins so this test should run deprovisioning in about 45m
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, expirationTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
env.MeasureDurationFor(func() {
By("kicking off deprovisioning expiration by setting the ttlSecondsUntilExpired value on the provisioner")
// Change Provisioner limits so that replacement nodes will use another provisioner.
provisioner.Spec.Limits = disableProvisioningLimits
// Enable Expiration
provisioner.Spec.TTLSecondsUntilExpired = lo.ToPtr[int64](0)
noExpireProvisioner := test.Provisioner(provisionerOptions)
noExpireProvisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
env.ExpectCreatedOrUpdated(provisioner, noExpireProvisioner)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount)
env.EventuallyExpectNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.DeprovisioningEventType, expirationTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Hour))
})
Context("Drift", func() {
It("should drift all nodes", func(_ context.Context) {
// Before Deprovisioning, we need to Provision the cluster to the state that we need.
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 20 // we're currently doing around 1 node/2 mins so this test should run deprovisioning in about 45m
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, driftTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
env.MeasureDurationFor(func() {
By("kicking off deprovisioning drift by changing the nodeTemplate AMIFamily")
nodeTemplate.Spec.AMIFamily = &v1alpha1.AMIFamilyBottlerocket
env.ExpectCreatedOrUpdated(nodeTemplate)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount)
env.EventuallyExpectNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.DeprovisioningEventType, driftTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Hour))
})
Context("Interruption", func() {
It("should interrupt all nodes due to scheduledChange", func(_ context.Context) {
env.ExpectQueueExists() // Ensure the queue exists before sending messages
replicasPerNode := 20
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 200
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
var nodes []*v1.Node
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
nodes = env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, interruptionTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
env.Monitor.Reset() // Reset the monitor so that we now track the nodes starting at this point in time
var msgs []interface{}
for _, node := range nodes {
instanceID, err := utils.ParseInstanceID(node.Spec.ProviderID)
Expect(err).ToNot(HaveOccurred())
msgs = append(msgs, scheduledChangeMessage(env.Region, "000000000000", instanceID))
}
env.MeasureDurationFor(func() {
By("kicking off deprovisioning by adding scheduledChange messages to the queue")
env.ExpectMessagesCreated(msgs...)
env.EventuallyExpectDeletedNodeCount("==", expectedNodeCount)
env.EventuallyExpectNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.DeprovisioningEventType, interruptionTestGroup, defaultTestName, aws.GenerateTestDimensions(expectedNodeCount, expectedNodeCount, replicasPerNode))
}, SpecTimeout(time.Minute*30))
})
})
func scheduledChangeMessage(region, accountID, involvedInstanceID string) scheduledchange.Message {
return scheduledchange.Message{
Metadata: messages.Metadata{
Version: "0",
Account: accountID,
DetailType: "AWS Health Event",
ID: string(uuid.NewUUID()),
Region: region,
Resources: []string{
fmt.Sprintf("arn:aws:ec2:%s:instance/%s", region, involvedInstanceID),
},
Source: "aws.health",
Time: time.Now(),
},
Detail: scheduledchange.Detail{
Service: "EC2",
EventTypeCategory: "scheduledChange",
AffectedEntities: []scheduledchange.AffectedEntity{
{
EntityValue: involvedInstanceID,
},
},
},
}
}
| 680 |
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 scale_test
import (
"context"
"time"
. "github.com/onsi/ginkgo/v2"
"github.com/samber/lo"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/debug"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
const testGroup = "provisioning"
var _ = Describe("Provisioning", Label(debug.NoWatch), func() {
var provisioner *v1alpha5.Provisioner
var nodeTemplate *v1alpha1.AWSNodeTemplate
var deployment *appsv1.Deployment
var selector labels.Selector
var dsCount int
BeforeEach(func() {
nodeTemplate = awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner = test.Provisioner(test.ProvisionerOptions{
ProviderRef: &v1alpha5.MachineTemplateRef{
Name: nodeTemplate.Name,
},
Requirements: []v1.NodeSelectorRequirement{
{
Key: v1alpha5.LabelCapacityType,
Operator: v1.NodeSelectorOpIn,
Values: []string{v1alpha1.CapacityTypeOnDemand},
},
{
Key: v1.LabelOSStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{string(v1.Linux)},
},
{
Key: "karpenter.k8s.aws/instance-hypervisor",
Operator: v1.NodeSelectorOpIn,
Values: []string{"nitro"},
},
},
// No limits!!!
// https://tenor.com/view/chaos-gif-22919457
Limits: v1.ResourceList{},
})
deployment = test.Deployment(test.DeploymentOptions{
PodOptions: test.PodOptions{
ResourceRequirements: v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("10m"),
v1.ResourceMemory: resource.MustParse("50Mi"),
},
},
TerminationGracePeriodSeconds: lo.ToPtr[int64](0),
},
})
selector = labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels)
// Get the DS pod count and use it to calculate the DS pod overhead
dsCount = env.GetDaemonSetCount(provisioner)
})
It("should scale successfully on a node-dense scale-up", func(_ context.Context) {
// Disable Prefix Delegation for the node-dense scale-up to not exhaust the IPs
// This is required because of the number of Warm ENIs that will be created and the number of IPs
// that will be allocated across this large number of nodes, despite the fact that the ENI CIDR space will
// be extremely under-utilized
env.ExpectPrefixDelegationDisabled()
replicasPerNode := 1
expectedNodeCount := 500
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
// Hostname anti-affinity to require one pod on each node
deployment.Spec.Template.Spec.Affinity = &v1.Affinity{
PodAntiAffinity: &v1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
{
LabelSelector: deployment.Spec.Selector,
TopologyKey: v1.LabelHostname,
},
},
},
}
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
env.MeasureDurationFor(func() {
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, testGroup, "node-dense", aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
}, SpecTimeout(time.Minute*30))
It("should scale successfully on a pod-dense scale-up", Label(debug.NoEvents), func(_ context.Context) {
replicasPerNode := 110
maxPodDensity := replicasPerNode + dsCount
expectedNodeCount := 60
replicas := replicasPerNode * expectedNodeCount
deployment.Spec.Replicas = lo.ToPtr[int32](int32(replicas))
provisioner.Spec.KubeletConfiguration = &v1alpha5.KubeletConfiguration{
MaxPods: lo.ToPtr[int32](int32(maxPodDensity)),
}
provisioner.Spec.Requirements = append(provisioner.Spec.Requirements,
v1.NodeSelectorRequirement{
// With Prefix Delegation enabled, .large instances can have 434 pods.
Key: v1alpha1.LabelInstanceSize,
Operator: v1.NodeSelectorOpIn,
Values: []string{"large"},
},
)
env.MeasureDurationFor(func() {
By("waiting for the deployment to deploy all of its pods")
env.ExpectCreated(deployment)
env.EventuallyExpectPendingPodCount(selector, replicas)
By("kicking off provisioning by applying the provisioner and nodeTemplate")
env.ExpectCreated(provisioner, nodeTemplate)
env.EventuallyExpectCreatedMachineCount("==", expectedNodeCount)
env.EventuallyExpectCreatedNodeCount("==", expectedNodeCount)
env.EventuallyExpectInitializedNodeCount("==", expectedNodeCount)
env.EventuallyExpectHealthyPodCount(selector, replicas)
}, aws.ProvisioningEventType, testGroup, "pod-dense", aws.GenerateTestDimensions(expectedNodeCount, 0, replicasPerNode))
}, SpecTimeout(time.Minute*30))
})
| 162 |
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 scale_test
import (
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
func TestScale(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
SetDefaultEventuallyTimeout(time.Hour)
})
RunSpecs(t, "Scale")
}
var _ = BeforeEach(func() {
env.ExpectPrefixDelegationEnabled()
env.BeforeEach()
})
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() {
env.AfterEach()
env.ExpectPrefixDelegationDisabled()
})
| 47 |
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 utilization_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/labels"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/test"
"github.com/aws/karpenter/pkg/apis/settings"
"github.com/aws/karpenter/pkg/apis/v1alpha1"
"github.com/aws/karpenter/test/pkg/debug"
awstest "github.com/aws/karpenter/pkg/test"
"github.com/aws/karpenter/test/pkg/environment/aws"
)
var env *aws.Environment
func TestUtilization(t *testing.T) {
RegisterFailHandler(Fail)
BeforeSuite(func() {
env = aws.NewEnvironment(t)
})
RunSpecs(t, "Utilization")
}
var _ = BeforeEach(func() { env.BeforeEach() })
var _ = AfterEach(func() { env.Cleanup() })
var _ = AfterEach(func() { env.AfterEach() })
var _ = Describe("Utilization", Label(debug.NoWatch), Label(debug.NoEvents), func() {
It("should provision one pod per node", func() {
provider := awstest.AWSNodeTemplate(v1alpha1.AWSNodeTemplateSpec{AWS: v1alpha1.AWS{
SecurityGroupSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
SubnetSelector: map[string]string{"karpenter.sh/discovery": settings.FromContext(env.Context).ClusterName},
}})
provisioner := test.Provisioner(test.ProvisionerOptions{ProviderRef: &v1alpha5.MachineTemplateRef{Name: provider.Name}, Requirements: []v1.NodeSelectorRequirement{{
Key: v1.LabelInstanceTypeStable,
Operator: v1.NodeSelectorOpIn,
Values: []string{"t3a.small"},
}}})
deployment := test.Deployment(test.DeploymentOptions{
Replicas: 100,
PodOptions: test.PodOptions{ResourceRequirements: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceCPU: resource.MustParse("1.5")}}}})
env.ExpectCreated(provisioner, provider, deployment)
env.EventuallyExpectHealthyPodCount(labels.SelectorFromSet(deployment.Spec.Selector.MatchLabels), int(*deployment.Spec.Replicas))
env.ExpectCreatedNodeCount("==", int(*deployment.Spec.Replicas)) // One pod per node enforced by instance size
})
})
| 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 (
"context"
"encoding/csv"
"flag"
"fmt"
"log"
"os"
"sort"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/manager"
coreoperator "github.com/aws/karpenter-core/pkg/operator"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
corecloudprovider "github.com/aws/karpenter-core/pkg/cloudprovider"
"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/operator"
)
var clusterName string
var outFile string
var overheadPercent float64
func init() {
flag.StringVar(&clusterName, "cluster-name", "", "cluster name to use when passing subnets into GetInstanceTypes()")
flag.StringVar(&outFile, "out-file", "allocatable-diff.csv", "file to output the generated data")
flag.Float64Var(&overheadPercent, "overhead-percent", 0, "overhead percentage to use for calculations")
flag.Parse()
}
func main() {
if clusterName == "" {
log.Fatalf("cluster name cannot be empty")
}
restConfig := config.GetConfigOrDie()
kubeClient := lo.Must(client.New(restConfig, client.Options{}))
ctx := context.Background()
ctx = settings.ToContext(ctx, &settings.Settings{ClusterName: clusterName, IsolatedVPC: true, VMMemoryOverheadPercent: overheadPercent})
file := lo.Must(os.OpenFile(outFile, os.O_RDWR|os.O_CREATE, 0777))
defer file.Close()
w := csv.NewWriter(file)
defer w.Flush()
nodeList := &v1.NodeList{}
lo.Must0(kubeClient.List(ctx, nodeList))
ctx, op := operator.NewOperator(ctx, &coreoperator.Operator{
Manager: lo.Must(manager.New(restConfig, manager.Options{})),
KubernetesInterface: kubernetes.NewForConfigOrDie(restConfig),
})
cloudProvider := cloudprovider.New(
op.InstanceTypesProvider,
op.InstanceProvider,
op.GetClient(),
op.AMIProvider,
op.SecurityGroupProvider,
op.SubnetProvider,
)
raw := &runtime.RawExtension{}
lo.Must0(raw.UnmarshalJSON(lo.Must(json.Marshal(&v1alpha1.AWS{
SubnetSelector: map[string]string{
"karpenter.sh/discovery": clusterName,
},
}))))
instanceTypes := lo.Must(cloudProvider.GetInstanceTypes(ctx, &v1alpha5.Provisioner{
Spec: v1alpha5.ProvisionerSpec{
Provider: raw,
},
}))
// Write the header information into the CSV
lo.Must0(w.Write([]string{"Instance Type", "Expected Capacity", "", "", "Expected Allocatable", "", "", "Actual Capacity", "", "", "Actual Allocatable", ""}))
lo.Must0(w.Write([]string{"", "Memory (Mi)", "CPU (m)", "Storage (Mi)", "Memory (Mi)", "CPU (m)", "Storage (Mi)", "Memory (Mi)", "CPU (m)", "Storage (Mi)", "Memory (Mi)", "CPU (m)", "Storage (Mi)"}))
nodeList.Items = lo.Filter(nodeList.Items, func(n v1.Node, _ int) bool {
return n.Labels["karpenter.sh/provisioner-name"] != "" && n.Status.Allocatable.Memory().Value() != 0
})
sort.Slice(nodeList.Items, func(i, j int) bool {
return nodeList.Items[i].Labels[v1.LabelInstanceTypeStable] < nodeList.Items[j].Labels[v1.LabelInstanceTypeStable]
})
for _, node := range nodeList.Items {
instanceType, ok := lo.Find(instanceTypes, func(i *corecloudprovider.InstanceType) bool {
return i.Name == node.Labels[v1.LabelInstanceTypeStable]
})
if !ok {
log.Fatalf("retrieving instance type for instance %s", node.Labels[v1.LabelInstanceTypeStable])
}
allocatable := instanceType.Allocatable()
// Write the details of the expected instance and the actual instance into a CSV line format
lo.Must0(w.Write([]string{
instanceType.Name,
fmt.Sprintf("%d", instanceType.Capacity.Memory().Value()/1024/1024),
fmt.Sprintf("%d", instanceType.Capacity.Cpu().MilliValue()),
fmt.Sprintf("%d", instanceType.Capacity.StorageEphemeral().Value()/1024/1024),
fmt.Sprintf("%d", allocatable.Memory().Value()/1024/1024),
fmt.Sprintf("%d", allocatable.Cpu().MilliValue()),
fmt.Sprintf("%d", allocatable.StorageEphemeral().Value()/1024/1024),
fmt.Sprintf("%d", node.Status.Capacity.Memory().Value()/1024/1024),
fmt.Sprintf("%d", node.Status.Capacity.Cpu().MilliValue()),
fmt.Sprintf("%d", node.Status.Capacity.StorageEphemeral().Value()/1024/1024),
fmt.Sprintf("%d", node.Status.Allocatable.Memory().Value()/1024/1024),
fmt.Sprintf("%d", node.Status.Allocatable.Cpu().MilliValue()),
fmt.Sprintf("%d", node.Status.Allocatable.StorageEphemeral().Value()/1024/1024),
}))
}
}
| 135 |
karpenter-core | 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
import (
_ "embed"
"github.com/samber/lo"
v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/utils/functional"
)
var (
// Builder includes all types within the apis package
Builder = runtime.NewSchemeBuilder(
v1alpha5.SchemeBuilder.AddToScheme,
)
// AddToScheme may be used to add all resources defined in the project to a Scheme
AddToScheme = Builder.AddToScheme
Settings = []settings.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.sh_provisioners.yaml
ProvisionerCRD []byte
//go:embed crds/karpenter.sh_machines.yaml
MachineCRD []byte
CRDs = []*v1.CustomResourceDefinition{
lo.Must(functional.Unmarshal[v1.CustomResourceDefinition](ProvisionerCRD)),
lo.Must(functional.Unmarshal[v1.CustomResourceDefinition](MachineCRD)),
}
)
| 50 |
karpenter-core | 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"
v1 "k8s.io/api/core/v1"
)
// Injectable defines a ConfigMap registration to be loaded into context on startup
type Injectable interface {
ConfigMap() string
Inject(context.Context, *v1.ConfigMap) (context.Context, error)
}
| 28 |
karpenter-core | 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"
"fmt"
"time"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"knative.dev/pkg/configmap"
)
type settingsKeyType struct{}
var ContextKey = settingsKeyType{}
var defaultSettings = &Settings{
BatchMaxDuration: &metav1.Duration{Duration: time.Second * 10},
BatchIdleDuration: &metav1.Duration{Duration: time.Second * 1},
DriftEnabled: false,
}
// +k8s:deepcopy-gen=true
type Settings struct {
BatchMaxDuration *metav1.Duration
BatchIdleDuration *metav1.Duration
// This feature flag is temporary and will be removed in the near future.
DriftEnabled bool
}
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,
AsMetaDuration("batchMaxDuration", &s.BatchMaxDuration),
AsMetaDuration("batchIdleDuration", &s.BatchIdleDuration),
configmap.AsBool("featureGates.driftEnabled", &s.DriftEnabled),
); 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
}
func (in *Settings) Validate() (err error) {
if in.BatchMaxDuration == nil {
err = multierr.Append(err, fmt.Errorf("batchMaxDuration is required"))
} else if in.BatchMaxDuration.Duration <= 0 {
err = multierr.Append(err, fmt.Errorf("batchMaxDuration cannot be negative"))
}
if in.BatchIdleDuration == nil {
err = multierr.Append(err, fmt.Errorf("batchIdleDuration is required"))
} else if in.BatchIdleDuration.Duration <= 0 {
err = multierr.Append(err, fmt.Errorf("batchIdleDuration cannot be negative"))
}
return err
}
// AsMetaDuration parses the value at key as a time.Duration into the target, if it exists.
func AsMetaDuration(key string, target **metav1.Duration) configmap.ParseFunc {
return func(data map[string]string) error {
if raw, ok := data[key]; ok {
if raw == "" {
*target = nil
return nil
}
val, err := time.ParseDuration(raw)
if err != nil {
return fmt.Errorf("failed to parse %q: %w", key, err)
}
*target = &metav1.Duration{Duration: val}
}
return nil
}
}
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)
}
| 111 |
karpenter-core | 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"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
v1 "k8s.io/api/core/v1"
. "knative.dev/pkg/logging/testing"
"github.com/aws/karpenter-core/pkg/apis/settings"
)
var ctx context.Context
func TestSettings(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{},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.BatchMaxDuration.Duration).To(Equal(time.Second * 10))
Expect(s.BatchIdleDuration.Duration).To(Equal(time.Second))
Expect(s.DriftEnabled).To(BeFalse())
})
It("should succeed to set custom values", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"batchMaxDuration": "30s",
"batchIdleDuration": "5s",
"featureGates.driftEnabled": "true",
},
}
ctx, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).ToNot(HaveOccurred())
s := settings.FromContext(ctx)
Expect(s.BatchMaxDuration.Duration).To(Equal(time.Second * 30))
Expect(s.BatchIdleDuration.Duration).To(Equal(time.Second * 5))
Expect(s.DriftEnabled).To(BeTrue())
})
It("should fail validation when batchMaxDuration is negative", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"batchMaxDuration": "-10s",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when batchMaxDuration is set to empty", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"batchMaxDuration": "",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when batchIdleDuration is negative", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"batchIdleDuration": "-1s",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when batchIdleDuration is set to empty", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"batchMaxDuration": "",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
It("should fail validation when driftEnabled is not a valid boolean value", func() {
cm := &v1.ConfigMap{
Data: map[string]string{
"featureGates.driftEnabled": "foobar",
},
}
_, err := (&settings.Settings{}).Inject(ctx, cm)
Expect(err).To(HaveOccurred())
})
})
| 111 |
karpenter-core | 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 (
"k8s.io/apimachinery/pkg/apis/meta/v1"
)
// 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.BatchMaxDuration != nil {
in, out := &in.BatchMaxDuration, &out.BatchMaxDuration
*out = new(v1.Duration)
**out = **in
}
if in.BatchIdleDuration != nil {
in, out := &in.BatchIdleDuration, &out.BatchIdleDuration
*out = new(v1.Duration)
**out = **in
}
}
// 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
}
| 50 |
karpenter-core | 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.sh
package v1alpha5 // doc.go is discovered by codegen
| 20 |
karpenter-core | 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 (
"fmt"
"strings"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
// Well known labels and resources
const (
ArchitectureAmd64 = "amd64"
ArchitectureArm64 = "arm64"
CapacityTypeSpot = "spot"
CapacityTypeOnDemand = "on-demand"
)
// Karpenter specific domains and labels
const (
ProvisionerNameLabelKey = Group + "/provisioner-name"
LabelNodeInitialized = Group + "/initialized"
LabelCapacityType = Group + "/capacity-type"
)
// Karpenter specific annotations
const (
DoNotEvictPodAnnotationKey = Group + "/do-not-evict"
DoNotConsolidateNodeAnnotationKey = Group + "/do-not-consolidate"
EmptinessTimestampAnnotationKey = Group + "/emptiness-timestamp"
VoluntaryDisruptionAnnotationKey = Group + "/voluntary-disruption"
MachineLinkedAnnotationKey = Group + "/linked"
MachineManagedByAnnotationKey = Group + "/managed-by"
ProviderCompatabilityAnnotationKey = CompatabilityGroup + "/provider"
// Karpenter specific annotation values
VoluntaryDisruptionDriftedAnnotationValue = "drifted"
VoluntaryDisruptionExpiredAnnotationValue = "expired"
)
// Karpenter specific finalizers
const (
TerminationFinalizer = Group + "/termination"
)
var (
// RestrictedLabelDomains are either prohibited by the kubelet or reserved by karpenter
RestrictedLabelDomains = sets.NewString(
"kubernetes.io",
"k8s.io",
Group,
)
// LabelDomainExceptions are sub-domains of the RestrictedLabelDomains but allowed because
// they are not used in a context where they may be passed as argument to kubelet.
LabelDomainExceptions = sets.NewString(
"kops.k8s.io",
v1.LabelNamespaceSuffixNode,
TestingGroup,
)
// WellKnownLabels are labels that belong to the RestrictedLabelDomains but allowed.
// Karpenter is aware of these labels, and they can be used to further narrow down
// the range of the corresponding values by either provisioner or pods.
WellKnownLabels = sets.NewString(
ProvisionerNameLabelKey,
v1.LabelTopologyZone,
v1.LabelTopologyRegion,
v1.LabelInstanceTypeStable,
v1.LabelArchStable,
v1.LabelOSStable,
LabelCapacityType,
)
// RestrictedLabels are labels that should not be used
// because they may interfere with the internal provisioning logic.
RestrictedLabels = sets.NewString(
EmptinessTimestampAnnotationKey,
v1.LabelHostname,
)
// NormalizedLabels translate aliased concepts into the controller's
// WellKnownLabels. Pod requirements are translated for compatibility.
NormalizedLabels = map[string]string{
v1.LabelFailureDomainBetaZone: v1.LabelTopologyZone,
"beta.kubernetes.io/arch": v1.LabelArchStable,
"beta.kubernetes.io/os": v1.LabelOSStable,
v1.LabelInstanceType: v1.LabelInstanceTypeStable,
v1.LabelFailureDomainBetaRegion: v1.LabelTopologyRegion,
}
)
// IsRestrictedLabel returns an error if the label is restricted.
func IsRestrictedLabel(key string) error {
if WellKnownLabels.Has(key) {
return nil
}
if IsRestrictedNodeLabel(key) {
return fmt.Errorf("label %s is restricted; specify a well known label: %v, or a custom label that does not use a restricted domain: %v", key, WellKnownLabels.List(), RestrictedLabelDomains.List())
}
return nil
}
// IsRestrictedNodeLabel returns true if a node label should not be injected by Karpenter.
// They are either known labels that will be injected by cloud providers,
// or label domain managed by other software (e.g., kops.k8s.io managed by kOps).
func IsRestrictedNodeLabel(key string) bool {
if WellKnownLabels.Has(key) {
return true
}
labelDomain := getLabelDomain(key)
if LabelDomainExceptions.Has(labelDomain) {
return false
}
for restrictedLabelDomain := range RestrictedLabelDomains {
if strings.HasSuffix(labelDomain, restrictedLabelDomain) {
return true
}
}
return RestrictedLabels.Has(key)
}
func getLabelDomain(key string) string {
if parts := strings.SplitN(key, "/", 2); len(parts) == 2 {
return parts[0]
}
return ""
}
| 144 |
karpenter-core | 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 (
"fmt"
v1 "k8s.io/api/core/v1"
)
// Limits define bounds on the resources being provisioned by Karpenter
type Limits struct {
// Resources contains all the allocatable resources that Karpenter supports for limiting.
Resources v1.ResourceList `json:"resources,omitempty"`
}
func (l *Limits) ExceededBy(resources v1.ResourceList) error {
if l == nil || l.Resources == nil {
return nil
}
for resourceName, usage := range resources {
if limit, ok := l.Resources[resourceName]; ok {
if usage.Cmp(limit) > 0 {
return fmt.Errorf("%s resource usage of %v exceeds limit of %v", resourceName, usage.AsDec(), limit.AsDec())
}
}
}
return nil
}
| 42 |
karpenter-core | 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 (
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// MachineSpec describes the desired state of the Machine
type MachineSpec struct {
// Taints will be applied to the machine's node.
// +optional
Taints []v1.Taint `json:"taints,omitempty"`
// StartupTaints are taints that are applied to nodes upon startup which are expected to be removed automatically
// within a short period of time, typically by a DaemonSet that tolerates the taint. These are commonly used by
// daemonsets to allow initialization and enforce startup ordering. StartupTaints are ignored for provisioning
// purposes in that pods are not required to tolerate a StartupTaint in order to have nodes provisioned for them.
// +optional
StartupTaints []v1.Taint `json:"startupTaints,omitempty"`
// Requirements are layered with Labels and applied to every node.
Requirements []v1.NodeSelectorRequirement `json:"requirements,omitempty"`
// Resources models the resource requirements for the Machine to launch
Resources ResourceRequirements `json:"resources,omitempty"`
// Kubelet are options passed to the kubelet when provisioning nodes
// +optional
Kubelet *KubeletConfiguration `json:"kubelet,omitempty"`
// MachineTemplateRef is a reference to an object that defines provider specific configuration
MachineTemplateRef *MachineTemplateRef `json:"machineTemplateRef,omitempty"`
}
// KubeletConfiguration defines args to be used when configuring kubelet on provisioned nodes.
// They are a subset of the upstream types, recognizing not all options may be supported.
// Wherever possible, the types and names should reflect the upstream kubelet types.
// https://pkg.go.dev/k8s.io/kubelet/config/v1beta1#KubeletConfiguration
// https://github.com/kubernetes/kubernetes/blob/9f82d81e55cafdedab619ea25cabf5d42736dacf/cmd/kubelet/app/options/options.go#L53
type KubeletConfiguration struct {
// clusterDNS is a list of IP addresses for the cluster DNS server.
// Note that not all providers may use all addresses.
//+optional
ClusterDNS []string `json:"clusterDNS,omitempty"`
// ContainerRuntime is the container runtime to be used with your worker nodes.
// +optional
ContainerRuntime *string `json:"containerRuntime,omitempty"`
// MaxPods is an override for the maximum number of pods that can run on
// a worker node instance.
// +kubebuilder:validation:Minimum:=0
// +optional
MaxPods *int32 `json:"maxPods,omitempty"`
// PodsPerCore is an override for the number of pods that can run on a worker node
// instance based on the number of cpu cores. This value cannot exceed MaxPods, so, if
// MaxPods is a lower value, that value will be used.
// +kubebuilder:validation:Minimum:=0
// +optional
PodsPerCore *int32 `json:"podsPerCore,omitempty"`
// SystemReserved contains resources reserved for OS system daemons and kernel memory.
// +optional
SystemReserved v1.ResourceList `json:"systemReserved,omitempty"`
// KubeReserved contains resources reserved for Kubernetes system components.
// +optional
KubeReserved v1.ResourceList `json:"kubeReserved,omitempty"`
// EvictionHard is the map of signal names to quantities that define hard eviction thresholds
// +optional
EvictionHard map[string]string `json:"evictionHard,omitempty"`
// EvictionSoft is the map of signal names to quantities that define soft eviction thresholds
// +optional
EvictionSoft map[string]string `json:"evictionSoft,omitempty"`
// EvictionSoftGracePeriod is the map of signal names to quantities that define grace periods for each eviction signal
// +optional
EvictionSoftGracePeriod map[string]metav1.Duration `json:"evictionSoftGracePeriod,omitempty"`
// EvictionMaxPodGracePeriod is the maximum allowed grace period (in seconds) to use when terminating pods in
// response to soft eviction thresholds being met.
// +optional
EvictionMaxPodGracePeriod *int32 `json:"evictionMaxPodGracePeriod,omitempty"`
// ImageGCHighThresholdPercent is the percent of disk usage after which image
// garbage collection is always run. The percent is calculated by dividing this
// field value by 100, so this field must be between 0 and 100, inclusive.
// When specified, the value must be greater than ImageGCLowThresholdPercent.
// +kubebuilder:validation:Minimum:=0
// +kubebuilder:validation:Maximum:=100
// +optional
ImageGCHighThresholdPercent *int32 `json:"imageGCHighThresholdPercent,omitempty"`
// ImageGCLowThresholdPercent is the percent of disk usage before which image
// garbage collection is never run. Lowest disk usage to garbage collect to.
// The percent is calculated by dividing this field value by 100,
// so the field value must be between 0 and 100, inclusive.
// When specified, the value must be less than imageGCHighThresholdPercent
// +kubebuilder:validation:Minimum:=0
// +kubebuilder:validation:Maximum:=100
// +optional
ImageGCLowThresholdPercent *int32 `json:"imageGCLowThresholdPercent,omitempty"`
// CPUCFSQuota enables CPU CFS quota enforcement for containers that specify CPU limits.
// +optional
CPUCFSQuota *bool `json:"cpuCFSQuota,omitempty"`
}
type MachineTemplateRef struct {
// Kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds"
Kind string `json:"kind,omitempty"`
// Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names
// +required
Name string `json:"name"`
// API version of the referent
// +optional
APIVersion string `json:"apiVersion,omitempty"`
}
// ResourceRequirements models the required resources for the Machine to launch
// Ths will eventually be transformed into v1.ResourceRequirements when we support resources.limits
type ResourceRequirements struct {
// Requests describes the minimum required resources for the Machine to launch
// +optional
Requests v1.ResourceList `json:"requests,omitempty"`
}
// Machine is the Schema for the Machines API
// +kubebuilder:object:root=true
// +kubebuilder:resource:path=machines,scope=Cluster,categories=karpenter
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Type",type="string",JSONPath=".metadata.labels.node\\.kubernetes\\.io/instance-type",description=""
// +kubebuilder:printcolumn:name="Zone",type="string",JSONPath=".metadata.labels.topology\\.kubernetes\\.io/zone",description=""
// +kubebuilder:printcolumn:name="Node",type="string",JSONPath=".status.nodeName",description=""
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.conditions[?(@.type==\"Ready\")].status",description=""
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description=""
// +kubebuilder:printcolumn:name="Capacity",type="string",JSONPath=".metadata.labels.karpenter\\.sh/capacity-type",priority=1,description=""
// +kubebuilder:printcolumn:name="Provisioner",type="string",JSONPath=".metadata.labels.karpenter\\.sh/provisioner-name",priority=1,description=""
// +kubebuilder:printcolumn:name="Template",type="string",JSONPath=".spec.machineTemplateRef.name",priority=1,description=""
type Machine struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MachineSpec `json:"spec,omitempty"`
Status MachineStatus `json:"status,omitempty"`
}
// MachineList contains a list of Provisioner
// +kubebuilder:object:root=true
type MachineList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Machine `json:"items"`
}
| 155 |
karpenter-core | 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 (
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
)
// MachineStatus defines the observed state of Machine
type MachineStatus struct {
// NodeName is the name of the corresponding node object
// +optional
NodeName string `json:"nodeName,omitempty"`
// ProviderID of the corresponding node object
// +optional
ProviderID string `json:"providerID,omitempty"`
// Capacity is the estimated full capacity of the machine
// +optional
Capacity v1.ResourceList `json:"capacity,omitempty"`
// Allocatable is the estimated allocatable capacity of the machine
// +optional
Allocatable v1.ResourceList `json:"allocatable,omitempty"`
// Conditions contains signals for health and readiness
// +optional
Conditions apis.Conditions `json:"conditions,omitempty"`
}
func (in *Machine) StatusConditions() apis.ConditionManager {
return apis.NewLivingConditionSet(
MachineLaunched,
MachineRegistered,
MachineInitialized,
).Manage(in)
}
var (
MachineLaunched apis.ConditionType = "MachineLaunched"
MachineRegistered apis.ConditionType = "MachineRegistered"
MachineInitialized apis.ConditionType = "MachineInitialized"
)
func (in *Machine) GetConditions() apis.Conditions {
return in.Status.Conditions
}
func (in *Machine) SetConditions(conditions apis.Conditions) {
in.Status.Conditions = conditions
}
| 62 |
karpenter-core | 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 (
"encoding/json"
"sort"
"github.com/samber/lo"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"knative.dev/pkg/ptr"
)
// ProvisionerSpec is the top level provisioner specification. Provisioners
// launch nodes in response to pods that are unschedulable. A single provisioner
// is capable of managing a diverse set of nodes. Node properties are determined
// from a combination of provisioner and pod scheduling constraints.
type ProvisionerSpec struct {
// Annotations are applied to every node.
//+optional
Annotations map[string]string `json:"annotations,omitempty"`
// Labels are layered with Requirements and applied to every node.
//+optional
Labels map[string]string `json:"labels,omitempty"`
// Taints will be applied to every node launched by the Provisioner. If
// specified, the provisioner will not provision nodes for pods that do not
// have matching tolerations. Additional taints will be created that match
// pod tolerations on a per-node basis.
// +optional
Taints []v1.Taint `json:"taints,omitempty"`
// StartupTaints are taints that are applied to nodes upon startup which are expected to be removed automatically
// within a short period of time, typically by a DaemonSet that tolerates the taint. These are commonly used by
// daemonsets to allow initialization and enforce startup ordering. StartupTaints are ignored for provisioning
// purposes in that pods are not required to tolerate a StartupTaint in order to have nodes provisioned for them.
// +optional
StartupTaints []v1.Taint `json:"startupTaints,omitempty"`
// Requirements are layered with Labels and applied to every node.
Requirements []v1.NodeSelectorRequirement `json:"requirements,omitempty"`
// KubeletConfiguration are options passed to the kubelet when provisioning nodes
//+optional
KubeletConfiguration *KubeletConfiguration `json:"kubeletConfiguration,omitempty"`
// Provider contains fields specific to your cloudprovider.
// +kubebuilder:pruning:PreserveUnknownFields
Provider *Provider `json:"provider,omitempty"`
// ProviderRef is a reference to a dedicated CRD for the chosen provider, that holds
// additional configuration options
// +optional
ProviderRef *MachineTemplateRef `json:"providerRef,omitempty"`
// TTLSecondsAfterEmpty is the number of seconds the controller will wait
// before attempting to delete a node, measured from when the node is
// detected to be empty. A Node is considered to be empty when it does not
// have pods scheduled to it, excluding daemonsets.
//
// Termination due to no utilization is disabled if this field is not set.
// +optional
TTLSecondsAfterEmpty *int64 `json:"ttlSecondsAfterEmpty,omitempty"`
// TTLSecondsUntilExpired is the number of seconds the controller will wait
// before terminating a node, measured from when the node is created. This
// is useful to implement features like eventually consistent node upgrade,
// memory leak protection, and disruption testing.
//
// Termination due to expiration is disabled if this field is not set.
// +optional
TTLSecondsUntilExpired *int64 `json:"ttlSecondsUntilExpired,omitempty"`
// Limits define a set of bounds for provisioning capacity.
Limits *Limits `json:"limits,omitempty"`
// Weight is the priority given to the provisioner during scheduling. A higher
// numerical weight indicates that this provisioner will be ordered
// ahead of other provisioners with lower weights. A provisioner with no weight
// will be treated as if it is a provisioner with a weight of 0.
// +kubebuilder:validation:Minimum:=1
// +kubebuilder:validation:Maximum:=100
// +optional
Weight *int32 `json:"weight,omitempty"`
// Consolidation are the consolidation parameters
// +optional
Consolidation *Consolidation `json:"consolidation,omitempty"`
}
type Consolidation struct {
// Enabled enables consolidation if it has been set
Enabled *bool `json:"enabled,omitempty"`
}
// +kubebuilder:object:generate=false
type Provider = runtime.RawExtension
func ProviderAnnotation(p *Provider) map[string]string {
if p == nil {
return nil
}
raw := lo.Must(json.Marshal(p)) // Provider should already have been validated so this shouldn't fail
return map[string]string{ProviderCompatabilityAnnotationKey: string(raw)}
}
// Provisioner is the Schema for the Provisioners API
// +kubebuilder:object:root=true
// +kubebuilder:resource:path=provisioners,scope=Cluster,categories=karpenter
// +kubebuilder:subresource:status
type Provisioner struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ProvisionerSpec `json:"spec,omitempty"`
Status ProvisionerStatus `json:"status,omitempty"`
}
// ProvisionerList contains a list of Provisioner
// +kubebuilder:object:root=true
type ProvisionerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Provisioner `json:"items"`
}
// OrderByWeight orders the provisioners in the ProvisionerList
// by their priority weight in-place
func (pl *ProvisionerList) OrderByWeight() {
sort.Slice(pl.Items, func(a, b int) bool {
return ptr.Int32Value(pl.Items[a].Spec.Weight) > ptr.Int32Value(pl.Items[b].Spec.Weight)
})
}
| 137 |
karpenter-core | 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"
)
// SetDefaults for the provisioner
func (p *Provisioner) SetDefaults(_ context.Context) {}
| 23 |
karpenter-core | 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 (
v1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
)
// ProvisionerStatus defines the observed state of Provisioner
type ProvisionerStatus struct {
// LastScaleTime is the last time the Provisioner scaled the number
// of nodes
// +optional
// +kubebuilder:validation:Format="date-time"
LastScaleTime *apis.VolatileTime `json:"lastScaleTime,omitempty"`
// Conditions is the set of conditions required for this provisioner to scale
// its target, and indicates whether or not those conditions are met.
// +optional
Conditions apis.Conditions `json:"conditions,omitempty"`
// Resources is the list of resources that have been provisioned.
Resources v1.ResourceList `json:"resources,omitempty"`
}
func (p *Provisioner) StatusConditions() apis.ConditionManager {
return apis.NewLivingConditionSet(
Active,
).Manage(p)
}
func (p *Provisioner) GetConditions() apis.Conditions {
return p.Status.Conditions
}
func (p *Provisioner) SetConditions(conditions apis.Conditions) {
p.Status.Conditions = conditions
}
| 52 |
karpenter-core | 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"
"fmt"
"strconv"
"strings"
"github.com/samber/lo"
"go.uber.org/multierr"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"knative.dev/pkg/apis"
"knative.dev/pkg/ptr"
)
var (
SupportedNodeSelectorOps = sets.NewString(
string(v1.NodeSelectorOpIn),
string(v1.NodeSelectorOpNotIn),
string(v1.NodeSelectorOpGt),
string(v1.NodeSelectorOpLt),
string(v1.NodeSelectorOpExists),
string(v1.NodeSelectorOpDoesNotExist),
)
SupportedReservedResources = sets.NewString(
v1.ResourceCPU.String(),
v1.ResourceMemory.String(),
v1.ResourceEphemeralStorage.String(),
"pid",
)
SupportedEvictionSignals = sets.NewString(
"memory.available",
"nodefs.available",
"nodefs.inodesFree",
"imagefs.available",
"imagefs.inodesFree",
"pid.available",
)
)
const (
providerPath = "provider"
providerRefPath = "providerRef"
)
func (p *Provisioner) SupportedVerbs() []admissionregistrationv1.OperationType {
return []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
}
}
func (p *Provisioner) Validate(ctx context.Context) (errs *apis.FieldError) {
return errs.Also(
apis.ValidateObjectMetadata(p).ViaField("metadata"),
p.Spec.validate(ctx).ViaField("spec"),
)
}
func (s *ProvisionerSpec) validate(ctx context.Context) (errs *apis.FieldError) {
return errs.Also(
s.validateTTLSecondsUntilExpired(),
s.validateTTLSecondsAfterEmpty(),
s.Validate(ctx),
)
}
func (s *ProvisionerSpec) validateTTLSecondsUntilExpired() (errs *apis.FieldError) {
if ptr.Int64Value(s.TTLSecondsUntilExpired) < 0 {
return errs.Also(apis.ErrInvalidValue("cannot be negative", "ttlSecondsUntilExpired"))
}
return errs
}
func (s *ProvisionerSpec) validateTTLSecondsAfterEmpty() (errs *apis.FieldError) {
if ptr.Int64Value(s.TTLSecondsAfterEmpty) < 0 {
return errs.Also(apis.ErrInvalidValue("cannot be negative", "ttlSecondsAfterEmpty"))
}
// TTLSecondsAfterEmpty and consolidation are mutually exclusive
if s.Consolidation != nil && ptr.BoolValue(s.Consolidation.Enabled) && s.TTLSecondsAfterEmpty != nil {
return errs.Also(apis.ErrMultipleOneOf("ttlSecondsAfterEmpty", "consolidation.enabled"))
}
return errs
}
// Validate the constraints
func (s *ProvisionerSpec) Validate(ctx context.Context) (errs *apis.FieldError) {
return errs.Also(
s.validateProvider(),
s.validateLabels(),
s.validateTaints(),
s.validateRequirements(),
s.validateKubeletConfiguration().ViaField("kubeletConfiguration"),
)
}
func (s *ProvisionerSpec) validateLabels() (errs *apis.FieldError) {
for key, value := range s.Labels {
if key == ProvisionerNameLabelKey {
errs = errs.Also(apis.ErrInvalidKeyName(key, "labels", "restricted"))
}
for _, err := range validation.IsQualifiedName(key) {
errs = errs.Also(apis.ErrInvalidKeyName(key, "labels", err))
}
for _, err := range validation.IsValidLabelValue(value) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("%s, %s", value, err), fmt.Sprintf("labels[%s]", key)))
}
if err := IsRestrictedLabel(key); err != nil {
errs = errs.Also(apis.ErrInvalidKeyName(key, "labels", err.Error()))
}
}
return errs
}
type taintKeyEffect struct {
Key string
Effect v1.TaintEffect
}
func (s *ProvisionerSpec) validateTaints() (errs *apis.FieldError) {
existing := map[taintKeyEffect]struct{}{}
errs = errs.Also(s.validateTaintsField(s.Taints, existing, "taints"))
errs = errs.Also(s.validateTaintsField(s.StartupTaints, existing, "startupTaints"))
return errs
}
func (s *ProvisionerSpec) validateTaintsField(taints []v1.Taint, existing map[taintKeyEffect]struct{}, fieldName string) *apis.FieldError {
var errs *apis.FieldError
for i, taint := range taints {
// Validate Key
if len(taint.Key) == 0 {
errs = errs.Also(apis.ErrInvalidArrayValue(errs, fieldName, i))
}
for _, err := range validation.IsQualifiedName(taint.Key) {
errs = errs.Also(apis.ErrInvalidArrayValue(err, fieldName, i))
}
// Validate Value
if len(taint.Value) != 0 {
for _, err := range validation.IsQualifiedName(taint.Value) {
errs = errs.Also(apis.ErrInvalidArrayValue(err, fieldName, i))
}
}
// Validate effect
switch taint.Effect {
case v1.TaintEffectNoSchedule, v1.TaintEffectPreferNoSchedule, v1.TaintEffectNoExecute, "":
default:
errs = errs.Also(apis.ErrInvalidArrayValue(taint.Effect, "effect", i))
}
// Check for duplicate Key/Effect pairs
key := taintKeyEffect{Key: taint.Key, Effect: taint.Effect}
if _, ok := existing[key]; ok {
errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("duplicate taint Key/Effect pair %s=%s", taint.Key, taint.Effect), apis.CurrentField).
ViaFieldIndex("taints", i))
}
existing[key] = struct{}{}
}
return errs
}
// This function is used by the provisioner validation webhook to verify the provisioner requirements.
// When this function is called, the provisioner's requirments do not include the requirements from labels.
// Provisioner requirements only support well known labels.
func (s *ProvisionerSpec) validateRequirements() (errs *apis.FieldError) {
for i, requirement := range s.Requirements {
if requirement.Key == ProvisionerNameLabelKey {
errs = errs.Also(apis.ErrInvalidArrayValue(fmt.Sprintf("%s is restricted", requirement.Key), "requirements", i))
}
if err := ValidateRequirement(requirement); err != nil {
errs = errs.Also(apis.ErrInvalidArrayValue(err, "requirements", i))
}
}
return errs
}
// validateProvider checks if exactly one of provider and providerRef are set
func (s *ProvisionerSpec) validateProvider() *apis.FieldError {
if s.Provider != nil && s.ProviderRef != nil {
return apis.ErrMultipleOneOf(providerPath, providerRefPath)
}
if s.Provider == nil && s.ProviderRef == nil {
return apis.ErrMissingOneOf(providerPath, providerRefPath)
}
return nil
}
func (s *ProvisionerSpec) validateKubeletConfiguration() (errs *apis.FieldError) {
if s.KubeletConfiguration == nil {
return
}
return errs.Also(
validateEvictionThresholds(s.KubeletConfiguration.EvictionHard, "evictionHard"),
validateEvictionThresholds(s.KubeletConfiguration.EvictionSoft, "evictionSoft"),
validateReservedResources(s.KubeletConfiguration.KubeReserved, "kubeReserved"),
validateReservedResources(s.KubeletConfiguration.SystemReserved, "systemReserved"),
s.KubeletConfiguration.validateImageGCHighThresholdPercent(),
s.KubeletConfiguration.validateImageGCLowThresholdPercent(),
s.KubeletConfiguration.validateEvictionSoftGracePeriod(),
s.KubeletConfiguration.validateEvictionSoftPairs(),
)
}
func (kc *KubeletConfiguration) validateEvictionSoftGracePeriod() (errs *apis.FieldError) {
for k := range kc.EvictionSoftGracePeriod {
if !SupportedEvictionSignals.Has(k) {
errs = errs.Also(apis.ErrInvalidKeyName(k, "evictionSoftGracePeriod"))
}
}
return errs
}
func (kc *KubeletConfiguration) validateEvictionSoftPairs() (errs *apis.FieldError) {
evictionSoftKeys := sets.NewString(lo.Keys(kc.EvictionSoft)...)
evictionSoftGracePeriodKeys := sets.NewString(lo.Keys(kc.EvictionSoftGracePeriod)...)
evictionSoftDiff := evictionSoftKeys.Difference(evictionSoftGracePeriodKeys)
for k := range evictionSoftDiff {
errs = errs.Also(apis.ErrInvalidKeyName(k, "evictionSoft", "Key does not have a matching evictionSoftGracePeriod"))
}
evictionSoftGracePeriodDiff := evictionSoftGracePeriodKeys.Difference(evictionSoftKeys)
for k := range evictionSoftGracePeriodDiff {
errs = errs.Also(apis.ErrInvalidKeyName(k, "evictionSoftGracePeriod", "Key does not have a matching evictionSoft threshold value"))
}
return errs
}
func validateReservedResources(m v1.ResourceList, fieldName string) (errs *apis.FieldError) {
for k, v := range m {
if !SupportedReservedResources.Has(k.String()) {
errs = errs.Also(apis.ErrInvalidKeyName(k.String(), fieldName))
}
if v.Value() < 0 {
errs = errs.Also(apis.ErrInvalidValue(v.String(), fmt.Sprintf(`%s["%s"]`, fieldName, k), "Value cannot be a negative resource quantity"))
}
}
return errs
}
func validateEvictionThresholds(m map[string]string, fieldName string) (errs *apis.FieldError) {
if m == nil {
return
}
for k, v := range m {
if !SupportedEvictionSignals.Has(k) {
errs = errs.Also(apis.ErrInvalidKeyName(k, fieldName))
}
if strings.HasSuffix(v, "%") {
p, err := strconv.ParseFloat(strings.Trim(v, "%"), 64)
if err != nil {
errs = errs.Also(apis.ErrInvalidValue(v, fmt.Sprintf(`%s["%s"]`, fieldName, k), fmt.Sprintf("Value could not be parsed as a percentage value, %v", err.Error())))
}
if p < 0 {
errs = errs.Also(apis.ErrInvalidValue(v, fmt.Sprintf(`%s["%s"]`, fieldName, k), "Percentage values cannot be negative"))
}
if p > 100 {
errs = errs.Also(apis.ErrInvalidValue(v, fmt.Sprintf(`%s["%s"]`, fieldName, k), "Percentage values cannot be greater than 100"))
}
} else {
_, err := resource.ParseQuantity(v)
if err != nil {
errs = errs.Also(apis.ErrInvalidValue(v, fmt.Sprintf("%s[%s]", fieldName, k), fmt.Sprintf("Value could not be parsed as a resource quantity, %v", err.Error())))
}
}
}
return errs
}
func ValidateRequirement(requirement v1.NodeSelectorRequirement) error { //nolint:gocyclo
var errs error
if normalized, ok := NormalizedLabels[requirement.Key]; ok {
requirement.Key = normalized
}
if !SupportedNodeSelectorOps.Has(string(requirement.Operator)) {
errs = multierr.Append(errs, fmt.Errorf("key %s has an unsupported operator %s not in %s", requirement.Key, requirement.Operator, SupportedNodeSelectorOps.UnsortedList()))
}
if e := IsRestrictedLabel(requirement.Key); e != nil {
errs = multierr.Append(errs, e)
}
for _, err := range validation.IsQualifiedName(requirement.Key) {
errs = multierr.Append(errs, fmt.Errorf("key %s is not a qualified name, %s", requirement.Key, err))
}
for _, value := range requirement.Values {
for _, err := range validation.IsValidLabelValue(value) {
errs = multierr.Append(errs, fmt.Errorf("invalid value %s for key %s, %s", value, requirement.Key, err))
}
}
if requirement.Operator == v1.NodeSelectorOpIn && len(requirement.Values) == 0 {
errs = multierr.Append(errs, fmt.Errorf("key %s with operator %s must have a value defined", requirement.Key, requirement.Operator))
}
if requirement.Operator == v1.NodeSelectorOpGt || requirement.Operator == v1.NodeSelectorOpLt {
if len(requirement.Values) != 1 {
errs = multierr.Append(errs, fmt.Errorf("key %s with operator %s must have a single positive integer value", requirement.Key, requirement.Operator))
} else {
value, err := strconv.Atoi(requirement.Values[0])
if err != nil || value < 0 {
errs = multierr.Append(errs, fmt.Errorf("key %s with operator %s must have a single positive integer value", requirement.Key, requirement.Operator))
}
}
}
return errs
}
// Validate validateImageGCHighThresholdPercent
func (kc *KubeletConfiguration) validateImageGCHighThresholdPercent() (errs *apis.FieldError) {
if kc.ImageGCHighThresholdPercent != nil && ptr.Int32Value(kc.ImageGCHighThresholdPercent) < ptr.Int32Value(kc.ImageGCLowThresholdPercent) {
return errs.Also(apis.ErrInvalidValue("must be greater than imageGCLowThresholdPercent", "imageGCHighThresholdPercent"))
}
return errs
}
// Validate imageGCLowThresholdPercent
func (kc *KubeletConfiguration) validateImageGCLowThresholdPercent() (errs *apis.FieldError) {
if kc.ImageGCHighThresholdPercent != nil && ptr.Int32Value(kc.ImageGCLowThresholdPercent) > ptr.Int32Value(kc.ImageGCHighThresholdPercent) {
return errs.Also(apis.ErrInvalidValue("must be less than imageGCHighThresholdPercent", "imageGCLowThresholdPercent"))
}
return errs
}
| 340 |
karpenter-core | 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 (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"knative.dev/pkg/apis"
)
const (
Group = "karpenter.sh"
ExtensionsGroup = "extensions." + Group
CompatabilityGroup = "compatibility." + Group
TestingGroup = "testing." + Group // Exclusively used for labeling/discovery in testing
)
var (
SchemeGroupVersion = schema.GroupVersion{Group: Group, Version: "v1alpha5"}
SchemeBuilder = runtime.NewSchemeBuilder(func(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&Provisioner{},
&ProvisionerList{},
&Machine{},
&MachineList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
})
)
const (
// Active is a condition implemented by all resources. It indicates that the
// controller is able to take actions: it's correctly configured, can make
// necessary API calls, and isn't disabled.
Active apis.ConditionType = "Active"
)
| 51 |
karpenter-core | 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"
"strings"
"testing"
"time"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/Pallinder/go-randomdata"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "knative.dev/pkg/logging/testing"
"knative.dev/pkg/ptr"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
)
var ctx context.Context
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Validation")
}
var _ = Describe("Validation", func() {
var provisioner *Provisioner
BeforeEach(func() {
provisioner = &Provisioner{
ObjectMeta: metav1.ObjectMeta{Name: strings.ToLower(randomdata.SillyName())},
Spec: ProvisionerSpec{
ProviderRef: &MachineTemplateRef{
Kind: "NodeTemplate",
Name: "default",
},
},
}
})
It("should fail on negative expiry ttl", func() {
provisioner.Spec.TTLSecondsUntilExpired = ptr.Int64(-1)
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should succeed on a missing expiry ttl", func() {
// this already is true, but to be explicit
provisioner.Spec.TTLSecondsUntilExpired = nil
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail on negative empty ttl", func() {
provisioner.Spec.TTLSecondsAfterEmpty = ptr.Int64(-1)
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should succeed on a missing empty ttl", func() {
provisioner.Spec.TTLSecondsAfterEmpty = nil
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should succeed on a valid empty ttl", func() {
provisioner.Spec.TTLSecondsAfterEmpty = ptr.Int64(30)
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail if both consolidation and TTLSecondsAfterEmpty are enabled", func() {
provisioner.Spec.TTLSecondsAfterEmpty = ptr.Int64(30)
provisioner.Spec.Consolidation = &Consolidation{Enabled: ptr.Bool(true)}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should succeed if consolidation is off and TTLSecondsAfterEmpty is set", func() {
provisioner.Spec.TTLSecondsAfterEmpty = ptr.Int64(30)
provisioner.Spec.Consolidation = &Consolidation{Enabled: ptr.Bool(false)}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should succeed if consolidation is on and TTLSecondsAfterEmpty is not set", func() {
provisioner.Spec.TTLSecondsAfterEmpty = nil
provisioner.Spec.Consolidation = &Consolidation{Enabled: ptr.Bool(true)}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
Context("Limits", func() {
It("should allow undefined limits", func() {
provisioner.Spec.Limits = &Limits{}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should allow empty limits", func() {
provisioner.Spec.Limits = &Limits{Resources: v1.ResourceList{}}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
})
Context("Provider", func() {
It("should not allow provider and providerRef", func() {
provisioner.Spec.Provider = &Provider{}
provisioner.Spec.ProviderRef = &MachineTemplateRef{Name: "providerRef"}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should require at least one of provider and providerRef", func() {
provisioner.Spec.ProviderRef = nil
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
Context("Labels", func() {
It("should allow unrecognized labels", func() {
provisioner.Spec.Labels = map[string]string{"foo": randomdata.SillyName()}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail for the provisioner name label", func() {
provisioner.Spec.Labels = map[string]string{ProvisionerNameLabelKey: randomdata.SillyName()}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for invalid label keys", func() {
provisioner.Spec.Labels = map[string]string{"spaces are not allowed": randomdata.SillyName()}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for invalid label values", func() {
provisioner.Spec.Labels = map[string]string{randomdata.SillyName(): "/ is not allowed"}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for restricted label domains", func() {
for label := range RestrictedLabelDomains {
provisioner.Spec.Labels = map[string]string{label + "/unknown": randomdata.SillyName()}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
}
})
It("should allow labels kOps require", func() {
provisioner.Spec.Labels = map[string]string{
"kops.k8s.io/instancegroup": "karpenter-nodes",
"kops.k8s.io/gpu": "1",
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should allow labels in restricted domains exceptions list", func() {
for label := range LabelDomainExceptions {
provisioner.Spec.Labels = map[string]string{
label: "test-value",
}
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
})
Context("Taints", func() {
It("should succeed for valid taints", func() {
provisioner.Spec.Taints = []v1.Taint{
{Key: "a", Value: "b", Effect: v1.TaintEffectNoSchedule},
{Key: "c", Value: "d", Effect: v1.TaintEffectNoExecute},
{Key: "e", Value: "f", Effect: v1.TaintEffectPreferNoSchedule},
{Key: "key-only", Effect: v1.TaintEffectNoExecute},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail for invalid taint keys", func() {
provisioner.Spec.Taints = []v1.Taint{{Key: "???"}}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for missing taint key", func() {
provisioner.Spec.Taints = []v1.Taint{{Effect: v1.TaintEffectNoSchedule}}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for invalid taint value", func() {
provisioner.Spec.Taints = []v1.Taint{{Key: "invalid-value", Effect: v1.TaintEffectNoSchedule, Value: "???"}}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail for invalid taint effect", func() {
provisioner.Spec.Taints = []v1.Taint{{Key: "invalid-effect", Effect: "???"}}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should not fail for same key with different effects", func() {
provisioner.Spec.Taints = []v1.Taint{
{Key: "a", Effect: v1.TaintEffectNoSchedule},
{Key: "a", Effect: v1.TaintEffectNoExecute},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail for duplicate taint key/effect pairs", func() {
provisioner.Spec.Taints = []v1.Taint{
{Key: "a", Effect: v1.TaintEffectNoSchedule},
{Key: "a", Effect: v1.TaintEffectNoSchedule},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
provisioner.Spec.Taints = []v1.Taint{
{Key: "a", Effect: v1.TaintEffectNoSchedule},
}
provisioner.Spec.StartupTaints = []v1.Taint{
{Key: "a", Effect: v1.TaintEffectNoSchedule},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
Context("Requirements", func() {
It("should fail for the provisioner name label", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: ProvisionerNameLabelKey, Operator: v1.NodeSelectorOpIn, Values: []string{randomdata.SillyName()}},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should allow supported ops", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpGt, Values: []string{"1"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpLt, Values: []string{"1"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpNotIn},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpExists},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail for unsupported ops", func() {
for _, op := range []v1.NodeSelectorOperator{"unknown"} {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: op, Values: []string{"test"}},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
}
})
It("should fail for restricted domains", func() {
for label := range RestrictedLabelDomains {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: label + "/test", Operator: v1.NodeSelectorOpIn, Values: []string{"test"}},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
}
})
It("should allow restricted domains exceptions", func() {
for label := range LabelDomainExceptions {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: label + "/test", Operator: v1.NodeSelectorOpIn, Values: []string{"test"}},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
It("should allow well known label exceptions", func() {
for label := range WellKnownLabels.Difference(sets.NewString(ProvisionerNameLabelKey)) {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: label, Operator: v1.NodeSelectorOpIn, Values: []string{"test"}},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
}
})
It("should allow non-empty set after removing overlapped value", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpIn, Values: []string{"test", "foo"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpNotIn, Values: []string{"test", "bar"}},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should allow empty requirements", func() {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail with invalid GT or LT values", func() {
for _, requirement := range []v1.NodeSelectorRequirement{
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpGt, Values: []string{}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpGt, Values: []string{"1", "2"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpGt, Values: []string{"a"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpGt, Values: []string{"-1"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpLt, Values: []string{}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpLt, Values: []string{"1", "2"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpLt, Values: []string{"a"}},
{Key: v1.LabelTopologyZone, Operator: v1.NodeSelectorOpLt, Values: []string{"-1"}},
} {
provisioner.Spec.Requirements = []v1.NodeSelectorRequirement{requirement}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
}
})
})
Context("KubeletConfiguration", func() {
It("should fail on kubeReserved with invalid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
KubeReserved: v1.ResourceList{
v1.ResourcePods: resource.MustParse("2"),
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on systemReserved with invalid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
SystemReserved: v1.ResourceList{
v1.ResourcePods: resource.MustParse("2"),
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
Context("Eviction Signals", func() {
Context("Eviction Hard", func() {
It("should succeed on evictionHard with valid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "5%",
"nodefs.available": "10%",
"nodefs.inodesFree": "15%",
"imagefs.available": "5%",
"imagefs.inodesFree": "5%",
"pid.available": "5%",
},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail on evictionHard with invalid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionHard: map[string]string{
"memory": "5%",
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid formatted percentage value in evictionHard", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "5%3",
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid percentage value (too large) in evictionHard", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "110%",
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid quantity value in evictionHard", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionHard: map[string]string{
"memory.available": "110GB",
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
})
Context("Eviction Soft", func() {
It("should succeed on evictionSoft with valid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "5%",
"nodefs.available": "10%",
"nodefs.inodesFree": "15%",
"imagefs.available": "5%",
"imagefs.inodesFree": "5%",
"pid.available": "5%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
"nodefs.available": {Duration: time.Second * 90},
"nodefs.inodesFree": {Duration: time.Minute * 5},
"imagefs.available": {Duration: time.Hour},
"imagefs.inodesFree": {Duration: time.Hour * 24},
"pid.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail on evictionSoft with invalid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory": "5%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid formatted percentage value in evictionSoft", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "5%3",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid percentage value (too large) in evictionSoft", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "110%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail on invalid quantity value in evictionSoft", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "110GB",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail when eviction soft doesn't have matching grace period", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "200Mi",
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
Context("GCThresholdPercent", func() {
Context("ImageGCHighThresholdPercent", func() {
It("should succeed on a imageGCHighThresholdPercent", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
ImageGCHighThresholdPercent: ptr.Int32(10),
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail when imageGCHighThresholdPercent is less than imageGCLowThresholdPercent", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
ImageGCHighThresholdPercent: ptr.Int32(50),
ImageGCLowThresholdPercent: ptr.Int32(60),
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
Context("ImageGCLowThresholdPercent", func() {
It("should succeed on a imageGCLowThresholdPercent", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
ImageGCLowThresholdPercent: ptr.Int32(10),
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail when imageGCLowThresholdPercent is greather than imageGCHighThresheldPercent", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
ImageGCHighThresholdPercent: ptr.Int32(50),
ImageGCLowThresholdPercent: ptr.Int32(60),
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
})
Context("Eviction Soft Grace Period", func() {
It("should succeed on evictionSoftGracePeriod with valid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoft: map[string]string{
"memory.available": "5%",
"nodefs.available": "10%",
"nodefs.inodesFree": "15%",
"imagefs.available": "5%",
"imagefs.inodesFree": "5%",
"pid.available": "5%",
},
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
"nodefs.available": {Duration: time.Second * 90},
"nodefs.inodesFree": {Duration: time.Minute * 5},
"imagefs.available": {Duration: time.Hour},
"imagefs.inodesFree": {Duration: time.Hour * 24},
"pid.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).To(Succeed())
})
It("should fail on evictionSoftGracePeriod with invalid keys", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
It("should fail when eviction soft grace period doesn't have matching threshold", func() {
provisioner.Spec.KubeletConfiguration = &KubeletConfiguration{
EvictionSoftGracePeriod: map[string]metav1.Duration{
"memory.available": {Duration: time.Minute},
},
}
Expect(provisioner.Validate(ctx)).ToNot(Succeed())
})
})
})
})
var _ = Describe("Limits", func() {
var provisioner *Provisioner
BeforeEach(func() {
provisioner = &Provisioner{
ObjectMeta: metav1.ObjectMeta{Name: strings.ToLower(randomdata.SillyName())},
Spec: ProvisionerSpec{
Limits: &Limits{
Resources: v1.ResourceList{
"cpu": resource.MustParse("16"),
},
},
},
}
})
It("should work when usage is lower than limit", func() {
provisioner.Status.Resources = v1.ResourceList{"cpu": resource.MustParse("15")}
Expect(provisioner.Spec.Limits.ExceededBy(provisioner.Status.Resources)).To(Succeed())
})
It("should work when usage is equal to limit", func() {
provisioner.Status.Resources = v1.ResourceList{"cpu": resource.MustParse("16")}
Expect(provisioner.Spec.Limits.ExceededBy(provisioner.Status.Resources)).To(Succeed())
})
It("should fail when usage is higher than limit", func() {
provisioner.Status.Resources = v1.ResourceList{"cpu": resource.MustParse("17")}
Expect(provisioner.Spec.Limits.ExceededBy(provisioner.Status.Resources)).To(MatchError("cpu resource usage of 17 exceeds limit of 16"))
})
})
| 524 |
karpenter-core | 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 (
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"knative.dev/pkg/apis"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Consolidation) DeepCopyInto(out *Consolidation) {
*out = *in
if in.Enabled != nil {
in, out := &in.Enabled, &out.Enabled
*out = new(bool)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Consolidation.
func (in *Consolidation) DeepCopy() *Consolidation {
if in == nil {
return nil
}
out := new(Consolidation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *KubeletConfiguration) DeepCopyInto(out *KubeletConfiguration) {
*out = *in
if in.ClusterDNS != nil {
in, out := &in.ClusterDNS, &out.ClusterDNS
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ContainerRuntime != nil {
in, out := &in.ContainerRuntime, &out.ContainerRuntime
*out = new(string)
**out = **in
}
if in.MaxPods != nil {
in, out := &in.MaxPods, &out.MaxPods
*out = new(int32)
**out = **in
}
if in.PodsPerCore != nil {
in, out := &in.PodsPerCore, &out.PodsPerCore
*out = new(int32)
**out = **in
}
if in.SystemReserved != nil {
in, out := &in.SystemReserved, &out.SystemReserved
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
if in.KubeReserved != nil {
in, out := &in.KubeReserved, &out.KubeReserved
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
if in.EvictionHard != nil {
in, out := &in.EvictionHard, &out.EvictionHard
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.EvictionSoft != nil {
in, out := &in.EvictionSoft, &out.EvictionSoft
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.EvictionSoftGracePeriod != nil {
in, out := &in.EvictionSoftGracePeriod, &out.EvictionSoftGracePeriod
*out = make(map[string]metav1.Duration, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.EvictionMaxPodGracePeriod != nil {
in, out := &in.EvictionMaxPodGracePeriod, &out.EvictionMaxPodGracePeriod
*out = new(int32)
**out = **in
}
if in.ImageGCHighThresholdPercent != nil {
in, out := &in.ImageGCHighThresholdPercent, &out.ImageGCHighThresholdPercent
*out = new(int32)
**out = **in
}
if in.ImageGCLowThresholdPercent != nil {
in, out := &in.ImageGCLowThresholdPercent, &out.ImageGCLowThresholdPercent
*out = new(int32)
**out = **in
}
if in.CPUCFSQuota != nil {
in, out := &in.CPUCFSQuota, &out.CPUCFSQuota
*out = new(bool)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KubeletConfiguration.
func (in *KubeletConfiguration) DeepCopy() *KubeletConfiguration {
if in == nil {
return nil
}
out := new(KubeletConfiguration)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Limits) DeepCopyInto(out *Limits) {
*out = *in
if in.Resources != nil {
in, out := &in.Resources, &out.Resources
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Limits.
func (in *Limits) DeepCopy() *Limits {
if in == nil {
return nil
}
out := new(Limits)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Machine) DeepCopyInto(out *Machine) {
*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 Machine.
func (in *Machine) DeepCopy() *Machine {
if in == nil {
return nil
}
out := new(Machine)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Machine) 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 *MachineList) DeepCopyInto(out *MachineList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Machine, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineList.
func (in *MachineList) DeepCopy() *MachineList {
if in == nil {
return nil
}
out := new(MachineList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineList) 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 *MachineSpec) DeepCopyInto(out *MachineSpec) {
*out = *in
if in.Taints != nil {
in, out := &in.Taints, &out.Taints
*out = make([]v1.Taint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.StartupTaints != nil {
in, out := &in.StartupTaints, &out.StartupTaints
*out = make([]v1.Taint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
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])
}
}
in.Resources.DeepCopyInto(&out.Resources)
if in.Kubelet != nil {
in, out := &in.Kubelet, &out.Kubelet
*out = new(KubeletConfiguration)
(*in).DeepCopyInto(*out)
}
if in.MachineTemplateRef != nil {
in, out := &in.MachineTemplateRef, &out.MachineTemplateRef
*out = new(MachineTemplateRef)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSpec.
func (in *MachineSpec) DeepCopy() *MachineSpec {
if in == nil {
return nil
}
out := new(MachineSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineStatus) DeepCopyInto(out *MachineStatus) {
*out = *in
if in.Capacity != nil {
in, out := &in.Capacity, &out.Capacity
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
if in.Allocatable != nil {
in, out := &in.Allocatable, &out.Allocatable
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions
*out = make(apis.Conditions, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineStatus.
func (in *MachineStatus) DeepCopy() *MachineStatus {
if in == nil {
return nil
}
out := new(MachineStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineTemplateRef) DeepCopyInto(out *MachineTemplateRef) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineTemplateRef.
func (in *MachineTemplateRef) DeepCopy() *MachineTemplateRef {
if in == nil {
return nil
}
out := new(MachineTemplateRef)
in.DeepCopyInto(out)
return out
}
// 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
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProvisionerList) DeepCopyInto(out *ProvisionerList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Provisioner, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProvisionerList.
func (in *ProvisionerList) DeepCopy() *ProvisionerList {
if in == nil {
return nil
}
out := new(ProvisionerList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ProvisionerList) 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 *ProvisionerSpec) DeepCopyInto(out *ProvisionerSpec) {
*out = *in
if in.Annotations != nil {
in, out := &in.Annotations, &out.Annotations
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.Labels != nil {
in, out := &in.Labels, &out.Labels
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.Taints != nil {
in, out := &in.Taints, &out.Taints
*out = make([]v1.Taint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.StartupTaints != nil {
in, out := &in.StartupTaints, &out.StartupTaints
*out = make([]v1.Taint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
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])
}
}
if in.KubeletConfiguration != nil {
in, out := &in.KubeletConfiguration, &out.KubeletConfiguration
*out = new(KubeletConfiguration)
(*in).DeepCopyInto(*out)
}
if in.Provider != nil {
in, out := &in.Provider, &out.Provider
*out = new(runtime.RawExtension)
(*in).DeepCopyInto(*out)
}
if in.ProviderRef != nil {
in, out := &in.ProviderRef, &out.ProviderRef
*out = new(MachineTemplateRef)
**out = **in
}
if in.TTLSecondsAfterEmpty != nil {
in, out := &in.TTLSecondsAfterEmpty, &out.TTLSecondsAfterEmpty
*out = new(int64)
**out = **in
}
if in.TTLSecondsUntilExpired != nil {
in, out := &in.TTLSecondsUntilExpired, &out.TTLSecondsUntilExpired
*out = new(int64)
**out = **in
}
if in.Limits != nil {
in, out := &in.Limits, &out.Limits
*out = new(Limits)
(*in).DeepCopyInto(*out)
}
if in.Weight != nil {
in, out := &in.Weight, &out.Weight
*out = new(int32)
**out = **in
}
if in.Consolidation != nil {
in, out := &in.Consolidation, &out.Consolidation
*out = new(Consolidation)
(*in).DeepCopyInto(*out)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProvisionerSpec.
func (in *ProvisionerSpec) DeepCopy() *ProvisionerSpec {
if in == nil {
return nil
}
out := new(ProvisionerSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProvisionerStatus) DeepCopyInto(out *ProvisionerStatus) {
*out = *in
if in.LastScaleTime != nil {
in, out := &in.LastScaleTime, &out.LastScaleTime
*out = new(apis.VolatileTime)
(*in).DeepCopyInto(*out)
}
if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions
*out = make(apis.Conditions, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.Resources != nil {
in, out := &in.Resources, &out.Resources
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProvisionerStatus.
func (in *ProvisionerStatus) DeepCopy() *ProvisionerStatus {
if in == nil {
return nil
}
out := new(ProvisionerStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ResourceRequirements) DeepCopyInto(out *ResourceRequirements) {
*out = *in
if in.Requests != nil {
in, out := &in.Requests, &out.Requests
*out = make(v1.ResourceList, len(*in))
for key, val := range *in {
(*out)[key] = val.DeepCopy()
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResourceRequirements.
func (in *ResourceRequirements) DeepCopy() *ResourceRequirements {
if in == nil {
return nil
}
out := new(ResourceRequirements)
in.DeepCopyInto(out)
return out
}
| 522 |
karpenter-core | 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"
"errors"
"fmt"
"math"
"sort"
"github.com/samber/lo"
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/utils/resources"
)
// CloudProvider interface is implemented by cloud providers to support provisioning.
type CloudProvider interface {
// Create launches a machine with the given resource requests and requirements and returns a hydrated
// machine back with resolved machine labels for the launched machine
Create(context.Context, *v1alpha5.Machine) (*v1alpha5.Machine, error)
// Delete removes a machine from the cloudprovider by its provider id
Delete(context.Context, *v1alpha5.Machine) error
// Get retrieves a machine from the cloudprovider by its provider id
Get(context.Context, string) (*v1alpha5.Machine, error)
// List retrieves all machines from the cloudprovider
List(context.Context) ([]*v1alpha5.Machine, error)
// GetInstanceTypes returns instance types supported by the cloudprovider.
// Availability of types or zone may vary by provisioner or over time. Regardless of
// availability, the GetInstanceTypes method should always return all instance types,
// even those with no offerings available.
GetInstanceTypes(context.Context, *v1alpha5.Provisioner) ([]*InstanceType, error)
// IsMachineDrifted returns whether a machine has drifted from the provisioning requirements
// it is tied to.
IsMachineDrifted(context.Context, *v1alpha5.Machine) (bool, error)
// Name returns the CloudProvider implementation name.
Name() string
}
type InstanceTypes []*InstanceType
func (its InstanceTypes) OrderByPrice(reqs scheduling.Requirements) InstanceTypes {
// Order instance types so that we get the cheapest instance types of the available offerings
sort.Slice(its, func(i, j int) bool {
iPrice := math.MaxFloat64
jPrice := math.MaxFloat64
if len(its[i].Offerings.Available().Requirements(reqs)) > 0 {
iPrice = its[i].Offerings.Available().Requirements(reqs).Cheapest().Price
}
if len(its[j].Offerings.Available().Requirements(reqs)) > 0 {
jPrice = its[j].Offerings.Available().Requirements(reqs).Cheapest().Price
}
if iPrice == jPrice {
return its[i].Name < its[j].Name
}
return iPrice < jPrice
})
return its
}
// InstanceType describes the properties of a potential node (either concrete attributes of an instance of this type
// or supported options in the case of arrays)
type InstanceType struct {
// Name of the instance type, must correspond to v1.LabelInstanceTypeStable
Name string
// Requirements returns a flexible set of properties that may be selected
// for scheduling. Must be defined for every well known label, even if empty.
Requirements scheduling.Requirements
// Note that though this is an array it is expected that all the Offerings are unique from one another
Offerings Offerings
// Resources are the full resource capacities for this instance type
Capacity v1.ResourceList
// Overhead is the amount of resource overhead expected to be used by kubelet and any other system daemons outside
// of Kubernetes.
Overhead *InstanceTypeOverhead
}
func (i *InstanceType) Allocatable() v1.ResourceList {
return resources.Subtract(i.Capacity, i.Overhead.Total())
}
type InstanceTypeOverhead struct {
// KubeReserved returns the default resources allocated to kubernetes system daemons by default
KubeReserved v1.ResourceList
// SystemReserved returns the default resources allocated to the OS system daemons by default
SystemReserved v1.ResourceList
// EvictionThreshold returns the resources used to maintain a hard eviction threshold
EvictionThreshold v1.ResourceList
}
func (i InstanceTypeOverhead) Total() v1.ResourceList {
return resources.Merge(i.KubeReserved, i.SystemReserved, i.EvictionThreshold)
}
// An Offering describes where an InstanceType is available to be used, with the expectation that its properties
// may be tightly coupled (e.g. the availability of an instance type in some zone is scoped to a capacity type)
type Offering struct {
CapacityType string
Zone string
Price float64
// Available is added so that Offerings can return all offerings that have ever existed for an instance type,
// so we can get historical pricing data for calculating savings in consolidation
Available bool
}
type Offerings []Offering
// Get gets the offering from an offering slice that matches the
// passed zone and capacity type
func (ofs Offerings) Get(ct, zone string) (Offering, bool) {
return lo.Find(ofs, func(of Offering) bool {
return of.CapacityType == ct && of.Zone == zone
})
}
// Available filters the available offerings from the returned offerings
func (ofs Offerings) Available() Offerings {
return lo.Filter(ofs, func(o Offering, _ int) bool {
return o.Available
})
}
// Requirements filters the offerings based on the passed requirements
func (ofs Offerings) Requirements(reqs scheduling.Requirements) Offerings {
return lo.Filter(ofs, func(offering Offering, _ int) bool {
return (!reqs.Has(v1.LabelTopologyZone) || reqs.Get(v1.LabelTopologyZone).Has(offering.Zone)) &&
(!reqs.Has(v1alpha5.LabelCapacityType) || reqs.Get(v1alpha5.LabelCapacityType).Has(offering.CapacityType))
})
}
// Cheapest returns the cheapest offering from the returned offerings
func (ofs Offerings) Cheapest() Offering {
return lo.MinBy(ofs, func(a, b Offering) bool {
return a.Price < b.Price
})
}
// MachineNotFoundError is an error type returned by CloudProviders when the reason for failure is NotFound
type MachineNotFoundError struct {
error
}
func NewMachineNotFoundError(err error) *MachineNotFoundError {
return &MachineNotFoundError{
error: err,
}
}
func (e *MachineNotFoundError) Error() string {
return fmt.Sprintf("machine not found, %s", e.error)
}
func IsMachineNotFoundError(err error) bool {
if err == nil {
return false
}
var mnfErr *MachineNotFoundError
return errors.As(err, &mnfErr)
}
func IgnoreMachineNotFoundError(err error) error {
if IsMachineNotFoundError(err) {
return nil
}
return err
}
// InsufficientCapacityError is an error type returned by CloudProviders when a launch fails due to a lack of capacity from machine requirements
type InsufficientCapacityError struct {
error
}
func NewInsufficientCapacityError(err error) *InsufficientCapacityError {
return &InsufficientCapacityError{
error: err,
}
}
func (e *InsufficientCapacityError) Error() string {
return fmt.Sprintf("insufficient capacity, %s", e.error)
}
func IsInsufficientCapacityError(err error) bool {
if err == nil {
return false
}
var icErr *InsufficientCapacityError
return errors.As(err, &icErr)
}
func IgnoreInsufficientCapacityError(err error) error {
if IsInsufficientCapacityError(err) {
return nil
}
return err
}
| 212 |
karpenter-core | 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"
"math"
"sort"
"sync"
"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"
"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/test"
"github.com/aws/karpenter-core/pkg/utils/functional"
"github.com/aws/karpenter-core/pkg/utils/resources"
)
var _ cloudprovider.CloudProvider = (*CloudProvider)(nil)
type CloudProvider struct {
InstanceTypes []*cloudprovider.InstanceType
mu sync.RWMutex
// CreateCalls contains the arguments for every create call that was made since it was cleared
CreateCalls []*v1alpha5.Machine
AllowedCreateCalls int
NextCreateErr error
DeleteCalls []*v1alpha5.Machine
CreatedMachines map[string]*v1alpha5.Machine
Drifted bool
}
func NewCloudProvider() *CloudProvider {
return &CloudProvider{
AllowedCreateCalls: math.MaxInt,
CreatedMachines: map[string]*v1alpha5.Machine{},
}
}
// Reset is for BeforeEach calls in testing to reset the tracking of CreateCalls
func (c *CloudProvider) Reset() {
c.mu.Lock()
defer c.mu.Unlock()
c.CreateCalls = []*v1alpha5.Machine{}
c.CreatedMachines = map[string]*v1alpha5.Machine{}
c.AllowedCreateCalls = math.MaxInt
c.NextCreateErr = nil
c.DeleteCalls = []*v1alpha5.Machine{}
c.Drifted = false
}
func (c *CloudProvider) Create(ctx context.Context, machine *v1alpha5.Machine) (*v1alpha5.Machine, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.NextCreateErr != nil {
temp := c.NextCreateErr
c.NextCreateErr = nil
return nil, temp
}
c.CreateCalls = append(c.CreateCalls, machine)
if len(c.CreateCalls) > c.AllowedCreateCalls {
return &v1alpha5.Machine{}, fmt.Errorf("erroring as number of AllowedCreateCalls has been exceeded")
}
reqs := scheduling.NewNodeSelectorRequirements(machine.Spec.Requirements...)
instanceTypes := lo.Filter(lo.Must(c.GetInstanceTypes(ctx, nil)), 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())
})
// Order instance types so that we get the cheapest instance types of the available offerings
sort.Slice(instanceTypes, func(i, j int) bool {
iOfferings := instanceTypes[i].Offerings.Available().Requirements(reqs)
jOfferings := instanceTypes[j].Offerings.Available().Requirements(reqs)
return iOfferings.Cheapest().Price < jOfferings.Cheapest().Price
})
instanceType := instanceTypes[0]
// Labels
labels := map[string]string{}
for key, requirement := range instanceType.Requirements {
if requirement.Operator() == v1.NodeSelectorOpIn {
labels[key] = requirement.Values()[0]
}
}
// Find Offering
for _, o := range instanceType.Offerings.Available() {
if reqs.Compatible(scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelTopologyZone, v1.NodeSelectorOpIn, o.Zone),
scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpIn, o.CapacityType),
)) == nil {
labels[v1.LabelTopologyZone] = o.Zone
labels[v1alpha5.LabelCapacityType] = o.CapacityType
break
}
}
created := &v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Name: machine.Name,
Labels: lo.Assign(labels, machine.Labels),
Annotations: machine.Annotations,
},
Spec: *machine.Spec.DeepCopy(),
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Capacity: functional.FilterMap(instanceType.Capacity, func(_ v1.ResourceName, v resource.Quantity) bool { return !resources.IsZero(v) }),
Allocatable: functional.FilterMap(instanceType.Allocatable(), func(_ v1.ResourceName, v resource.Quantity) bool { return !resources.IsZero(v) }),
},
}
c.CreatedMachines[created.Status.ProviderID] = created
return created, nil
}
func (c *CloudProvider) Get(_ context.Context, id string) (*v1alpha5.Machine, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if machine, ok := c.CreatedMachines[id]; ok {
return machine.DeepCopy(), nil
}
return nil, cloudprovider.NewMachineNotFoundError(fmt.Errorf("no machine exists with id '%s'", id))
}
func (c *CloudProvider) List(_ context.Context) ([]*v1alpha5.Machine, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return lo.Map(lo.Values(c.CreatedMachines), func(m *v1alpha5.Machine, _ int) *v1alpha5.Machine {
return m.DeepCopy()
}), nil
}
func (c *CloudProvider) GetInstanceTypes(_ context.Context, _ *v1alpha5.Provisioner) ([]*cloudprovider.InstanceType, error) {
if c.InstanceTypes != nil {
return c.InstanceTypes, nil
}
return []*cloudprovider.InstanceType{
NewInstanceType(InstanceTypeOptions{
Name: "default-instance-type",
}),
NewInstanceType(InstanceTypeOptions{
Name: "small-instance-type",
Resources: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("2"),
v1.ResourceMemory: resource.MustParse("2Gi"),
},
}),
NewInstanceType(InstanceTypeOptions{
Name: "gpu-vendor-instance-type",
Resources: map[v1.ResourceName]resource.Quantity{
ResourceGPUVendorA: resource.MustParse("2"),
}}),
NewInstanceType(InstanceTypeOptions{
Name: "gpu-vendor-b-instance-type",
Resources: map[v1.ResourceName]resource.Quantity{
ResourceGPUVendorB: resource.MustParse("2"),
},
}),
NewInstanceType(InstanceTypeOptions{
Name: "arm-instance-type",
Architecture: "arm64",
OperatingSystems: sets.NewString("ios", string(v1.Linux), string(v1.Windows), "darwin"),
Resources: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("16"),
v1.ResourceMemory: resource.MustParse("128Gi"),
},
}),
NewInstanceType(InstanceTypeOptions{
Name: "single-pod-instance-type",
Resources: map[v1.ResourceName]resource.Quantity{
v1.ResourcePods: resource.MustParse("1"),
},
}),
}, nil
}
func (c *CloudProvider) Delete(_ context.Context, m *v1alpha5.Machine) error {
c.mu.Lock()
defer c.mu.Unlock()
c.DeleteCalls = append(c.DeleteCalls, m)
if _, ok := c.CreatedMachines[m.Status.ProviderID]; ok {
delete(c.CreatedMachines, m.Status.ProviderID)
return nil
}
return cloudprovider.NewMachineNotFoundError(fmt.Errorf("no machine exists with provider id '%s'", m.Status.ProviderID))
}
func (c *CloudProvider) IsMachineDrifted(context.Context, *v1alpha5.Machine) (bool, error) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.Drifted, nil
}
// Name returns the CloudProvider implementation name.
func (c *CloudProvider) Name() string {
return "fake"
}
| 221 |
karpenter-core | 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/samber/lo"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
utilsets "k8s.io/apimachinery/pkg/util/sets"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/scheduling"
)
const (
LabelInstanceSize = "size"
ExoticInstanceLabelKey = "special"
IntegerInstanceLabelKey = "integer"
ResourceGPUVendorA v1.ResourceName = "fake.com/vendor-a"
ResourceGPUVendorB v1.ResourceName = "fake.com/vendor-b"
)
func init() {
v1alpha5.WellKnownLabels.Insert(
LabelInstanceSize,
ExoticInstanceLabelKey,
IntegerInstanceLabelKey,
)
}
func NewInstanceType(options InstanceTypeOptions) *cloudprovider.InstanceType {
if options.Resources == nil {
options.Resources = map[v1.ResourceName]resource.Quantity{}
}
if r := options.Resources[v1.ResourceCPU]; r.IsZero() {
options.Resources[v1.ResourceCPU] = resource.MustParse("4")
}
if r := options.Resources[v1.ResourceMemory]; r.IsZero() {
options.Resources[v1.ResourceMemory] = resource.MustParse("4Gi")
}
if r := options.Resources[v1.ResourcePods]; r.IsZero() {
options.Resources[v1.ResourcePods] = resource.MustParse("5")
}
if len(options.Offerings) == 0 {
options.Offerings = []cloudprovider.Offering{
{CapacityType: "spot", Zone: "test-zone-1", Price: priceFromResources(options.Resources), Available: true},
{CapacityType: "spot", Zone: "test-zone-2", Price: priceFromResources(options.Resources), Available: true},
{CapacityType: "on-demand", Zone: "test-zone-1", Price: priceFromResources(options.Resources), Available: true},
{CapacityType: "on-demand", Zone: "test-zone-2", Price: priceFromResources(options.Resources), Available: true},
{CapacityType: "on-demand", Zone: "test-zone-3", Price: priceFromResources(options.Resources), Available: true},
}
}
if len(options.Architecture) == 0 {
options.Architecture = "amd64"
}
if options.OperatingSystems.Len() == 0 {
options.OperatingSystems = utilsets.NewString(string(v1.Linux), string(v1.Windows), "darwin")
}
requirements := scheduling.NewRequirements(
scheduling.NewRequirement(v1.LabelInstanceTypeStable, v1.NodeSelectorOpIn, options.Name),
scheduling.NewRequirement(v1.LabelArchStable, v1.NodeSelectorOpIn, options.Architecture),
scheduling.NewRequirement(v1.LabelOSStable, v1.NodeSelectorOpIn, options.OperatingSystems.List()...),
scheduling.NewRequirement(v1.LabelTopologyZone, v1.NodeSelectorOpIn, lo.Map(options.Offerings.Available(), func(o cloudprovider.Offering, _ int) string { return o.Zone })...),
scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpIn, lo.Map(options.Offerings.Available(), func(o cloudprovider.Offering, _ int) string { return o.CapacityType })...),
scheduling.NewRequirement(LabelInstanceSize, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(ExoticInstanceLabelKey, v1.NodeSelectorOpDoesNotExist),
scheduling.NewRequirement(IntegerInstanceLabelKey, v1.NodeSelectorOpIn, fmt.Sprint(options.Resources.Cpu().Value())),
)
if options.Resources.Cpu().Cmp(resource.MustParse("4")) > 0 &&
options.Resources.Memory().Cmp(resource.MustParse("8Gi")) > 0 {
requirements.Get(LabelInstanceSize).Insert("large")
requirements.Get(ExoticInstanceLabelKey).Insert("optional")
} else {
requirements.Get(LabelInstanceSize).Insert("small")
}
return &cloudprovider.InstanceType{
Name: options.Name,
Requirements: requirements,
Offerings: options.Offerings,
Capacity: options.Resources,
Overhead: &cloudprovider.InstanceTypeOverhead{
KubeReserved: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("100m"),
v1.ResourceMemory: resource.MustParse("10Mi"),
},
},
}
}
// InstanceTypesAssorted create many unique instance types with varying CPU/memory/architecture/OS/zone/capacity type.
func InstanceTypesAssorted() []*cloudprovider.InstanceType {
var instanceTypes []*cloudprovider.InstanceType
for _, cpu := range []int{1, 2, 4, 8, 16, 32, 64} {
for _, mem := range []int{1, 2, 4, 8, 16, 32, 64, 128} {
for _, zone := range []string{"test-zone-1", "test-zone-2", "test-zone-3"} {
for _, ct := range []string{v1alpha5.CapacityTypeSpot, v1alpha5.CapacityTypeOnDemand} {
for _, os := range []utilsets.String{utilsets.NewString(string(v1.Linux)), utilsets.NewString(string(v1.Windows))} {
for _, arch := range []string{v1alpha5.ArchitectureAmd64, v1alpha5.ArchitectureArm64} {
opts := InstanceTypeOptions{
Name: fmt.Sprintf("%d-cpu-%d-mem-%s-%s-%s-%s", cpu, mem, arch, strings.Join(os.List(), ","), zone, ct),
Architecture: arch,
OperatingSystems: os,
Resources: v1.ResourceList{
v1.ResourceCPU: resource.MustParse(fmt.Sprintf("%d", cpu)),
v1.ResourceMemory: resource.MustParse(fmt.Sprintf("%dGi", mem)),
},
}
price := priceFromResources(opts.Resources)
opts.Offerings = []cloudprovider.Offering{
{
CapacityType: ct,
Zone: zone,
Price: price,
Available: true,
},
}
instanceTypes = append(instanceTypes, NewInstanceType(opts))
}
}
}
}
}
}
return instanceTypes
}
// InstanceTypes creates instance types with incrementing resources
// 2Gi of RAM and 10 pods for every 1vcpu
// i.e. 1vcpu, 2Gi mem, 10 pods
//
// 2vcpu, 4Gi mem, 20 pods
// 3vcpu, 6Gi mem, 30 pods
func InstanceTypes(total int) []*cloudprovider.InstanceType {
instanceTypes := []*cloudprovider.InstanceType{}
for i := 0; i < total; i++ {
instanceTypes = append(instanceTypes, NewInstanceType(InstanceTypeOptions{
Name: fmt.Sprintf("fake-it-%d", i),
Resources: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse(fmt.Sprintf("%d", i+1)),
v1.ResourceMemory: resource.MustParse(fmt.Sprintf("%dGi", (i+1)*2)),
v1.ResourcePods: resource.MustParse(fmt.Sprintf("%d", (i+1)*10)),
},
}))
}
return instanceTypes
}
type InstanceTypeOptions struct {
Name string
Offerings cloudprovider.Offerings
Architecture string
OperatingSystems utilsets.String
Resources v1.ResourceList
}
func priceFromResources(resources v1.ResourceList) float64 {
price := 0.0
for k, v := range resources {
switch k {
case v1.ResourceCPU:
price += 0.1 * v.AsApproximateFloat64()
case v1.ResourceMemory:
price += 0.1 * v.AsApproximateFloat64() / (1e9)
case ResourceGPUVendorA, ResourceGPUVendorB:
price += 1.0
}
}
return price
}
| 188 |
karpenter-core | 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 metrics
import (
"context"
"github.com/prometheus/client_golang/prometheus"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/operator/injection"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/metrics"
)
const (
metricLabelController = "controller"
metricLabelMethod = "method"
metricLabelProvider = "provider"
metricLabelError = "error"
// MetricLabelErrorDefaultVal is the default string value that represents "error type unknown"
MetricLabelErrorDefaultVal = ""
// Well-known metricLabelError values
MachineNotFoundError = "MachineNotFoundError"
InsufficientCapacityError = "InsufficientCapacityError"
)
// decorator implements CloudProvider
var _ cloudprovider.CloudProvider = (*decorator)(nil)
var methodDurationHistogramVec = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: metrics.Namespace,
Subsystem: "cloudprovider",
Name: "duration_seconds",
Help: "Duration of cloud provider method calls. Labeled by the controller, method name and provider.",
},
[]string{
metricLabelController,
metricLabelMethod,
metricLabelProvider,
},
)
var (
errorsTotalCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: metrics.Namespace,
Subsystem: "cloudprovider",
Name: "errors_total",
Help: "Total number of errors returned from CloudProvider calls.",
},
[]string{
metricLabelController,
metricLabelMethod,
metricLabelProvider,
metricLabelError,
},
)
)
func init() {
crmetrics.Registry.MustRegister(methodDurationHistogramVec, errorsTotalCounter)
}
type decorator struct {
cloudprovider.CloudProvider
}
// Decorate returns a new `CloudProvider` instance that will delegate all method
// calls to the argument, `cloudProvider`, and publish aggregated latency metrics. The
// value used for the metric label, "controller", is taken from the `Context` object
// passed to the methods of `CloudProvider`.
//
// Do not decorate a `CloudProvider` multiple times or published metrics will contain
// duplicated method call counts and latencies.
func Decorate(cloudProvider cloudprovider.CloudProvider) cloudprovider.CloudProvider {
return &decorator{cloudProvider}
}
func (d *decorator) Create(ctx context.Context, machine *v1alpha5.Machine) (*v1alpha5.Machine, error) {
method := "Create"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
machine, err := d.CloudProvider.Create(ctx, machine)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return machine, err
}
func (d *decorator) Delete(ctx context.Context, machine *v1alpha5.Machine) error {
method := "Delete"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
err := d.CloudProvider.Delete(ctx, machine)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return err
}
func (d *decorator) Get(ctx context.Context, id string) (*v1alpha5.Machine, error) {
method := "Get"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
machine, err := d.CloudProvider.Get(ctx, id)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return machine, err
}
func (d *decorator) List(ctx context.Context) ([]*v1alpha5.Machine, error) {
method := "List"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
machines, err := d.CloudProvider.List(ctx)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return machines, err
}
func (d *decorator) GetInstanceTypes(ctx context.Context, provisioner *v1alpha5.Provisioner) ([]*cloudprovider.InstanceType, error) {
method := "GetInstanceTypes"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
instanceType, err := d.CloudProvider.GetInstanceTypes(ctx, provisioner)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return instanceType, err
}
func (d *decorator) IsMachineDrifted(ctx context.Context, machine *v1alpha5.Machine) (bool, error) {
method := "IsMachineDrifted"
defer metrics.Measure(methodDurationHistogramVec.With(getLabelsMapForDuration(ctx, d, method)))()
isDrifted, err := d.CloudProvider.IsMachineDrifted(ctx, machine)
if err != nil {
errorsTotalCounter.With(getLabelsMapForError(ctx, d, method, err)).Inc()
}
return isDrifted, err
}
// getLabelsMapForDuration is a convenience func that constructs a map[string]string
// for a prometheus Label map used to compose a duration metric spec
func getLabelsMapForDuration(ctx context.Context, d *decorator, method string) map[string]string {
return prometheus.Labels{
metricLabelController: injection.GetControllerName(ctx),
metricLabelMethod: method,
metricLabelProvider: d.Name(),
}
}
// getLabelsMapForError is a convenience func that constructs a map[string]string
// for a prometheus Label map used to compose a counter metric spec
func getLabelsMapForError(ctx context.Context, d *decorator, method string, err error) map[string]string {
return prometheus.Labels{
metricLabelController: injection.GetControllerName(ctx),
metricLabelMethod: method,
metricLabelProvider: d.Name(),
metricLabelError: GetErrorTypeLabelValue(err),
}
}
// GetErrorTypeLabelValue is a convenience func that returns
// a string representation of well-known CloudProvider error types
func GetErrorTypeLabelValue(err error) string {
if cloudprovider.IsInsufficientCapacityError(err) {
return InsufficientCapacityError
} else if cloudprovider.IsMachineNotFoundError(err) {
return MachineNotFoundError
}
return MetricLabelErrorDefaultVal
}
| 186 |
karpenter-core | 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 metrics_test
import (
"errors"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/cloudprovider/metrics"
)
var _ = Describe("Cloudprovider", func() {
var machineNotFoundErr = cloudprovider.NewMachineNotFoundError(errors.New("not found"))
var insufficientCapacityErr = cloudprovider.NewInsufficientCapacityError(errors.New("not enough capacity"))
var unknownErr = errors.New("this is an error we don't know about")
Describe("CloudProvider machine errors via GetErrorTypeLabelValue()", func() {
Context("when the error is known", func() {
It("machine not found should be recognized", func() {
Expect(metrics.GetErrorTypeLabelValue(machineNotFoundErr)).To(Equal(metrics.MachineNotFoundError))
})
It("insufficient capacity should be recognized", func() {
Expect(metrics.GetErrorTypeLabelValue(insufficientCapacityErr)).To(Equal(metrics.InsufficientCapacityError))
})
})
Context("when the error is unknown", func() {
It("should always return empty string", func() {
Expect(metrics.GetErrorTypeLabelValue(unknownErr)).To(Equal(metrics.MetricLabelErrorDefaultVal))
})
})
})
})
| 48 |
karpenter-core | 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 metrics_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestMetrics(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Metrics Suite")
}
| 28 |
karpenter-core | 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"
"k8s.io/client-go/kubernetes"
"k8s.io/utils/clock"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/controllers/consistency"
"github.com/aws/karpenter-core/pkg/controllers/counter"
"github.com/aws/karpenter-core/pkg/controllers/deprovisioning"
machinegarbagecollection "github.com/aws/karpenter-core/pkg/controllers/machine/garbagecollection"
machinelifecycle "github.com/aws/karpenter-core/pkg/controllers/machine/lifecycle"
machinetermination "github.com/aws/karpenter-core/pkg/controllers/machine/termination"
metricspod "github.com/aws/karpenter-core/pkg/controllers/metrics/pod"
metricsprovisioner "github.com/aws/karpenter-core/pkg/controllers/metrics/provisioner"
metricsstate "github.com/aws/karpenter-core/pkg/controllers/metrics/state"
"github.com/aws/karpenter-core/pkg/controllers/node"
"github.com/aws/karpenter-core/pkg/controllers/provisioning"
"github.com/aws/karpenter-core/pkg/controllers/state"
"github.com/aws/karpenter-core/pkg/controllers/state/informer"
"github.com/aws/karpenter-core/pkg/controllers/termination"
"github.com/aws/karpenter-core/pkg/controllers/termination/terminator"
"github.com/aws/karpenter-core/pkg/events"
"github.com/aws/karpenter-core/pkg/operator/controller"
)
func NewControllers(
ctx context.Context,
clock clock.Clock,
kubeClient client.Client,
kubernetesInterface kubernetes.Interface,
cluster *state.Cluster,
recorder events.Recorder,
cloudProvider cloudprovider.CloudProvider,
) []controller.Controller {
provisioner := provisioning.NewProvisioner(kubeClient, kubernetesInterface.CoreV1(), recorder, cloudProvider, cluster)
terminator := terminator.NewTerminator(clock, kubeClient, terminator.NewEvictionQueue(ctx, kubernetesInterface.CoreV1(), recorder))
return []controller.Controller{
provisioner,
metricsstate.NewController(cluster),
deprovisioning.NewController(clock, kubeClient, provisioner, cloudProvider, recorder, cluster),
provisioning.NewController(kubeClient, provisioner, recorder),
informer.NewDaemonSetController(kubeClient, cluster),
informer.NewNodeController(kubeClient, cluster),
informer.NewPodController(kubeClient, cluster),
informer.NewProvisionerController(kubeClient, cluster),
informer.NewMachineController(kubeClient, cluster),
node.NewController(clock, kubeClient, cloudProvider, cluster),
termination.NewController(kubeClient, cloudProvider, terminator, recorder),
metricspod.NewController(kubeClient),
metricsprovisioner.NewController(kubeClient),
counter.NewController(kubeClient, cluster),
consistency.NewController(clock, kubeClient, recorder, cloudProvider),
machinelifecycle.NewController(clock, kubeClient, cloudProvider),
machinegarbagecollection.NewController(clock, kubeClient, cloudProvider),
machinetermination.NewController(kubeClient, cloudProvider),
}
}
| 78 |
karpenter-core | 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 consistency
import (
"context"
"fmt"
"reflect"
"time"
"github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
v1 "k8s.io/api/core/v1"
"k8s.io/utils/clock"
"knative.dev/pkg/logging"
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/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/events"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
machineutil "github.com/aws/karpenter-core/pkg/utils/machine"
)
var _ corecontroller.TypedController[*v1alpha5.Machine] = (*Controller)(nil)
type Controller struct {
clock clock.Clock
kubeClient client.Client
checks []Check
recorder events.Recorder
lastScanned *cache.Cache
}
type Issue string
type Check interface {
// Check performs the consistency check, this should return a list of slice discovered, or an empty
// slice if no issues were found
Check(context.Context, *v1.Node, *v1alpha5.Machine) ([]Issue, error)
}
// scanPeriod is how often we inspect and report issues that are found.
const scanPeriod = 10 * time.Minute
func NewController(clk clock.Clock, kubeClient client.Client, recorder events.Recorder,
provider cloudprovider.CloudProvider) corecontroller.Controller {
return corecontroller.Typed[*v1alpha5.Machine](kubeClient, &Controller{
clock: clk,
kubeClient: kubeClient,
recorder: recorder,
lastScanned: cache.New(scanPeriod, 1*time.Minute),
checks: []Check{
NewTermination(kubeClient),
NewNodeShape(provider),
}},
)
}
func (c *Controller) Name() string {
return "consistency"
}
func (c *Controller) Reconcile(ctx context.Context, machine *v1alpha5.Machine) (reconcile.Result, error) {
if machine.Status.ProviderID == "" {
return reconcile.Result{}, nil
}
// If we get an event before we should check for consistency checks, we ignore and wait
if lastTime, ok := c.lastScanned.Get(client.ObjectKeyFromObject(machine).String()); ok {
if lastTime, ok := lastTime.(time.Time); ok {
remaining := scanPeriod - c.clock.Since(lastTime)
return reconcile.Result{RequeueAfter: remaining}, nil
}
// the above should always succeed
return reconcile.Result{RequeueAfter: scanPeriod}, nil
}
c.lastScanned.SetDefault(client.ObjectKeyFromObject(machine).String(), c.clock.Now())
// We assume the invariant that there is a single node for a single machine. If this invariant is violated,
// then we assume this is bubbled up through the machine lifecycle controller and don't perform consistency checks
node, err := machineutil.NodeForMachine(ctx, c.kubeClient, machine)
if err != nil {
return reconcile.Result{}, machineutil.IgnoreDuplicateNodeError(machineutil.IgnoreNodeNotFoundError(err))
}
for _, check := range c.checks {
issues, err := check.Check(ctx, node, machine)
if err != nil {
return reconcile.Result{}, fmt.Errorf("checking node with %T, %w", check, err)
}
for _, issue := range issues {
logging.FromContext(ctx).Errorf("check failed, %s", issue)
consistencyErrors.With(prometheus.Labels{checkLabel: reflect.TypeOf(check).Elem().Name()}).Inc()
c.recorder.Publish(CheckEvent(machine, string(issue)))
}
}
return reconcile.Result{RequeueAfter: scanPeriod}, nil
}
func (c *Controller) Builder(ctx context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1alpha5.Machine{}).
Watches(
&source.Kind{Type: &v1.Node{}},
machineutil.NodeEventHandler(ctx, c.kubeClient),
).
WithOptions(controller.Options{MaxConcurrentReconciles: 10}),
)
}
| 128 |
karpenter-core | 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 consistency
import (
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/events"
)
func CheckEvent(machine *v1alpha5.Machine, message string) events.Event {
return events.Event{
InvolvedObject: machine,
Type: v1.EventTypeWarning,
Reason: "FailedConsistencyCheck",
Message: message,
DedupeValues: []string{machine.Name, message},
}
}
| 33 |
karpenter-core | 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 consistency
import (
"github.com/prometheus/client_golang/prometheus"
crmetrics "sigs.k8s.io/controller-runtime/pkg/metrics"
"github.com/aws/karpenter-core/pkg/metrics"
)
func init() {
crmetrics.Registry.MustRegister(consistencyErrors)
}
const (
checkLabel = "check"
consistencySubsystem = "consistency"
)
var consistencyErrors = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: metrics.Namespace,
Subsystem: consistencySubsystem,
Name: "errors",
Help: "Number of consistency checks that have failed.",
},
[]string{checkLabel},
)
| 42 |
karpenter-core | 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 consistency
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
)
// NodeShape detects nodes that have launched with 10% or less of any resource than was expected.
type NodeShape struct {
provider cloudprovider.CloudProvider
}
func NewNodeShape(provider cloudprovider.CloudProvider) Check {
return &NodeShape{
provider: provider,
}
}
func (n *NodeShape) Check(ctx context.Context, node *v1.Node, machine *v1alpha5.Machine) ([]Issue, error) {
// ignore machines that are deleting
if !machine.DeletionTimestamp.IsZero() {
return nil, nil
}
// and machines that haven't initialized yet
if !machine.StatusConditions().GetCondition(v1alpha5.MachineInitialized).IsTrue() {
return nil, nil
}
var issues []Issue
for resourceName, expectedQuantity := range machine.Status.Capacity {
nodeQuantity, ok := node.Status.Capacity[resourceName]
if !ok && !expectedQuantity.IsZero() {
issues = append(issues, Issue(fmt.Sprintf("expected resource %q not found", resourceName)))
continue
}
pct := nodeQuantity.AsApproximateFloat64() / expectedQuantity.AsApproximateFloat64()
if pct < 0.90 {
issues = append(issues, Issue(fmt.Sprintf("expected %s of resource %s, but found %s (%0.1f%% of expected)", expectedQuantity.String(),
resourceName, nodeQuantity.String(), pct*100)))
}
}
return issues, nil
}
| 64 |
karpenter-core | 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 consistency_test
import (
"context"
"fmt"
"testing"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
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/intstr"
clock "k8s.io/utils/clock/testing"
. "knative.dev/pkg/logging/testing"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis"
"github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider/fake"
"github.com/aws/karpenter-core/pkg/controllers/consistency"
"github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/operator/scheme"
"github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
)
var ctx context.Context
var consistencyController controller.Controller
var env *test.Environment
var fakeClock *clock.FakeClock
var cp *fake.CloudProvider
var recorder *test.EventRecorder
func TestAPIs(t *testing.T) {
ctx = TestContextWithLogger(t)
RegisterFailHandler(Fail)
RunSpecs(t, "Node")
}
var _ = BeforeSuite(func() {
fakeClock = clock.NewFakeClock(time.Now())
env = test.NewEnvironment(scheme.Scheme, test.WithCRDs(apis.CRDs...), test.WithFieldIndexers(func(c cache.Cache) error {
return c.IndexField(ctx, &v1.Node{}, "spec.providerID", func(obj client.Object) []string {
return []string{obj.(*v1.Node).Spec.ProviderID}
})
}))
ctx = settings.ToContext(ctx, test.Settings())
cp = &fake.CloudProvider{}
recorder = test.NewEventRecorder()
consistencyController = consistency.NewController(fakeClock, env.Client, recorder, cp)
})
var _ = AfterSuite(func() {
Expect(env.Stop()).To(Succeed(), "Failed to stop environment")
})
var _ = Describe("Controller", func() {
var provisioner *v1alpha5.Provisioner
BeforeEach(func() {
provisioner = &v1alpha5.Provisioner{
ObjectMeta: metav1.ObjectMeta{Name: test.RandomName()},
Spec: v1alpha5.ProvisionerSpec{},
}
recorder.Reset()
})
AfterEach(func() {
fakeClock.SetTime(time.Now())
ExpectCleanedUp(ctx, env.Client)
})
Context("Termination failure", func() {
It("should detect issues with a node that is stuck deleting due to a PDB", func() {
machine, node := test.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: "default-instance-type",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Capacity: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("1"),
v1.ResourceMemory: resource.MustParse("1Gi"),
v1.ResourcePods: resource.MustParse("10"),
},
},
})
podsLabels := map[string]string{"myapp": "deleteme"}
pdb := test.PodDisruptionBudget(test.PDBOptions{
Labels: podsLabels,
MaxUnavailable: &intstr.IntOrString{IntVal: 0, Type: intstr.Int},
})
machine.Finalizers = []string{"prevent.deletion/now"}
p := test.Pod(test.PodOptions{ObjectMeta: metav1.ObjectMeta{Labels: podsLabels}})
ExpectApplied(ctx, env.Client, provisioner, machine, node, p, pdb)
ExpectManualBinding(ctx, env.Client, p, node)
_ = env.Client.Delete(ctx, machine)
ExpectReconcileSucceeded(ctx, consistencyController, client.ObjectKeyFromObject(machine))
Expect(recorder.DetectedEvent(fmt.Sprintf("can't drain node, PDB %s/%s is blocking evictions", pdb.Namespace, pdb.Name))).To(BeTrue())
})
})
Context("Node Shape", func() {
It("should detect issues that launch with much fewer resources than expected", func() {
machine, node := test.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: provisioner.Name,
v1.LabelInstanceTypeStable: "arm-instance-type",
v1alpha5.LabelNodeInitialized: "true",
},
},
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Capacity: v1.ResourceList{
v1.ResourceCPU: resource.MustParse("16"),
v1.ResourceMemory: resource.MustParse("128Gi"),
v1.ResourcePods: resource.MustParse("10"),
},
},
})
node.Status.Capacity = v1.ResourceList{
v1.ResourceCPU: resource.MustParse("16"),
v1.ResourceMemory: resource.MustParse("64Gi"),
v1.ResourcePods: resource.MustParse("10"),
}
ExpectApplied(ctx, env.Client, provisioner, machine, node)
ExpectMakeMachinesInitialized(ctx, env.Client, machine)
ExpectReconcileSucceeded(ctx, consistencyController, client.ObjectKeyFromObject(machine))
Expect(recorder.DetectedEvent("expected 128Gi of resource memory, but found 64Gi (50.0% of expected)")).To(BeTrue())
})
})
})
| 154 |
karpenter-core | 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 consistency
import (
"context"
"fmt"
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/controllers/deprovisioning"
nodeutils "github.com/aws/karpenter-core/pkg/utils/node"
)
// Termination detects nodes that are stuck terminating and reports why.
type Termination struct {
kubeClient client.Client
}
func NewTermination(kubeClient client.Client) Check {
return &Termination{
kubeClient: kubeClient,
}
}
func (t *Termination) Check(ctx context.Context, node *v1.Node, machine *v1alpha5.Machine) ([]Issue, error) {
// we are only looking at nodes that are hung deleting
if machine.DeletionTimestamp.IsZero() {
return nil, nil
}
pdbs, err := deprovisioning.NewPDBLimits(ctx, t.kubeClient)
if err != nil {
return nil, err
}
pods, err := nodeutils.GetNodePods(ctx, t.kubeClient, node)
if err != nil {
return nil, err
}
var issues []Issue
if pdb, ok := pdbs.CanEvictPods(pods); !ok {
issues = append(issues, Issue(fmt.Sprintf("can't drain node, PDB %s is blocking evictions", pdb)))
}
return issues, nil
}
| 59 |
karpenter-core | 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 counter
import (
"context"
"time"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/controllers/state"
corecontroller "github.com/aws/karpenter-core/pkg/operator/controller"
"github.com/aws/karpenter-core/pkg/utils/functional"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
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/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/aws/karpenter-core/pkg/utils/resources"
)
var _ corecontroller.TypedController[*v1alpha5.Provisioner] = (*Controller)(nil)
// Controller for the resource
type Controller struct {
kubeClient client.Client
cluster *state.Cluster
}
// NewController is a constructor
func NewController(kubeClient client.Client, cluster *state.Cluster) corecontroller.Controller {
return corecontroller.Typed[*v1alpha5.Provisioner](kubeClient, &Controller{
kubeClient: kubeClient,
cluster: cluster,
})
}
func (c *Controller) Name() string {
return "counter"
}
// Reconcile a control loop for the resource
func (c *Controller) Reconcile(ctx context.Context, provisioner *v1alpha5.Provisioner) (reconcile.Result, error) {
// We need to ensure that our internal cluster state mechanism is synced before we proceed
// Otherwise, we have the potential to patch over the status with a lower value for the provisioner resource
// counts on startup
if !c.cluster.Synced(ctx) {
return reconcile.Result{RequeueAfter: time.Second}, nil
}
stored := provisioner.DeepCopy()
// Determine resource usage and update provisioner.status.resources
provisioner.Status.Resources = c.resourceCountsFor(provisioner.Name)
if !equality.Semantic.DeepEqual(stored, provisioner) {
if err := c.kubeClient.Status().Patch(ctx, provisioner, client.MergeFrom(stored)); err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
func (c *Controller) resourceCountsFor(provisionerName string) v1.ResourceList {
var res v1.ResourceList
// Record all resources provisioned by the provisioners, we look at the cluster state nodes as their capacity
// is accurately reported even for nodes that haven't fully started yet. This allows us to update our provisioner
// status immediately upon node creation instead of waiting for the node to become ready.
c.cluster.ForEachNode(func(n *state.StateNode) bool {
// Don't count nodes that we are planning to delete. This is to ensure that we are consistent throughout
// our provisioning and deprovisioning loops
if n.MarkedForDeletion() {
return true
}
if n.Labels()[v1alpha5.ProvisionerNameLabelKey] == provisionerName {
res = resources.Merge(res, n.Capacity())
}
return true
})
return functional.FilterMap(res, func(_ v1.ResourceName, v resource.Quantity) bool { return !v.IsZero() })
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) corecontroller.Builder {
return corecontroller.Adapt(controllerruntime.
NewControllerManagedBy(m).
For(&v1alpha5.Provisioner{}).
Watches(
&source.Kind{Type: &v1.Node{}},
handler.EnqueueRequestsFromMapFunc(func(o client.Object) []reconcile.Request {
if name, ok := o.GetLabels()[v1alpha5.ProvisionerNameLabelKey]; ok {
return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: name}}}
}
return nil
}),
).
WithOptions(controller.Options{MaxConcurrentReconciles: 10}))
}
| 115 |
karpenter-core | 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 deprovisioning
import (
"context"
"errors"
"fmt"
"sort"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/utils/clock"
"knative.dev/pkg/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
deprovisioningevents "github.com/aws/karpenter-core/pkg/controllers/deprovisioning/events"
"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/metrics"
"github.com/aws/karpenter-core/pkg/scheduling"
)
// consolidation is the base consolidation controller that provides common functionality used across the different
// consolidation methods.
type consolidation struct {
clock clock.Clock
cluster *state.Cluster
kubeClient client.Client
provisioner *provisioning.Provisioner
cloudProvider cloudprovider.CloudProvider
recorder events.Recorder
lastConsolidationState int64
}
func makeConsolidation(clock clock.Clock, cluster *state.Cluster, kubeClient client.Client, provisioner *provisioning.Provisioner,
cloudProvider cloudprovider.CloudProvider, recorder events.Recorder) consolidation {
return consolidation{
clock: clock,
cluster: cluster,
kubeClient: kubeClient,
provisioner: provisioner,
cloudProvider: cloudProvider,
recorder: recorder,
lastConsolidationState: 0,
}
}
// consolidationTTL is the TTL between creating a consolidation command and validating that it still works.
const consolidationTTL = 15 * time.Second
// string is the string representation of the deprovisioner
func (c *consolidation) String() string {
return metrics.ConsolidationReason
}
// sortAndFilterCandidates orders deprovisionable nodes by the disruptionCost, removing any that we already know won't
// be viable consolidation options.
func (c *consolidation) sortAndFilterCandidates(ctx context.Context, nodes []*Candidate) ([]*Candidate, error) {
candidates, err := filterCandidates(ctx, c.kubeClient, c.recorder, nodes)
if err != nil {
return nil, fmt.Errorf("filtering candidates, %w", err)
}
sort.Slice(candidates, func(i int, j int) bool {
return candidates[i].disruptionCost < candidates[j].disruptionCost
})
return candidates, nil
}
// ShouldDeprovision is a predicate used to filter deprovisionable nodes
func (c *consolidation) ShouldDeprovision(_ context.Context, cn *Candidate) bool {
if val, ok := cn.Annotations()[v1alpha5.DoNotConsolidateNodeAnnotationKey]; ok {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(cn.Node, cn.Machine, fmt.Sprintf("%s annotation exists", v1alpha5.DoNotConsolidateNodeAnnotationKey))...)
return val != "true"
}
if cn.provisioner == nil {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(cn.Node, cn.Machine, "provisioner is unknown")...)
return false
}
if cn.provisioner.Spec.Consolidation == nil || !ptr.BoolValue(cn.provisioner.Spec.Consolidation.Enabled) {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(cn.Node, cn.Machine, fmt.Sprintf("provisioner %s has consolidation disabled", cn.provisioner.Name))...)
return false
}
return true
}
// computeConsolidation computes a consolidation action to take
//
// nolint:gocyclo
func (c *consolidation) computeConsolidation(ctx context.Context, candidates ...*Candidate) (Command, error) {
// Run scheduling simulation to compute consolidation option
results, err := simulateScheduling(ctx, c.kubeClient, c.cluster, c.provisioner, candidates...)
if err != nil {
// if a candidate node is now deleting, just retry
if errors.Is(err, errCandidateDeleting) {
return Command{}, nil
}
return Command{}, err
}
// if not all of the pods were scheduled, we can't do anything
if !results.AllPodsScheduled() {
// This method is used by multi-node consolidation as well, so we'll only report in the single node case
if len(candidates) == 1 {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(candidates[0].Node, candidates[0].Machine, results.PodSchedulingErrors())...)
}
return Command{}, nil
}
// were we able to schedule all the pods on the inflight candidates?
if len(results.NewMachines) == 0 {
return Command{
candidates: candidates,
}, nil
}
// we're not going to turn a single node into multiple candidates
if len(results.NewMachines) != 1 {
if len(candidates) == 1 {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(candidates[0].Node, candidates[0].Machine, fmt.Sprintf("can't remove without creating %d candidates", len(results.NewMachines)))...)
}
return Command{}, nil
}
// get the current node price based on the offering
// fallback if we can't find the specific zonal pricing data
nodesPrice, err := getCandidatePrices(candidates)
if err != nil {
return Command{}, fmt.Errorf("getting offering price from candidate node, %w", err)
}
results.NewMachines[0].InstanceTypeOptions = filterByPrice(results.NewMachines[0].InstanceTypeOptions, results.NewMachines[0].Requirements, nodesPrice)
if len(results.NewMachines[0].InstanceTypeOptions) == 0 {
if len(candidates) == 1 {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(candidates[0].Node, candidates[0].Machine, "can't replace with a cheaper node")...)
}
// no instance types remain after filtering by price
return Command{}, nil
}
// If the existing candidates are all spot and the replacement is spot, we don't consolidate. We don't have a reliable
// mechanism to determine if this replacement makes sense given instance type availability (e.g. we may replace
// a spot node with one that is less available and more likely to be reclaimed).
allExistingAreSpot := true
for _, cn := range candidates {
if cn.capacityType != v1alpha5.CapacityTypeSpot {
allExistingAreSpot = false
}
}
if allExistingAreSpot &&
results.NewMachines[0].Requirements.Get(v1alpha5.LabelCapacityType).Has(v1alpha5.CapacityTypeSpot) {
if len(candidates) == 1 {
c.recorder.Publish(deprovisioningevents.Unconsolidatable(candidates[0].Node, candidates[0].Machine, "can't replace a spot node with a spot node")...)
}
return Command{}, nil
}
// We are consolidating a node from OD -> [OD,Spot] but have filtered the instance types by cost based on the
// assumption, that the spot variant will launch. We also need to add a requirement to the node to ensure that if
// spot capacity is insufficient we don't replace the node with a more expensive on-demand node. Instead the launch
// should fail and we'll just leave the node alone.
ctReq := results.NewMachines[0].Requirements.Get(v1alpha5.LabelCapacityType)
if ctReq.Has(v1alpha5.CapacityTypeSpot) && ctReq.Has(v1alpha5.CapacityTypeOnDemand) {
results.NewMachines[0].Requirements.Add(scheduling.NewRequirement(v1alpha5.LabelCapacityType, v1.NodeSelectorOpIn, v1alpha5.CapacityTypeSpot))
}
return Command{
candidates: candidates,
replacements: results.NewMachines,
}, nil
}
// getCandidatePrices returns the sum of the prices of the given candidate nodes
func getCandidatePrices(candidates []*Candidate) (float64, error) {
var price float64
for _, c := range candidates {
offering, ok := c.instanceType.Offerings.Get(c.capacityType, c.zone)
if !ok {
return 0.0, fmt.Errorf("unable to determine offering for %s/%s/%s", c.instanceType.Name, c.capacityType, c.zone)
}
price += offering.Price
}
return price, nil
}
| 201 |
karpenter-core | 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 deprovisioning
import (
"context"
"fmt"
"sync"
"time"
"github.com/avast/retry-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/samber/lo"
"go.uber.org/multierr"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"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/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
deprovisioningevents "github.com/aws/karpenter-core/pkg/controllers/deprovisioning/events"
"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/metrics"
"github.com/aws/karpenter-core/pkg/operator/controller"
)
// Controller is the deprovisioning controller.
type Controller struct {
kubeClient client.Client
cluster *state.Cluster
provisioner *provisioning.Provisioner
recorder events.Recorder
clock clock.Clock
cloudProvider cloudprovider.CloudProvider
deprovisioners []Deprovisioner
mu sync.Mutex
lastRun map[string]time.Time
}
// pollingPeriod that we inspect cluster to look for opportunities to deprovision
const pollingPeriod = 10 * time.Second
const immediately = time.Millisecond
var errCandidateDeleting = fmt.Errorf("candidate is deleting")
// waitRetryOptions are the retry options used when waiting on a machine to become ready or to be deleted
// readiness can take some time as the node needs to come up, have any daemonset extended resoruce plugins register, etc.
// deletion can take some time in the case of restrictive PDBs that throttle the rate at which the node is drained
var waitRetryOptions = []retry.Option{
retry.Delay(2 * time.Second),
retry.LastErrorOnly(true),
retry.Attempts(60),
retry.MaxDelay(10 * time.Second), // 22 + (60-5)*10 =~ 9.5 minutes in total
}
func NewController(clk clock.Clock, kubeClient client.Client, provisioner *provisioning.Provisioner,
cp cloudprovider.CloudProvider, recorder events.Recorder, cluster *state.Cluster) *Controller {
return &Controller{
clock: clk,
kubeClient: kubeClient,
cluster: cluster,
provisioner: provisioner,
recorder: recorder,
cloudProvider: cp,
lastRun: map[string]time.Time{},
deprovisioners: []Deprovisioner{
// Expire any machines that must be deleted, allowing their pods to potentially land on currently
NewExpiration(clk, kubeClient, cluster, provisioner, recorder),
// Terminate any machines that have drifted from provisioning specifications, allowing the pods to reschedule.
NewDrift(kubeClient, cluster, provisioner, recorder),
// Delete any remaining empty machines as there is zero cost in terms of disruption. Emptiness and
// emptyNodeConsolidation are mutually exclusive, only one of these will operate
NewEmptiness(clk),
NewEmptyMachineConsolidation(clk, cluster, kubeClient, provisioner, cp, recorder),
// Attempt to identify multiple machines that we can consolidate simultaneously to reduce pod churn
NewMultiMachineConsolidation(clk, cluster, kubeClient, provisioner, cp, recorder),
// And finally fall back our single machines consolidation to further reduce cluster cost.
NewSingleMachineConsolidation(clk, cluster, kubeClient, provisioner, cp, recorder),
},
}
}
func (c *Controller) Name() string {
return "deprovisioning"
}
func (c *Controller) Builder(_ context.Context, m manager.Manager) controller.Builder {
return controller.NewSingletonManagedBy(m)
}
func (c *Controller) Reconcile(ctx context.Context, _ reconcile.Request) (reconcile.Result, error) {
// this won't catch if the reconcile loop hangs forever, but it will catch other issues
c.logAbnormalRuns(ctx)
defer c.logAbnormalRuns(ctx)
c.recordRun("deprovisioning-loop")
// We need to ensure that our internal cluster state mechanism is synced before we proceed
// with making any scheduling decision off of our state nodes. Otherwise, we have the potential to make
// a scheduling decision based on a smaller subset of nodes in our cluster state than actually exist.
if !c.cluster.Synced(ctx) {
logging.FromContext(ctx).Debugf("waiting on cluster sync")
return reconcile.Result{RequeueAfter: time.Second}, nil
}
// Attempt different deprovisioning methods. We'll only let one method perform an action
isConsolidated := c.cluster.Consolidated()
for _, d := range c.deprovisioners {
c.recordRun(fmt.Sprintf("%T", d))
success, err := c.deprovision(ctx, d)
if err != nil {
return reconcile.Result{}, fmt.Errorf("deprovisioning via %q, %w", d, err)
}
if success {
return reconcile.Result{RequeueAfter: immediately}, nil
}
}
if !isConsolidated {
// Mark cluster as consolidated, only if the deprovisioners ran and were not able to perform any work.
c.cluster.SetConsolidated(true)
}
// All deprovisioners did nothing, so return nothing to do
return reconcile.Result{RequeueAfter: pollingPeriod}, nil
}
func (c *Controller) deprovision(ctx context.Context, deprovisioner Deprovisioner) (bool, error) {
defer metrics.Measure(deprovisioningDurationHistogram.WithLabelValues(deprovisioner.String()))()
candidates, err := GetCandidates(ctx, c.cluster, c.kubeClient, c.recorder, c.clock, c.cloudProvider, deprovisioner.ShouldDeprovision)
if err != nil {
return false, fmt.Errorf("determining candidates, %w", err)
}
// If there are no candidate nodes, move to the next deprovisioner
if len(candidates) == 0 {
return false, nil
}
// Determine the deprovisioning action
cmd, err := deprovisioner.ComputeCommand(ctx, candidates...)
if err != nil {
return false, fmt.Errorf("computing deprovisioning decision, %w", err)
}
if cmd.Action() == NoOpAction {
return false, nil
}
// Attempt to deprovision
if err := c.executeCommand(ctx, deprovisioner, cmd); err != nil {
return false, fmt.Errorf("deprovisioning candidates, %w", err)
}
return true, nil
}
func (c *Controller) executeCommand(ctx context.Context, d Deprovisioner, command Command) error {
deprovisioningActionsPerformedCounter.With(map[string]string{
// TODO: make this just command.Action() since we've added the deprovisioner as its own label.
actionLabel: fmt.Sprintf("%s/%s", d, command.Action()),
deprovisionerLabel: d.String(),
}).Inc()
logging.FromContext(ctx).Infof("deprovisioning via %s %s", d, command)
reason := fmt.Sprintf("%s/%s", d, command.Action())
if command.Action() == ReplaceAction {
if err := c.launchReplacementMachines(ctx, command, reason); err != nil {
// If we failed to launch the replacement, don't deprovision. If this is some permanent failure,
// we don't want to disrupt workloads with no way to provision new nodes for them.
return fmt.Errorf("launching replacement machine, %w", err)
}
}
for _, candidate := range command.candidates {
c.recorder.Publish(deprovisioningevents.Terminating(candidate.Node, candidate.Machine, command.String())...)
if err := c.kubeClient.Delete(ctx, candidate.Machine); err != nil {
if errors.IsNotFound(err) {
continue
}
logging.FromContext(ctx).Errorf("terminating machine, %s", err)
} else {
metrics.MachinesTerminatedCounter.With(prometheus.Labels{
metrics.ReasonLabel: reason,
metrics.ProvisionerLabel: candidate.provisioner.Name,
}).Inc()
}
}
// We wait for nodes to delete to ensure we don't start another round of deprovisioning until this node is fully
// deleted.
for _, oldCandidate := range command.candidates {
c.waitForDeletion(ctx, oldCandidate.Machine)
}
return nil
}
// launchReplacementMachines launches replacement machines and blocks until it is ready
// nolint:gocyclo
func (c *Controller) launchReplacementMachines(ctx context.Context, action Command, reason string) error {
defer metrics.Measure(deprovisioningReplacementNodeInitializedHistogram)()
candidateNodeNames := lo.Map(action.candidates, func(c *Candidate, _ int) string { return c.Node.Name })
// cordon the old nodes before we launch the replacements to prevent new pods from scheduling to the old nodes
if err := c.setNodesUnschedulable(ctx, true, candidateNodeNames...); err != nil {
return fmt.Errorf("cordoning nodes, %w", err)
}
machineNames, err := c.provisioner.LaunchMachines(ctx, action.replacements, provisioning.WithReason(reason))
if err != nil {
// uncordon the nodes as the launch may fail (e.g. ICE)
err = multierr.Append(err, c.setNodesUnschedulable(ctx, false, candidateNodeNames...))
return err
}
if len(machineNames) != len(action.replacements) {
// shouldn't ever occur since a partially failed LaunchMachines should return an error
return fmt.Errorf("expected %d machines, got %d", len(action.replacements), len(machineNames))
}
// We have the new machines created at the API server so mark the old machines for deletion
c.cluster.MarkForDeletion(candidateNodeNames...)
errs := make([]error, len(machineNames))
workqueue.ParallelizeUntil(ctx, len(machineNames), len(machineNames), func(i int) {
// machine never became ready or the machines that we tried to launch got Insufficient Capacity or some
// other transient error
errs[i] = c.waitForReadiness(ctx, action, machineNames[i])
})
if err = multierr.Combine(errs...); err != nil {
c.cluster.UnmarkForDeletion(candidateNodeNames...)
return multierr.Combine(c.setNodesUnschedulable(ctx, false, candidateNodeNames...),
fmt.Errorf("timed out checking machine readiness, %w", err))
}
return nil
}
// TODO @njtran: Allow to bypass this check for certain deprovisioners
func (c *Controller) waitForReadiness(ctx context.Context, action Command, name string) error {
// Wait for the machine to be initialized
var once sync.Once
pollStart := time.Now()
return retry.Do(func() error {
machine := &v1alpha5.Machine{}
if err := c.kubeClient.Get(ctx, types.NamespacedName{Name: name}, machine); err != nil {
// If the machine was deleted after a few seconds (to give the cache time to update), then we assume
// that the machine was deleted due to an Insufficient Capacity error
if errors.IsNotFound(err) && c.clock.Since(pollStart) > time.Second*5 {
return retry.Unrecoverable(fmt.Errorf("getting machine, %w", err))
}
return fmt.Errorf("getting machine, %w", err)
}
once.Do(func() {
c.recorder.Publish(deprovisioningevents.Launching(machine, action.String()))
})
if !machine.StatusConditions().GetCondition(v1alpha5.MachineInitialized).IsTrue() {
// make the user aware of why deprovisioning is paused
c.recorder.Publish(deprovisioningevents.WaitingOnReadiness(machine))
return fmt.Errorf("machine is not initialized")
}
return nil
}, waitRetryOptions...)
}
// waitForDeletion waits for the specified machine to be removed from the API server. This deletion can take some period
// of time if there are PDBs that govern pods on the machine as we need to wait until the node drains before
// it's actually deleted.
func (c *Controller) waitForDeletion(ctx context.Context, machine *v1alpha5.Machine) {
if err := retry.Do(func() error {
m := &v1alpha5.Machine{}
nerr := c.kubeClient.Get(ctx, client.ObjectKeyFromObject(machine), m)
// We expect the not machine found error, at which point we know the machine is deleted.
if errors.IsNotFound(nerr) {
return nil
}
// make the user aware of why deprovisioning is paused
c.recorder.Publish(deprovisioningevents.WaitingOnDeletion(machine))
if nerr != nil {
return fmt.Errorf("expected machine to be not found, %w", nerr)
}
// the machine still exists
return fmt.Errorf("expected machine to be not found")
}, waitRetryOptions...,
); err != nil {
logging.FromContext(ctx).Errorf("Waiting on machine deletion, %s", err)
}
}
func (c *Controller) setNodesUnschedulable(ctx context.Context, isUnschedulable bool, names ...string) error {
var multiErr error
for _, name := range names {
node := &v1.Node{}
if err := c.kubeClient.Get(ctx, client.ObjectKey{Name: name}, node); err != nil {
multiErr = multierr.Append(multiErr, fmt.Errorf("getting node, %w", err))
}
// node is being deleted already, so no need to un-cordon
if !isUnschedulable && !node.DeletionTimestamp.IsZero() {
continue
}
// already matches the state we want to be in
if node.Spec.Unschedulable == isUnschedulable {
continue
}
stored := node.DeepCopy()
node.Spec.Unschedulable = isUnschedulable
if err := c.kubeClient.Patch(ctx, node, client.MergeFrom(stored)); err != nil {
multiErr = multierr.Append(multiErr, fmt.Errorf("patching node %s, %w", node.Name, err))
}
}
return multiErr
}
func (c *Controller) recordRun(s string) {
c.mu.Lock()
defer c.mu.Unlock()
c.lastRun[s] = c.clock.Now()
}
func (c *Controller) logAbnormalRuns(ctx context.Context) {
const AbnormalTimeLimit = 15 * time.Minute
c.mu.Lock()
defer c.mu.Unlock()
for name, runTime := range c.lastRun {
if timeSince := c.clock.Since(runTime); timeSince > AbnormalTimeLimit {
logging.FromContext(ctx).Debugf("abnormal time between runs of %s = %s", name, timeSince)
}
}
}
| 348 |
karpenter-core | 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 deprovisioning
import (
"context"
"errors"
"fmt"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/samber/lo"
"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/metrics"
)
// Drift is a subreconciler that deletes drifted machines.
type Drift struct {
kubeClient client.Client
cluster *state.Cluster
provisioner *provisioning.Provisioner
recorder events.Recorder
}
func NewDrift(kubeClient client.Client, cluster *state.Cluster, provisioner *provisioning.Provisioner, recorder events.Recorder) *Drift {
return &Drift{
kubeClient: kubeClient,
cluster: cluster,
provisioner: provisioner,
recorder: recorder,
}
}
// ShouldDeprovision is a predicate used to filter deprovisionable machines
func (d *Drift) ShouldDeprovision(ctx context.Context, c *Candidate) bool {
// Look up the feature flag to see if we should deprovision the machine because of drift.
if !settings.FromContext(ctx).DriftEnabled {
return false
}
return c.Annotations()[v1alpha5.VoluntaryDisruptionAnnotationKey] == v1alpha5.VoluntaryDisruptionDriftedAnnotationValue
}
// ComputeCommand generates a deprovisioning command given deprovisionable machines
func (d *Drift) ComputeCommand(ctx context.Context, nodes ...*Candidate) (Command, error) {
candidates, err := filterCandidates(ctx, d.kubeClient, d.recorder, nodes)
if err != nil {
return Command{}, fmt.Errorf("filtering candidates, %w", err)
}
deprovisioningEligibleMachinesGauge.WithLabelValues(d.String()).Set(float64(len(candidates)))
// Deprovision all empty drifted nodes, as they require no scheduling simulations.
if empty := lo.Filter(candidates, func(c *Candidate, _ int) bool {
return len(c.pods) == 0
}); len(empty) > 0 {
return Command{
candidates: empty,
}, nil
}
for _, candidate := range candidates {
// Check if we need to create any machines.
results, err := simulateScheduling(ctx, d.kubeClient, d.cluster, d.provisioner, candidate)
if err != nil {
// if a candidate machine is now deleting, just retry
if errors.Is(err, errCandidateDeleting) {
continue
}
return Command{}, err
}
// Log when all pods can't schedule, as the command will get executed immediately.
if !results.AllPodsScheduled() {
logging.FromContext(ctx).With("machine", candidate.Machine.Name, "node", candidate.Node.Name).Debug("Continuing to terminate drifted machine after scheduling simulation failed to schedule all pods %s", results.PodSchedulingErrors())
}
if len(results.NewMachines) == 0 {
return Command{
candidates: []*Candidate{candidate},
}, nil
}
return Command{
candidates: []*Candidate{candidate},
replacements: results.NewMachines,
}, nil
}
return Command{}, nil
}
// String is the string representation of the deprovisioner
func (d *Drift) String() string {
return metrics.DriftReason
}
| 109 |
karpenter-core | 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 deprovisioning_test
import (
"sync"
"time"
. "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/types"
"knative.dev/pkg/ptr"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/karpenter-core/pkg/apis/settings"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/cloudprovider"
"github.com/aws/karpenter-core/pkg/cloudprovider/fake"
"github.com/aws/karpenter-core/pkg/test"
. "github.com/aws/karpenter-core/pkg/test/expectations"
)
var _ = Describe("Drift", func() {
var prov *v1alpha5.Provisioner
var machine *v1alpha5.Machine
var node *v1.Node
BeforeEach(func() {
prov = test.Provisioner()
machine, node = test.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionDriftedAnnotationValue,
},
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: prov.Name,
v1.LabelInstanceTypeStable: mostExpensiveInstance.Name,
v1alpha5.LabelCapacityType: mostExpensiveOffering.CapacityType,
v1.LabelTopologyZone: mostExpensiveOffering.Zone,
},
},
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Allocatable: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("32"),
v1.ResourcePods: resource.MustParse("100"),
},
},
})
})
It("should ignore drifted nodes if the feature flag is disabled", func() {
ctx = settings.ToContext(ctx, test.Settings(settings.Settings{DriftEnabled: false}))
ExpectApplied(ctx, env.Client, machine, node, prov)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Expect to not create or delete more machines
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(1))
ExpectExists(ctx, env.Client, machine)
})
It("should ignore nodes with the disrupted annotation key, but not the drifted value", func() {
node.Annotations = lo.Assign(node.Annotations, map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: "wrong-value",
})
ExpectApplied(ctx, env.Client, machine, node, prov)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Expect to not create or delete more machines
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(1))
ExpectExists(ctx, env.Client, machine)
})
It("should ignore nodes without the disrupted annotation key", func() {
delete(node.Annotations, v1alpha5.VoluntaryDisruptionAnnotationKey)
ExpectApplied(ctx, env.Client, machine, node, prov)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
// Expect to not create or delete more machines
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(1))
ExpectExists(ctx, env.Client, machine)
})
It("can delete drifted nodes", func() {
node.Annotations = lo.Assign(node.Annotations, map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionDriftedAnnotationValue,
})
ExpectApplied(ctx, env.Client, machine, node, prov)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Cascade any deletion of the machine to the node
ExpectMachinesCascadeDeletion(ctx, env.Client, machine)
// We should delete the machine that has drifted
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(0))
Expect(ExpectNodes(ctx, env.Client)).To(HaveLen(0))
ExpectNotFound(ctx, env.Client, machine, node)
})
It("should deprovision all empty drifted nodes in parallel", func() {
machines, nodes := test.MachinesAndNodes(100, v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionDriftedAnnotationValue,
},
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: prov.Name,
v1.LabelInstanceTypeStable: mostExpensiveInstance.Name,
v1alpha5.LabelCapacityType: mostExpensiveOffering.CapacityType,
v1.LabelTopologyZone: mostExpensiveOffering.Zone,
},
},
Status: v1alpha5.MachineStatus{
Allocatable: map[v1.ResourceName]resource.Quantity{
v1.ResourceCPU: resource.MustParse("32"),
v1.ResourcePods: resource.MustParse("100"),
},
},
})
for _, m := range machines {
ExpectApplied(ctx, env.Client, m)
}
for _, n := range nodes {
ExpectApplied(ctx, env.Client, n)
}
ExpectApplied(ctx, env.Client, prov)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, nodes, machines)
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Cascade any deletion of the machine to the node
ExpectMachinesCascadeDeletion(ctx, env.Client, machines...)
// Expect that the expired machines are gone
Expect(ExpectNodes(ctx, env.Client)).To(HaveLen(0))
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(0))
})
It("can replace drifted nodes", func() {
labels := map[string]string{
"app": "test",
}
// create our RS so we can link a pod to it
rs := test.ReplicaSet()
ExpectApplied(ctx, env.Client, rs)
Expect(env.Client.Get(ctx, client.ObjectKeyFromObject(rs), rs)).To(Succeed())
pod := test.Pod(test.PodOptions{
ObjectMeta: metav1.ObjectMeta{Labels: labels,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Name: rs.Name,
UID: rs.UID,
Controller: ptr.Bool(true),
BlockOwnerDeletion: ptr.Bool(true),
},
}}})
node.Annotations = lo.Assign(node.Annotations, map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionDriftedAnnotationValue,
})
ExpectApplied(ctx, env.Client, rs, pod, machine, node, prov)
// bind the pods to the node
ExpectManualBinding(ctx, env.Client, pod, node)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
// deprovisioning won't delete the old machine until the new machine is ready
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectMakeNewMachinesReady(ctx, env.Client, &wg, cluster, cloudProvider, 1)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Cascade any deletion of the machine to the node
ExpectMachinesCascadeDeletion(ctx, env.Client, machine)
ExpectNotFound(ctx, env.Client, machine, node)
// Expect that the new machine was created and its different than the original
machines := ExpectMachines(ctx, env.Client)
nodes := ExpectNodes(ctx, env.Client)
Expect(machines).To(HaveLen(1))
Expect(nodes).To(HaveLen(1))
Expect(machines[0].Name).ToNot(Equal(machine.Name))
Expect(nodes[0].Name).ToNot(Equal(node.Name))
})
It("can replace drifted nodes with multiple nodes", func() {
currentInstance := fake.NewInstanceType(fake.InstanceTypeOptions{
Name: "current-on-demand",
Offerings: []cloudprovider.Offering{
{
CapacityType: v1alpha5.CapacityTypeOnDemand,
Zone: "test-zone-1a",
Price: 0.5,
Available: false,
},
},
})
replacementInstance := fake.NewInstanceType(fake.InstanceTypeOptions{
Name: "replacement-on-demand",
Offerings: []cloudprovider.Offering{
{
CapacityType: v1alpha5.CapacityTypeOnDemand,
Zone: "test-zone-1a",
Price: 0.3,
Available: true,
},
},
Resources: map[v1.ResourceName]resource.Quantity{v1.ResourceCPU: resource.MustParse("3")},
})
cloudProvider.InstanceTypes = []*cloudprovider.InstanceType{
currentInstance,
replacementInstance,
}
labels := map[string]string{
"app": "test",
}
// create our RS so we can link a pod to it
rs := test.ReplicaSet()
ExpectApplied(ctx, env.Client, rs)
Expect(env.Client.Get(ctx, client.ObjectKeyFromObject(rs), rs)).To(Succeed())
pods := test.Pods(3, test.PodOptions{
ObjectMeta: metav1.ObjectMeta{Labels: labels,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Name: rs.Name,
UID: rs.UID,
Controller: ptr.Bool(true),
BlockOwnerDeletion: ptr.Bool(true),
},
}},
// Make each pod request about a third of the allocatable on the node
ResourceRequirements: v1.ResourceRequirements{
Requests: map[v1.ResourceName]resource.Quantity{v1.ResourceCPU: resource.MustParse("2")},
},
})
machine, node = test.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: prov.Name,
v1.LabelInstanceTypeStable: currentInstance.Name,
v1alpha5.LabelCapacityType: currentInstance.Offerings[0].CapacityType,
v1.LabelTopologyZone: currentInstance.Offerings[0].Zone,
},
},
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Allocatable: map[v1.ResourceName]resource.Quantity{v1.ResourceCPU: resource.MustParse("8")},
},
})
node.Annotations = lo.Assign(node.Annotations, map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionDriftedAnnotationValue,
})
ExpectApplied(ctx, env.Client, rs, machine, node, prov, pods[0], pods[1], pods[2])
// bind the pods to the node
ExpectManualBinding(ctx, env.Client, pods[0], node)
ExpectManualBinding(ctx, env.Client, pods[1], node)
ExpectManualBinding(ctx, env.Client, pods[2], node)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node}, []*v1alpha5.Machine{machine})
fakeClock.Step(10 * time.Minute)
// deprovisioning won't delete the old node until the new node is ready
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectMakeNewMachinesReady(ctx, env.Client, &wg, cluster, cloudProvider, 3)
ExpectReconcileSucceeded(ctx, deprovisioningController, client.ObjectKey{})
wg.Wait()
// Cascade any deletion of the machine to the node
ExpectMachinesCascadeDeletion(ctx, env.Client, machine)
// expect that drift provisioned three nodes, one for each pod
ExpectNotFound(ctx, env.Client, machine, node)
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(3))
Expect(ExpectNodes(ctx, env.Client)).To(HaveLen(3))
})
It("should drift one non-empty node at a time", func() {
labels := map[string]string{
"app": "test",
}
// create our RS so we can link a pod to it
rs := test.ReplicaSet()
ExpectApplied(ctx, env.Client, rs)
pods := test.Pods(2, test.PodOptions{
ObjectMeta: metav1.ObjectMeta{Labels: labels,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Name: rs.Name,
UID: rs.UID,
Controller: ptr.Bool(true),
BlockOwnerDeletion: ptr.Bool(true),
},
},
},
})
machine2, node2 := test.MachineAndNode(v1alpha5.Machine{
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
v1alpha5.VoluntaryDisruptionAnnotationKey: v1alpha5.VoluntaryDisruptionExpiredAnnotationValue,
},
Labels: map[string]string{
v1alpha5.ProvisionerNameLabelKey: prov.Name,
v1.LabelInstanceTypeStable: mostExpensiveInstance.Name,
v1alpha5.LabelCapacityType: mostExpensiveOffering.CapacityType,
v1.LabelTopologyZone: mostExpensiveOffering.Zone,
},
},
Status: v1alpha5.MachineStatus{
ProviderID: test.RandomProviderID(),
Allocatable: map[v1.ResourceName]resource.Quantity{v1.ResourceCPU: resource.MustParse("32")},
},
})
ExpectApplied(ctx, env.Client, rs, pods[0], pods[1], machine, node, machine2, node2, prov)
// bind pods to node so that they're not empty and don't deprovision in parallel.
ExpectManualBinding(ctx, env.Client, pods[0], node)
ExpectManualBinding(ctx, env.Client, pods[1], node2)
// inform cluster state about nodes and machines
ExpectMakeInitializedAndStateUpdated(ctx, env.Client, nodeStateController, machineStateController, []*v1.Node{node, node2}, []*v1alpha5.Machine{machine, machine2})
// deprovisioning won't delete the old node until the new node is ready
var wg sync.WaitGroup
ExpectTriggerVerifyAction(&wg)
ExpectMakeNewMachinesReady(ctx, env.Client, &wg, cluster, cloudProvider, 1)
ExpectReconcileSucceeded(ctx, deprovisioningController, types.NamespacedName{})
wg.Wait()
// Cascade any deletion of the machine to the node
ExpectMachinesCascadeDeletion(ctx, env.Client, machine, machine2)
nodes := ExpectNodes(ctx, env.Client)
_, ok1 := lo.Find(nodes, func(n *v1.Node) bool {
return n.Name == node.Name
})
_, ok2 := lo.Find(nodes, func(n *v1.Node) bool {
return n.Name == node2.Name
})
// Expect that one of the drifted machines is gone and replaced
Expect(ok1 || ok2).To(BeTrue())
Expect(ExpectNodes(ctx, env.Client)).To(HaveLen(2))
Expect(ExpectMachines(ctx, env.Client)).To(HaveLen(2))
})
})
| 415 |
karpenter-core | 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 deprovisioning
import (
"context"
"time"
"k8s.io/utils/clock"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
"github.com/samber/lo"
"github.com/aws/karpenter-core/pkg/apis/v1alpha5"
"github.com/aws/karpenter-core/pkg/metrics"
)
// Emptiness is a subreconciler that deletes empty machines.
// Emptiness will respect TTLSecondsAfterEmpty
type Emptiness struct {
clock clock.Clock
}
func NewEmptiness(clk clock.Clock) *Emptiness {
return &Emptiness{
clock: clk,
}
}
// ShouldDeprovision is a predicate used to filter deprovisionable machines
func (e *Emptiness) ShouldDeprovision(ctx context.Context, c *Candidate) bool {
if c.provisioner == nil || c.provisioner.Spec.TTLSecondsAfterEmpty == nil || len(c.pods) != 0 {
return false
}
emptinessTimestamp, hasEmptinessTimestamp := c.Node.Annotations[v1alpha5.EmptinessTimestampAnnotationKey]
if !hasEmptinessTimestamp {
return false
}
ttl := time.Duration(ptr.Int64Value(c.provisioner.Spec.TTLSecondsAfterEmpty)) * time.Second
emptinessTime, err := time.Parse(time.RFC3339, emptinessTimestamp)
if err != nil {
logging.FromContext(ctx).With("emptiness-timestamp", emptinessTimestamp).Errorf("unable to parse emptiness timestamp")
return true
}
// Don't deprovision if node's emptiness timestamp is before the emptiness TTL
return e.clock.Now().After(emptinessTime.Add(ttl))
}
// ComputeCommand generates a deprovisioning command given deprovisionable machines
func (e *Emptiness) ComputeCommand(_ context.Context, candidates ...*Candidate) (Command, error) {
emptyCandidates := lo.Filter(candidates, func(cn *Candidate, _ int) bool {
return cn.Machine.DeletionTimestamp.IsZero() && len(cn.pods) == 0
})
deprovisioningEligibleMachinesGauge.WithLabelValues(e.String()).Set(float64(len(candidates)))
return Command{
candidates: emptyCandidates,
}, nil
}
// string is the string representation of the deprovisioner
func (e *Emptiness) String() string {
return metrics.EmptinessReason
}
| 80 |
karpenter-core | 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 deprovisioning
import (
"context"
"errors"
"fmt"
"github.com/samber/lo"
"k8s.io/utils/clock"
"knative.dev/pkg/logging"
"sigs.k8s.io/controller-runtime/pkg/client"
"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"
)
// EmptyMachineConsolidation is the consolidation controller that performs multi-machine consolidation of entirely empty machines
type EmptyMachineConsolidation struct {
consolidation
}
func NewEmptyMachineConsolidation(clk clock.Clock, cluster *state.Cluster, kubeClient client.Client,
provisioner *provisioning.Provisioner, cp cloudprovider.CloudProvider, recorder events.Recorder) *EmptyMachineConsolidation {
return &EmptyMachineConsolidation{consolidation: makeConsolidation(clk, cluster, kubeClient, provisioner, cp, recorder)}
}
// ComputeCommand generates a deprovisioning command given deprovisionable machines
func (c *EmptyMachineConsolidation) ComputeCommand(ctx context.Context, candidates ...*Candidate) (Command, error) {
if c.cluster.Consolidated() {
return Command{}, nil
}
candidates, err := c.sortAndFilterCandidates(ctx, candidates)
if err != nil {
return Command{}, fmt.Errorf("sorting candidates, %w", err)
}
deprovisioningEligibleMachinesGauge.WithLabelValues(c.String()).Set(float64(len(candidates)))
// select the entirely empty nodes
emptyCandidates := lo.Filter(candidates, func(n *Candidate, _ int) bool { return len(n.pods) == 0 })
if len(emptyCandidates) == 0 {
return Command{}, nil
}
cmd := Command{
candidates: emptyCandidates,
}
// empty machine consolidation doesn't use Validation as we get to take advantage of cluster.IsNodeNominated. This
// lets us avoid a scheduling simulation (which is performed periodically while pending pods exist and drives
// cluster.IsNodeNominated already).
select {
case <-ctx.Done():
return Command{}, errors.New("interrupted")
case <-c.clock.After(consolidationTTL):
}
validationCandidates, err := GetCandidates(ctx, c.cluster, c.kubeClient, c.recorder, c.clock, c.cloudProvider, c.ShouldDeprovision)
if err != nil {
logging.FromContext(ctx).Errorf("computing validation candidates %s", err)
return Command{}, err
}
candidatesToDelete := mapCandidates(cmd.candidates, validationCandidates)
// the deletion of empty machines is easy to validate, we just ensure that all the candidatesToDelete are still empty and that
// the machine isn't a target of a recent scheduling simulation
for _, n := range candidatesToDelete {
if len(n.pods) != 0 || c.cluster.IsNodeNominated(n.Name()) {
return Command{}, fmt.Errorf("command is no longer valid, %s", cmd)
}
}
return cmd, nil
}
| 88 |
Subsets and Splits