util

package
v5.0.0-...-5e9b562 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2021 License: Apache-2.0 Imports: 59 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// InsecureHTTPTransport is a global insecure http transport
	InsecureHTTPTransport = &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
)

Functions

func AddFinalizer

func AddFinalizer(obj metav1.Object, finalizer string) bool

AddFinalizer adds the finalizer to the object if it doesn't contains it already

func BuildExternalSecretPath

func BuildExternalSecretPath(client *vaultApi.Client, kms nbv1.KeyManagementServiceSpec, uid string) (string, error)

BuildExternalSecretPath builds a string that specifies the root key secret path

func CombineErrors

func CombineErrors(errs ...error) error

CombineErrors takes a list of errors and combines them to one. Generally it will return the first non-nil error, but if a persistent error is found it will be returned instead of non-persistent errors.

func ComposePredicates

func ComposePredicates(predicates ...predicate.Predicate) predicate.Predicate

ComposePredicates will compose a variable number of predicte and return a predicate that will allow events that are allowed by any of the given predicates.

func Contains

func Contains(s string, arr []string) bool

Contains checks if string array arr contains string s

func Context

func Context() context.Context

Context returns a default Context

func CurrentNamespace

func CurrentNamespace() string

CurrentNamespace reads the current namespace from the kube config

func DeleteSecret

func DeleteSecret(client *vaultApi.Client, secretPath string) error

DeleteSecret deletes the secret from the secrets store

func DeleteStorageClass

func DeleteStorageClass(sc *storagev1.StorageClass) error

DeleteStorageClass deletes storage class

func EnsureCommonMetaFields

func EnsureCommonMetaFields(object metav1.Object, finalizer string) bool

EnsureCommonMetaFields ensures that the resource has all mandatory meta fields

func GetAWSRegion

func GetAWSRegion() (string, error)

GetAWSRegion parses the region from a node's name

func GetCmDataHash

func GetCmDataHash(input map[string]string) string

GetCmDataHash calculates a Hash string repersnting an array of key value strings

func GetContainerStatusLine

func GetContainerStatusLine(cont *corev1.ContainerStatus) string

GetContainerStatusLine returns a one liner status for a container

func GetEnvVariable

func GetEnvVariable(env *[]corev1.EnvVar, name string) *corev1.EnvVar

GetEnvVariable is looknig for env variable called name in env and return a pointer to the variable

func GetFlagStringOrPrompt

func GetFlagStringOrPrompt(cmd *cobra.Command, flag string) string

GetFlagStringOrPrompt returns flag value but if empty will promtp to read from stdin

func GetFlagStringOrPromptPassword

func GetFlagStringOrPromptPassword(cmd *cobra.Command, flag string) string

GetFlagStringOrPromptPassword is like GetFlagStringOrPrompt but does not show the input characters on the terminal to avoid leaking secret data in shell history

func GetIBMRegion

func GetIBMRegion() (string, error)

GetIBMRegion returns the cluster's region in IBM Cloud

func GetPodLogs

func GetPodLogs(pod corev1.Pod) (map[string]io.ReadCloser, error)

GetPodLogs info

func GetPodStatusLine

func GetPodStatusLine(pod *corev1.Pod) string

GetPodStatusLine returns a one liner status for a pod

func GetSecret

func GetSecret(client *vaultApi.Client, secretName, secretPath string, backendPath string) (string, error)

GetSecret reads the secret to the secrets store

func GetVaultTLSConfig

func GetVaultTLSConfig(config map[string]string, namespace string) (*api.TLSConfig, error)

GetVaultTLSConfig returns tlsConfig if given

func GetWatchNamespace

func GetWatchNamespace() (string, error)

GetWatchNamespace returns the namespace the operator should be watching for changes this was implemented in operator-sdk v0.17 and removed. copied from here: https://github.com/operator-framework/operator-sdk/blob/53b00d125fb12515cd74fb169149913b401c8995/pkg/k8sutil/k8sutil.go#L45

func IgnoreError

func IgnoreError(err error)

IgnoreError do nothing if err is not nil

func InitLogger

func InitLogger()

InitLogger initializes the logrus logger with defaults

func InitVaultClient

func InitVaultClient(config map[string]string, tokenSecretName string, namespace string) (*vaultApi.Client, error)

InitVaultClient inits the secret store

func IsAWSPlatform

func IsAWSPlatform() bool

IsAWSPlatform returns true if this cluster is running on AWS

func IsAzurePlatform

func IsAzurePlatform() bool

IsAzurePlatform returns true if this cluster is running on Azure

func IsGCPPlatform

func IsGCPPlatform() bool

IsGCPPlatform returns true if this cluster is running on GCP

