skewer

package module
v0.0.19 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2023 License: MIT Imports: 8 Imported by: 7

README

skewer GoDoc codecov

A package to simplify working with Azure's Resource SKU APIs by wrapping the existing Azure SDK for Go.

Usage

This package requires an existing, authorized Azure client. Here is a complete example using the simplest methods.

package main

import (
    "context"
    "fmt"

    "github.com/Azure/go-autorest/autorest/azure/auth"
    "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2022-08-01/compute" //nolint:staticcheck

    "github.com/Azure/skewer"
)

func main() {
    // Create an authorizer
    authorizer, err := auth.NewAuthorizerFromEnvironment()
    if err != nil {
        fmt.Printf("failed to get authorizer: %s", err)
        os.Exit(1)
    }

    // Create a skus client
    client := compute.NewResourceSkusClient(sub)
    client.Authorizer = authorizer

    // Now we can use the client...
    resourceSkuIterator, err := client.ListComplete(context.Background(), "eastus")
    if err != nil {
        fmt.Printf("failed to list skus: %s", err)
        os.Exit(1)
    }

    // or instantiate a cache for this package!
    cache, err := skewer.NewCache(context.Background(), skewer.WithLocation("eastus"), skewer.WithResourceClient(client))
    if err != nil {
        fmt.Printf("failed to instantiate sku cache: %s", err)
        os.Exit(1)
    }
}

Once we have a cache, we can query against its contents:

sku, found := cache.Get(context.Background, "standard_d4s_v3", skewer.VirtualMachines, "eastus")
if !found {
    return fmt.Errorf("expected to find virtual machine sku standard_d4s_v3")
}

// Check for capabilities
if sku.IsEphemeralOSDiskSupported() {
    fmt.Println("SKU %s supports ephemeral OS disk!", sku.GetName())
}

cpu, err := sku.VCPU()
if err != nil {
    return fmt.Errorf("failed to parse cpu from sku: %s", err)
}

memory, err := sku.Memory()
if err != nil {
    return fmt.Errorf("failed to parse memory from sku: %s", err)
}

fmt.Printf("vm sku %s has %d vCPU cores and %.2fGi of memory", sku.GetName(), cpu, memory)

Development

This project uses a simple justfile for make-like functionality. The commands are simple enough to run on their own if you do not want to install just.

For each command below like just $CMD, the full manual commands are below separated by one line.

Default: tidy, fmt, lint, test and calculate coverage.

$ just
$
$ go mod tidy
$ go fmt
$ golangci-lint run --fix
$ go test -v -race -coverprofile=coverage.out -covermode=atomic ./...
$ go tool cover -html=coverage.out -o coverage.html

Clean up dependencies:

$ just tidy
$
$ go mod tidy

Format:

$ just fmt
$
$ go fmt

Lint:

$ just lint
$
$ golangci-lint run --fix

Test and calculate coverage:

$ just cover
$ 
$ go test -v -race -coverprofile=coverage.out -covermode=atomic ./...
$ go tool cover -html=coverage.out -o coverage.html

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.

When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Documentation

Index

Constants

View Source
const (
	// VirtualMachines is the .
	VirtualMachines = "virtualMachines"
	// Disks is a convenience constant to filter resource SKUs to only include disks.
	Disks = "disks"
)
View Source
const (
	// EphemeralOSDisk identifies the capability for ephemeral os support.
	EphemeralOSDisk = "EphemeralOSDiskSupported"
	// AcceleratedNetworking identifies the capability for accelerated networking support.
	AcceleratedNetworking = "AcceleratedNetworkingEnabled"
	// VCPUs identifies the capability for the number of vCPUS.
	VCPUs = "vCPUs"
	// GPUs identifies the capability for the number of GPUS.
	GPUs = "GPUs"
	// MemoryGB identifies the capability for memory capacity.
	MemoryGB = "MemoryGB"
	// HyperVGenerations identifies the hyper-v generations this vm sku supports.
	HyperVGenerations = "HyperVGenerations"
	// EncryptionAtHost identifies the capability for accelerated networking support.
	EncryptionAtHost = "EncryptionAtHostSupported"
	// UltraSSDAvailable identifies the capability for ultra ssd
	// enablement.
	UltraSSDAvailable = "UltraSSDAvailable"
	// CachedDiskBytes identifies the maximum size of the cache disk for
	// a vm.
	CachedDiskBytes = "CachedDiskBytes"
	// MaxResourceVolumeMB identifies the maximum size of the temporary
	// disk for a vm.
	MaxResourceVolumeMB = "MaxResourceVolumeMB"
	// CapabilityPremiumIO identifies the capability for PremiumIO.
	CapabilityPremiumIO = "PremiumIO"
	// CapabilityCpuArchitectureType identifies the type of CPU architecture (x64,Arm64).
	CapabilityCPUArchitectureType = "CpuArchitectureType"
	// CapabilityTrustedLaunchDisabled identifes whether TrustedLaunch is disabled.
	CapabilityTrustedLaunchDisabled = "TrustedLaunchDisabled"
	// CapabilityConfidentialComputingType identifies the type of ConfidentialComputing.
	CapabilityConfidentialComputingType = "ConfidentialComputingType"
	// ConfidentialComputingTypeSNP denoted the "SNP" ConfidentialComputing.
	ConfidentialComputingTypeSNP = "SNP"
)
View Source
const (
	// HyperVGeneration1 identifies a sku which supports HyperV
	// Generation 1.
	HyperVGeneration1 = "V1"
	// HyperVGeneration2 identifies a sku which supports HyperV
	// Generation 2.
	HyperVGeneration2 = "V2"
)

Variables

This section is empty.

Functions

func All

func All(sku *SKU, conditions []FilterFn) bool

All returns true if the provided sku meets all provided conditions.

func LocationFilter added in v0.0.4

func LocationFilter(location string) func(*SKU) bool

LocationFilter matches against a SKU listing the given location

func NameFilter

func NameFilter(name string) func(*SKU) bool

NameFilter produces a filter function for the name of a resource sku.

func ResourceTypeFilter

func ResourceTypeFilter(resourceType string) func(*SKU) bool

ResourceTypeFilter produces a filter function for any resource type.

func UnsafeLocationFilter added in v0.0.5

func UnsafeLocationFilter(location string) func(*SKU) bool

UnsafeLocationFilter produces a filter function for the location of a resource sku. This function dangerously ignores all SKUS without a properly specified location. Use this only if you know what you are doing.

Types

type Cache

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

Cache stores a list of known skus, possibly fetched with a provided client

func NewCache

func NewCache(ctx context.Context, opts ...Option) (*Cache, error)

NewCache instantiates a cache of resource sku data with a ResourceClient client, optionally with additional filtering by location. The accepted client interface matches the real Azure clients (it returns a paginated iterator).

func NewStaticCache

func NewStaticCache(data []SKU, opts ...Option) (*Cache, error)

NewStaticCache initializes a cache with data and no ability to refresh. Used for testing.

func (*Cache) Equal

func (c *Cache) Equal(other *Cache) bool

Equal compares two caches.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, name, resourceType, location string) (SKU, error)

Get returns the first matching resource of a given name and type in a location.

func (*Cache) GetAvailabilityZones

func (c *Cache) GetAvailabilityZones(ctx context.Context, filters ...FilterFn) []string

GetAvailabilityZones returns the list of all availability zones in a given azure location.

func (*Cache) GetVirtualMachineAvailabilityZones

func (c *Cache) GetVirtualMachineAvailabilityZones(ctx context.Context) []string

GetVirtualMachineAvailabilityZones returns all virtual machine zones available in a given location.

func (*Cache) GetVirtualMachineAvailabilityZonesForSize

func (c *Cache) GetVirtualMachineAvailabilityZonesForSize(ctx context.Context, size string) []string

GetVirtualMachineAvailabilityZonesForSize returns all virtual machine zones available in a given location.

func (*Cache) GetVirtualMachines

func (c *Cache) GetVirtualMachines(ctx context.Context) []SKU

GetVirtualMachines returns the list of all virtual machines *SKUs in a given azure location.

func (*Cache) List

func (c *Cache) List(ctx context.Context, filters ...FilterFn) []SKU

List returns all resource types for this location.

type Config

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

Config contains configuration options for a cache.

func (*Config) Equal

func (c *Config) Equal(other *Config) bool

Equal compares two configs.

type ErrCapabilityNotFound

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

ErrCapabilityNotFound will be returned when a capability could not be found, even without a value.

func (*ErrCapabilityNotFound) Error

func (e *ErrCapabilityNotFound) Error() string

type ErrCapabilityValueNil

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

ErrCapabilityValueNil will be returned when a capability was found by name but the value was nil.

func (*ErrCapabilityValueNil) Error

func (e *ErrCapabilityValueNil) Error() string

type ErrCapabilityValueParse

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

ErrCapabilityValueParse will be returned when a capability was found by name but there was error parsing the capability.

func (*ErrCapabilityValueParse) Error

func (e *ErrCapabilityValueParse) Error() string

type ErrClientNil

type ErrClientNil struct {
}

ErrClientNil will be returned when a user attempts to create a cache without a client and use it.

func (*ErrClientNil) Error

func (e *ErrClientNil) Error() string

type ErrClientNotNil

type ErrClientNotNil struct {
}

ErrClientNotNil will be returned when a user attempts to set two clients on the same cache.

func (*ErrClientNotNil) Error

func (e *ErrClientNotNil) Error() string

type ErrMultipleSKUsMatch added in v0.0.7

type ErrMultipleSKUsMatch struct {
	Name     string
	Location string
	Type     string
}

ErrMultipleSKUsMatch will be returned when multiple skus match a fully qualified triple of resource type, location and name. This should usually not happen.

func (*ErrMultipleSKUsMatch) Error added in v0.0.7

func (e *ErrMultipleSKUsMatch) Error() string

type ErrSKUNotFound added in v0.0.7

type ErrSKUNotFound struct {
	Name     string
	Location string
	Type     string
}

ErrSKUNotFound will be returned when no skus match a fully qualified triple of resource type, location and name. The SKU may not exist.

func (*ErrSKUNotFound) Error added in v0.0.7

func (e *ErrSKUNotFound) Error() string

type FilterFn

type FilterFn func(*SKU) bool

FilterFn is a convenience type for filtering.

type MapFn

type MapFn func(*SKU) SKU

MapFn is a convenience type for mapping.

type NewCacheFunc

type NewCacheFunc func(ctx context.Context, opts ...Option) (*Cache, error)

NewCacheFunc describes the live cache instantiation signature. Used for testing.

type Option

type Option func(c *Config) (*Config, error)

Option describes functional options to customize the listing behavior of the cache.

func WithClient

func WithClient(client client) Option

WithClient is a functional option to use a cache backed by a client meeting the skewer signature.

func WithExtendedLocations added in v0.0.16

func WithExtendedLocations() Option

WithExtendedLocations is a functional option to include extended locations

func WithLocation

func WithLocation(location string) Option

WithLocation is a functional option to filter skus by location

func WithResourceClient

func WithResourceClient(client ResourceClient) Option

WithResourceClient is a functional option to use a cache backed by a ResourceClient.

func WithResourceProviderClient

func WithResourceProviderClient(client ResourceProviderClient) Option

WithResourceProviderClient is a functional option to use a cache backed by a ResourceProviderClient.

type ResourceClient

type ResourceClient interface {
	ListComplete(ctx context.Context, filter, includeExtendedLocations string) (compute.ResourceSkusResultIterator, error)
}

ResourceClient is the required Azure client interface used to populate skewer's data.

type ResourceProviderClient

type ResourceProviderClient interface {
	List(ctx context.Context, filter, includeExtendedLocations string) (compute.ResourceSkusResultPage, error)
}

ResourceProviderClient is a convenience interface for uses cases specific to Azure resource providers.

type SKU

type SKU compute.ResourceSku

SKU wraps an Azure compute SKU with richer functionality

func Filter

func Filter(skus []SKU, filterFn ...FilterFn) []SKU

Filter returns a new slice containing all values in the slice that satisfy all filterFn predicates.

func Map

func Map(skus []SKU, fn MapFn) []SKU

Map returns a new slice containing the results of applying the mapFn to each value in the original slice.

func Wrap

func Wrap(in []compute.ResourceSku) []SKU

Wrap takes an array of compute resource skus and wraps them into an array of our richer type.

func (*SKU) AvailabilityZones

func (s *SKU) AvailabilityZones(location string) map[string]bool

AvailabilityZones returns the list of Availability Zones which have this resource SKU available and unrestricted.

func (*SKU) Equal

func (s *SKU) Equal(other *SKU) bool

Equal returns true when two skus have the same location, type, and name.

func (*SKU) GPU added in v0.0.18

func (s *SKU) GPU() (int64, error)

GPU returns the number of GPU this SKU supports.

func (*SKU) GetCPUArchitectureType added in v0.0.18

func (s *SKU) GetCPUArchitectureType() (string, error)

GetCPUArchitectureType returns cpu arch for the VM size. It errors if value is nil or not found.

func (*SKU) GetCapabilityFloatQuantity

func (s *SKU) GetCapabilityFloatQuantity(name string) (float64, error)

GetCapabilityFloatQuantity retrieves and parses the value of a floating point numeric capability with the provided name. It errors if the capability is not found, the value was nil, or the value could not be parsed as an integer.

