dcl

package
v1.23.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2022 License: Apache-2.0 Imports: 27 Imported by: 60

Documentation

Overview

Copyright 2022 Google LLC. All Rights Reserved.

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 dcl contains functions and type definitions for working with the generated portions of the Declarative Client Library.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Copyright 2022 Google LLC. All Rights Reserved.

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.

Index

Constants

View Source
const BackoffInitialInterval = 500 * time.Millisecond

BackoffInitialInterval is the default InitialInterval value for Backoff.

View Source
const BackoffMaxInterval = 30 * time.Second

BackoffMaxInterval is the default MaxInterval value for Backoff.

View Source
const Stop time.Duration = -1

Stop is a value that indicates that no more retries should be attempted.

Variables

View Source
var Scopes = []string{
	"https://www.googleapis.com/auth/cloud-platform",
	"https://www.googleapis.com/auth/userinfo.email",
}

Scopes defines the common OAuth scopes needed for clients making GCP API calls.

Functions

func APIRequestID

func APIRequestID(ctx context.Context) string

APIRequestID returns the RequestID for the API call. APIRequestID is supposed to be used in log to help with debugging Since we do not want explicit error handling everywhere we are logging, so not throwing error. Its okay to print empty requestID in worse scenario.

func AddQueryParams

func AddQueryParams(rawurl string, params map[string]string) (string, error)

AddQueryParams adds the specified query parameters to the specified url.

func AnySet

func AnySet(v ...interface{}) bool

AnySet returns true if any of the values provided is nonempty.

func Bool

func Bool(b bool) *bool

Bool converts a bool to a *bool

func BoolCanonicalize

func BoolCanonicalize(l, r *bool) bool

BoolCanonicalize checks canonicalization for booleans.

func CaseInsensitiveString

func CaseInsensitiveString(l, r *string) bool

CaseInsensitiveString returns true if the arguments are considered equal ignoring case.

func CaseInsensitiveStringArray

func CaseInsensitiveStringArray(l, r []string) bool

CaseInsensitiveStringArray returns true if the arguments are considered equal ignoring case, but including ordering.

func CompareStringSets

func CompareStringSets(a, b []string) (toAdd, toRemove []string)

CompareStringSets returns two slices of strings, one of strings in set a but not b, and one of strings in set b but not a.

func ConstructLogPrefixFromContext

func ConstructLogPrefixFromContext(ctx context.Context) string

ConstructLogPrefixFromContext constructs log prefix from info in context

func ContextWithRequestID

func ContextWithRequestID(ctx context.Context) context.Context

ContextWithRequestID adds APIRequestID to ctx if APIRequestID is not present.

func ConvertToMap

func ConvertToMap(obj interface{}) (map[string]interface{}, error)

ConvertToMap converts the specified object into the map[string]interface{} which can be serialized into the same json object as the input object.

func Copy

func Copy(src interface{}) interface{}

Copy makes a deep copy of an interface.

func CreateAPIRequestID

func CreateAPIRequestID() string

CreateAPIRequestID creates a random APIRequestId.

func DeriveField

func DeriveField(pattern string, cVal *string, fs ...*string) (*string, error)

DeriveField deals with the outgoing portion of derived fields. The derived fields' inputs might be in any form - for instance, a derived name field might be set to project/region/name, projects/project/regions/region/objects/name, or just name. This function returns the best reasonable guess at the user's intent. If the current value (cVal) matches any of those, it will return the current value. If it doesn't, it will be ignored (even if nil).

func DeriveFieldArray

func DeriveFieldArray(pattern string, cVal []string, fs ...interface{}) ([]string, error)

DeriveFieldArray calls DeriveField on each entry in the provided slice. The final entry in the input variadic argument can be a slice, and those values will be replaced by the values in the provided current value.

func DeriveFromPattern

func DeriveFromPattern(pattern string, cVal *string, fs ...*string) (*string, error)

DeriveFromPattern attempts to achieve the same end goal as DeriveField but by using regular expressions rather than assumptions about the format of the inputs based on the number of `/`. This is important for fields that allow `/` characters in their names.

func Do

func Do(ctx context.Context, op Operation, retryProvider RetryProvider) error

Do performs op as a retryable operation, using retry to determine when and if to retry. Do will only continue if a OperationNotDone{} is returned. If op() returns another error or no error, Do will finish. OperationNotDone{} may have an error inside of it, indicating that it's a retryable error.

func EmptyValue

func EmptyValue() (map[string]interface{}, error)

EmptyValue returns an empty value to exclude PARAMETER-type values from being expanded

func ExpandProjectIDsToNumbers added in v1.10.0

func ExpandProjectIDsToNumbers(config *Config, fromConfig *string) (*string, error)

ExpandProjectIDsToNumbers converts a project ID to a project number.

func ExtractElementFromList

func ExtractElementFromList(b []byte, listKey string, isElement func([]byte) bool) ([]byte, error)

ExtractElementFromList takes in bytes corresponding to a json object of the structure { "listKey": [{"foo": "bar", ...}, {"foo": "baz", ...}] } and returns the first element for which isElement returns true. isElement operates on the serialized json representation of each element - to the extent that json.Marshal(json.Unmarshal(X)) != X, this may differ from the actual elements in the input bytes - but this should be exclusively differences which are not semantically significant in json.

func FalseToNil

func FalseToNil(b *bool) (*bool, error)

FalseToNil returns nil if the pointed-to boolean is 'false' - otherwise returns the pass-in pointer.

func FindStringInArray

func FindStringInArray(s string, items []string) bool

FindStringInArray returns true if value found in array of strings

func FlattenBool

func FlattenBool(v interface{}) *bool

FlattenBool asserts that an interface is a bool and returns a pointer to it, or a pointer to false if the value is invalid.

func FlattenDouble

func FlattenDouble(v interface{}) *float64

FlattenDouble asserts that an interface is a float64 and returns a pointer to it, or to 0.0 if the value is invalid.

func FlattenFloatSlice

func FlattenFloatSlice(v interface{}) []float64

FlattenFloatSlice asserts that an interface is a []float64 and returns it.

func FlattenIntSlice

func FlattenIntSlice(v interface{}) []int64

FlattenIntSlice asserts that an interface is a []int and returns it.

func FlattenInteger

func FlattenInteger(v interface{}) *int64

