refactor: move VolumeRequest validation to Validate method

This commit is contained in:
Tim Gross
2021-04-06 13:54:53 -04:00
committed by Tim Gross
parent 144239600d
commit 0c51bb02dd
3 changed files with 36 additions and 18 deletions

View File

@@ -6189,20 +6189,14 @@ func (tg *TaskGroup) Validate(j *Job) error {
}
// Validate the volume requests
for name, decl := range tg.Volumes {
if !(decl.Type == VolumeTypeHost ||
decl.Type == VolumeTypeCSI) {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Volume %s has unrecognised type %s", name, decl.Type))
continue
}
if decl.PerAlloc && tg.Update != nil && tg.Update.Canary > 0 {
mErr.Errors = append(mErr.Errors,
fmt.Errorf("Volume %s cannot be per_alloc when canaries are in use", name))
}
if decl.Source == "" {
mErr.Errors = append(mErr.Errors, fmt.Errorf("Volume %s has an empty source", name))
var canaries int
if tg.Update != nil {
canaries = tg.Update.Canary
}
for name, volReq := range tg.Volumes {
if err := volReq.Validate(canaries); err != nil {
mErr.Errors = append(mErr.Errors, fmt.Errorf(
"Task group volume validation for %s failed: %v", name, err))
}
}

View File

@@ -1088,7 +1088,7 @@ func TestTaskGroup_Validate(t *testing.T) {
},
}
err = tg.Validate(&Job{})
require.Contains(t, err.Error(), `Volume foo has unrecognised type nothost`)
require.Contains(t, err.Error(), `volume has unrecognised type nothost`)
tg = &TaskGroup{
Volumes: map[string]*VolumeRequest{
@@ -1104,7 +1104,7 @@ func TestTaskGroup_Validate(t *testing.T) {
},
}
err = tg.Validate(&Job{})
require.Contains(t, err.Error(), `Volume foo has an empty source`)
require.Contains(t, err.Error(), `volume has an empty source`)
tg = &TaskGroup{
Name: "group-a",
@@ -1125,8 +1125,8 @@ func TestTaskGroup_Validate(t *testing.T) {
},
}
err = tg.Validate(&Job{})
require.Contains(t, err.Error(), `Volume foo has an empty source`)
require.Contains(t, err.Error(), `Volume foo cannot be per_alloc when canaries are in use`)
require.Contains(t, err.Error(), `volume has an empty source`)
require.Contains(t, err.Error(), `volume cannot be per_alloc when canaries are in use`)
tg = &TaskGroup{
Volumes: map[string]*VolumeRequest{

View File

@@ -1,5 +1,11 @@
package structs
import (
"fmt"
multierror "github.com/hashicorp/go-multierror"
)
const (
VolumeTypeHost = "host"
)
@@ -94,6 +100,24 @@ type VolumeRequest struct {
PerAlloc bool
}
func (v *VolumeRequest) Validate(canaries int) error {
if !(v.Type == VolumeTypeHost ||
v.Type == VolumeTypeCSI) {
return fmt.Errorf("volume has unrecognised type %s", v.Type)
}
var mErr multierror.Error
if v.PerAlloc && canaries > 0 {
mErr.Errors = append(mErr.Errors,
fmt.Errorf("volume cannot be per_alloc when canaries are in use"))
}
if v.Source == "" {
mErr.Errors = append(mErr.Errors, fmt.Errorf("volume has an empty source"))
}
return mErr.ErrorOrNil()
}
func (v *VolumeRequest) Copy() *VolumeRequest {
if v == nil {
return nil