func IsIBMPlatform

func IsIBMPlatform() bool

IsIBMPlatform returns true if this cluster is running on IBM Cloud

func IsPersistentError

func IsPersistentError(err error) bool

IsPersistentError checks if the provided error is persistent.

func IsStringGraphicOrSpacesCharsOnly

func IsStringGraphicOrSpacesCharsOnly(s string) bool

IsStringGraphicOrSpacesCharsOnly returns true only if all the chars are graphic or spaces

func IsValidS3BucketName

func IsValidS3BucketName(name string) bool

IsValidS3BucketName checks the name according to https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-s3-bucket-naming-requirements.html

func IsVaultKMS

func IsVaultKMS(provider string) bool

IsVaultKMS return true if kms provider is vault

func KubeApply

func KubeApply(obj client.Object) bool

KubeApply will check if the object exists and will create/update accordingly and report the object status.

func KubeCheck

func KubeCheck(obj client.Object) bool

KubeCheck checks if the object exists and reports the object status.

func KubeCheckOptional

func KubeCheckOptional(obj client.Object) bool

KubeCheckOptional checks if the object exists and reports the object status. It detects the situation of a missing CRD and reports it as an optional feature.

func KubeCheckQuiet

func KubeCheckQuiet(obj client.Object) bool

KubeCheckQuiet checks if the object exists fills the given object if found. returns true if the object was found. It does not print any status

func KubeClient

func KubeClient() client.Client

KubeClient resturns a controller-runtime client We use a lazy mapper and a specialized implementation of fast mapper in order to avoid lags when running a CLI client to a far away cluster.

func KubeConfig

func KubeConfig() *rest.Config

KubeConfig loads kubernetes client config from default locations (flags, user dir, etc)

func KubeCreateFailExisting

func KubeCreateFailExisting(obj client.Object) bool

KubeCreateFailExisting will check if the object exists and will create/skip accordingly and report the object status.

func KubeCreateOptional

func KubeCreateOptional(obj client.Object) bool

KubeCreateOptional will check if the object exists and will create/skip accordingly It detects the situation of a missing CRD and reports it as an optional feature.

func KubeCreateSkipExisting

func KubeCreateSkipExisting(obj client.Object) bool

KubeCreateSkipExisting will try to create an object returns true of the object exist or was created returns false otherwise

func KubeDelete

func KubeDelete(obj client.Object, opts ...client.DeleteOption) bool

KubeDelete deletes an object and reports the object status.

func KubeDeleteAllOf

func KubeDeleteAllOf(obj client.Object, opts ...client.DeleteAllOfOption) bool

KubeDeleteAllOf deletes an list of objects and reports the status.

func KubeDeleteNoPolling

func KubeDeleteNoPolling(obj client.Object, opts ...client.DeleteOption) bool

KubeDeleteNoPolling deletes an object without waiting for acknowledgement the object got deleted

func KubeGet

func KubeGet(obj client.Object) (name string, kind string, err error)

KubeGet gets a client.Object, fills the given object and returns the name and kind returns error on failure

func KubeList

func KubeList(list client.ObjectList, options ...client.ListOption) bool

KubeList returns a list of objects.

func KubeObject

func KubeObject(text string) runtime.Object

KubeObject loads a text yaml/json to a kubernets object.

func KubeUpdate

func KubeUpdate(obj client.Object) bool

KubeUpdate updates an object and reports the object status.

func LoadBucketReplicationJSON

func LoadBucketReplicationJSON(replicationJSONFilePath string) (string, error)

LoadBucketReplicationJSON loads the bucket replication from a json file

func LogError

func LogError(err error)

LogError prints the error to the log and continue

func Logger

func Logger() *logrus.Entry

Logger returns a default logger

func MapperProvider

func MapperProvider(config *rest.Config) (meta.RESTMapper, error)

MapperProvider creates RESTMapper

func MergeEnvArrays

func MergeEnvArrays(envA, envB *[]corev1.EnvVar)

MergeEnvArrays takes two Env variables arrays and merge them into the first

func MergeVolumeList

func MergeVolumeList(existing, template *[]corev1.Volume)

MergeVolumeList takes two Volume arrays and merge them into the first

func MergeVolumeMountList

func MergeVolumeMountList(existing, template *[]corev1.VolumeMount)

MergeVolumeMountList takes two VolumeMount arrays and merge them into the first

func NewFastRESTMapper

func NewFastRESTMapper(dc discovery.DiscoveryInterface, filter APIGroupFilterFunc) meta.RESTMapper

NewFastRESTMapper initializes a FastRESTMapper

func NoGroupFilter

func NoGroupFilter(*metav1.APIGroup) bool