FlattenInteger turns an interface pointing to an arbitary type into *in64, taking into account that it may have been represented as various types per https://developers.google.com/discovery/v1/type-format. string, float64, int64, and int64 values will return a *int64. nil and unrecognised types will return 0.

func FlattenKeyValueInterface

func FlattenKeyValueInterface(v interface{}) map[string]interface{}

FlattenKeyValueInterface returns a pointer to an interface. It can only be used for untyped maps.

func FlattenKeyValuePairs

func FlattenKeyValuePairs(v interface{}) map[string]string

FlattenKeyValuePairs asserts that an interface is a map[string]string and returns it, or an empty map if the value is invalid.

func FlattenProjectNumbersToIDs added in v1.10.0

func FlattenProjectNumbersToIDs(config *Config, fromServer *string) *string

FlattenProjectNumbersToIDs converts a project number to project ID.

func FlattenSecretValue

func FlattenSecretValue(v interface{}) *string

FlattenSecretValue behaves the same way as FlattenString, except that it returns nil if the value is not present.

func FlattenString

func FlattenString(v interface{}) *string

FlattenString asserts that an interface is a string and returns a pointer to it, or to the empty string if the value is invalid.

func FlattenStringSlice

func FlattenStringSlice(v interface{}) []string

FlattenStringSlice asserts that an interface is a []string and returns it.

func FlattenTime

func FlattenTime(v interface{}) time.Time

FlattenTime asserts that an interface is a time.Time and returns it. Time values transmitted in JSON will be an RFC3339 time as per https://developers.google.com/discovery/v1/type-format Otherwise, it returns the empty time.

func Float64

func Float64(f float64) *float64

Float64 converts a float64 to *float64

func Float64OrNil

func Float64OrNil(f float64) *float64

Float64OrNil converts a float64 to *float64, returning nil if it's empty (0.0).

func FloatSliceEquals

func FloatSliceEquals(v []float64, q []float64) bool

FloatSliceEquals takes in two slices of float64s and checks their equality

func GetMTLSEndpoint

func GetMTLSEndpoint(baseEndpoint string) (string, error)

GetMTLSEndpoint returns the API endpoint used for mTLS authentication.

func GetMapEntry

func GetMapEntry(m map[string]interface{}, path []string) (interface{}, error)

GetMapEntry returns the value at `path` from `m`, following the same rules as `MoveMapEntry` except that a missing map or value is an error.

func HandleLogArgs

func HandleLogArgs(args ...interface{}) []interface{}

HandleLogArgs ensures that pointer arguments are dereferenced well.

func HasCode

func HasCode(err error, code int) bool

HasCode returns true if the given error is an HTTP response with the given code.

func HasLifecycleParam

func HasLifecycleParam(lps []LifecycleParam, p LifecycleParam) bool

HasLifecycleParam returns whether the given slice has the requested param.

func Int64

func Int64(i int64) *int64

Int64 converts an int64 to *int64

func Int64OrNil

func Int64OrNil(i int64) *int64

Int64OrNil converts an int64 to *int64, returning nil if it's empty (0).

func IntSliceEquals

func IntSliceEquals(v []int64, q []int64) bool

IntSliceEquals takes in two slices of int64s and checks their equality

func IsConflictError

func IsConflictError(err error) bool

IsConflictError returns true if the error has conflict error code 409.

func IsEmptyValueIndirect

func IsEmptyValueIndirect(i interface{}) bool

IsEmptyValueIndirect returns true if the value provided is "empty", according to the golang rules. This corresponds to whether the value should be sent by the client if the existing value is nil - it is useful for diffing a response against a provided value. The "Indirect" refers to the fact that this method returns correct results even if the provided value is a pointer.

func IsNonRetryableHTTPError

func IsNonRetryableHTTPError(err error, retryability map[int]Retryability, start time.Time) bool

IsNonRetryableHTTPError returns true if we know that the error is not retryable - in GCP that's a 400, 403, 404, or 409.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the given error is a NotFoundError or is an HTTP 404.

func IsNotFoundOrCode

func IsNotFoundOrCode(err error, code int) bool

IsNotFoundOrCode returns true if the given error is a NotFoundError, an HTTP 404, or an HTTP response with the given code.

func IsPartialSelfLink(s string) bool

IsPartialSelfLink returns true if this string represents a partial self link.

func IsRegion

func IsRegion(s *string) bool

IsRegion returns true if this string refers to a GCP region.

func IsRetryableGoogleError

func IsRetryableGoogleError(gerr *googleapi.Error, retryability Retryability, start time.Time) bool

IsRetryableGoogleError returns true if the error is retryable according to the given retryability.

func IsRetryableHTTPError

func IsRetryableHTTPError(err error, retryability map[int]Retryability, start time.Time) bool

IsRetryableHTTPError returns true if the error is retryable - in GCP that's a 500, 502, 503, or 429.

func IsRetryableRequestError

func IsRetryableRequestError(c *Config, err error, retryNotFound bool, start time.Time) bool

IsRetryableRequestError returns true if an error is determined to be a common retryable error based on heuristics about GCP API behaviours. The start time is used to determine if errors with custom timeouts should be retried.

func IsSelfLink(s string) bool

IsSelfLink returns true if this string represents a full self link.

func IsZeroValue

func IsZeroValue(v interface{}) bool

IsZeroValue returns true if the argument is considered empty/unset.

func IsZone

func IsZone(s *string) bool

IsZone returns true if this string refers to a GCP zone.

func ListOfKeyValuesFromMap

func ListOfKeyValuesFromMap(m map[string]string, keyName, valueName string) ([]map[string]string, error)

ListOfKeyValuesFromMap is the opposite of MapFromListOfKeyValues, used in marshalling instead of unmarshalling.

func ListOfKeyValuesFromMapInStruct

func ListOfKeyValuesFromMapInStruct(m map[string]string, subfieldName, keyName, valueName string) (map[string][]map[string]string, error)

ListOfKeyValuesFromMapInStruct returns the opposite of MapFromListOfKeyValues, except nested inside an struct under the subfield name.

func MapEquals

func MapEquals(di, ai interface{}, ignorePrefixes []string) bool

MapEquals returns if two maps are equal, while ignoring any keys with ignorePrefixes.

func MapFromListOfKeyValues

func MapFromListOfKeyValues(rawFetch map[string]interface{}, path []string, keyName, valueName string) (map[string]string, error)

