ec2

package
v0.0.0-...-16b5795 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2026 License: OSL-3.0 Imports: 16 Imported by: 0

Documentation

Overview

Package ec2 provides AWS EC2 Reserved Instances client

Index

Constants

View Source
const (
	OneYearSeconds   = purchasecfg.OneYearSeconds   // 365 days in seconds
	ThreeYearSeconds = purchasecfg.ThreeYearSeconds // 3 * 365 days in seconds
)

Duration constants for RI term calculations.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API interface {
	PurchaseReservedInstancesOffering(ctx context.Context, params *ec2.PurchaseReservedInstancesOfferingInput, optFns ...func(*ec2.Options)) (*ec2.PurchaseReservedInstancesOfferingOutput, error)
	DescribeReservedInstancesOfferings(ctx context.Context, params *ec2.DescribeReservedInstancesOfferingsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeReservedInstancesOfferingsOutput, error)
	DescribeReservedInstances(ctx context.Context, params *ec2.DescribeReservedInstancesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeReservedInstancesOutput, error)
	DescribeInstanceTypeOfferings(ctx context.Context, params *ec2.DescribeInstanceTypeOfferingsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeInstanceTypeOfferingsOutput, error)
	GetReservedInstancesExchangeQuote(ctx context.Context, params *ec2.GetReservedInstancesExchangeQuoteInput, optFns ...func(*ec2.Options)) (*ec2.GetReservedInstancesExchangeQuoteOutput, error)
	AcceptReservedInstancesExchangeQuote(ctx context.Context, params *ec2.AcceptReservedInstancesExchangeQuoteInput, optFns ...func(*ec2.Options)) (*ec2.AcceptReservedInstancesExchangeQuoteOutput, error)
	CreateTags(ctx context.Context, params *ec2.CreateTagsInput, optFns ...func(*ec2.Options)) (*ec2.CreateTagsOutput, error)
	CreateReservedInstancesListing(ctx context.Context, params *ec2.CreateReservedInstancesListingInput, optFns ...func(*ec2.Options)) (*ec2.CreateReservedInstancesListingOutput, error)
	DescribeReservedInstancesListings(ctx context.Context, params *ec2.DescribeReservedInstancesListingsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeReservedInstancesListingsOutput, error)
	CancelReservedInstancesListing(ctx context.Context, params *ec2.CancelReservedInstancesListingInput, optFns ...func(*ec2.Options)) (*ec2.CancelReservedInstancesListingOutput, error)
}

API defines the interface for EC2 operations (enables mocking).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client handles AWS EC2 Reserved Instances.

func NewClient

func NewClient(cfg aws.Config) *Client

NewClient creates a new EC2 client with purchase-path retry/timeout settings. The tightened config (2 attempts, 15s HTTP timeout) bounds read-only calls to 30s wall clock. The purchase call itself is sent exactly once (no ClientToken exists, so a retry could double-buy); see PurchaseCommitment.

func (*Client) CancelMarketplaceListing

func (c *Client) CancelMarketplaceListing(ctx context.Context, listingID string) (MarketplaceListingResult, error)

CancelMarketplaceListing calls ec2:CancelReservedInstancesListing to withdraw an active listing. Returns the updated listing state.

func (*Client) CreateMarketplaceListing

func (c *Client) CreateMarketplaceListing(ctx context.Context, req MarketplaceListingRequest) (MarketplaceListingResult, error)

CreateMarketplaceListing calls ec2:CreateReservedInstancesListing. Only Standard (not Convertible) RIs can be listed; AWS rejects requests for Convertible RIs with an explicit API error — the caller should gate on offering_class == "standard" before calling this to surface a cleaner error. AWS also requires the seller account to have a US bank account on file; that precondition is checked in the API handler so the UI can show a tailored message before making the API call.

func (*Client) DescribeMarketplaceListing

func (c *Client) DescribeMarketplaceListing(ctx context.Context, listingID string) (MarketplaceListingResult, error)

DescribeMarketplaceListing polls the status of a single listing by ID. Returns an error when the listing is not found.

func (*Client) FetchOfferingClass

func (c *Client) FetchOfferingClass(ctx context.Context, reservedInstancesID string) (string, error)