NoGroupFilter is a filtering function that includes all the server groups

func ObjectKey

func ObjectKey(obj client.Object) client.ObjectKey

ObjectKey returns the objects key (namespace + name)

func Panic

func Panic(err error)

Panic is conviniently calling panic only if err is not nil

func PrintThisNoteWhenFinishedApplyingAndStartWaitLoop

func PrintThisNoteWhenFinishedApplyingAndStartWaitLoop()

PrintThisNoteWhenFinishedApplyingAndStartWaitLoop is a common log task

func PutSecret

func PutSecret(client *vaultApi.Client, secretName, secretValue, secretPath string, backendPath string) error

PutSecret writes the secret to the secrets store

func RandomBase64

func RandomBase64(numBytes int) string

RandomBase64 creates a random buffer with numBytes and returns it encoded in base64 Returned string length is 4*math.Ceil(numBytes/3)

func RandomHex

func RandomHex(numBytes int) string

RandomHex creates a random buffer with numBytes and returns it encoded in hex Returned string length is 2*numBytes

func ReflectEnvVariable

func ReflectEnvVariable(env *[]corev1.EnvVar, name string)

ReflectEnvVariable will add, update or remove an env variable base on the existence and value of an env variable with the same name on the container running this function.

func RemoveFinalizer

func RemoveFinalizer(obj metav1.Object, finalizer string) bool

RemoveFinalizer modifies the object and removes the finalizer

func SaveCRsToFile

func SaveCRsToFile(crs runtime.Object, path string) error

SaveCRsToFile info

func SaveStreamToFile

func SaveStreamToFile(body io.ReadCloser, path string) error

SaveStreamToFile info

func SecretResetStringDataFromData

func SecretResetStringDataFromData(obj runtime.Object)

SecretResetStringDataFromData reads the secret data into string data to streamline the paths that use the secret values as strings.

func SetAvailableCondition

func SetAvailableCondition(conditions *[]conditionsv1.Condition, reason string, message string)

SetAvailableCondition updates the status conditions to available state

func SetErrorCondition

func SetErrorCondition(conditions *[]conditionsv1.Condition, reason string, message string)

SetErrorCondition updates the status conditions to error state

func SetProgressingCondition

func SetProgressingCondition(conditions *[]conditionsv1.Condition, reason string, message string)

SetProgressingCondition updates the status conditions to in-progress state

func Tar

func Tar(src string, writers ...io.Writer) error

Tar takes a source and variable writers and walks 'source' writing each file found to the tar writer; the purpose for accepting multiple writers is to allow for multiple outputs (for example a file, or md5 hash)

func ValidateConnectionDetails

func ValidateConnectionDetails(config map[string]string, tokenSecretName string, namespace string) error

ValidateConnectionDetails return error if kms connection details are faulty

func ValidateVaultConnectionDetails

func ValidateVaultConnectionDetails(config map[string]string, tokenName string, namespace string) error

ValidateVaultConnectionDetails return error if vault connection details are faulty

func VerifyCredsInSecret

func VerifyCredsInSecret(secretName string, namespace string, mandatoryProperties []string)

VerifyCredsInSecret throws fatal error when a given secret doesn't contain the mandatory properties

func VerifyExternalSecretsDeletion

func VerifyExternalSecretsDeletion(kms nbv1.KeyManagementServiceSpec, namespace string, uid string) error

VerifyExternalSecretsDeletion checks if noobaa is on un-installation process if true, deletes secrets from external KMS

func WriteYamlFile

func WriteYamlFile(name string, obj runtime.Object, moreObjects ...runtime.Object) error

WriteYamlFile writes a yaml file from the given objects

Types

type APIGroupFilterFunc

type APIGroupFilterFunc func(*metav1.APIGroup) bool

APIGroupFilterFunc is a filtering function to limit the amount of server groups we load

type FastRESTMapper

type FastRESTMapper struct {
	Discovery discovery.DiscoveryInterface
	Filter    APIGroupFilterFunc
	Mapper    meta.RESTMapper
}

FastRESTMapper loads the mapper data from the server with filter and concurrency and rediscovers the mapping on meta.NoKindMatchError errors See https://github.com/kubernetes-sigs/controller-runtime/issues/537

func (*FastRESTMapper) Discover

func (m *FastRESTMapper) Discover() error

Discover reads server groups and then reads each group to initialize the mapper groups.

func (*FastRESTMapper) DiscoverGroup

func (m *FastRESTMapper) DiscoverGroup(gr *restmapper.APIGroupResources) error

DiscoverGroup reads the server group

func (*FastRESTMapper) DiscoverOnError

