common

package
v39.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2021 License: Apache-2.0, UPL-1.0 Imports: 31 Imported by: 0

Documentation

Overview

Package common provides supporting functions and structs used by service packages

Index

Constants

View Source
const (
	// DefaultHostURLTemplate The default url template for service hosts
	DefaultHostURLTemplate = "%s.%s.oraclecloud.com"
)
View Source
const (
	// UnlimitedNumAttemptsValue is the value for indicating unlimited attempts for reaching success
	UnlimitedNumAttemptsValue = uint(0)
)

Variables

View Source
var DeadlineExceededByBackoff error = deadlineExceededByBackoffError{}

DeadlineExceededByBackoff is the error returned by Call() when GetNextDuration() returns a time.Duration that would force the user to wait past the request deadline before re-issuing a request. This enables us to exit early, since we cannot succeed based on the configured retry policy.

Functions

func Bool

func Bool(value bool) *bool

Bool returns a pointer to the provided bool

func CloseBodyIfValid

func CloseBodyIfValid(httpResponse *http.Response)

CloseBodyIfValid closes the body of an http response if the response and the body are valid

func CloseLogFile

func CloseLogFile() error

CloseLogFile close the logging file and return error

func Debug

func Debug(v ...interface{})

Debug logs v if debug mode is set

func Debugf

func Debugf(format string, v ...interface{})

Debugf logs v with the provided format if debug mode is set

func Debugln

func Debugln(v ...interface{})

Debugln logs v appending a new line if debug mode is set

func DefaultBodyHeaders

func DefaultBodyHeaders() []string

DefaultBodyHeaders list of default body headers that is used in signing

func DefaultGenericHeaders

func DefaultGenericHeaders() []string

DefaultGenericHeaders list of default generic headers that is used in signing

func EnableInstanceMetadataServiceLookup

func EnableInstanceMetadataServiceLookup()

EnableInstanceMetadataServiceLookup provides the interface to lookup IMDS region info

func Float32

func Float32(value float32) *float32

Float32 returns a pointer to the provided float32

func Float64

func Float64(value float64) *float64

Float64 returns a pointer to the provided float64

func GetBodyHash

func GetBodyHash(request *http.Request) (hashString string, err error)

GetBodyHash creates a base64 string from the hash of body the request

func HTTPRequestMarshaller

func HTTPRequestMarshaller(requestStruct interface{}, httpRequest *http.Request) (err error)

HTTPRequestMarshaller marshals a structure to an http request using tag values in the struct The marshaller tag should like the following

type A struct {
		 ANumber string `contributesTo="query" name="number"`
		 TheBody `contributesTo="body"`
}

where the contributesTo tag can be: header, path, query, body and the 'name' tag is the name of the value used in the http request(not applicable for path) If path is specified as part of the tag, the values are appened to the url path in the order they appear in the structure The current implementation only supports primitive types, except for the body tag, which needs a struct type. The body of a request will be marshaled using the tags of the structure

func IfDebug

func IfDebug(fn func())

IfDebug executes closure if debug is enabled

func IfInfo

func IfInfo(fn func())

IfInfo executes closure if info is enabled

func Int

func Int(value int) *int

Int returns a pointer to the provided int

func Int64

func Int64(value int64) *int64

Int64 returns a pointer to the provided int64

func IsConfigurationProviderValid

func IsConfigurationProviderValid(conf ConfigurationProvider) (ok bool, err error)

IsConfigurationProviderValid Tests all parts of the configuration provider do not return an error, this method will not check AuthType(), since authType() is not required to be there.

func Logf

func Logf(format string, v ...interface{})

Logf logs v with the provided format

func Logln

func Logln(v ...interface{})

Logln logs v appending a new line at the end Deprecated

func MakeDefaultHTTPRequest

func MakeDefaultHTTPRequest(method, path string) (httpRequest http.Request)

MakeDefaultHTTPRequest creates the basic http request with the necessary headers set

func MakeDefaultHTTPRequestWithTaggedStruct

