utils

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 22, 2023 License: MIT Imports: 43 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddPatchesToKustomize

func AddPatchesToKustomize(kustomizationFile, targetKind, targetName string, patches []KustomizePatch) (string, error)

Example ******************************************************* Input kustomization file: ******************************************************* apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization

resources: - storageos-cluster.yaml ****************************************************** Other inputs: targetKind: "StorageOSCluster" targetName: "storageoscluster-sample"

patches: []KustomizePatch{
	{
		Op: "replace",
		Path: "/spec/kvBackend/address",
		Value: 	"storageos.storageos-etcd:2379",
	},
}

******************************************************* Results in the following output kustomization file: ******************************************************* apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization

resources: - storageos-cluster.yaml

patches:

  • target: kind: StorageOSCluster name: storageoscluster-sample patch: |
  • op: replace path: /spec/kvBackend/address value: storageos.storageos-etcd:2379

*******************************************************

func AllInstructionTypesExcept

func AllInstructionTypesExcept(instruction string, exceptions ...string) ([][]string, error)

AllInstructionTypesExcept returns [][]string of all instructino types for instruction, except for those provided

func AskUser

func AskUser(prompt promptui.Prompt, log *logger.Logger) (string, error)

AskUser creates an interactive prompt and waits for user input with timeout

func ConvertPanicToError

func ConvertPanicToError(setError func(err error))

ConvertPanicToError tries to catch panic and convert it to normal error.

func CreateJobAndFetchResult

func CreateJobAndFetchResult(config *rest.Config, name, namespace, image, cmd string) (string, error)

CreateJobAndFetchResult Creates a job, fetches the output of the job and deletes the created resources.

func CreateNamespaceIfNotPresent added in v1.4.0

func CreateNamespaceIfNotPresent(config *rest.Config, namespace string) error

CreateNamespaceIfNotPresent creates a namespace if it does not exists yet.

func CreateSecret

func CreateSecret(config *rest.Config, secret *corev1.Secret, namespace string) error

CreateSecret creates k8s secret.

func CreateStorageClass

func CreateStorageClass(config *rest.Config, storageClass *kstoragev1.StorageClass) error

CreateStorageClass creates k8s storage class.

func DeleteNamespace

func DeleteNamespace(config *rest.Config, namespace string) error

DeleteNamespace deletes the given namespace

func EtcdClusterDoesNotExist

func EtcdClusterDoesNotExist(config *rest.Config, name, namespace string) error

EtcdClusterDoesNotExist return no error only if no etcdcluster object exists in k8s cluster

func ExecToPod

func ExecToPod(config *rest.Config, command []string, containerName, podName, namespace string, stdin io.Reader, showOutput bool) error

ExecToPod execs into a pod and executes command from inside that pod. containerName can be "" if the pod contains only a single container.

Allows for the output from the pod to be printed or hidden. When printed it happens as soon as the buffers get any bytes back (real time).

func ExportTarball added in v1.1.0

func ExportTarball(image gocontainerv1.Image) (bytes.Buffer, error)

ExportTarball take image and return an tarball of that image

func ExtractFile added in v1.1.0

func ExtractFile(filename string, r io.Reader) ([]byte, error)

ExtractFile returns the contents of filename from tarball stored in r

func FetchHttpContent

func FetchHttpContent(url string, headers map[string]string) ([]byte, error)

FetchHttpContent downloads something from given URL

func FetchPodLogs

func FetchPodLogs(config *rest.Config, name, namespace string) (string, error)

func FindFirstPodByLabel

func FindFirstPodByLabel(config *rest.Config, namespace, label string) (*corev1.Pod, error)

func GetAllManifestsOfKindFromMultiDoc

func GetAllManifestsOfKindFromMultiDoc(multiDoc, kind string) ([]string, error)

GetAllManifestsOfKindFromMultiDoc returns a slice of strings from a multi-doc yaml file after searching by kind. Each string represents a sinlge manifest of 'kind'.

func GetClientsetFromConfig

func GetClientsetFromConfig(config *rest.Config) (*kubernetes.Clientset, error)

GetClientsetFromConfig returns a k8s clientset from a client-go rest config

func GetDecodedManifestField

func GetDecodedManifestField(fn func() (string, error)) (string, error)

GetDecodediFieldInManifest returns a decoded field from a manifest (useful for secrets). This function can accept fn GetFieldInManifest() or GetFieldInManifestMultiSearch().

func GetDefaultStorageClass

func GetDefaultStorageClass(config *rest.Config) (*kstoragev1.StorageClass, error)

GetDefaultStorage returns the the default storage class in the cluster, if more than one storage class is set to default, the first one discovered is returned. An error is returned if no default storage class is found.