FetchOfferingClass calls ec2:DescribeReservedInstances to fetch the offering_class ("standard" or "convertible") for a specific Reserved Instance ID. Used by the marketplace-list handler to lazily populate offering_class for rows created before migration 000087 or for externally- created (pre-CUDly) Standard RIs whose offering_class was never stamped. Returns an error when the RI is not found (e.g. it has expired or was exchanged) because a missing RI cannot be listed.

func (*Client) FindConvertibleOffering

func (c *Client) FindConvertibleOffering(ctx context.Context, params FindConvertibleOfferingParams) (string, error)

FindConvertibleOffering finds a convertible RI offering ID for the given parameters.

func (*Client) GetExistingCommitments

func (c *Client) GetExistingCommitments(ctx context.Context) ([]common.Commitment, error)

GetExistingCommitments retrieves existing EC2 Reserved Instances, including queued ones (scheduled future purchases) so the duplicate check sees them.

func (*Client) GetOfferingDetails

func (c *Client) GetOfferingDetails(ctx context.Context, rec common.Recommendation) (*common.OfferingDetails, error)

GetOfferingDetails retrieves offering details. All prices are per ONE reservation (callers multiply by rec.Count): UpfrontCost is FixedPrice, RecurringCost is the hourly rate, TotalCost is upfront plus hourly over the term. The offering class does not change any price field. Uses the convertible class (empty = convertible default) since the details-fetch path has no GlobalConfig context.

func (*Client) GetRecommendations

func (c *Client) GetRecommendations(_ context.Context, _ *common.RecommendationParams) ([]common.Recommendation, error)

GetRecommendations returns empty as EC2 uses centralized Cost Explorer recommendations.

func (*Client) GetRegion

func (c *Client) GetRegion() string

GetRegion returns the region.

func (*Client) GetServiceType

func (c *Client) GetServiceType() common.ServiceType

GetServiceType returns the service type.

func (*Client) GetValidResourceTypes

func (c *Client) GetValidResourceTypes(ctx context.Context) ([]string, error)

GetValidResourceTypes returns valid EC2 instance types.

func (*Client) ListConvertibleReservedInstances

func (c *Client) ListConvertibleReservedInstances(ctx context.Context) ([]ConvertibleRI, error)

ListConvertibleReservedInstances returns all active convertible RIs in the region.

func (*Client) ListTargetOfferings

func (c *Client) ListTargetOfferings(ctx context.Context, params ListTargetOfferingsParams) ([]TargetOffering, error)