func (*SKU) GetCapabilityIntegerQuantity

func (s *SKU) GetCapabilityIntegerQuantity(name string) (int64, error)

GetCapabilityIntegerQuantity retrieves and parses the value of an integer numeric capability with the provided name. It errors if the capability is not found, the value was nil, or the value could not be parsed as an integer.

func (*SKU) GetCapabilityString added in v0.0.18

func (s *SKU) GetCapabilityString(name string) (string, error)

GetCapabilityString retrieves string capability with the provided name. It errors if the capability is not found or the value was nil

func (*SKU) GetFamilyName added in v0.0.14

func (s *SKU) GetFamilyName() string

GetFamilyName returns the family name of this resource sku. It normalizes pointers to the empty string for comparison purposes. For example, "standardDSv2Family" for a virtual machine.

func (*SKU) GetLocation

func (s *SKU) GetLocation() (string, error)

GetLocation returns the location for a given SKU.

func (*SKU) GetName

func (s *SKU) GetName() string

GetName returns the name of this resource sku. It normalizes pointers to the empty string for comparison purposes. For example, "Standard_D8s_v3" for a virtual machine.

func (*SKU) GetResourceType

func (s *SKU) GetResourceType() string

GetResourceType returns the name of this resource sku. It normalizes pointers to the empty string for comparison purposes. For example, "virtualMachines" for a virtual machine.

func (*SKU) GetSize added in v0.0.18

func (s *SKU) GetSize() string

GetSize returns the size of this resource sku. It normalizes pointers to the empty string for comparison purposes. For example, "M416ms_v2" for a virtual machine.

func (*SKU) GetVMSize added in v0.0.18

func (s *SKU) GetVMSize() (*VMSizeType, error)

func (*SKU) HasCapability

func (s *SKU) HasCapability(name string) bool

HasCapability return true for a capability which can be either supported or not. Examples include "EphemeralOSDiskSupported", "EncryptionAtHostSupported", "AcceleratedNetworkingEnabled", and "RdmaEnabled"

func (*SKU) HasCapabilityInZone added in v0.0.13

func (s *SKU) HasCapabilityInZone(name, zone string) bool

HasCapabilityInZone return true if the specified capability name is supported in the specified zone.

func (*SKU) HasCapabilityWithMinCapacity added in v0.0.8

func (s *SKU) HasCapabilityWithMinCapacity(name string, value int64) (bool, error)

HasCapabilityWithMinCapacity returns true when the SKU has a capability with the requested name, and the value is greater than or equal to the desired value. "MaxResourceVolumeMB", "OSVhdSizeMB", "vCPUs", "MemoryGB","MaxDataDiskCount", "CombinedTempDiskAndCachedIOPS", "CombinedTempDiskAndCachedReadBytesPerSecond", "CombinedTempDiskAndCachedWriteBytesPerSecond", "UncachedDiskIOPS", and "UncachedDiskBytesPerSecond"

func (*SKU) HasCapabilityWithSeparator

func (s *SKU) HasCapabilityWithSeparator(name, value string) bool

HasCapabilityWithSeparator return true for a capability which may be exposed as a comma-separated list. We check that the list contains the desired substring. An example is "HyperVGenerations" which may be "V1,V2"

func (*SKU) HasLocation added in v0.0.7

func (s *SKU) HasLocation(location string) bool

HasLocation returns true if the given sku exposes this region for deployment.

func (*SKU) HasLocationRestriction added in v0.0.7

func (s *SKU) HasLocationRestriction(location string) bool

HasLocationRestriction returns true if the location is restricted for this sku.

func (*SKU) HasZonalCapability

func (s *SKU) HasZonalCapability(name string) bool

HasZonalCapability return true for a capability which can be either supported or not. Examples include "UltraSSDAvailable". This function only checks that zone details suggest support: it will return true for a whole location even when only one zone supports the feature. Currently, the only real scenario that appears to use zoneDetails is UltraSSDAvailable which always lists all regions as available. For per zone capability check, use "HasCapabilityInZone"

func (*SKU) IsAcceleratedNetworkingSupported added in v0.0.9

func (s *SKU) IsAcceleratedNetworkingSupported() bool

IsAcceleratedNetworkingSupported returns true when the VM size supports accelerated networking.

func (*SKU) IsAvailable

func (s *SKU) IsAvailable(location string) bool

IsAvailable returns true when the requested location matches one on the sku, and there are no total restrictions on the location.

func (*SKU) IsConfidentialComputingTypeSNP added in v0.0.18