func GetEtcdCluster

func GetEtcdCluster(config *rest.Config, name, namespace string) (*etcdoperatorapi.EtcdCluster, error)

GetEtcdCluster returns the etcdcluster object of name and namespace.

func GetFieldInManifest

func GetFieldInManifest(manifest string, fields ...string) (string, error)

GetFieldInManifest returns the string value at path in manifest defined by fields. See TestGetFieldInManifest for examples.

func GetFieldInManifestMultiSearch

func GetFieldInManifestMultiSearch(manifest string, searchPaths [][]string) (string, error)

GetFieldInManifestMultiSearch searches multiple paths and return string value when found. See TestGetFieldInManifestMultiSearch for examples.

func GetFieldInMultiDocByKind

func GetFieldInMultiDocByKind(multidoc, kind string, fields ...string) (string, error)

GetFieldInMultiDocByKind uses GetManifestFromMultiDocByKind and GetFieldInManifest internally to find a single manifest in a multi-doc and return the value at path defined by fields.

func GetFirstStorageOSCluster

func GetFirstStorageOSCluster(config *rest.Config) (*operatorapi.StorageOSCluster, error)

GetFirstStorageOSCluster returns the storageoscluster object if it exists in the k8s cluster. Use 'List' to discover as there can only be one object per k8s cluster and 'List' does not require name/namespace.

func GetKubernetesVersion

func GetKubernetesVersion(config *rest.Config) (*kversion.Info, error)

GetKubernetesVersion fetches Kubernetes version.

func GetManifestFromConfigMapData added in v1.4.0

func GetManifestFromConfigMapData(configMap string) (string, error)

GetManifestFromConfigMapData returns a manifest from the data of a configmap. By passing the following configmap string:

apiVersion: v1 data:

 operator_config.yaml: |
   apiVersion: config.storageos.com/v1
   kind: OperatorConfig
   health:
	    healthProbeBindAddress: :8081
	  metrics:
	    bindAddress: 127.0.0.1:8080
	  webhook:
	    port: 9443
	  leaderElection:
	    leaderElect: true
	    resourceName: storageos-operator
	  webhookCertRefreshInterval: 15m
	  webhookServiceName: storageos-operator-webhook
	  webhookSecretRef: storageos-operator-webhook
	  validatingWebhookConfigRef: storageos-operator-validating-webhook

the 'inner' manifest will be returned, eg:

apiVersion: config.storageos.com/v1 kind: OperatorConfig health:

healthProbeBindAddress: :8081

metrics:

bindAddress: 127.0.0.1:8080

webhook:

port: 9443

leaderElection:

leaderElect: true
resourceName: storageos-operator

webhookCertRefreshInterval: 15m webhookServiceName: storageos-operator-webhook webhookSecretRef: storageos-operator-webhook validatingWebhookConfigRef: storageos-operator-validating-webhook

WARNING: This function is only capable of reliably returning a manifest from the configmap, if only a single manifest exists in the configmap's data as per the example above. TODO: Improve to find for multiple manifests.

func GetManifestFromMultiDocByKind

func GetManifestFromMultiDocByKind(multiDoc, kind string) (string, error)

GetManifestFromMultiDocByKind returns an individual object string from a multi-doc yaml file after searching by kind. Note: the first object in multiManifest matching kind is returned.

func GetManifestFromMultiDocByName

func GetManifestFromMultiDocByName(multiDoc, name string) (string, error)

GetManifestFromMultiDocByName returns an individual object string from a multi-doc yaml file after searching by name..

func GetNamespace

func GetNamespace(config *rest.Config, namespace string) (*corev1.Namespace, error)

GetNamespace return namespace object

func GetSecret

func GetSecret(config *rest.Config, name, namespace string) (*corev1.Secret, error)

GetSecret returns data of secret name/namespace

func GetStorageClassByName added in v1.4.0

func GetStorageClassByName(config *rest.Config, name string) (*kstoragev1.StorageClass, error)

func HandleError

func HandleError(command string, err error, printStackTrace bool) error

HandleError tries to convert program error to something useful for user.

func HasFlagSet added in v1.2.0

func HasFlagSet(name string) bool

HasFlagSet detects user given flag

func Image added in v1.3.3

func Image(imageUrl string) (gocontainerv1.Image, error)

Image attempts to get an image from the docker daemon.

func IsDeploymentReady

func IsDeploymentReady(config *rest.Config, name, namespace string) error

IsDeploymentReady attempts to `get` a deployment by name and namespace, the function returns no error if no deployment replicas are ready.

func IsPodRunning

func IsPodRunning(config *rest.Config, name, namespace string) error