ListTargetOfferings returns convertible RI offerings that are valid exchange targets for a source RI described by params. The query uses the same typed-field approach as findOffering / describeInputFromQuery (PR #690): typed primary fields (OfferingClass, OfferingType, Duration, ProductDescription, InstanceTenancy) instead of Filters[]-heavy style to avoid the empty-page pagination bug documented in issue #688. Scope has no typed field and stays in Filters[] as before.

InstanceType is intentionally left unset so AWS returns all instance types matching the other constraints -- that is exactly the "valid targets" set for a convertible RI exchange.

func (*Client) PurchaseCommitment

func (c *Client) PurchaseCommitment(ctx context.Context, rec common.Recommendation, opts common.PurchaseOptions) (common.PurchaseResult, error)

PurchaseCommitment purchases an EC2 Reserved Instance.

func (*Client) SetEC2API

func (c *Client) SetEC2API(api API)

SetEC2API sets a custom EC2 API client (for testing).

func (*Client) ValidateOffering

func (c *Client) ValidateOffering(ctx context.Context, rec common.Recommendation) error

ValidateOffering checks if an offering exists without purchasing. Uses the convertible class (empty = convertible default) since the validation path has no GlobalConfig context.

type ConvertibleRI

type ConvertibleRI struct {
	ReservedInstanceID  string    `json:"reserved_instance_id"`
	InstanceType        string    `json:"instance_type"`
	AvailabilityZone    string    `json:"availability_zone"`
	InstanceCount       int32     `json:"instance_count"`
	Start               time.Time `json:"start"`
	End                 time.Time `json:"end"`
	OfferingType        string    `json:"offering_type"`
	FixedPrice          float64   `json:"fixed_price"`
	UsagePrice          float64   `json:"usage_price"`
	State               string    `json:"state"`
	NormalizationFactor float64   `json:"normalization_factor"`
	ProductDescription  string    `json:"product_description"`
	InstanceTenancy     string    `json:"instance_tenancy"`
	Scope               string    `json:"scope"`
	Duration            int64     `json:"duration"`
	// CurrencyCode is the ISO-4217 currency that FixedPrice / UsagePrice
	// are denominated in (typically "USD"). Plumbed through to
	// exchange.RIInfo so the dollar-units pre-filter on cross-family
	// alternatives can refuse comparisons across currencies.
	CurrencyCode string `json:"currency_code,omitempty"`
	// RecurringHourlyAmount is the per-hour recurring charge (sum across
	// the SDK's RecurringCharges slice) — this is non-zero for
	// no-upfront and partial-upfront RIs where some of the cost is
	// billed hourly rather than as the upfront FixedPrice. Used by the
	// exchange-package dollar-units calculation.
	RecurringHourlyAmount float64 `json:"recurring_hourly_amount,omitempty"`
}

ConvertibleRI represents an active convertible Reserved Instance.

type FindConvertibleOfferingParams

type FindConvertibleOfferingParams struct {
	InstanceType       string
	ProductDescription string
	Tenancy            string
	Scope              string
	Duration           int64
}

FindConvertibleOfferingParams holds the parameters for finding a convertible RI offering.

type ListTargetOfferingsParams

type ListTargetOfferingsParams struct {
	ProductDescription string
	Tenancy            string
	Scope              string
	Duration           int64
	OfferingType       string
}

ListTargetOfferingsParams holds the source RI attributes used to narrow the DescribeReservedInstancesOfferings query to valid exchange targets.

type MarketplaceListingRequest

type MarketplaceListingRequest struct {
	// ReservedInstancesID is the AWS ReservedInstancesId to list.
	ReservedInstancesID string
	// ClientToken is a caller-supplied idempotency token (UUID). AWS dedupes
	// CreateReservedInstancesListing calls sharing the same token for the same
	// RI within a short window.
	ClientToken string //nolint:gosec // G117 false positive: an idempotency token (UUID), not a credential; matches the configured G101 secret-name pattern only because it contains "token"
	// PriceSchedule is the per-month price schedule. At least one entry is
	// required. Each entry specifies how many months the price applies and the
	// list price per unit.
	PriceSchedule []MarketplacePriceTier
	// InstanceCount is the number of Reserved Instances to list. A purchase
	// row of N RIs must list all N; this mirrors purchase_history.count. Values
	// <= 0 are rejected before the outbound call so a misconfigured caller can
	// never silently list a single RI from a multi-count row.
	InstanceCount int32
}

MarketplaceListingRequest carries the parameters for CreateMarketplaceListing. PriceSchedule is required by the AWS API; a nil/empty slice is rejected before the outbound call is made.

type MarketplaceListingResult

type MarketplaceListingResult struct {
	// ListingID is the AWS ReservedInstancesListingId.
	ListingID string
	// State is the AWS listing status, preserved verbatim from types.ListingStatus.
	State string
}

MarketplaceListingResult is returned by CreateMarketplaceListing and DescribeMarketplaceListing.

type MarketplacePriceTier

type MarketplacePriceTier struct {
	// Term is the remaining-months count this tier covers.
	Term int64
	// Price is the USD list price per unit for this tier.
	Price float64
}

MarketplacePriceTier represents one tier of the AWS RI Marketplace price schedule. Term is the number of months this price applies, counting down from the remaining RI term. Price is the per-unit listing price in USD.

type TargetOffering

type TargetOffering struct {
	OfferingID          string  `json:"offering_id"`
	InstanceType        string  `json:"instance_type"`
	OfferingType        string  `json:"offering_type"`
	ProductDescription  string  `json:"product_description"`
	Duration            int64   `json:"duration"`
	FixedPrice          float64 `json:"fixed_price"`
	UsagePrice          float64 `json:"usage_price"`
	CurrencyCode        string  `json:"currency_code"`
	Scope               string  `json:"scope"`
	NormalizationFactor float64 `json:"normalization_factor"`
}

TargetOffering is one valid target offering for a convertible RI exchange.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL