common

package
v47.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2021 License: Apache-2.0, UPL-1.0 Imports: 33 Imported by: 2

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)
)
View Source
const (
	//UsingExpectHeaderEnvVar is the key to determine whether expect 100-continue is enabled or not
	UsingExpectHeaderEnvVar = "OCI_GOSDK_USING_EXPECT_HEADER"
)

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.

View Source
var EcContext = EventuallyConsistentContext{
	// contains filtered or unexported fields
}

EcContext contains the information about the end of the eventually consistent window for this process.

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 DefaultShouldRetryOperation

func DefaultShouldRetryOperation(r OCIOperationResponse) bool

DefaultShouldRetryOperation is the function that should be used for RetryPolicy.ShouldRetryOperation when not taking eventual consistency into account.

func EnableInstanceMetadataServiceLookup

func EnableInstanceMetadataServiceLookup()

EnableInstanceMetadataServiceLookup provides the interface to lookup IMDS region info

func EventuallyConsistentShouldRetryOperation

func EventuallyConsistentShouldRetryOperation(r OCIOperationResponse) bool

EventuallyConsistentShouldRetryOperation is the function that should be used for RetryPolicy.ShouldRetryOperation when taking eventual consistency into account

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 GetBackoffWithoutJitter

func GetBackoffWithoutJitter(policy RetryPolicy, attempt uint) time.Duration

GetBackoffWithoutJitter calculates the backoff without jitter for the attempt, given the retry policy.

func GetBodyHash

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

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

func GetEventuallyConsistentBackoffWithoutJitter

func GetEventuallyConsistentBackoffWithoutJitter(policy RetryPolicy, attempt uint, backoffScalingFactor float64) time.Duration

GetEventuallyConsistentBackoffWithoutJitter calculates the backoff without jitter for the attempt, given the retry policy and dealing with eventually consistent effects. The result is then multiplied by backoffScalingFactor.

func GetMaximumCumulativeBackoffWithoutJitter

func GetMaximumCumulativeBackoffWithoutJitter(policy RetryPolicy) time.Duration

GetMaximumCumulativeBackoffWithoutJitter calculates the maximum backoff without jitter, according to the retry policy, if every retry attempt is made.

func GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter

func GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter(policy RetryPolicy) time.Duration

GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter calculates the maximum backoff without jitter, according to the retry policy and taking eventually consistent effects into account, if every retry attempt is made.

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 IsEnvVarFalse

func IsEnvVarFalse(envVarKey string) bool

IsEnvVarFalse is used for checking if an environment variable is explicitly set to false, otherwise would set it true by default

func IsErrorAffectedByEventualConsistency

func IsErrorAffectedByEventualConsistency(Error error) bool

IsErrorAffectedByEventualConsistency returns true if the error is affected by eventual consistency.

func IsErrorRetryableByDefault

func IsErrorRetryableByDefault(Error error) bool

IsErrorRetryableByDefault returns true if the error is retryable by OCI default retry policy

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError validatas if an error is a net.Error and check if it's temporary or timeout

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 MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders

func MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path string, requestStruct interface{}, extraHeaders map[string]string) (httpRequest http.Request, err error)

MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders 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 UpdateRequestBinaryBody

func UpdateRequestBinaryBody(httpRequest *http.Request, rsc *OCIReadSeekCloser)

UpdateRequestBinaryBody updates the http request's body once it is binary request and the request body is seekable if the content length is zero, no need to update request body(since it's already been set to http.Nody)

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 parameters, this function provides a way to override some settings present in the client

func (*BaseClient) Endpoint

func (client *BaseClient) Endpoint() string

Endpoint returns the endpoint 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 EventuallyConsistentContext

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

EventuallyConsistentContext contains the information about the end of the eventually consistent window.

func (*EventuallyConsistentContext) GetEndOfWindow

func (e *EventuallyConsistentContext) GetEndOfWindow() *time.Time

GetEndOfWindow returns the end time an eventually consistent window, or nil if no eventually consistent requests were made

