Skip to content

Commit

Permalink
fix: resolve pod creation failure on retry when using `workspace.<nam…
Browse files Browse the repository at this point in the history
…e>.volume`

fix #7886

Change the naming method of the workspace volume from completely random to
hashed, ensuring that the name generated during a single taskRun lifecycle is
consistent each time, and is unique within all current workspaces.

This way, we can reuse the logic of retrieving the taskSpec from the status,
and also store the content after variable expansion in the taskSpec of the
status for easy debugging; it will also not affect the reconstruction of the
pod when retrying.
  • Loading branch information
l-qing authored and tekton-robot committed Apr 25, 2024
1 parent a494d6a commit e556bc7
Show file tree
Hide file tree
Showing 7 changed files with 300 additions and 71 deletions.
19 changes: 19 additions & 0 deletions pkg/names/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ package names

import (
"fmt"
"hash/fnv"
"regexp"
"strconv"
"strings"

utilrand "k8s.io/apimachinery/pkg/util/rand"
)
Expand Down Expand Up @@ -73,3 +76,19 @@ func (simpleNameGenerator) RestrictLength(base string) string {
}
return base
}

// GenerateHashedName creates a unique name with a hashed suffix.
func GenerateHashedName(prefix, name string, hashedLength int) string {
if hashedLength <= 0 {
hashedLength = randomLength
}
h := fnv.New32a()
h.Write([]byte(name))
suffix := strconv.FormatUint(uint64(h.Sum32()), 16)
if ln := len(suffix); ln > hashedLength {
suffix = suffix[:hashedLength]
} else if ln < hashedLength {
suffix += strings.Repeat("0", hashedLength-ln)
}
return fmt.Sprintf("%s-%s", prefix, suffix)
}
61 changes: 61 additions & 0 deletions pkg/names/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,64 @@ func TestRestrictLength(t *testing.T) {
})
}
}

func TestGenerateHashedName(t *testing.T) {
tests := []struct {
title string
prefix string
name string
randomLength int
expectedHashedName string
}{{
title: "generate hashed name with custom random length",
prefix: "ws",
name: "workspace-name",
randomLength: 10,
expectedHashedName: "ws-d70baf7a00",
}, {
title: "generate hashed name with default random length",
prefix: "ws",
name: "workspace-name",
randomLength: -1,
expectedHashedName: "ws-d70ba",
}, {
title: "generate hashed name with empty prefix",
prefix: "",
name: "workspace-name",
randomLength: 0,
expectedHashedName: "-d70ba",
}, {
title: "consistent hashed name for different inputs - 1",
prefix: "ws",
name: "test-01097628",
randomLength: 5,
expectedHashedName: "ws-f32ff",
}, {
title: "consistent hashed name for different inputs - 2",
prefix: "ws",
name: "test-01617609",
randomLength: 5,
expectedHashedName: "ws-f32ff",
}, {
title: "consistent hashed name for different inputs - 3",
prefix: "ws",
name: "test-01675975",
randomLength: 5,
expectedHashedName: "ws-f32ff",
}, {
title: "consistent hashed name for different inputs - 4",
prefix: "ws",
name: "test-01809743",
randomLength: 5,
expectedHashedName: "ws-f32ff",
}}

for _, tc := range tests {
t.Run(tc.title, func(t *testing.T) {
hashedName := pkgnames.GenerateHashedName(tc.prefix, tc.name, tc.randomLength)
if hashedName != tc.expectedHashedName {
t.Errorf("expected %q, got %q", tc.expectedHashedName, hashedName)
}
})
}
}
30 changes: 15 additions & 15 deletions pkg/reconciler/taskrun/resources/apply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1141,29 +1141,29 @@ func TestApplyWorkspaces(t *testing.T) {
EmptyDir: &corev1.EmptyDirVolumeSource{},
}},
want: applyMutation(ts, func(spec *v1.TaskSpec) {
spec.StepTemplate.Env[0].Value = "ws-9l9zj"
spec.StepTemplate.Env[0].Value = "ws-b31db"
spec.StepTemplate.Env[1].Value = "foo"
spec.StepTemplate.Env[2].Value = ""

spec.Steps[0].Name = "ws-9l9zj"
spec.Steps[0].Image = "ws-mz4c7"
spec.Steps[0].WorkingDir = "ws-mz4c7"
spec.Steps[0].Name = "ws-b31db"
spec.Steps[0].Image = "ws-a6f34"
spec.Steps[0].WorkingDir = "ws-a6f34"
spec.Steps[0].Args = []string{"/workspace/myws"}

spec.Steps[1].VolumeMounts[0].Name = "ws-9l9zj"
spec.Steps[1].VolumeMounts[0].Name = "ws-b31db"
spec.Steps[1].VolumeMounts[0].MountPath = "path/to//foo"
spec.Steps[1].VolumeMounts[0].SubPath = "ws-9l9zj"
spec.Steps[1].VolumeMounts[0].SubPath = "ws-b31db"

spec.Steps[2].Env[0].Value = "ws-9l9zj"
spec.Steps[2].Env[1].ValueFrom.SecretKeyRef.LocalObjectReference.Name = "ws-9l9zj"
spec.Steps[2].Env[1].ValueFrom.SecretKeyRef.Key = "ws-9l9zj"
spec.Steps[2].EnvFrom[0].Prefix = "ws-9l9zj"
spec.Steps[2].EnvFrom[0].ConfigMapRef.LocalObjectReference.Name = "ws-9l9zj"
spec.Steps[2].Env[0].Value = "ws-b31db"
spec.Steps[2].Env[1].ValueFrom.SecretKeyRef.LocalObjectReference.Name = "ws-b31db"
spec.Steps[2].Env[1].ValueFrom.SecretKeyRef.Key = "ws-b31db"
spec.Steps[2].EnvFrom[0].Prefix = "ws-b31db"
spec.Steps[2].EnvFrom[0].ConfigMapRef.LocalObjectReference.Name = "ws-b31db"

spec.Volumes[0].Name = "ws-9l9zj"
spec.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name = "ws-9l9zj"
spec.Volumes[1].VolumeSource.Secret.SecretName = "ws-9l9zj"
spec.Volumes[2].VolumeSource.PersistentVolumeClaim.ClaimName = "ws-9l9zj"
spec.Volumes[0].Name = "ws-b31db"
spec.Volumes[0].VolumeSource.ConfigMap.LocalObjectReference.Name = "ws-b31db"
spec.Volumes[1].VolumeSource.Secret.SecretName = "ws-b31db"
spec.Volumes[2].VolumeSource.PersistentVolumeClaim.ClaimName = "ws-b31db"
}),
}, {
name: "optional-workspace-provided-variable-replacement",
Expand Down
8 changes: 4 additions & 4 deletions pkg/reconciler/taskrun/taskrun_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1046,7 +1046,7 @@ spec:
},
wantPod: addVolumeMounts(expectedPod("test-taskrun-with-output-config-ws-pod", "", "test-taskrun-with-output-config-ws", "foo", config.DefaultServiceAccountValue, false,
[]corev1.Volume{{
Name: "ws-9l9zj",
Name: "ws-d872e",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
Expand All @@ -1058,7 +1058,7 @@ spec:
cmd: "/mycmd",
}}),
[]corev1.VolumeMount{{
Name: "ws-9l9zj",
Name: "ws-d872e",
MountPath: "/workspace/data",
}}),
}} {
Expand Down Expand Up @@ -4034,8 +4034,8 @@ spec:
t.Fatalf("create pod threw error %v", err)
}

if vm := pod.Spec.Containers[0].VolumeMounts[0]; !strings.HasPrefix(vm.Name, "ws-9l9zj") || vm.MountPath != expectedMountPath {
t.Fatalf("failed to find expanded Workspace mountpath %v", expectedMountPath)
if vm := pod.Spec.Containers[0].VolumeMounts[0]; !strings.HasPrefix(vm.Name, "ws-f888c") || vm.MountPath != expectedMountPath {
t.Fatalf("failed to find expanded Workspace mountpath %v for %v", expectedMountPath, vm.Name)
}

if a := pod.Spec.Containers[0].Args; a[len(a)-1] != expectedReplacedArgs {
Expand Down
27 changes: 22 additions & 5 deletions pkg/workspace/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ import (
"fmt"

v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1"
"github.com/tektoncd/pipeline/pkg/names"
pkgnames "github.com/tektoncd/pipeline/pkg/names"
"github.com/tektoncd/pipeline/pkg/substitution"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
)

const (
volumeNameBase = "ws"
volumeNameBase = "ws"
defaultRandomLength = 5
)

// nameVolumeMap is a map from a workspace's name to its Volume.
Expand All @@ -42,15 +43,31 @@ func (nvm nameVolumeMap) setVolumeSource(workspaceName string, volumeName string
}
}

// generateVolumeName generates a unique name for a volume based on the workspace name.
func generateVolumeName(name string) string {
return pkgnames.GenerateHashedName(volumeNameBase, name, defaultRandomLength)
}

// CreateVolumes will return a dictionary where the keys are the names of the workspaces bound in
// wb and the value is a newly-created Volume to use. If the same Volume is bound twice, the
// resulting volumes will both have the same name to prevent the same Volume from being attached
// to a pod twice. The names of the returned volumes will be a short random string starting "ws-".
// to a pod twice. The names of the returned volumes will be a short hash string starting "ws-".
func CreateVolumes(wb []v1.WorkspaceBinding) map[string]corev1.Volume {
pvcs := map[string]corev1.Volume{}
v := make(nameVolumeMap)
v := make(nameVolumeMap, len(wb))
// Track the names we've used so far to avoid collisions
usedNames := make(map[string]struct{}, len(wb))

for _, w := range wb {
name := names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(volumeNameBase)
name := generateVolumeName(w.Name)

// If we've already generated this name, try appending extra characters until we find a unique name
for _, exists := usedNames[name]; exists; _, exists = usedNames[name] {
name = generateVolumeName(name + "$")
}
// Track the name we've used
usedNames[name] = struct{}{}

switch {
case w.PersistentVolumeClaim != nil:
// If it's a PVC, we need to check if we've encountered it before so we avoid mounting it twice
Expand Down
Loading

0 comments on commit e556bc7

Please sign in to comment.