MapFromListOfKeyValues turns a [{"key": k, "value": v}, ...] format-map into a normal string-string map. This is useful for a handful of GCP APIs which have chosen to represent maps this way. We expect relatively few of these in newer APIs - it is explicitly against https://aip.dev/apps/2717 - ("such a map is represented by a normal JSON object"). That AIP didn't exist at the time of development of, for instance, Compute v1.

func MatchingSemver

func MatchingSemver(lp, rp *string) bool

MatchingSemver returns whether the two strings should be considered equivalent according to semver rules. If one provides more detail than the other, this is acceptable, as long as both are consistent in the detail they do provide. For instance, 1.16 == 1.16.4 != 1.15.

func MatchingSemverInterface

func MatchingSemverInterface(lp, rp interface{}) bool

MatchingSemverInterface matches two interfaces according to MatchingSemver

func MoveMapEntry

func MoveMapEntry(m map[string]interface{}, from, to []string) error

MoveMapEntry moves the entry at `from` to `to`. `from` and `to` are slices of string keys. Each key except the last must refer to a map[string]interface{} in m - we will descend into m following those keys. If the maps at the levels above the target are empty after the move, they will be deleted. If there are no maps along the path to `to`, they will be created. If a map above the level of the target is missing, nothing will be done. If the map exists but `target` is not present, `nil` will be inserted at `to`.

func NameFromSelfLink(sl *string) (*string, error)

NameFromSelfLink takes in a self link string and returns the name.

func NameToSelfLink(l, r *string) bool

NameToSelfLink returns true if left and right are equivalent for Names / SelfLinks. It allows all the deviations that SelfLinkToSelfLink allows, plus it allows one of the values to simply be the last element of the other value.

func Nprintf

func Nprintf(format string, params map[string]interface{}) string

Nprintf takes in a format string (with format {{key}} instead of %s) and a params map. Returns filled string.

func ParseResponse

func ParseResponse(resp *http.Response, ptr interface{}) error

ParseResponse reads a JSON response into a Go struct

func PartialSelfLinkToSelfLink(l, r *string) bool

PartialSelfLinkToSelfLink returns true if left and right are equivalent for SelfLinks and partial SelfLinks. It allows all the deviations that SelfLink allows, except that it works backwards, and returns true when one or the other is empty - in that sense, it allows whatever specification, starting from the most-specific

func PartialSelfLinkToSelfLinkArray

func PartialSelfLinkToSelfLinkArray(l, r []string) bool

PartialSelfLinkToSelfLinkArray returns true if left and right are all equivalent for SelfLinks.

func ProtoCamelCase

func ProtoCamelCase(s string) string

ProtoCamelCase converts a snake case name to a upper camel case name using the go protoc special rules: convert to camel case, except when the character following the underscore is a digit; e.g., foo_bar_2 -> FooBar_2. From: http://google3/net/goa/codegen/names.go;l=14;rcl=294425921

func ProtoToTime

func ProtoToTime(s string) time.Time

ProtoToTime converts a string from a DCL proto time string to a time.Time.

func PutMapEntry

func PutMapEntry(m map[string]interface{}, path []string, item interface{}) error

PutMapEntry inserts `item` at `path` into `m` - the inverse of GetMapEntry.

func QuoteAndCaseInsensitiveString

func QuoteAndCaseInsensitiveString(l, r *string) bool

QuoteAndCaseInsensitiveString returns true if the arguments are considered equal ignoring case and quotedness (e.g. "foo" and foo are equivalent).

func QuoteAndCaseInsensitiveStringArray

func QuoteAndCaseInsensitiveStringArray(l, r []string) bool

QuoteAndCaseInsensitiveStringArray returns true if the arguments are considered equal ignoring case and quotedness (e.g. "foo" and foo are equivalent), but including ordering.

func RandomString

func RandomString(length int) string

RandomString generates a random alpha-numeric string of input length.

func Required

func Required(r interface{}, path string) error

Required takes in a DCL resource (represented as an interface) and a dot-notated path (with JSON names). If the path is not set, an error will be returned.

func RequiredParameter

func RequiredParameter(v interface{}, name string) error