func (*EventuallyConsistentContext) UpdateEndOfWindow

func (e *EventuallyConsistentContext) UpdateEndOfWindow(windowSize time.Duration) *time.Time

UpdateEndOfWindow sets the end time of the eventually consistent window the specified duration into the future

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 NonSeekableRequestRetryFailure

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

NonSeekableRequestRetryFailure is the error returned when the request is with binary request body, and is configured retry, but the request body is not retryable

func (NonSeekableRequestRetryFailure) Error

type OCIOperation

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

	// End of eventually consistent effects, or nil if no such effects
	EndOfWindowTime *time.Time

	// Backoff scaling factor (only used for dealing with eventual consistency)
	BackoffScalingFactor float64

	// Time of the initial attempt
	InitialAttemptTime time.Time
}

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. Note that InitialAttemptTime is not set, nor is EndOfWindowTime, and BackoffScalingFactor is set to 1.0. EndOfWindowTime and BackoffScalingFactor are only important for eventual consistency. InitialAttemptTime can be useful for time-based (as opposed to count-based) retry policies.

func NewOCIOperationResponseExtended

func NewOCIOperationResponseExtended(response OCIResponse, err error, attempt uint, endOfWindowTime *time.Time, backoffScalingFactor float64,
	initialAttemptTime time.Time) OCIOperationResponse

NewOCIOperationResponseExtended assembles an OCI Operation Response object, with the value for the EndOfWindowTime, BackoffScalingFactor, and InitialAttemptTime set. EndOfWindowTime and BackoffScalingFactor are only important for eventual consistency. InitialAttemptTime can be useful for time-based (as opposed to count-based) retry policies.

type OCIReadSeekCloser

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

OCIReadSeekCloser is a thread-safe io.ReadSeekCloser to prevent racing with retrying binary requests

func NewOCIReadSeekCloser

func NewOCIReadSeekCloser(rc io.ReadCloser) *OCIReadSeekCloser

NewOCIReadSeekCloser constructs OCIReadSeekCloser, the only input is binary request body

func (*OCIReadSeekCloser) Close

func (rsc *OCIReadSeekCloser) Close() error

Close is a thread-safe operation, it closes the instance of the OCIReadSeekCloser's access to the underlying io.ReadCloser.

func (*OCIReadSeekCloser) Read

func (rsc *OCIReadSeekCloser) Read(p []byte) (n int, err error)

Read is a thread-safe operation, it implements io.Read() interface

func (*OCIReadSeekCloser) Seek

func (rsc *OCIReadSeekCloser) Seek(offset int64, whence int) (int64, error)

Seek is a thread-safe operation, it implements io.seek() interface, if the original request body implements io.seek() interface, or implements "well-known" data type like os.File, io.SectionReader, or wrapped by ioutil.NopCloser can be supported

func (*OCIReadSeekCloser) Seekable

func (rsc *OCIReadSeekCloser) Seekable() bool

Seekable is used for check if the binary request body can be seek or no

type OCIRequest

type OCIRequest interface {
	// HTTPRequest assembles an HTTP request.
	HTTPRequest(method, path string, binaryRequestBody *OCIReadSeekCloser, extraHeaders map[string]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 should implement this method, if has binary body, return OCIReadSeekCloser and true, otherwise return nil, false
	BinaryRequestBody() (*OCIReadSeekCloser, bool)

	// 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"
	//RegionSAVinhedo1 region for vinhedo
	RegionSAVinhedo1 Region = "sa-vinhedo-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

	// minimum sleep between attempts in seconds
	MinSleepBetween float64

	// maximum sleep between attempts in seconds
	MaxSleepBetween float64

	// the base for the exponential backoff
	ExponentialBackoffBase float64

	// DeterminePolicyToUse may modify the policy to handle eventual consistency; the return values are
	// the retry policy to use, the end of the eventually consistent time window, and the backoff scaling factor
	// If eventual consistency is not considered, this function should return the unmodified policy that was
	// provided as input, along with (*time.Time)(nil) (no time window), and 1.0 (unscaled backoff).
	DeterminePolicyToUse func(policy RetryPolicy) (RetryPolicy, *time.Time, float64)

	// if the retry policy considers eventual consistency, but there is no eventual consistency present
	// the retries will fall back to the policy specified here; recommendation is to set this to DefaultRetryPolicyWithoutEventualConsistency()
	NonEventuallyConsistentPolicy *RetryPolicy

	// Stores the maximum cumulative backoff in seconds. This can usually be calculated using
	// MaximumNumberAttempts, MinSleepBetween, MaxSleepBetween, and ExponentialBackoffBase,
	// but if MaximumNumberAttempts is 0 (unlimited attempts), then this needs to be set explicitly
	// for Eventual Consistency retries to work.
	MaximumCumulativeBackoffWithoutJitter float64
}

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

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy is a helper method that assembles and returns a return policy that is defined to be a default one The default retry policy will retry on (409, IncorrectState), (429, TooManyRequests) and any 5XX errors except (501, MethodNotImplemented) The default retry behavior is using exponential backoff with jitter, the maximum wait time is 30s plus 1s jitter The maximum cumulative backoff after all 8 attempts have been made is about 1.5 minutes. It will also retry on errors affected by eventual consistency. The eventual consistency retry behavior is using exponential backoff with jitter, the maximum wait time is 45s plus 1s jitter Under eventual consistency, the maximum cumulative backoff after all 9 attempts have been made is about 4 minutes.

func DefaultRetryPolicyWithoutEventualConsistency

func DefaultRetryPolicyWithoutEventualConsistency() RetryPolicy

DefaultRetryPolicyWithoutEventualConsistency is a helper method that assembles and returns a return policy that is defined to be a default one The default retry policy will retry on (409, IncorrectState), (429, TooManyRequests) and any 5XX errors except (501, MethodNotImplemented) It will not retry on errors affected by eventual consistency. The default retry behavior is using exponential backoff with jitter, the maximum wait time is 30s plus 1s jitter

func EventuallyConsistentRetryPolicy

func EventuallyConsistentRetryPolicy(nonEventuallyConsistentPolicy RetryPolicy) RetryPolicy

EventuallyConsistentRetryPolicy is a helper method that assembles and returns a return policy that is defined to be a default one plus dealing with errors affected by eventual consistency. The default retry behavior is using exponential backoff with jitter, the maximum wait time is 45s plus 1s jitter

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. It does not handle eventual consistency, so as to not break existing code. If you want to handle eventual consistency, the simplest way to do that is to replace the code

NewRetryPolicy(a, r, n)

with the code

  NewRetryPolicyWithOptions(
		WithMaximumNumberAttempts(a),
		WithFixedBackoff(fb) // fb is the fixed backoff duration
		WithShouldRetryOperation(r))

or

  NewRetryPolicyWithOptions(
		WithMaximumNumberAttempts(a),
		WithExponentialBackoff(mb, e) // mb is the maximum backoff duration, and e is the base for exponential backoff, e.g. 2.0
		WithShouldRetryOperation(r))

or, if a == 0 (the maximum number of attempts is unlimited)

NewRetryPolicyWithEventualConsistencyUnlimitedAttempts(a, r, n, mcb) // mcb is the maximum cumulative backoff duration without jitter

func NewRetryPolicyWithEventualConsistencyUnlimitedAttempts

func NewRetryPolicyWithEventualConsistencyUnlimitedAttempts(attempts uint, retryOperation func(OCIOperationResponse) bool, nextDuration func(OCIOperationResponse) time.Duration,
	maximumCumulativeBackoffWithoutJitter time.Duration) (*RetryPolicy, error)

NewRetryPolicyWithEventualConsistencyUnlimitedAttempts is a helper method for assembling a Retry Policy object. It does handle eventual consistency, but other than that, it is very similar to NewRetryPolicy. NewRetryPolicyWithEventualConsistency does not support limited attempts, use NewRetryPolicyWithEventualConsistency instead.

func NewRetryPolicyWithOptions

func NewRetryPolicyWithOptions(opts ...RetryPolicyOption) RetryPolicy

NewRetryPolicyWithOptions is a helper method for assembling a Retry Policy object. It starts out with the values returned by DefaultRetryPolicy() and does handle eventual consistency, unless you replace all options set using ReplaceWithValuesFromRetryPolicy(DefaultRetryPolicyWithoutEventualConsistency()).

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

func (RetryPolicy) GetMaximumCumulativeBackoffWithoutJitter

func (rp RetryPolicy) GetMaximumCumulativeBackoffWithoutJitter() time.Duration

GetMaximumCumulativeBackoffWithoutJitter returns the maximum cumulative backoff the retry policy would do, taking into account whether eventually consistency is considered or not. This function uses either GetMaximumCumulativeBackoffWithoutJitter or GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter, whichever is appropriate

func (RetryPolicy) String

func (rp RetryPolicy) String() string

Convert retry policy to human-readable string representation

type RetryPolicyOption

type RetryPolicyOption func(rp *RetryPolicy)

RetryPolicyOption is the type of the options for NewRetryPolicy.

func ReplaceWithValuesFromRetryPolicy

func ReplaceWithValuesFromRetryPolicy(other RetryPolicy) RetryPolicyOption

ReplaceWithValuesFromRetryPolicy is an option for NewRetryPolicyWithOptions that copies over all settings from another RetryPolicy

func WithConditionalOption

func WithConditionalOption(enabled bool, otherOption RetryPolicyOption) RetryPolicyOption

WithConditionalOption is an option for NewRetryPolicyWithOptions that enables or disables another option.

func WithEventualConsistency

func WithEventualConsistency() RetryPolicyOption

WithEventualConsistency is the option for NewRetryPolicyWithOptions that enables considering eventual backoff for the policy.

func WithExponentialBackoff

func WithExponentialBackoff(newMaxSleepBetween time.Duration, newExponentialBackoffBase float64) RetryPolicyOption

WithExponentialBackoff is an option for NewRetryPolicyWithOptions that sets the exponential backoff base, minimum and maximum sleep between attempts, and next duration function. Therefore, WithExponentialBackoff is a combination of WithNextDuration, withMinSleepBetween, withMaxSleepBetween, and withExponentialBackoffBase.

func WithFixedBackoff

func WithFixedBackoff(newSleepBetween time.Duration) RetryPolicyOption

WithFixedBackoff is an option for NewRetryPolicyWithOptions that sets the backoff to always be exactly the same value. There is no jitter either. Therefore, WithFixedBackoff is a combination of WithNextDuration, withMinSleepBetween, withMaxSleepBetween, and withExponentialBackoffBase.

func WithMaximumNumberAttempts

func WithMaximumNumberAttempts(attempts uint) RetryPolicyOption

WithMaximumNumberAttempts is the option for NewRetryPolicyWithOptions that sets the maximum number of attempts.

func WithNextDuration

func WithNextDuration(nextDuration func(OCIOperationResponse) time.Duration) RetryPolicyOption

WithNextDuration is the option for NewRetryPolicyWithOptions that sets the function for computing the next backoff duration. It is preferred to use WithFixedBackoff or WithExponentialBackoff instead.

func WithShouldRetryOperation

func WithShouldRetryOperation(retryOperation func(OCIOperationResponse) bool) RetryPolicyOption

WithShouldRetryOperation is the option for NewRetryPolicyWithOptions that sets the function that checks whether retries should be performed.

func WithUnlimitedAttempts

func WithUnlimitedAttempts(maximumCumulativeBackoffWithoutJitter time.Duration) RetryPolicyOption

WithUnlimitedAttempts is the option for NewRetryPolicyWithOptions that sets unlimited number of attempts, but it needs to set a MaximumCumulativeBackoffWithoutJitter duration. If you use WithUnlimitedAttempts, you should set your own NextDuration function using WithNextDuration.

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