func (m *FastRESTMapper) DiscoverOnError(err error) bool

DiscoverOnError check if the error is NoMatchError and calls discover

func (*FastRESTMapper) KindFor

KindFor implements Mapper.KindFor

func (*FastRESTMapper) KindsFor

KindsFor implements Mapper.KindsFor

func (*FastRESTMapper) RESTMapping

func (m *FastRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error)

RESTMapping implements Mapper.RESTMapping

func (*FastRESTMapper) RESTMappings

func (m *FastRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error)

RESTMappings implements Mapper.RESTMappings

func (*FastRESTMapper) ResourceFor

ResourceFor implements Mapper.ResourceFor

func (*FastRESTMapper) ResourceSingularizer

func (m *FastRESTMapper) ResourceSingularizer(resource string) (string, error)

ResourceSingularizer implements Mapper.ResourceSingularizer

func (*FastRESTMapper) ResourcesFor

ResourcesFor implements Mapper.ResourcesFor

type FilterForOwner

type FilterForOwner struct {
	OwnerType runtime.Object
	Scheme    *runtime.Scheme
}

FilterForOwner will only allow events that owned by noobaa

func (FilterForOwner) Create

func (p FilterForOwner) Create(e event.CreateEvent) bool

Create implements the create event trap for FilterForOwner

func (FilterForOwner) Delete

func (p FilterForOwner) Delete(e event.DeleteEvent) bool

Delete implements the delete event trap for FilterForOwner

func (FilterForOwner) Generic

func (p FilterForOwner) Generic(e event.GenericEvent) bool

Generic implements the generic event trap for FilterForOwner

func (FilterForOwner) Update

func (p FilterForOwner) Update(e event.UpdateEvent) bool

Update implements the update event trap for FilterForOwner

type FinalizersChangedPredicate

type FinalizersChangedPredicate struct {
	predicate.Funcs
}

FinalizersChangedPredicate will only allow events that changed Metadata.Finalizers

func (FinalizersChangedPredicate) Update

Update implements the update event trap for FinalizersChangedPredicate

type LabelsChangedPredicate

type LabelsChangedPredicate struct {
	predicate.Funcs
}

LabelsChangedPredicate will only allow events that changed Metadata.Labels

func (LabelsChangedPredicate) Update

Update implements the update event trap for LabelsChangedPredicate

type LogEventsPredicate

type LogEventsPredicate struct {
}

LogEventsPredicate will passthrough events while loging a message for each

func (LogEventsPredicate) Create

Create implements the create event trap for LogEventsPredicate

func (LogEventsPredicate) Delete

Delete implements the delete event trap for LogEventsPredicate

func (LogEventsPredicate) Generic

Generic implements the generic event trap for LogEventsPredicate

func (LogEventsPredicate) Update

Update implements the update event trap for LogEventsPredicate

type OAuth2Endpoints

type OAuth2Endpoints struct {
	AuthorizationEndpoint string `json:"authorization_endpoint"`
	TokenEndpoint         string `json:"token_endpoint"`
}

OAuth2Endpoints holds OAuth2 endpoints information.

func DiscoverOAuthEndpoints

func DiscoverOAuthEndpoints() (*OAuth2Endpoints, error)

DiscoverOAuthEndpoints uses a well known url to get info on the cluster oauth2 endpoints

type PersistentError

type PersistentError struct {
	Reason  string
	Message string
}

PersistentError is an error type that tells the reconcile to avoid requeueing.

func NewPersistentError

func NewPersistentError(reason string, message string) *PersistentError

NewPersistentError returns a new persistent error.

func (*PersistentError) Error

func (e *PersistentError) Error() string

Error function makes PersistentError implement error interface

type PrintColumn

type PrintColumn struct {
	Items []string
	Width int
}

PrintColumn is a column in PrintTable

func (*PrintColumn) Pad

func (c *PrintColumn) Pad(s string) string

Pad adds padding the provided string to make it print nicely as a table cell

func (*PrintColumn) RecalcWidth

func (c *PrintColumn) RecalcWidth()

RecalcWidth can be called to recalculate the column width after manual updates are made

type PrintTable

type PrintTable struct {
	Columns []PrintColumn
	NumRows int
}

PrintTable is a table for printing with fixed column width and padding

func (*PrintTable) AddRow

func (t *PrintTable) AddRow(items ...string) *PrintTable

AddRow adds a row of headers/values to the table

func (*PrintTable) RecalcWidth

func (t *PrintTable) RecalcWidth() *PrintTable

RecalcWidth can be called to recalculate the columns width after manual updates are made

func (*PrintTable) String

func (t *PrintTable) String() string

Jump to

Keyboard shortcuts

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