Skip to content

Add nested condition block to wait block #1595

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

Merged
merged 3 commits into from
Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
41 changes: 37 additions & 4 deletions manifest/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,25 @@ func GetObjectTypeFromSchema(schema *tfprotov5.Schema) tftypes.Type {
}

for _, b := range schema.Block.BlockTypes {
attrs := map[string]tftypes.Type{}
a := map[string]tftypes.Type{}
for _, att := range b.Block.Attributes {
attrs[att.Name] = att.Type
a[att.Name] = att.Type
}
bm[b.TypeName] = tftypes.List{
ElementType: tftypes.Object{AttributeTypes: attrs},
ElementType: tftypes.Object{AttributeTypes: a},
}

// FIXME we can make this function recursive to handle
// n levels of nested blocks
for _, bb := range b.Block.BlockTypes {
aa := map[string]tftypes.Type{}
for _, att := range bb.Block.Attributes {
aa[att.Name] = att.Type
}
a[bb.TypeName] = tftypes.List{
ElementType: tftypes.Object{AttributeTypes: aa},
}
}
// TODO handle repeated blocks
}

return tftypes.Object{AttributeTypes: bm}
Expand Down Expand Up @@ -124,6 +135,28 @@ func GetProviderResourceSchema() map[string]*tfprotov5.Schema {
MaxItems: 1,
Block: &tfprotov5.SchemaBlock{
Description: "Configure waiter options.",
BlockTypes: []*tfprotov5.SchemaNestedBlock{
{
TypeName: "condition",
Nesting: tfprotov5.SchemaNestedBlockNestingModeList,
MinItems: 0,
Block: &tfprotov5.SchemaBlock{
Attributes: []*tfprotov5.SchemaAttribute{
{
Name: "status",
Type: tftypes.String,
Optional: true,
Description: "The condition status.",
}, {
Name: "type",
Type: tftypes.String,
Optional: true,
Description: "The type of condition.",
},
},
},
},
},
Attributes: []*tfprotov5.SchemaAttribute{
{
Name: "rollout",
Expand Down
19 changes: 13 additions & 6 deletions manifest/provider/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package provider
import (
"context"
"fmt"
"strings"
"time"

"github.com/hashicorp/terraform-plugin-go/tfprotov5"
Expand Down Expand Up @@ -124,18 +125,24 @@ func (s *RawProviderServer) ValidateResourceTypeConfig(ctx context.Context, req
if len(waitBlock) > 0 {
var w map[string]tftypes.Value
waitBlock[0].As(&w)
n := 0
for _, ww := range w {
waiters := []string{}
for k, ww := range w {
if !ww.IsNull() {
n += 1
if k == "condition" {
var cb []tftypes.Value
ww.As(&cb)
if len(cb) == 0 {
continue
}
}
waiters = append(waiters, k)
}
}
if n > 1 {

if len(waiters) > 1 {
resp.Diagnostics = append(resp.Diagnostics, &tfprotov5.Diagnostic{
Severity: tfprotov5.DiagnosticSeverityError,
Summary: "Invalid wait configuration",
Detail: `Only one of "rollout", "fields" may be set.`,
Detail: fmt.Sprintf(`You may only set one of "%s".`, strings.Join(waiters, "\", \"")),
Attribute: tftypes.NewAttributePath().WithAttributeName("wait"),
})
}
Expand Down
72 changes: 72 additions & 0 deletions manifest/provider/waiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ func NewResourceWaiter(resource dynamic.ResourceInterface, resourceName string,
}
}

if v, ok := waitForBlockVal["condition"]; ok {
var conditionsBlocks []tftypes.Value
v.As(&conditionsBlocks)
if len(conditionsBlocks) > 0 {
return &ConditionsWaiter{
resource,
resourceName,
conditionsBlocks,
hl,
}, nil
}
}

fields, ok := waitForBlockVal["fields"]
if !ok || fields.IsNull() || !fields.IsKnown() {
return &NoopWaiter{}, nil
Expand Down Expand Up @@ -300,3 +313,62 @@ func (w *RolloutWaiter) Wait(ctx context.Context) error {
w.logger.Info("[ApplyResourceChange][Wait] Rollout complete\n")
return nil
}

// ConditionsWaiter will wait for the specified conditions on
// the resource to be met
type ConditionsWaiter struct {
resource dynamic.ResourceInterface
resourceName string
conditions []tftypes.Value
logger hclog.Logger
}

// Wait checks all the configured conditions have been met
func (w *ConditionsWaiter) Wait(ctx context.Context) error {
w.logger.Info("[ApplyResourceChange][Wait] Waiting for conditions...\n")

for {
if deadline, ok := ctx.Deadline(); ok {
if time.Now().After(deadline) {
return context.DeadlineExceeded
}
}

res, err := w.resource.Get(ctx, w.resourceName, v1.GetOptions{})
if err != nil {
return err
}
if errors.IsGone(err) {
return fmt.Errorf("resource was deleted")
}

status := res.Object["status"].(map[string]interface{})
conditions := status["conditions"].([]interface{})
conditionsMet := true
for _, c := range w.conditions {
var condition map[string]tftypes.Value
c.As(&condition)
var conditionType, conditionStatus string
condition["type"].As(&conditionType)
condition["status"].As(&conditionStatus)
conditionMet := false
for _, cc := range conditions {
ccc := cc.(map[string]interface{})
if ccc["type"].(string) == conditionType {
conditionMet = ccc["status"].(string) == conditionStatus
break
}
}
conditionsMet = conditionsMet && conditionMet
}

if conditionsMet {
break
}

time.Sleep(waiterSleepTime) // lintignore:R018
}

w.logger.Info("[ApplyResourceChange][Wait] All conditions met.\n")
return nil
}
51 changes: 51 additions & 0 deletions manifest/test/acceptance/testdata/Wait/wait_for_conditions.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

resource "kubernetes_manifest" "test" {

manifest = {
apiVersion = "v1"
kind = "Pod"

metadata = {
name = var.name
namespace = var.namespace

annotations = {
"test.terraform.io" = "test"
}

labels = {
app = "nginx"
}
}

spec = {
containers = [
{
name = "nginx"
image = "nginx:1.19"

readinessProbe = {
initialDelaySeconds = 10

httpGet = {
path = "/"
port = 80
}
}
}
]
}
}

wait {
condition {
type = "Ready"
status = "True"
}

condition {
type = "ContainersReady"
status = "True"
}
}
}
59 changes: 59 additions & 0 deletions manifest/test/acceptance/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,62 @@ func TestKubernetesManifest_WaitRollout_Deployment(t *testing.T) {
"kubernetes_manifest.wait_for_rollout.wait.0.rollout": true,
})
}

func TestKubernetesManifest_WaitCondition_Pod(t *testing.T) {
ctx := context.Background()

name := randName()
namespace := randName()

reattachInfo, err := provider.ServeTest(ctx, hclog.Default(), t)
if err != nil {
t.Errorf("Failed to create provider instance: %q", err)
}

tf := tfhelper.RequireNewWorkingDir(ctx, t)
tf.SetReattachInfo(ctx, reattachInfo)
defer func() {
tf.Destroy(ctx)
tf.Close()
k8shelper.AssertNamespacedResourceDoesNotExist(t, "v1", "pods", namespace, name)
}()

k8shelper.CreateNamespace(t, namespace)
defer k8shelper.DeleteResource(t, namespace, kubernetes.NewGroupVersionResource("v1", "namespaces"))

tfvars := TFVARS{
"namespace": namespace,
"name": name,
}
tfconfig := loadTerraformConfig(t, "Wait/wait_for_conditions.tf", tfvars)
tf.SetConfig(ctx, tfconfig)
tf.Init(ctx)

startTime := time.Now()
err = tf.Apply(ctx)
if err != nil {
t.Fatalf("Failed to apply: %q", err)
}

k8shelper.AssertNamespacedResourceExists(t, "v1", "pods", namespace, name)

// NOTE We set a readinessProbe in the fixture with a delay of 10s
// so the apply should take at least 10 seconds to complete.
minDuration := time.Duration(10) * time.Second
applyDuration := time.Since(startTime)
if applyDuration < minDuration {
t.Fatalf("the apply should have taken at least %s", minDuration)
}

st, err := tf.State(ctx)
if err != nil {
t.Fatalf("Failed to get state: %q", err)
}
tfstate := tfstatehelper.NewHelper(st)
tfstate.AssertAttributeValues(t, tfstatehelper.AttributeValues{
"kubernetes_manifest.test.wait.0.condition.0.type": "Ready",
"kubernetes_manifest.test.wait.0.condition.0.status": "True",
"kubernetes_manifest.test.wait.0.condition.1.type": "ContainersReady",
"kubernetes_manifest.test.wait.0.condition.1.status": "True",
})
}
Loading