Merge pull request #14111 from ioito/hotfix/qx-aws-sku

fix(region): aws sku list
This commit is contained in:
Zexi Li
2022-04-24 19:21:24 +08:00
committed by GitHub
7 changed files with 1636 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
// Copyright 2019 Yunion
//
// 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 shell
import (
"yunion.io/x/onecloud/pkg/multicloud/aws"
"yunion.io/x/onecloud/pkg/util/shellutils"
)
func init() {
type InstanceTypeListOptions struct {
NextMarker string
}
shellutils.R(&InstanceTypeListOptions{}, "instance-type-list", "List intance types", func(cli *aws.SRegion, args *InstanceTypeListOptions) error {
skus, _, err := cli.GetInstanceTypes(args.NextMarker)
if err != nil {
return err
}
printList(skus, 0, 0, 0, []string{})
return nil
})
}
+144
View File
@@ -0,0 +1,144 @@
// Copyright 2019 Yunion
//
// 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 (
"github.com/aws/aws-sdk-go/service/pricing"
"yunion.io/x/jsonutils"
"yunion.io/x/pkg/errors"
)
type Product struct {
ProductFamily string `json:"productFamily"`
Attributes Attributes `json:"attributes"`
Sku string `json:"sku"`
}
type Attributes struct {
EnhancedNetworkingSupported string `json:"enhancedNetworkingSupported"`
IntelTurboAvailable string `json:"intelTurboAvailable"`
Memory string `json:"memory"`
DedicatedEbsThroughput string `json:"dedicatedEbsThroughput"`
Vcpu int `json:"vcpu"`
Gpu int `json:"gpu"`
Capacitystatus string `json:"capacitystatus"`
LocationType string `json:"locationType"`
Storage string `json:"storage"`
InstanceFamily string `json:"instanceFamily"`
OperatingSystem string `json:"operatingSystem"`
IntelAvx2Available string `json:"intelAvx2Available"`
PhysicalProcessor string `json:"physicalProcessor"`
ClockSpeed string `json:"clockSpeed"`
Ecu string `json:"ecu"`
NetworkPerformance string `json:"networkPerformance"`
Servicename string `json:"servicename"`
InstanceType string `json:"instanceType"`
InstanceSku string `json:"instancesku"`
Tenancy string `json:"tenancy"`
Usagetype string `json:"usagetype"`
NormalizationSizeFactor string `json:"normalizationSizeFactor"`
IntelAvxAvailable string `json:"intelAvxAvailable"`
ProcessorFeatures string `json:"processorFeatures"`
Servicecode string `json:"servicecode"`
LicenseModel string `json:"licenseModel"`
CurrentGeneration string `json:"currentGeneration"`
PreInstalledSw string `json:"preInstalledSw"`
Location string `json:"location"`
ProcessorArchitecture string `json:"processorArchitecture"`
Operation string `json:"operation"`
VolumeApiName string `json:"volumeApiName"`
}
type Terms struct {
OnDemand map[string]Term `json:"OnDemand"`
Reserved map[string]Term `json:"Reserved"`
}
type Term struct {
PriceDimensions map[string]Dimension `json:"priceDimensions"`
Sku string `json:"sku"`
EffectiveDate string `json:"effectiveDate"`
OfferTermCode string `json:"offerTermCode"`
TermAttributes TermAttributes `json:"termAttributes"`
}
type Dimension struct {
Unit string `json:"unit"`
EndRange string `json:"endRange"`
Description string `json:"description"`
AppliesTo []string `json:"appliesTo"`
RateCode string `json:"rateCode"`
BeginRange string `json:"beginRange"`
PricePerUnit PricePerUnit `json:"pricePerUnit"`
}
type TermAttributes struct {
LeaseContractLength string `json:"LeaseContractLength"`
OfferingClass string `json:"OfferingClass"`
PurchaseOption string `json:"PurchaseOption"`
}
type PricePerUnit struct {
Usd float64 `json:"USD"`
CNY float64 `json:"CNY"`
}
type SInstnaceType struct {
Product Product `json:"product"`
ServiceCode string `json:"serviceCode"`
Terms Terms `json:"terms"`
Version string `json:"version"`
PublicationDate string `json:"publicationDate"`
}
func (self *SRegion) GetInstanceTypes(nextToken string) ([]SInstnaceType, string, error) {
input := &pricing.GetProductsInput{}
input.SetServiceCode("AmazonEC2")
if len(nextToken) > 0 {
input.SetNextToken(nextToken)
}
GetFilter := func(k, v string) pricing.Filter {
filter := pricing.Filter{}
filter.SetType("TERM_MATCH")
filter.SetField(k)
filter.SetValue(v)
return filter
}
f1 := GetFilter("regionCode", self.RegionId)
f2 := GetFilter("operatingSystem", "Linux")
f3 := GetFilter("licenseModel", "No License required")
f4 := GetFilter("productFamily", "Compute Instance")
f5 := GetFilter("operation", "RunInstances")
f6 := GetFilter("preInstalledSw", "NA")
f7 := GetFilter("tenancy", "Shared")
f8 := GetFilter("capacitystatus", "Used")
input.SetFilters([]*pricing.Filter{&f1, &f2, &f3, &f4, &f5, &f6, &f7, &f8})
s, err := self.client.getAwsSession("ap-south-1", false)
if err != nil {
return nil, "", err
}
cli := pricing.New(s)
output, err := cli.GetProducts(input)
if err != nil {
return nil, "", errors.Wrap(err, "SZone.GetServerSku.GetProducts")
}
if output.NextToken != nil {
nextToken = *output.NextToken
}
ret := []SInstnaceType{}
return ret, nextToken, jsonutils.Update(&ret, output.PriceList)
}
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package pricing provides the client and types for making API
// requests to AWS Price List Service.
//
// AWS Price List Service API (AWS Price List Service) is a centralized and
// convenient way to programmatically query Amazon Web Services for services,
// products, and pricing information. The AWS Price List Service uses standardized
// product attributes such as Location, Storage Class, and Operating System,
// and provides prices at the SKU level. You can use the AWS Price List Service
// to build cost control and scenario planning tools, reconcile billing data,
// forecast future spend for budgeting purposes, and provide cost benefit analysis
// that compare your internal workloads with AWS.
//
// Use GetServices without a service code to retrieve the service codes for
// all AWS services, then GetServices with a service code to retreive the attribute
// names for that service. After you have the service code and attribute names,
// you can use GetAttributeValues to see what values are available for an attribute.
// With the service code and an attribute name and value, you can use GetProducts
// to find specific products that you're interested in, such as an AmazonEC2
// instance, with a Provisioned IOPS volumeType.
//
// Service Endpoint
//
// AWS Price List Service API provides the following two endpoints:
//
// * https://api.pricing.us-east-1.amazonaws.com
//
// * https://api.pricing.ap-south-1.amazonaws.com
//
// See https://docs.aws.amazon.com/goto/WebAPI/pricing-2017-10-15 for more information on this service.
//
// See pricing package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/pricing/
//
// Using the Client
//
// To contact AWS Price List Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the AWS Price List Service client Pricing for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/pricing/#New
package pricing
+49
View File
@@ -0,0 +1,49 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package pricing
import (
"github.com/aws/aws-sdk-go/private/protocol"
)
const (
// ErrCodeExpiredNextTokenException for service response error code
// "ExpiredNextTokenException".
//
// The pagination token expired. Try again without a pagination token.
ErrCodeExpiredNextTokenException = "ExpiredNextTokenException"
// ErrCodeInternalErrorException for service response error code
// "InternalErrorException".
//
// An error on the server occurred during the processing of your request. Try
// again later.
ErrCodeInternalErrorException = "InternalErrorException"
// ErrCodeInvalidNextTokenException for service response error code
// "InvalidNextTokenException".
//
// The pagination token is invalid. Try again without a pagination token.
ErrCodeInvalidNextTokenException = "InvalidNextTokenException"
// ErrCodeInvalidParameterException for service response error code
// "InvalidParameterException".
//
// One or more parameters had an invalid value.
ErrCodeInvalidParameterException = "InvalidParameterException"
// ErrCodeNotFoundException for service response error code
// "NotFoundException".
//
// The requested resource can't be found.
ErrCodeNotFoundException = "NotFoundException"
)
var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{
"ExpiredNextTokenException": newErrorExpiredNextTokenException,
"InternalErrorException": newErrorInternalErrorException,
"InvalidNextTokenException": newErrorInvalidNextTokenException,
"InvalidParameterException": newErrorInvalidParameterException,
"NotFoundException": newErrorNotFoundException,
}
+106
View File
@@ -0,0 +1,106 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package pricing
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
)
// Pricing provides the API operation methods for making requests to
// AWS Price List Service. See this package's package overview docs
// for details on the service.
//
// Pricing methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type Pricing struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "api.pricing" // Name of service.
EndpointsID = ServiceName // ID to lookup a service endpoint with.
ServiceID = "Pricing" // ServiceID is a unique identifier of a specific service.
)
// New creates a new instance of the Pricing client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// mySession := session.Must(session.NewSession())
//
// // Create a Pricing client from just a session.
// svc := pricing.New(mySession)
//
// // Create a Pricing client with additional configuration
// svc := pricing.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *Pricing {
c := p.ClientConfig(EndpointsID, cfgs...)
if c.SigningNameDerived || len(c.SigningName) == 0 {
c.SigningName = "pricing"
}
return newClient(*c.Config, c.Handlers, c.PartitionID, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, partitionID, endpoint, signingRegion, signingName string) *Pricing {
svc := &Pricing{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
PartitionID: partitionID,
Endpoint: endpoint,
APIVersion: "2017-10-15",
JSONVersion: "1.1",
TargetPrefix: "AWSPriceListService",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(
protocol.NewUnmarshalErrorHandler(jsonrpc.NewUnmarshalTypedError(exceptionFromCode)).NamedHandler(),
)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a Pricing operation and runs any
// custom request initialization.
func (c *Pricing) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
+1
View File
@@ -191,6 +191,7 @@ github.com/aws/aws-sdk-go/service/elasticache
github.com/aws/aws-sdk-go/service/elbv2
github.com/aws/aws-sdk-go/service/iam
github.com/aws/aws-sdk-go/service/organizations
github.com/aws/aws-sdk-go/service/pricing
github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi
github.com/aws/aws-sdk-go/service/route53
github.com/aws/aws-sdk-go/service/s3