func MakeDefaultHTTPRequestWithTaggedStruct(method, path string, requestStruct interface{}) (httpRequest http.Request, err error)

MakeDefaultHTTPRequestWithTaggedStruct creates an http request from an struct with tagged fields, see HTTPRequestMarshaller for more information

func PointerString

func PointerString(datastruct interface{}) (representation string)

PointerString prints the values of pointers in a struct Producing a human friendly string for an struct with pointers. useful when debugging the values of a struct

func PrivateKeyFromBytes

func PrivateKeyFromBytes(pemData []byte, password *string) (key *rsa.PrivateKey, e error)

PrivateKeyFromBytes is a helper function that will produce a RSA private key from bytes. This function is deprecated in favour of PrivateKeyFromBytesWithPassword Deprecated

func PrivateKeyFromBytesWithPassword

func PrivateKeyFromBytesWithPassword(pemData, password []byte) (key *rsa.PrivateKey, e error)

PrivateKeyFromBytesWithPassword is a helper function that will produce a RSA private key from bytes and a password.

func RetryToken

func RetryToken() string

RetryToken generates a retry token that must be included on any request passed to the Retry method.

func String

func String(value string) *string

String returns a pointer to the provided string

func Uint

func Uint(value uint) *uint

Uint returns a pointer to the provided uint

func UnmarshalResponse

func UnmarshalResponse(httpResponse *http.Response, responseStruct interface{}) (err error)

UnmarshalResponse hydrates the fields of a struct with the values of a http response, guided by the field tags. The directive tag is "presentIn" and it can be either

  • "header": Will look for the header tagged as "name" in the headers of the struct and set it value to that
  • "body": It will try to marshal the body from a json string to a struct tagged with 'presentIn: "body"'.

Further this method will consume the body it should be safe to close it after this function Notice the current implementation only supports native types:int, strings, floats, bool as the field types

func UnmarshalResponseWithPolymorphicBody

func UnmarshalResponseWithPolymorphicBody(httpResponse *http.Response, responseStruct interface{}, unmarshaler PolymorphicJSONUnmarshaler) (err error)

UnmarshalResponseWithPolymorphicBody similar to UnmarshalResponse but assumes the body of the response contains polymorphic json. This function will use the unmarshaler argument to unmarshal json content

func Version

func Version() string

Version returns semantic version of the sdk

Types

type AuthConfig

type AuthConfig struct {
	AuthType AuthenticationType
	// IsFromConfigFile is used to point out if the authConfig is from configuration file
	IsFromConfigFile bool
	OboToken         *string
}

AuthConfig is used for getting auth related paras in config file

type AuthenticationType

type AuthenticationType string

AuthenticationType for auth

const (
	// UserPrincipal is default auth type
	UserPrincipal AuthenticationType = "user_principal"
	// InstancePrincipal is used for instance principle auth type
	InstancePrincipal AuthenticationType = "instance_principal"
	// InstancePrincipalDelegationToken is used for instance principle delegation token auth type
	InstancePrincipalDelegationToken AuthenticationType = "instance_principle_delegation_token"
	// UnknownAuthenticationType is used for none meaningful auth type
	UnknownAuthenticationType AuthenticationType = "unknown_auth_type"
)

type BaseClient

type BaseClient struct {
	//HTTPClient performs the http network operations
	HTTPClient HTTPRequestDispatcher

	//Signer performs auth operation
	Signer HTTPRequestSigner

	//A request interceptor can be used to customize the request before signing and dispatching
	Interceptor RequestInterceptor

	//The host of the service
	Host string

	//The user agent
	UserAgent string

	//Base path for all operations of this client
	BasePath string

	Configuration CustomClientConfiguration
}

BaseClient struct implements all basic operations to call oci web services.

func DefaultBaseClientWithSigner

func DefaultBaseClientWithSigner(signer HTTPRequestSigner) BaseClient

DefaultBaseClientWithSigner creates a default base client with a given signer

func NewClientWithConfig

func NewClientWithConfig(configProvider ConfigurationProvider) (client BaseClient, err error)