IsPodRunning attempts to `get` a pod by name and namespace, the function returns no error if the pod is in running phase.

func IsProvisionedPVC

func IsProvisionedPVC(config *rest.Config, pvc *corev1.PersistentVolumeClaim, provisioners ...string) (bool, error)

IsProvisionedPVC returns true if the PVC was provided by one of the given provisioners.

func IsProvisionedStorageClass

func IsProvisionedStorageClass(sc *kstoragev1.StorageClass, provisioners ...string) bool

IsProvisionedStorageClass returns true if the StorageClass has one of the given provisioners.

func IsServiceReady

func IsServiceReady(config *rest.Config, name, namespace string) error

IsServiceReady attempts to `get` a service by name and namespace, the function returns no error if the service doesn't have a ClusterIP or any ready endpoints.

func IsURL added in v1.4.0

func IsURL(str string) bool

func ListConfigMaps

func ListConfigMaps(config *rest.Config, listOptions metav1.ListOptions) (*corev1.ConfigMapList, error)

ListConfigMaps returns ConfigMapList

func ListPersistentVolumeClaims

func ListPersistentVolumeClaims(config *rest.Config, listOptions metav1.ListOptions) (*corev1.PersistentVolumeClaimList, error)

ListPersistentVolumeClaims returns PersistentVolumeClaimList

func ListPods

func ListPods(config *rest.Config, namespace, label string) (*corev1.PodList, error)

func ListSecrets

func ListSecrets(config *rest.Config, listOptions metav1.ListOptions) (*corev1.SecretList, error)

ListSecrets returns SecretList

func ListStorageClasses

func ListStorageClasses(config *rest.Config, listOptions metav1.ListOptions) (*kstoragev1.StorageClassList, error)

ListStorageClasses returns StorageClassList

func NamespaceDoesNotExist

func NamespaceDoesNotExist(config *rest.Config, namespace string) error

NamespaceDoesNotExist returns no error only if the specified namespace does not exist in the k8s cluster

func NamespaceYaml

func NamespaceYaml(namespace string) string

NamespaceYaml returns a yaml string for a namespace object based on the namespace name

func NewClientConfig

func NewClientConfig() (*rest.Config, error)

NewClientConfig returns a client-go rest config

func OmitAndReturnKindFromMultiDoc

func OmitAndReturnKindFromMultiDoc(multiDoc, kind string) (string, []string, error)

OmitAndReturnKindFromMultiDoc returns 'multiDoc' without objects of 'kind', while also returning []string of 'kind' objects that are omitted

func OmitByNameFromMultiDoc added in v1.4.0

func OmitByNameFromMultiDoc(multiDoc, name string) (string, error)

OmitByNameFromMultiDoc returns 'multiDoc' without objects of 'name'.

func OmitKindFromMultiDoc

func OmitKindFromMultiDoc(multiDoc, kind string) (string, error)

OmitKindFromMultiDoc returns 'multiDoc' without objects of 'kind'.

func PVCStorageClassName

func PVCStorageClassName(pvc *corev1.PersistentVolumeClaim) string

PVCStorageClassName returns the PVC provisioner name.

func PodHasPVC

func PodHasPVC(pod *corev1.Pod, pvcName string) bool

func PullImage added in v1.1.0

func PullImage(imageUrl string) (gocontainerv1.Image, error)

PullImage pulls an image from imageUrl string of the form 'repo:tag'

func SecretDoesNotExist

func SecretDoesNotExist(config *rest.Config, name, namespace string) error

SecretDoesNotExist returns no error only if the specified secret does not exist in the k8s cluster

func SetFieldInManifest

func SetFieldInManifest(manifest, value, valueName string, fields ...string) (string, error)

SetFieldInManifest sets valueName equal to value at path in manifest defined by fields. See TestSetFieldInManifest for examples.

func SetManifestInConfigMapData added in v1.4.0

func SetManifestInConfigMapData(configMap, manifestName, manifestContent string) (string, error)

SetManifestInConfigMapData sets a manifest to the data of a configmap. An example of such a configmap is the storageos-operator configmap, which contains the storageos-operator.yaml operator config manifest.

apiVersion: v1

// data: // operator_config.yaml: | // apiVersion: config.storageos.com/v1 // kind: OperatorConfig // health: // healthProbeBindAddress: :8081 // metrics: // bindAddress: 127.0.0.1:8080 // webhook: // port: 9443 // leaderElection: // leaderElect: true // resourceName: storageos-operator // webhookCertRefreshInterval: 15m // webhookServiceName: storageos-operator-webhook // webhookSecretRef: storageos-operator-webhook // validatingWebhookConfigRef: storageos-operator-validating-webhook

