Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Persistent Volumes #1284

Merged
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions modules/k8s/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,21 @@ type UnknownServiceType struct {
service *corev1.Service
}

// PersistentVolumeNotAvailable is returned when a Kubernetes PersistentVolume is not available
type PersistentVolumeNotAvailable struct {
pv *corev1.PersistentVolume
}

// Error is a simple function to return a formatted error message as a string
func (err PersistentVolumeNotAvailable) Error() string {
return fmt.Sprintf("Pv %s is not available", err.pv.Name)
}

// NewPersistentVolumeNotAvailableError returns a PersistentVolumeNotAvailable struct when the given Persistent Volume is not available
func NewPersistentVolumeNotAvailableError(pv *corev1.PersistentVolume) PersistentVolumeNotAvailable {
return PersistentVolumeNotAvailable{pv}
}

// Error is a simple function to return a formatted error message as a string
func (err UnknownServiceType) Error() string {
return fmt.Sprintf("Service %s has an unknown service type", err.service.Name)
Expand Down
102 changes: 102 additions & 0 deletions modules/k8s/persistent_volume.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package k8s

import (
"context"
"fmt"
"time"

"github.com/stretchr/testify/require"

corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
)

// ListPersistentVolumes will look for PersistentVolumes in the given namespace that match the given filters and return them. This will fail the
// test if there is an error.
func ListPersistentVolumes(t testing.TestingT, options *KubectlOptions, filters metav1.ListOptions) []corev1.PersistentVolume {
pvs, err := ListPersistentVolumesE(t, options, filters)
require.NoError(t, err)
return pvs
}

// ListPersistentVolumesE will look for PersistentVolumes that match the given filters and return them.
func ListPersistentVolumesE(t testing.TestingT, options *KubectlOptions, filters metav1.ListOptions) ([]corev1.PersistentVolume, error) {
clientset, err := GetKubernetesClientFromOptionsE(t, options)
if err != nil {
return nil, err
}

resp, err := clientset.CoreV1().PersistentVolumes().List(context.Background(), filters)
if err != nil {
return nil, err
}
return resp.Items, nil
}

// GetPersistentVolume returns a Kubernetes PersistentVolume resource with the given name. This will fail the test if there is an error.
func GetPersistentVolume(t testing.TestingT, options *KubectlOptions, name string) *corev1.PersistentVolume {
pv, err := GetPersistentVolumeE(t, options, name)
require.NoError(t, err)
return pv
}

// GetPersistentVolumeE returns a Kubernetes PersistentVolume resource with the given name.
func GetPersistentVolumeE(t testing.TestingT, options *KubectlOptions, name string) (*corev1.PersistentVolume, error) {
clientset, err := GetKubernetesClientFromOptionsE(t, options)
if err != nil {
return nil, err
}
return clientset.CoreV1().PersistentVolumes().Get(context.Background(), name, metav1.GetOptions{})
}

// WaitUntilPersistentVolumeAvailableE waits until the given Persistent Volume is the 'Available' status,
kaisoz marked this conversation as resolved.
Show resolved Hide resolved
// retrying the check for the specified amount of times, sleeping
// for the provided duration between each try.
// This will fail the test if there is an error.
func WaitUntilPersistentVolumeAvailable(t testing.TestingT, options *KubectlOptions, pvName string, retries int, sleepBetweenRetries time.Duration) {
require.NoError(t, WaitUntilPersistentVolumeAvailableE(t, options, pvName, retries, sleepBetweenRetries))
}

// WaitUntilPersistentVolumeAvailableE waits until the given PersistentVolume is in the 'Available' status,
// retrying the check for the specified amount of times, sleeping
// for the provided duration between each try.
func WaitUntilPersistentVolumeAvailableE(
t testing.TestingT,
options *KubectlOptions,
pvName string,
retries int,
sleepBetweenRetries time.Duration,
) error {
statusMsg := fmt.Sprintf("Wait for Persistent Volume %s to be available", pvName)
message, err := retry.DoWithRetryE(
t,
statusMsg,
retries,
sleepBetweenRetries,
func() (string, error) {
pv, err := GetPersistentVolumeE(t, options, pvName)
if err != nil {
return "", err
}
if !IsPersistentVolumeAvailable(pv) {
return "", NewPersistentVolumeNotAvailableError(pv)
}
return "Persistent Volume is now available", nil
},
)
if err != nil {
logger.Logf(t, "Timedout waiting for PersistentVolume to be available: %s", err)
kaisoz marked this conversation as resolved.
Show resolved Hide resolved
return err
}
logger.Logf(t, message)
return nil
}

// IsPersistentVolume returns true if the given PersistentVolume is available
kaisoz marked this conversation as resolved.
Show resolved Hide resolved
func IsPersistentVolumeAvailable(pv *corev1.PersistentVolume) bool {
return pv != nil && pv.Status.Phase == corev1.VolumeAvailable
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was wondering if should be checked for corev1.VolumeBound / corev1.VolumeReleased?
Can be use-cases when is required to check already bound PV

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My initial intention was to have a generic WaitForPersistentVolumeInPhase which would receive the Phase to wait for. Then I would have smaller wrapper functions for each state.

However, at the end, and due to our requirements, I just implemented the 'Available' one, with the idea of implementing the others when I needed them.

I could implement the whole thing now though

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, the next PR, which will be for PersistentVolumeClaims, has a function which waits for the bound state

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review @denis256 , I'll address the comments. What about this one? Is it enough with what I have or you prefer me to implement other checks?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think will be helpful to have a function that can get status as argument

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

I replaced the wait and test functions to check the 'available' status for generic ones which receive the status phase. I've named the status argument pvStatusPhase to make clear the relationship between the status and the type of argument the functions receive (corev1.PersistentVolumePhase, which is what's compared).

I think there's no need to add smaller wrapper functions for each phase since the generic functions are clear enough. Adding the functions would make the module unnecessarily long since there're 5 possible status phases (which means 10 extra functions).

Waiting for you comments 😊

}
106 changes: 106 additions & 0 deletions modules/k8s/persistent_volume_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//go:build kubeall || kubernetes
// +build kubeall kubernetes