NewClientWithConfig Create a new client with a configuration provider, the configuration provider will be used for the default signer as well as reading the region This function does not check for valid regions to implement forward compatibility

func NewClientWithOboToken

func NewClientWithOboToken(configProvider ConfigurationProvider, oboToken string) (client BaseClient, err error)

NewClientWithOboToken Create a new client that will use oboToken for auth

func (BaseClient) Call

func (client BaseClient) Call(ctx context.Context, request *http.Request) (response *http.Response, err error)

Call executes the http request with the given context

func (BaseClient) CallWithDetails

func (client BaseClient) CallWithDetails(ctx context.Context, request *http.Request, details ClientCallDetails) (response *http.Response, err error)

CallWithDetails executes the http request, the given context using details specified in the paremeters, this function provides a way to override some settings present in the client

func (*BaseClient) Endpoint

func (client *BaseClient) Endpoint() string

Endpoint returns the enpoint configured for client

func (*BaseClient) RetryPolicy

func (client *BaseClient) RetryPolicy() *RetryPolicy

RetryPolicy returns the retryPolicy configured for client

func (*BaseClient) SetCustomClientConfiguration

func (client *BaseClient) SetCustomClientConfiguration(config CustomClientConfiguration)

SetCustomClientConfiguration sets client with retry and other custom configurations

type ClientCallDetails

type ClientCallDetails struct {
	Signer HTTPRequestSigner
}

ClientCallDetails a set of settings used by the a single Call operation of the http Client

type ConfigurationProvider

type ConfigurationProvider interface {
	KeyProvider
	TenancyOCID() (string, error)
	UserOCID() (string, error)
	KeyFingerprint() (string, error)
	Region() (string, error)
	// AuthType() is used for specify the needed auth type, like UserPrincipal, InstancePrincipal, etc.
	AuthType() (AuthConfig, error)
}

ConfigurationProvider wraps information about the account owner

func ComposingConfigurationProvider

func ComposingConfigurationProvider(providers []ConfigurationProvider) (ConfigurationProvider, error)

ComposingConfigurationProvider creates a composing configuration provider with the given slice of configuration providers A composing provider will return the configuration of the first provider that has the required property if no provider has the property it will return an error.

func ConfigurationProviderEnvironmentVariables

func ConfigurationProviderEnvironmentVariables(environmentVariablePrefix, privateKeyPassword string) ConfigurationProvider

ConfigurationProviderEnvironmentVariables creates a ConfigurationProvider from a uniform set of environment variables starting with a prefix The env variables should look like: [prefix]_private_key_path, [prefix]_tenancy_ocid, [prefix]_user_ocid, [prefix]_fingerprint [prefix]_region

func ConfigurationProviderFromFile