func (s *SKU) IsConfidentialComputingTypeSNP() (bool, error)

IsConfidentialComputingTypeSNP return true if ConfidentialComputingType is SNP for this sku.

func (*SKU) IsEncryptionAtHostSupported

func (s *SKU) IsEncryptionAtHostSupported() bool

IsEncryptionAtHostSupported returns true when Encryption at Host is supported for the VM size.

func (*SKU) IsEphemeralOSDiskSupported

func (s *SKU) IsEphemeralOSDiskSupported() bool

IsEphemeralOSDiskSupported returns true when the VM size supports ephemeral OS.

func (*SKU) IsHyperVGen1Supported added in v0.0.18

func (s *SKU) IsHyperVGen1Supported() bool

IsHyperVGen1Supported returns true when the VM size supports accelerated networking.

func (*SKU) IsHyperVGen2Supported added in v0.0.9

func (s *SKU) IsHyperVGen2Supported() bool

IsHyperVGen2Supported returns true when the VM size supports accelerated networking.

func (*SKU) IsPremiumIO added in v0.0.18

func (s *SKU) IsPremiumIO() bool

IsPremiumIO returns true when the VM size supports PremiumIO.

func (*SKU) IsResourceType

func (s *SKU) IsResourceType(t string) bool

IsResourceType returns true when the wrapped SKU has the provided value as its resource type. This may be used to filter using values such as "virtualMachines", "disks", "availabilitySets", "snapshots", and "hostGroups/hosts".

func (*SKU) IsRestricted

func (s *SKU) IsRestricted(location string) bool

IsRestricted returns true when a location restriction exists for this SKU.

func (*SKU) IsTrustedLaunchEnabled added in v0.0.18

func (s *SKU) IsTrustedLaunchEnabled() (bool, error)

Official documentation for Trusted Launch states: The response will be similar to the following form: IsTrustedLaunchEnabled True in the output indicates that the Generation 2 VM size does not support Trusted launch. If it's a Generation 2 VM size and TrustedLaunchDisabled is not part of the output, it implies that Trusted launch is supported for that VM size.

func (*SKU) IsUltraSSDAvailable deprecated

func (s *SKU) IsUltraSSDAvailable() bool

IsUltraSSDAvailable returns true when a VM size has ultra SSD enabled in at least 1 unrestricted zone.

Deprecated: use either IsUltraSSDAvailableWithoutAvailabilityZone or IsUltraSSDAvailableInAvailabilityZone

func (*SKU) IsUltraSSDAvailableInAvailabilityZone added in v0.0.13

func (s *SKU) IsUltraSSDAvailableInAvailabilityZone(zone string) bool

IsUltraSSDAvailableInAvailabilityZone returns true when a VM size has ultra SSD enabled in the given availability zone

func (*SKU) IsUltraSSDAvailableWithoutAvailabilityZone added in v0.0.13

func (s *SKU) IsUltraSSDAvailableWithoutAvailabilityZone() bool

IsUltraSSDAvailableWithoutAvailabilityZone returns true when a VM size has ultra SSD enabled in the region

func (*SKU) MaxCachedDiskBytes

func (s *SKU) MaxCachedDiskBytes() (int64, error)

MaxCachedDiskBytes returns the number of bytes available for the cache if it exists on this VM size.

func (*SKU) MaxResourceVolumeMB added in v0.0.10

func (s *SKU) MaxResourceVolumeMB() (int64, error)

MaxResourceVolumeMB returns the number of bytes available for the cache if it exists on this VM size.

func (*SKU) Memory

func (s *SKU) Memory() (float64, error)

Memory returns the amount of memory this SKU supports.

func (*SKU) VCPU

func (s *SKU) VCPU() (int64, error)

VCPU returns the number of vCPUs this SKU supports.

type Supported

type Supported string

Supported models an enum of possible boolean values for resource support in the Azure API.

const (
	// CapabilitySupported is an enum value for the string "True" returned when a SKU supports a binary capability.
	CapabilitySupported Supported = "True"
	// CapabilityUnsupported is an enum value for the string "False" returned when a SKU does not support a binary capability.
	CapabilityUnsupported Supported = "False"
)

type VMSizeType added in v0.0.18

type VMSizeType struct {
	Family                      string
	Subfamily                   *string
	Cpus                        string
	CpusConstrained             *string
	AdditiveFeatures            []rune
	AcceleratorType             *string
	ConfidentialChildCapability bool
	Version                     string
	PromoVersion                bool
	Series                      string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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