// NOTE: we have build tags to differentiate kubernetes tests from non-kubernetes tests. This is done because minikube
kaisoz marked this conversation as resolved.
Show resolved Hide resolved
// is heavy and can interfere with docker related tests in terratest. Specifically, many of the tests start to fail with
// `connection refused` errors from `minikube`. To avoid overloading the system, we run the kubernetes tests and helm
// tests separately from the others. This may not be necessary if you have a sufficiently powerful machine. We
// recommend at least 4 cores and 16GB of RAM if you want to run all the tests together.

package k8s

import (
"fmt"
"strings"
"testing"
"time"

"github.com/stretchr/testify/require"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
_ "k8s.io/client-go/plugin/pkg/client/auth"

"github.com/gruntwork-io/terratest/modules/random"
)

func TestListPersistentVolumesReturnsAllPersistentVolumes(t *testing.T) {
t.Parallel()

numPvFound := 0
pvNames := map[string]struct{}{
strings.ToLower(random.UniqueId()): {},
strings.ToLower(random.UniqueId()): {},
strings.ToLower(random.UniqueId()): {},
}

options := NewKubectlOptions("", "", "")
for pvName := range pvNames {
pv := fmt.Sprintf(PvFixtureYamlTemplate, pvName, pvName)
defer KubectlDeleteFromString(t, options, pv)
KubectlApplyFromString(t, options, pv)
}

pvs := ListPersistentVolumes(t, options, metav1.ListOptions{})
for _, pv := range pvs {
if _, ok := pvNames[pv.Name]; ok {
numPvFound++
}
}

require.Equal(t, numPvFound, len(pvNames))
}

func TestListPersistentVolumesReturnsZeroPersistentVolumesIfNoneCreated(t *testing.T) {
t.Parallel()

options := NewKubectlOptions("", "", "")
pvs := ListPersistentVolumes(t, options, metav1.ListOptions{})
require.Equal(t, 0, len(pvs))
}

func TestGetPersistentVolumeEReturnsErrorForNonExistentPersistentVolumes(t *testing.T) {
t.Parallel()

options := NewKubectlOptions("", "", "")
_, err := GetPersistentVolumeE(t, options, "non-existent")
require.Error(t, err)
}

func TestGetPersistentVolumeReturnsCorrectPersistentVolume(t *testing.T) {
t.Parallel()

pvName := strings.ToLower(random.UniqueId())
options := NewKubectlOptions("", "", "")
configData := fmt.Sprintf(PvFixtureYamlTemplate, pvName, pvName)
defer KubectlDeleteFromString(t, options, configData)
KubectlApplyFromString(t, options, configData)

pv := GetPersistentVolume(t, options, pvName)
require.Equal(t, pv.Name, pvName)
}

func TestWaitUntilPersistentVolumeAvailable(t *testing.T) {
t.Parallel()

pvName := strings.ToLower(random.UniqueId())
options := NewKubectlOptions("", "", pvName)
configData := fmt.Sprintf(PvFixtureYamlTemplate, pvName, pvName)
KubectlApplyFromString(t, options, configData)
defer KubectlDeleteFromString(t, options, configData)

WaitUntilPersistentVolumeAvailable(t, options, pvName, 60, 1*time.Second)
}

const PvFixtureYamlTemplate = `---
apiVersion: v1
kind: PersistentVolume
metadata:
name: %s
spec:
capacity:
storage: 10Mi
accessModes:
- ReadWriteOnce
hostPath:
path: "/tmp/%s"
`