func ConfigurationProviderFromFile(configFilePath, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderFromFile creates a configuration provider from a configuration file by reading the "DEFAULT" profile

func ConfigurationProviderFromFileWithProfile

func ConfigurationProviderFromFileWithProfile(configFilePath, profile, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderFromFileWithProfile creates a configuration provider from a configuration file and the given profile

func CustomProfileConfigProvider

func CustomProfileConfigProvider(customConfigPath string, profile string) ConfigurationProvider

CustomProfileConfigProvider returns the config provider of given profile. The custom profile config provider will look for configurations in 2 places: file in $HOME/.oci/config, and variables names starting with the string TF_VAR. If the same configuration is found in multiple places the provider will prefer the first one.

func DefaultConfigProvider

func DefaultConfigProvider() ConfigurationProvider

DefaultConfigProvider returns the default config provider. The default config provider will look for configurations in 3 places: file in $HOME/.oci/config, HOME/.obmcs/config and variables names starting with the string TF_VAR. If the same configuration is found in multiple places the provider will prefer the first one. If the config file is not placed in the default location, the environment variable OCI_CONFIG_FILE can provide the config file location.

func NewRawConfigurationProvider

func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) ConfigurationProvider

NewRawConfigurationProvider will create a ConfigurationProvider with the arguments of the function

type CustomClientConfiguration

type CustomClientConfiguration struct {
	RetryPolicy *RetryPolicy
}

CustomClientConfiguration contains configurations set at client level, currently it only includes RetryPolicy

type HTTPRequestDispatcher

type HTTPRequestDispatcher interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPRequestDispatcher wraps the execution of a http request, it is generally implemented by http.Client.Do, but can be customized for testing

type HTTPRequestSigner

type HTTPRequestSigner interface {
	Sign(r *http.Request) error
}

HTTPRequestSigner the interface to sign a request

func DefaultRequestSigner

func DefaultRequestSigner(provider KeyProvider) HTTPRequestSigner

DefaultRequestSigner creates a signer with default parameters.

func NewSignerFromOCIRequestSigner

func NewSignerFromOCIRequestSigner(oldSigner HTTPRequestSigner, predicate SignerBodyHashPredicate) (HTTPRequestSigner, error)

NewSignerFromOCIRequestSigner creates a copy of the request signer and attaches the new SignerBodyHashPredicate returns an error if the passed signer is not of type ociRequestSigner

func RequestSigner

func RequestSigner(provider KeyProvider, genericHeaders, bodyHeaders []string) HTTPRequestSigner

RequestSigner creates a signer that utilizes the specified headers for signing and the default predicate for using the body of the request as part of the signature

func RequestSignerExcludeBody

func RequestSignerExcludeBody(provider KeyProvider) HTTPRequestSigner

RequestSignerExcludeBody creates a signer without hash the body.

func RequestSignerWithBodyHashingPredicate

func RequestSignerWithBodyHashingPredicate(provider KeyProvider, genericHeaders, bodyHeaders []string, shouldHashBody SignerBodyHashPredicate) HTTPRequestSigner

RequestSignerWithBodyHashingPredicate creates a signer that utilizes the specified headers for signing, as well as a predicate for using the body of the request and bodyHeaders parameter as part of the signature

type KeyProvider

type KeyProvider interface {
	PrivateRSAKey() (*rsa.PrivateKey, error)
	KeyID() (string, error)
}

KeyProvider interface that wraps information about the key's account owner

type OCIOperation

type OCIOperation func(context.Context, OCIRequest) (OCIResponse, error)

OCIOperation is the generalization of a request-response cycle undergone by an OCI service.

type OCIOperationResponse

type OCIOperationResponse struct {
	// Response from OCI Operation
	Response OCIResponse

	// Error from OCI Operation
	Error error

	// Operation Attempt Number (one-based)
	AttemptNumber uint
}

OCIOperationResponse represents the output of an OCIOperation, with additional context of error message and operation attempt number.

func NewOCIOperationResponse

func NewOCIOperationResponse(response OCIResponse, err error, attempt uint) OCIOperationResponse

NewOCIOperationResponse assembles an OCI Operation Response object.

type OCIRequest

type OCIRequest interface {
	// HTTPRequest assembles an HTTP request.
	HTTPRequest(method, path string) (http.Request, error)
}

OCIRequest is any request made to an OCI service.

type OCIResponse

type OCIResponse interface {
	// HTTPResponse returns the raw HTTP response.
	HTTPResponse() *http.Response
}

OCIResponse is the response from issuing a request to an OCI service.

func Retry

func Retry(ctx context.Context, request OCIRetryableRequest, operation OCIOperation, policy RetryPolicy) (OCIResponse, error)

Retry is a package-level operation that executes the retryable request using the specified operation and retry policy.

type OCIRetryableRequest

type OCIRetryableRequest interface {
	// Any retryable request must implement the OCIRequest interface
	OCIRequest

	// Each operation specifies default retry behavior. By passing no arguments to this method, the default retry
	// behavior, as determined on a per-operation-basis, will be honored. Variadic retry policy option arguments
	// passed to this method will override the default behavior.
	RetryPolicy() *RetryPolicy
}

OCIRetryableRequest represents a request that can be reissued according to the specified policy.

type PolymorphicJSONUnmarshaler

type PolymorphicJSONUnmarshaler interface {
	UnmarshalPolymorphicJSON(data []byte) (interface{}, error)
}

PolymorphicJSONUnmarshaler is the interface to unmarshal polymorphic json payloads

type Region

type Region string

Region type for regions

const (

	//RegionSEA region SEA
	RegionSEA Region = "sea"
	//RegionCAToronto1 region for Toronto
	RegionCAToronto1 Region = "ca-toronto-1"
	//RegionCAMontreal1 region for Montreal
	RegionCAMontreal1 Region = "ca-montreal-1"
	//RegionPHX region PHX
	RegionPHX Region = "us-phoenix-1"
	//RegionIAD region IAD
	RegionIAD Region = "us-ashburn-1"
	//RegionSJC1 region SJC
	RegionSJC1 Region = "us-sanjose-1"

	//RegionFRA region FRA
	RegionFRA Region = "eu-frankfurt-1"

	//RegionUKCardiff1 region for Cardiff
	RegionUKCardiff1 Region = "uk-cardiff-1"
	//RegionLHR region LHR
	RegionLHR Region = "uk-london-1"

	//RegionAPTokyo1 region for Tokyo
	RegionAPTokyo1 Region = "ap-tokyo-1"
	//RegionAPOsaka1 region for Osaka
	RegionAPOsaka1 Region = "ap-osaka-1"
	//RegionAPChiyoda1 region for Chiyoda
	RegionAPChiyoda1 Region = "ap-chiyoda-1"
	//RegionAPSeoul1 region for Seoul
	RegionAPSeoul1 Region = "ap-seoul-1"
	//RegionAPChuncheon1 region for Chuncheon
	RegionAPChuncheon1 Region = "ap-chuncheon-1"
	//RegionAPMumbai1 region for Mumbai
	RegionAPMumbai1 Region = "ap-mumbai-1"
	//RegionAPHyderabad1 region for Hyderabad
	RegionAPHyderabad1 Region = "ap-hyderabad-1"
	//RegionAPMelbourne1 region for Melbourne
	RegionAPMelbourne1 Region = "ap-melbourne-1"
	//RegionAPSydney1 region for Sydney
	RegionAPSydney1 Region = "ap-sydney-1"

	//RegionMEJeddah1 region for Jeddah
	RegionMEJeddah1 Region = "me-jeddah-1"
	//RegionMEDubai1 region for Dubai
	RegionMEDubai1 Region = "me-dubai-1"

	//RegionEUZurich1 region for Zurich
	RegionEUZurich1 Region = "eu-zurich-1"
	//RegionEUAmsterdam1 region for Amsterdam
	RegionEUAmsterdam1 Region = "eu-amsterdam-1"

	//RegionSASaopaulo1 region for Sao Paulo
	RegionSASaopaulo1 Region = "sa-saopaulo-1"
	//RegionSASantiago1 region for santiago
	RegionSASantiago1 Region = "sa-santiago-1"

	//RegionUSLangley1 region for Langley
	RegionUSLangley1 Region = "us-langley-1"
	//RegionUSLuke1 region for Luke
	RegionUSLuke1 Region = "us-luke-1"

	//RegionUSGovAshburn1 gov region Ashburn
	RegionUSGovAshburn1 Region = "us-gov-ashburn-1"
	//RegionUSGovChicago1 gov region Chicago
	RegionUSGovChicago1 Region = "us-gov-chicago-1"
	//RegionUSGovPhoenix1 region for Phoenix
	RegionUSGovPhoenix1 Region = "us-gov-phoenix-1"
	//RegionUKGovLondon1 gov region London
	RegionUKGovLondon1 Region = "uk-gov-london-1"
	//RegionUKGovCardiff1 gov region Cardiff
	RegionUKGovCardiff1 Region = "uk-gov-cardiff-1"
)

func StringToRegion

func StringToRegion(stringRegion string) (r Region)

StringToRegion convert a string to Region type

func (Region) Endpoint

func (region Region) Endpoint(service string) string

Endpoint returns a endpoint for a service

func (Region) EndpointForTemplate

func (region Region) EndpointForTemplate(service string, serviceEndpointTemplate string) string

EndpointForTemplate returns a endpoint for a service based on template, only unknown region name can fall back to "oc1", but not short code region name.

type RequestInterceptor

type RequestInterceptor func(*http.Request) error

RequestInterceptor function used to customize the request before calling the underlying service

type RequestMetadata

type RequestMetadata struct {
	// RetryPolicy is the policy for reissuing the request. If no retry policy is set on the request,
	// then the request will be issued exactly once.
	RetryPolicy *RetryPolicy
}

RequestMetadata is metadata about an OCIRequest. This structure represents the behavior exhibited by the SDK when issuing (or reissuing) a request.

type RetryPolicy

type RetryPolicy struct {
	// MaximumNumberAttempts is the maximum number of times to retry a request. Zero indicates an unlimited
	// number of attempts.
	MaximumNumberAttempts uint

	// ShouldRetryOperation inspects the http response, error, and operation attempt number, and
	// - returns true if we should retry the operation
	// - returns false otherwise
	ShouldRetryOperation func(OCIOperationResponse) bool

	// GetNextDuration computes the duration to pause between operation retries.
	NextDuration func(OCIOperationResponse) time.Duration
}

RetryPolicy is the class that holds all relevant information for retrying operations.

func NewRetryPolicy

func NewRetryPolicy(attempts uint, retryOperation func(OCIOperationResponse) bool, nextDuration func(OCIOperationResponse) time.Duration) RetryPolicy

NewRetryPolicy is a helper method for assembling a Retry Policy object.

func NoRetryPolicy

func NoRetryPolicy() RetryPolicy

NoRetryPolicy is a helper method that assembles and returns a return policy that indicates an operation should never be retried (the operation is performed exactly once).

type SDKDate

type SDKDate struct {
	//Date date information
	Date time.Time
}

SDKDate a struct that parses/renders to/from json using only date information

func NewSDKDateFromString

func NewSDKDateFromString(dateString string) (*SDKDate, error)

NewSDKDateFromString parses the dateString into SDKDate

func (*SDKDate) MarshalJSON

func (t *SDKDate) MarshalJSON() (buff []byte, e error)

MarshalJSON marshals to JSON

func (*SDKDate) String

func (t *SDKDate) String() string

String returns string representation of SDKDate

func (*SDKDate) UnmarshalJSON

func (t *SDKDate) UnmarshalJSON(data []byte) (e error)

UnmarshalJSON unmarshals from json

type SDKTime

type SDKTime struct {
	time.Time
}

SDKTime a struct that parses/renders to/from json using RFC339 date-time information

func (*SDKTime) MarshalJSON

func (t *SDKTime) MarshalJSON() (buff []byte, e error)

MarshalJSON marshals to JSON

func (*SDKTime) UnmarshalJSON

func (t *SDKTime) UnmarshalJSON(data []byte) (e error)

UnmarshalJSON unmarshals from json

type ServiceError

type ServiceError interface {
	// The http status code of the error
	GetHTTPStatusCode() int

	// The human-readable error string as sent by the service
	GetMessage() string

	// A short error code that defines the error, meant for programmatic parsing.
	// See https://docs.cloud.oracle.com/Content/API/References/apierrors.htm
	GetCode() string

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	GetOpcRequestID() string
}

ServiceError models all potential errors generated the service call

func IsServiceError

func IsServiceError(err error) (failure ServiceError, ok bool)

IsServiceError returns false if the error is not service side, otherwise true additionally it returns an interface representing the ServiceError

type SignerBodyHashPredicate

type SignerBodyHashPredicate func(r *http.Request) bool

SignerBodyHashPredicate a function that allows to disable/enable body hashing of requests and headers associated with body content

Directories

Path Synopsis
Package auth provides supporting functions and structs for authentication
Package auth provides supporting functions and structs for authentication

Jump to

Keyboard shortcuts

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