ec2

package
v0.0.0-...-519451a Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: OSL-3.0 Imports: 17 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
var ErrTargetOfferingsTruncated = errors.New("target offerings pagination cap reached")

ErrTargetOfferingsTruncated reports that ListTargetOfferings hit its page bound (maxListPages) while AWS still had more pages. No partial list is returned alongside it.

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. Offerings AWS returns that do not match the request are skipped, not trusted.

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 prices the convertible offering (the PurchaseCommitment default when PurchaseOptions.OfferingClass is empty). Callers that purchase a standard RI must use GetOfferingDetailsForClass: the classes are distinct offerings with different prices.

func (*Client) GetOfferingDetailsForClass

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

GetOfferingDetailsForClass retrieves the details of the offering the purchase would buy for offeringClass, resolved exactly as PurchaseCommitment resolves PurchaseOptions.OfferingClass: "" and "convertible" select the convertible offering, "standard" the standard one, anything else errors. 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.

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) 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. Returned offerings are re-checked against the request and mismatches are dropped.

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.

After maxListPages pages with more still to read it returns ErrTargetOfferingsTruncated and no list, never a partial one.

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) ReconcilePurchase

func (c *Client) ReconcilePurchase(ctx context.Context, req common.ReconcileRequest) common.ReconcileResult

ReconcilePurchase reports, read-only, whether a purchase that returned ErrOutcomeUnknown landed. Any doubt or failure is Unknown; see purchasecfg.Decide.

func (*Client) SetEC2API

func (c *Client) SetEC2API(api API)

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

type ConvertibleRI

type ConvertibleRI struct {
	Start              time.Time `json:"start"`
	End                time.Time `json:"end"`
	ReservedInstanceID string    `json:"reserved_instance_id"`
	InstanceType       string    `json:"instance_type"`
	AvailabilityZone   string    `json:"availability_zone"`
	OfferingType       string    `json:"offering_type"`
	State              string    `json:"state"`
	ProductDescription string    `json:"product_description"`
	InstanceTenancy    string    `json:"instance_tenancy"`
	Scope              string    `json:"scope"`

	// 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"`

	FixedPrice          float64 `json:"fixed_price"`
	UsagePrice          float64 `json:"usage_price"`
	NormalizationFactor float64 `json:"normalization_factor"`
	Duration            int64   `json:"duration"`

	// 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"`

	InstanceCount int32 `json:"instance_count"`

	// PriceReported is true only when EC2 reported FixedPrice and a recurring
	// price (UsagePrice or a RecurringCharges amount). The float fields cannot
	// tell "not reported" from a real 0. The zero value means unknown.
	PriceReported bool `json:"-"`
}

ConvertibleRI represents an active convertible Reserved Instance.

type FindConvertibleOfferingParams

type FindConvertibleOfferingParams struct {
	InstanceType       string
	ProductDescription string
	Tenancy            string
	Scope              string
	// AvailabilityZone is the source RI's AZ name: required for zonal scope and
	// refused for regional scope.
	AvailabilityZone string
	// OfferingType is the source RI's AWS offering type (ConvertibleRI.OfferingType:
	// "All Upfront", "Partial Upfront" or "No Upfront"). The target must match it,
	// so an exchange never changes the payment option the operator chose (#553).
	// Required.
	OfferingType string
	Duration     int64
}

FindConvertibleOfferingParams holds the parameters for finding a convertible RI offering.

type ListTargetOfferingsParams

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

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"`
	CurrencyCode        string  `json:"currency_code"`
	Scope               string  `json:"scope"`
	Duration            int64   `json:"duration"`
	FixedPrice          float64 `json:"fixed_price"`
	UsagePrice          float64 `json:"usage_price"`
	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