RequiredParameter takes in a value (typically one that's not exported in JSON) and returns an error if it is not set.

func RequiresRecreate

func RequiresRecreate() func(d *FieldDiff) []string

RequiresRecreate is for Operations that require recreating.

func ResponseBodyAsJSON

func ResponseBodyAsJSON(retry *RetryDetails) (map[string]interface{}, error)

ResponseBodyAsJSON reads the response body from a *RetryDetails and returns it as unstructured JSON in a map[string]interface{}.

func SelfLinkToName

func SelfLinkToName(v *string) *string

SelfLinkToName returns the element of a string after the last slash.

func SelfLinkToNameArray

func SelfLinkToNameArray(v []string) []string

SelfLinkToNameArray returns a slice of the elements of a slice of strings after the last slash.

func SelfLinkToNameArrayExpander

func SelfLinkToNameArrayExpander(v []string) ([]string, error)

SelfLinkToNameArrayExpander returns the last element of each string in a slice after the last slash. Return value also has error since the dcl template requires the expander to return error.

func SelfLinkToNameExpander

func SelfLinkToNameExpander(v *string) (*string, error)

SelfLinkToNameExpander returns the element of a string after the last slash. Return value also has error since the dcl template requires the expander to return error.

func SelfLinkToNameWithPattern

func SelfLinkToNameWithPattern(v *string, pattern string) *string

SelfLinkToNameWithPattern handles when the resource name can have `/` in it by matching the pattern.

func SelfLinkToSelfLink(l, r *string) bool

SelfLinkToSelfLink returns true if left and right are equivalent for selflinks. That means that they are piecewise equal, comparing components, allowing for certain elements to be dropped ("projects", "regions", etc.). It also allows any value to be present in the second-to-last field (where "instances" or "databases", etc, would be.)

func ShouldLogRequest

func ShouldLogRequest(ctx context.Context) (bool, error)

ShouldLogRequest returns true if the request should be logged.

func SliceEquals

func SliceEquals(v []string, q []string) bool

SliceEquals takes in two slices of strings and checks their equality

func SnakeCaseUpdateMask

func SnakeCaseUpdateMask(ds []*FieldDiff) string

SnakeCaseUpdateMask returns the update mask, but all fields are snake case.

func SnakeToJSONCase

func SnakeToJSONCase(s string) string

SnakeToJSONCase converts a snake_case string to jsonCase / camelCase, for use in JSON serialization.

func SnakeToTitleCase

func SnakeToTitleCase(s string) string

SnakeToTitleCase converts a snake_case string to TitleCase / Go struct case.

func SnakeToTitleCasePath

func SnakeToTitleCasePath(s, sep string) string

SnakeToTitleCasePath converts a resource path from snake to title case. For example: foo_bar.baz.qux -> FooBar.Baz.Qux

func SnakeToTitleParts

func SnakeToTitleParts(s string) []string

SnakeToTitleParts returns the parts of a snake_case string titlecased as an array, taking into account common initialisms.

func SprintResource

func SprintResource(v interface{}) string

SprintResource prints a struct into a multiline string to display to readers.

func SprintResourceCompact

func SprintResourceCompact(v interface{}) string

SprintResourceCompact prints a struct into a compact single line string.

func String

func String(s string) *string

String converts a string to a *string

func StringArrayCanonicalize

func StringArrayCanonicalize(l, r []string) bool

StringArrayCanonicalize checks canonicalization for arrays of strings. It matches self-links using NameToSelfLink.

func StringCanonicalize

func StringCanonicalize(l, r *string) bool

StringCanonicalize checks canonicalization for strings. It matches self-links using NameToSelfLink.

func StringEquals

func StringEquals(l, r *string) bool

StringEquals returns true if these two strings are equal.

func StringEqualsWithSelfLink(l, r *string) bool

StringEqualsWithSelfLink returns true if these two strings are equal. If these functions are self links, they'll do self-link comparisons.

func StringOrNil

func StringOrNil(s string) *string

StringOrNil converts a string to a *string, returning nil if it's empty ("").

func StringSliceContains

func StringSliceContains(s string, ss []string) bool

StringSliceContains returns true if the slice ss contains string s.

func StringSliceEquals

func StringSliceEquals(v, q []string) bool

StringSliceEquals returns true if v, q arrays of strings are equal according to StringEquals.

func StringSliceEqualsWithSelfLink(v, q []string) bool

StringSliceEqualsWithSelfLink returns true if v, q arrays of strings are equal according to StringEqualsWithSelfLink

func StringWithError

func StringWithError(s string) (*string, error)

StringWithError converts a string to a *string, returning a nil error to satisfy type signatures that expect one.

func TimeToProto

func TimeToProto(t time.Time) string

TimeToProto converts a time.Time to a proto time string.

func TitleToCamelCasePath

func TitleToCamelCasePath(s string) string

TitleToCamelCasePath converts a resource path from title case to lower title case. For example: FooBar.Baz.Qux -> fooBar.baz.qux

func TitleToSnakeCase

func TitleToSnakeCase(s string) string

TitleToSnakeCase takes in a TitleCase string and returns a snake_case string.

func TopLevelUpdateMask

func TopLevelUpdateMask(ds []*FieldDiff) string

TopLevelUpdateMask returns only the top-level fields.

func TriggersOperation

func TriggersOperation(op string) func(d *FieldDiff) []string

TriggersOperation is used to tell the diff checker to trigger an operation.

func URL

func URL(urlpath, basePath, userPath string, params map[string]interface{}) string

URL takes in a partial URL, default base path, optional user-specified base-path and a params map.

func UnorderedStringSliceEquals

func UnorderedStringSliceEquals(a, b []string) bool

UnorderedStringSliceEquals returns true if a, b contains same set of elements irrespective of their ordering.

func UpdateMask

func UpdateMask(ds []*FieldDiff) string

UpdateMask creates a Update Mask string according to https://google.aip.dev/161

func UpdateMaskWithPrefix

func UpdateMaskWithPrefix(ds []*FieldDiff, prefix string) string

UpdateMaskWithPrefix returns a Standard Update Mask with a prefix attached.

func UserProjectOverride

func UserProjectOverride(c *Config, url string) (bool, string)

UserProjectOverride returns true if user project override should be used and the project that should be set.

func ValidateAtLeastOneOfFieldsSet

func ValidateAtLeastOneOfFieldsSet(fieldNames []string, v ...interface{}) error

ValidateAtLeastOneOfFieldsSet returns an error if none of the provided values is nonempty.

func ValidateAtMostOneOfFieldsSet

func ValidateAtMostOneOfFieldsSet(fieldNames []string, v ...interface{}) error

ValidateAtMostOneOfFieldsSet returns an error if more than one of the provided values is nonempty.

func ValidateExactlyOneOfFieldsSet

func ValidateExactlyOneOfFieldsSet(fieldNames []string, v ...interface{}) error

ValidateExactlyOneOfFieldsSet returns an error if 0 or 2+ of the provided values is nonempty.

func ValueFromRegexOnField

func ValueFromRegexOnField(fieldName string, val *string, containerVal *string, regex string) (*string, error)

ValueFromRegexOnField assigns val to the regex value on containerVal if val is unset

func ValueOrEmptyBool

func ValueOrEmptyBool(s *bool) bool

ValueOrEmptyBool returns the value or the default value if the pointer is nil.

func ValueOrEmptyDouble

func ValueOrEmptyDouble(s *float64) float64

ValueOrEmptyDouble returns the value or the default value if the pointer is nil.

func ValueOrEmptyInt64

func ValueOrEmptyInt64(s *int64) int64

ValueOrEmptyInt64 returns the value or the default value if the pointer is nil.

func ValueOrEmptyString

func ValueOrEmptyString(i interface{}) string

ValueOrEmptyString takes a scalar or pointer to a scalar and returns either the empty string or its value.

func ValueShouldBeSent

func ValueShouldBeSent(v interface{}) bool

ValueShouldBeSent returns if a value should be sent as part of the JSON request.

func ValueType

func ValueType(i interface{}) string

ValueType returns the reflect-style kind of an interface or the underlying type of a pointer.

func WithoutTrailingDot

func WithoutTrailingDot(l, r string) bool

WithoutTrailingDot returns true if the arguments are equivalent ignoring a final period. This is useful for comparing absolute & relative domain names.

func WithoutTrailingDotArray

func WithoutTrailingDotArray(l, r []string) bool

WithoutTrailingDotArray returns true if WithoutTrailingDot returns true for each pair of elements in the lists.

func WithoutTrailingDotArrayInterface

func WithoutTrailingDotArrayInterface(l, r interface{}) bool

func WrapStringsWithKey

func WrapStringsWithKey(key string, values []string) ([]map[string]string, error)

WrapStringsWithKey returns a slice of maps with one key (the 'key' argument) and one value (each value in 'values'). e.g. ("foo", ["bar", "baz", "qux"]) => [{"foo": "bar"}, {"foo": "baz"}, {"foo": "qux"}]. Useful for, for instance, https://cloud.google.com/compute/docs/reference/rest/v1/targetPools/addHealthCheck

Types

type ApplyInfeasibleError

type ApplyInfeasibleError struct {
	Message string
}

ApplyInfeasibleError is returned when lifecycle directives prevent an Apply from proceeding. This error means that no imperative requests were issued.

func (ApplyInfeasibleError) Error

func (e ApplyInfeasibleError) Error() string

type ApplyOption

type ApplyOption interface {
	Apply(*ApplyOpts)
}

ApplyOption is an option that is accepted by Apply() functions.

func WithLifecycleParam

func WithLifecycleParam(d LifecycleParam) ApplyOption

WithLifecycleParam allows a user to specify the proper lifecycle params.

func WithStateHint

func WithStateHint(r Resource) ApplyOption

WithStateHint takes in a resource which will be used in place of the applied resource any time the current configuration of the resource is relevant. For instance, if an identity field will change, passing a state hint will ensure that the current resource is fetched (and possibly deleted).

type ApplyOpts

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

ApplyOpts refers to options that are taken in the apply function.

type AttemptToIndexNilArray added in v1.4.0

type AttemptToIndexNilArray struct {
	FieldName string
}

AttemptToIndexNilArray is returned when GetMapEntry is called with a path that includes an array index and that array is unset in the map.

func (AttemptToIndexNilArray) Error added in v1.4.0

func (e AttemptToIndexNilArray) Error() string

type Backoff

type Backoff struct {
	// InitialInterval sets the time interval for the first retry delay.
	InitialInterval time.Duration
	// MaxInterval is the largest amount of time that should elapse between retries.
	MaxInterval time.Duration
	// contains filtered or unexported fields
}

Backoff is a Retry implementation that uses exponential backoff with jitter.

func NewBackoff

func NewBackoff() *Backoff

NewBackoff returns a Backoff with sensible defaults set.

func NewBackoffWithOptions added in v1.3.0

func NewBackoffWithOptions(initialInterval, maxInterval time.Duration) *Backoff

NewBackoffWithOptions returns a Backoff with caller-supplied parameters.

func (*Backoff) RetryAfter

func (n *Backoff) RetryAfter(_ *RetryDetails) time.Duration

RetryAfter implementation that uses exponential backoff.

type BackoffRetryProvider

type BackoffRetryProvider struct{}

BackoffRetryProvider is a default RetryProvider that returns a Backoff.

func (*BackoffRetryProvider) New

func (r *BackoffRetryProvider) New() Retry

New returns an initialized Retry.

type Component added in v1.10.3

type Component struct {
	Title           string   `yaml:"title,omitempty"`
	ID              string   `yaml:"x-dcl-id,omitempty"`
	Locations       []string `yaml:"x-dcl-locations,omitempty"`
	UsesStateHint   bool     `yaml:"x-dcl-uses-state-hint,omitempty"`
	ParentContainer string   `yaml:"x-dcl-parent-container,omitempty"`
	LabelsField     string   `yaml:"x-dcl-labels,omitempty"`
	HasCreate       bool     `yaml:"x-dcl-has-create"`
	HasIAM          bool     `yaml:"x-dcl-has-iam"`
	ReadTimeout     int      `yaml:"x-dcl-read-timeout"`
	ApplyTimeout    int      `yaml:"x-dcl-apply-timeout"`
	DeleteTimeout   int      `yaml:"x-dcl-delete-timeout"`

	// TODO: It appears that reused types are not fully conforming to the same spec as the rest of the components.
	// Reused Types seem to follow the property spec, but not the component spec.
	// This means that we need to have component "inline" all of the schema property fields to avoid having to override YAML parsing logic.
	SchemaProperty Property `yaml:",inline"`
}

Component contains all the information for a component (resource or reused type)

type Components added in v1.10.3

type Components struct {
	Schemas map[string]*Component
}

Components maps a Component name to the Component.

type Config

type Config struct {
	RetryProvider RetryProvider

	Logger   ContextLogger
	BasePath string
	// contains filtered or unexported fields
}

Config is used to enclose the credentials and http client used to make requests to GCP APIs.

func NewConfig

func NewConfig(o ...ConfigOption) *Config

NewConfig creates a Config object.

func (*Config) Clone

func (c *Config) Clone(o ...ConfigOption) *Config

Clone returns a copy of an existing Config with optional new values.

func (*Config) TimeoutOr

func (c *Config) TimeoutOr(t time.Duration) time.Duration

TimeoutOr returns a timeout for this config. If WithTimeout() was called, that timeout is used; if WithTimeout() was not called and a value is provided with `t`, that is used. Otherwise the default timeout is returned;

func (*Config) UserAgent

func (c *Config) UserAgent() string

UserAgent returns the user agent for the config, which will always include the declarative SDK name and version.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is used to functionally configure Configs.

func WithAPIKey

func WithAPIKey(apiKey string) ConfigOption

WithAPIKey returns a ConfigOption that specifies an API key to be used as the basis for authentication.

func WithBasePath

func WithBasePath(b string) ConfigOption

WithBasePath allows a base path to be overridden.

func WithBillingProject

func WithBillingProject(project string) ConfigOption

WithBillingProject returns a ConfigOption that specifies the user override project. This will be used to set X-Goog-User-Project on API calls. This option will be ignored unless WithUserProjectOverride is also used.

func WithClientCertSource

func WithClientCertSource(s option.ClientCertSource) ConfigOption

WithClientCertSource returns a ConfigOption that specifies a callback function for obtaining a TLS client certificate.

func WithCodeRetryability

func WithCodeRetryability(cr map[int]Retryability) ConfigOption

WithCodeRetryability allows a user to add additional retryable or non-retryable error codes. Each error code is mapped to a regexp which must match the error message to be retryable.

func WithContentType

func WithContentType(ct string) ConfigOption

WithContentType allows a user to override the default Content-Type header.

func WithContextLogger

func WithContextLogger(l ContextLogger) ConfigOption

WithContextLogger allows a user to specify a custom context logger.

func WithCredentials

func WithCredentials(creds *google.Credentials) ConfigOption

WithCredentials returns a ConfigOption that authenticates API calls using a caller-supplier Credentials struct.

func WithCredentialsFile

func WithCredentialsFile(filename string) ConfigOption

WithCredentialsFile returns a ConfigOption that authenticates API calls with the given service account or refresh token JSON credentials file.

func WithCredentialsJSON

func WithCredentialsJSON(p []byte) ConfigOption

WithCredentialsJSON returns a ConfigOption that authenticates API calls with the given service account or refresh token JSON credentials.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ConfigOption

WithHTTPClient returns a ConfigOption that specifies the HTTP client to use as the basis of communications. When used, the WithHTTPClient option takes precedent over all other supplied authentication options.

func WithHeader

func WithHeader(header, value string) ConfigOption

WithHeader allows aribitrary HTTP headers to be addded to requests. Not all headers (e.g., "Content-Type") can be overridden. To set the User-Agent header, use WithUserAgent().

func WithLogger

func WithLogger(l Logger) ConfigOption

WithLogger allows a user to specify a custom logger.

func WithQueryParams

func WithQueryParams(ps map[string]string) ConfigOption

WithQueryParams allows a user to override the default query parameters.

func WithRetryProvider

func WithRetryProvider(r RetryProvider) ConfigOption

WithRetryProvider allows a user to override default exponential backoff retry behavior.

func WithTimeout

func WithTimeout(to time.Duration) ConfigOption

WithTimeout allows a user to override default operation timeout.

func WithUserAgent

func WithUserAgent(ua string) ConfigOption

WithUserAgent allows a user to specify a custom user-agent.

func WithUserProjectOverride

func WithUserProjectOverride() ConfigOption

WithUserProjectOverride returns a ConfigOption that turns on WithUserProjectOverride. This will send the X-Goog-User-Project on API calls.

type ContextLogger

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

ContextLogger is the internal logger implementation.

func (ContextLogger) Fatal

func (l ContextLogger) Fatal(args ...interface{})

Fatal records Fatal errors.

func (ContextLogger) FatalWithContext

func (l ContextLogger) FatalWithContext(ctx context.Context, args ...interface{})

FatalWithContext records Fatal errors with context values.

func (ContextLogger) FatalWithContextf

func (l ContextLogger) FatalWithContextf(ctx context.Context, format string, args ...interface{})

FatalWithContextf records Fatal errors with added arguments with context values.

func (ContextLogger) Fatalf

func (l ContextLogger) Fatalf(format string, args ...interface{})

Fatalf records Fatal errors with added arguments.

func (ContextLogger) Info

func (l ContextLogger) Info(args ...interface{})

Info records Info errors.

func (ContextLogger) InfoWithContext

func (l ContextLogger) InfoWithContext(ctx context.Context, args ...interface{})

InfoWithContext records Info errors with context values.

func (ContextLogger) InfoWithContextf

func (l ContextLogger) InfoWithContextf(ctx context.Context, format string, args ...interface{})

InfoWithContextf records Info errors with added arguments with context values.

func (ContextLogger) Infof

func (l ContextLogger) Infof(format string, args ...interface{})

Infof records Info errors with added arguments.

func (ContextLogger) Warning

func (l ContextLogger) Warning(args ...interface{})

Warning records Warning errors.

func (ContextLogger) WarningWithContext

func (l ContextLogger) WarningWithContext(ctx context.Context, args ...interface{})

WarningWithContext records Warning errors with context values.

func (ContextLogger) WarningWithContextf

func (l ContextLogger) WarningWithContextf(ctx context.Context, format string, args ...interface{})

WarningWithContextf records Warning errors with added arguments with context values.

func (ContextLogger) Warningf

func (l ContextLogger) Warningf(format string, args ...interface{})

Warningf records Warning errors with added arguments.

type DiffAfterApplyError

type DiffAfterApplyError struct {
	Diffs []string
}

DiffAfterApplyError is returned when there are differences between the desired state and the intended state after Apply completes. This usually indicates an error in the SDK, probably related to a failure to canonicalize properly.

func (DiffAfterApplyError) Error

func (e DiffAfterApplyError) Error() string

type DiffInfo added in v1.10.3

type DiffInfo struct {
	// Ignore + OutputOnly cause the diff checker to always return no-diff.
	Ignore           bool
	OutputOnly       bool
	MergeNestedDiffs bool
	IgnoredPrefixes  []string
	Type             string

	// ObjectFunction is the function used to diff a Nested Object.
	ObjectFunction func(desired, actual interface{}, fn FieldName) ([]*FieldDiff, error)

	// CustomDiff is used to handle diffing a field when normal diff functions will not suffice.
	// It should return false if there is any diff between 'desired' and 'actual'.
	CustomDiff func(desired, actual interface{}) bool

	// OperationSelector takes in the field's diff and returns the name of the operation (or Recreate) that should be triggered.
	OperationSelector func(d *FieldDiff) []string

	EmptyObject interface{}
}

DiffInfo is a struct that contains all information about the diff that's about to occur.

type EnumInvalidError

type EnumInvalidError struct {
	Enum  string
	Value string
	Valid []string
}

EnumInvalidError is returned when an enum is set (by a client) to a string value that is not valid for that enum. It maps to HTTP 400, although it is usually generated client-side before the enum is sent to the server.

func (EnumInvalidError) Error

func (e EnumInvalidError) Error() string

type FieldDiff

type FieldDiff struct {
	FieldName string
	Message   string
	Desired   interface{}
	Actual    interface{}

	ToAdd    []interface{}
	ToRemove []interface{}

	// The name of the operation that should result (may be Recreate)
	// In the case of sets, more than one operation may be returned.
	ResultingOperation []string
}

FieldDiff contains all information about a diff that exists in the resource.

func Diff

func Diff(desired, actual interface{}, info DiffInfo, fn FieldName) ([]*FieldDiff, error)

Diff takes in two interfaces and diffs them according to Info.

func (*FieldDiff) String

func (d *FieldDiff) String() string

type FieldName

type FieldName struct {
	FieldName string
}

FieldName is used to add information about a field's name for logging purposes.

func (FieldName) AddIndex

func (i FieldName) AddIndex(index int) FieldName

AddIndex adds an index to a FieldName and returns the same item. Info is always pass-by-value, so the original field name still exists.

func (FieldName) AddNest

func (i FieldName) AddNest(field string) FieldName

AddNest adds an index to a FieldName and returns the same item. Info is always pass-by-value, so the original field name still exists.

type FieldType added in v1.10.3

type FieldType int

FieldType is an enum of all the types a field can be.

const (
	// UnknownType refers to a Field that does not have a proper type defined.
	UnknownType FieldType = iota
	// MapType refers to a Field that is a Map (typically from string to string).
	MapType
	// EnumType refers to a Field that is an Enum.
	EnumType
	// ArrayType refers to a Field that is an Array of any kind.
	ArrayType
	// ObjectType refers to a Field that is a dictionary with set subfields.
	ObjectType
	// ReferenceType refers to a Field that is referencing another GCP resource.
	ReferenceType
	// DoubleType refers to a Field that is a Double.
	DoubleType
	// StringType refers to a Field that is a String.
	StringType
	// TimeType refers to a Field that is a Timestamp.
	TimeType
	// IntegerType refers to a Field that is an Integer.
	IntegerType
	// BooleanType refers to a Field that is a Boolean.
	BooleanType
	// StatusType refers to a Field that is a Status.
	StatusType
	// ReusedType refers to a Field that does not require additional generation because it
	// is the same type as another field already being generated.
	ReusedType
	// UntypedType refers to a type that has no type (in Go-speak, that's an interface{}).
	// This can only be used for untyped maps (in proto-speak, google.protobuf.Struct) and cannot be used anywhere else.
	// This will not work properly if used outside of a map.
	UntypedType
)

type Info

type Info struct {
	Title       string  `yaml:"title"`
	Description string  `yaml:"description"`
	StructName  string  `yaml:"x-dcl-struct-name,omitempty"`
	HasIAM      bool    `yaml:"x-dcl-has-iam"`
	Mutex       string  `yaml:"x-dcl-mutex,omitempty"`
	Note        string  `yaml:"x-dcl-note,omitempty"`
	Warning     string  `yaml:"x-dcl-warning,omitempty"`
	Reference   *Link   `yaml:"x-dcl-ref,omitempty"`
	Guides      []*Link `yaml:"x-dcl-guides,omitempty"`
}

Info is the Info block for the OpenAPI schema.

func (*Info) ResourceTitle added in v1.10.3

func (i *Info) ResourceTitle() string

ResourceTitle returns the title of this resource.

type LifecycleParam

type LifecycleParam int

LifecycleParam is used to specify what operations are acceptable.

const (
	// BlockDestruction blocks deleting the resource.  This will
	// cause some Apply operations to be impossible - some fields
	// cannot be modified and require a destroy/recreate.
	BlockDestruction LifecycleParam = iota
	// BlockAcquire will error if the resource already exists.
	BlockAcquire
	// BlockCreation will error if the resource does not exist.
	BlockCreation
	// BlockModification will error if the resource is not in the desired state.
	BlockModification
	// IgnoreIfMissing does not create (and does not error) if the resource
	// does not exist.
	IgnoreIfMissing
	// NoopOnDestroy does not destroy the resource, even if Delete() is
	// called.
	NoopOnDestroy
)

func FetchLifecycleParams

func FetchLifecycleParams(c []ApplyOption) []LifecycleParam

FetchLifecycleParams returns the list of lifecycle params.

type Link struct {
	Text string `yaml:"text"`
	URL  string `yaml:"url"`
}

Link is a URL plus text that should be displayed to an end user, usually in docs.

type Logger

type Logger interface {
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Warningf(format string, args ...interface{})
	Warning(args ...interface{})
}

Logger is an interface for logging requests and responses.

func DefaultLogger

func DefaultLogger(level LoggerLevel) Logger

DefaultLogger returns the default logger for the Declarative Client Library.

type LoggerLevel

type LoggerLevel int32

LoggerLevel is the most basic level that a logger should print. Anything at this level or more severe will be printed by this logger.

const (
	// Fatal will print only Fatal logs.
	Fatal LoggerLevel = iota
	// Error will print Error and all Fatal logs.
	Error
	// Warning will print Warning and all Error logs.
	Warning
	// LoggerInfo will print Info and all Warning logs.
	LoggerInfo
)

type NoRetry

type NoRetry struct{}

NoRetry is a Retry implementation that will never retry.

func (*NoRetry) Reset

func (n *NoRetry) Reset()

Reset is a no-op.

func (*NoRetry) RetryAfter

func (n *NoRetry) RetryAfter(_ *RetryDetails) time.Duration

RetryAfter implementation that never retries.

type NotDeletedError

type NotDeletedError struct {
	ExistingResource interface{}
}

NotDeletedError is returned when the resource should be deleted but has not been. It is returned if the operation to delete the resource has apparently been successful, but Get() still fetches the resource successfully.

func (NotDeletedError) Error

func (e NotDeletedError) Error() string

type NotFoundError

type NotFoundError struct {
	Cause error
}

NotFoundError is returned when a resource does not exist. Some APIs will also return it if a resource may exist but the current user does not have permission to view it. It wraps an error, usually a *googleapi.Error. It maps to HTTP 404.

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Operation

type Operation func(ctx context.Context) (*RetryDetails, error)

Operation is a retryable function. Implementations should return nil to indicate that the operation has concluded successfully, OperationNotDone to indicate that the operation should be retried, and any other error to indicate that a non-retryable error has occurred.

type OperationNotDone

type OperationNotDone struct {
	Err error
}

OperationNotDone is returned when an API operation hasn't completed. It may wrap an error if the error means that the operation can be retried.

func (OperationNotDone) Error

func (e OperationNotDone) Error() string

type Path added in v1.10.3

type Path struct {
	Description string           `yaml:"description"`
	Parameters  []PathParameters `yaml:"parameters"`
}

Path is the Path used for a method.

type PathParameters added in v1.10.3

type PathParameters struct {
	Name        string                `yaml:"name"`
	Required    bool                  `yaml:"required"`
	Description string                `yaml:"description,omitempty"`
	Schema      *PathParametersSchema `yaml:"schema,omitempty"`
}

PathParameters is the Parameters for a given Path.

type PathParametersSchema added in v1.10.3

type PathParametersSchema struct {
	Type string `yaml:"type"`
}

PathParametersSchema is used to store the type. It is typically set to "string"

type Paths added in v1.10.3

type Paths struct {
	Get       *Path `yaml:"get"`
	Apply     *Path `yaml:"apply"`
	Delete    *Path `yaml:"delete,omitempty"`
	DeleteAll *Path `yaml:"deleteAll,omitempty"`
	List      *Path `yaml:"list,omitempty"`
}

Paths is the Paths block for the OpenAPI schema.

type ProjectResponse added in v1.10.0

type ProjectResponse struct {
	ProjectID     string `json:"projectId"`
	ProjectNumber string `json:"projectNumber"`
}

ProjectResponse is the response from Cloud Resource Manager.

func FetchProjectInfo added in v1.10.0

func FetchProjectInfo(config *Config, projectIdentifier string) (ProjectResponse, error)

FetchProjectInfo returns a ProjectResponse from CloudResourceManager.

type Property added in v1.10.3

type Property struct {
	Type                     string                       `yaml:"type,omitempty"`
	Format                   string                       `yaml:"format,omitempty"`
	AdditionalProperties     *Property                    `yaml:"additionalProperties,omitempty"`
	Ref                      string                       `yaml:"$ref,omitempty"`
	GoName                   string                       `yaml:"x-dcl-go-name,omitempty"`
	GoType                   string                       `yaml:"x-dcl-go-type,omitempty"`
	ReadOnly                 bool                         `yaml:"readOnly,omitempty"`
	Description              string                       `yaml:"description,omitempty"`
	Immutable                bool                         `yaml:"x-kubernetes-immutable,omitempty"`
	Conflicts                []string                     `yaml:"x-dcl-conflicts,omitempty"`
	Default                  interface{}                  `yaml:"default,omitempty"`
	ServerDefault            bool                         `yaml:"x-dcl-server-default,omitempty"`
	ServerGeneratedParameter bool                         `yaml:"x-dcl-server-generated-parameter,omitempty"`
	Sensitive                bool                         `yaml:"x-dcl-sensitive,omitempty"`
	ForwardSlashAllowed      bool                         `yaml:"x-dcl-forward-slash-allowed,omitempty"`
	SendEmpty                bool                         `yaml:"x-dcl-send-empty,omitempty"`
	ResourceReferences       []*PropertyResourceReference `yaml:"x-dcl-references,omitempty"`
	Enum                     []string                     `yaml:"enum,omitempty"`
	ListType                 string                       `yaml:"x-dcl-list-type,omitempty"`
	Items                    *Property                    `yaml:"items,omitempty"`
	Unreadable               bool                         `yaml:"x-dcl-mutable-unreadable,omitempty"`
	ExtractIfEmpty           bool                         `yaml:"x-dcl-extract-if-empty,omitempty"`
	Required                 []string                     `yaml:"required,omitempty"`
	Properties               map[string]*Property         `yaml:"properties,omitempty"`
	Deprecated               bool                         `yaml:"x-dcl-deprecated,omitempty"`
	OptionalType             bool                         `yaml:"x-dcl-optional-type,omitempty"`
}

Property contains all information for a field (i.e. property)

func (*Property) IsOptional added in v1.10.3

func (p *Property) IsOptional() bool

IsOptional returns if the type is an optional type.

func (*Property) TypeEnum added in v1.10.3

func (p *Property) TypeEnum() FieldType

TypeEnum returns an enum referring to the type.

type PropertyResourceReference added in v1.10.3

type PropertyResourceReference struct {
	Resource string `yaml:"resource"`
	Field    string `yaml:"field"`
	Format   string `yaml:"format,omitempty"`
	Parent   bool   `yaml:"parent,omitempty"`
}

PropertyResourceReference contains all resource reference information.

type ReqCtxKey

type ReqCtxKey string

ReqCtxKey is the key type for storing values in the context. Context requires custom type key.

const (
	DoNotLogRequestsKey ReqCtxKey = "DoNotLogRequestsKey"
	APIRequestIDKey     ReqCtxKey = "APIRequestIDKey"
)

Keys used in context Value.

type Resource

type Resource interface {
	Describe() ServiceTypeVersion
}

func FetchStateHint

func FetchStateHint(c []ApplyOption) Resource

FetchStateHint returns either nil or a dcl.Resource representing the pre-apply state.

type Retry

type Retry interface {
	// RetryAfter returns the amount of time that should elapse before an operation is re-run. Returning
	// Stop indicates that no more retries should occur, and returning zero indicates that the operation
	// should be immediately retried.
	RetryAfter(details *RetryDetails) time.Duration
}

Retry provides an interface for handling retryable operations in a flexible manner.

type RetryDetails

type RetryDetails struct {
	Request  *http.Request
	Response *http.Response
}

RetryDetails provides information about an operation that a Retry implementation can use to make decisions about when or if to perform further requests.

func SendRequest

func SendRequest(ctx context.Context, c *Config, verb, url string, body *bytes.Buffer, retryProvider RetryProvider) (*RetryDetails, error)

SendRequest applies the credentials in the provided Config to a request with the specified verb, url, and body. It returns the Response from the server if the request returns a 2XX success code, or the *googleapi.Error if it returns any other code. The retry is optional; if supplied HTTP errors that are deemed temporary will be retried according to the policy implemented by the retry.

type RetryProvider

type RetryProvider interface {
	// New returns an initialized Retry.
	New() Retry
}

RetryProvider allows callers to provide custom retry behavior.

type Retryability

type Retryability struct {
	Retryable bool
	Pattern   string

	Timeout time.Duration
	// contains filtered or unexported fields
}

Retryability holds the details for one error code to determine if it is retyable. The regex field is compiled for use in error handling. To be retryable, the boolean must be true and the regex must match.

type Schema added in v1.10.3

type Schema struct {
	Info       *Info       `yaml:"info"`
	Paths      *Paths      `yaml:"paths"`
	Components *Components `yaml:"components"`
}

Schema is the Entire OpenAPI schema.

func (*Schema) ResolveDefinition added in v1.10.3

func (s *Schema) ResolveDefinition(ref string) (*Component, error)

ResolveDefinition returns the schema component being referenced.

type ServiceTypeVersion

type ServiceTypeVersion struct {
	// Service indicates the service to which this resource
	// belongs, e.g., "compute". It is roughly analogous to the
	// K8S "Group" identifier.
	Service string

	// Type identifies the particular type of this resource,
	// e.g., "ComputeInstance". It maps to the K8S "Kind".
	Type string

	// Version is the DCL version of the resource, e.g.,
	// "beta" or "ga".
	Version string
}

ServiceTypeVersion is a tuple that can uniquely identify a DCL resource type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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