WARNING: using this function will overwrite ALL other data in the existing configmap it is only suitable for a specific scenario wherby a configmap storing a single manifest is required like the example above.

func StorageClassForPVC

func StorageClassForPVC(config *rest.Config, pvc *corev1.PersistentVolumeClaim) (*kstoragev1.StorageClass, error)

StorageClassForPVC returns the StorageClass of the PVC. If no StorageClass was specified, returns the cluster default if set.

func StorageOSClusterDoesNotExist

func StorageOSClusterDoesNotExist(config *rest.Config) error

StorageOSClusterDoesNotExist return no error only if no storageoscluster object exists in k8s cluster

func UpdateEtcdClusterWithoutFinalizers

func UpdateEtcdClusterWithoutFinalizers(config *rest.Config, etcdCluster *etcdoperatorapi.EtcdCluster) error

UpdateEtcdClusterWithoutFinalizers returns the etcdcluster object of name and namespace.

func UpdateStorageOSClusterWithoutFinalizers

func UpdateStorageOSClusterWithoutFinalizers(config *rest.Config, storageosCluster *operatorapi.StorageOSCluster) error

UpdateStorageOSClusterWithoutFinalizers updates the storageos cluster without any finalizers.

func VolumeHasPVC

func VolumeHasPVC(vol *corev1.Volume, pvcName string) bool

func WaitFor

func WaitFor(fn func() error, limit, interval time.Duration) error

WaitFor runs 'fn' every 'interval' for duration of 'limit', returning no error only if 'fn' returns no error inside 'limit'

func WriteDryRunManifests added in v1.1.0

func WriteDryRunManifests(filename string, fileData []byte) error

WriteDryRunManifests protects existing dry run output by postfixing directory. This function is used more than 1 time during the manifests generation, So it reuses the same directory for eaach run in a thread safe manner.

Types

type Distribution

type Distribution int
const (
	DistributionGKE Distribution = iota
	DistributionUnknown
)

func DetermineDistribution

func DetermineDistribution(version string) Distribution

DetermineDistribution tries to figure out Kubernetes distribution.

type KustomizePatch

type KustomizePatch struct {
	Op    string
	Path  string
	Value string
}

KustomizePatch is useed to pass a new patch to a kustomization file, see AddPatchesToKustomize

func GenericPatchesForSupportBundle

func GenericPatchesForSupportBundle(spec, instruction, value string, fields []string, skipLookUpValue string, pathsToSkip [][]string) ([]KustomizePatch, error)

GenericPatchesForSupportBundle creates and returns []KustomizePatch for a kustomization file to be applied to the SupportBundle.

Inputs: * spec: string of the SupportBundle manifest * instruction: "collectors" or "analyzers" * value: string of Value for patch * fields: path of fields (after instruction) to value to be changed in SupportBundle eg {"namespace"} * lookUpValue: value to compare at path skipByFields eg "storageos-operator-logs". If lookup value is left empty, any instruction with skipByFields path is skipped. This value is only to specify a single instruction for ignoring. * pathsToSkip: (optional) include paths of fields for an instructions to be ignored (ie no patch applied even if it matches 'fields' path above. Eg {{"logs"},{"run"}}

This function is useful in cases where it is desired to set a field such as namespace in a SupportBundle for most (but not all instructions). The appropriate patches are created and can then be added to the applicable kustomization.

func SpecificPatchForSupportBundle

func SpecificPatchForSupportBundle(spec, instruction, value string, fields []string, lookUpValue string, findByFields []string) (KustomizePatch, error)

SpecificPatchForSupportBundle creates and returns KustomizePatch for a kustomiziation file to be applied to the SupportBundle.

Inputs: * spec: string of the SupportBundle manifest * instruction: "collectors" or "analyzers" * value: string of Value for patch * fields: path of fields (after instruction) to value to be changed in SupportBundle eg {"run","namespace"} * lookUpValue: value to compare at path findByFields eg "storageos-operator-logs" * findByFields: path of fields to locate the specific instruction eg {"logs","name"}

This function is useful in cases where it is desired to set a field such as namespace in a SupportBundle for a specific collector or analyzer

type LogBuffer added in v1.4.0

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

LogBuffer is a custom implementation of the io.Writer interface that logs what's on the buffer on every Write thus printing its contents as close to "real time" as possible. Using this method we don't have to wai for CLI commands to finish before being able to print the buffers (stdout/err).

func (*LogBuffer) Write added in v1.4.0

func (l *LogBuffer) Write(p []byte) (int, error)

type ResourcesStillExists

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

ResourcesStillExists contains all the existing resource types in namespace

func (ResourcesStillExists) Error

func (e ResourcesStillExists) Error() string

Error generates error message

Jump to

Keyboard shortcuts

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