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

feat(container/serverless): add health_check block #2878

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
8 changes: 7 additions & 1 deletion docs/data-sources/container.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,13 @@ In addition to all arguments above, the following attributes are exported:

- `deploy` - Boolean indicating whether the container is on a production environment.

- `sandbox` - (Optional) Execution environment of the container.
- `sandbox` - Execution environment of the container.

- `heath_check` - Health check configuration block of the container.
- `http` - HTTP health check configuration.
- `path` - Path to use for the HTTP health check.
- `failure_threshold` - Number of consecutive health check failures before considering the container unhealthy.
- `interval`- Period between health checks (in seconds).

- `status` - The container status.

Expand Down
38 changes: 37 additions & 1 deletion docs/resources/container.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,12 @@ The following arguments are supported:

- `sandbox` - (Optional) Execution environment of the container.

- `heath_check` - (Optional) Health check configuration block of the container.
- `http` - HTTP health check configuration.
- `path` - Path to use for the HTTP health check.
- `failure_threshold` - Number of consecutive health check failures before considering the container unhealthy.
- `interval`- Period between health checks (in seconds).

- `port` - (Optional) The port to expose the container.

- `deploy` - (Optional) Boolean indicating whether the container is in a production environment.
Expand Down Expand Up @@ -152,4 +158,34 @@ The `memory_limit` (in MB) must correspond with the right amount of vCPU. Refer
| 4096 | 2240 |

~>**Important:** Make sure to select the right resources, as you will be billed based on compute usage over time and the number of Containers executions.
Refer to the [Serverless Containers pricing](https://www.scaleway.com/en/docs/faq/serverless-containers/#prices) for more information.
Refer to the [Serverless Containers pricing](https://www.scaleway.com/en/docs/faq/serverless-containers/#prices) for more information.

## Health check configuration

Custom health checks can be configured on the container.

It's possible to specify the HTTP path that the probe will listen to and the number of failures before considering the container as unhealthy.
During a deployment, if a newly created container fails to pass the health check, the deployment is aborted.
As a result, lowering this value can help to reduce the time it takes to detect a failed deployment.
The period between health checks is also configurable.

Example:

```terraform
resource scaleway_container main {
name = "my-container-02"
namespace_id = scaleway_container_namespace.main.id

health_check {
http {
path = "/ping"
}
failure_threshold = 40
interval = "3s"
}
}
```

~>**Important:** Another probe type can be set to TCP with the API, but currently the SDK has not been updated with this parameter.
This is why the only probe that can be used here is the HTTP probe.
Refer to the [API Reference](https://www.scaleway.com/en/developers/api/serverless-containers/#path-containers-create-a-new-container) for more information.
50 changes: 50 additions & 0 deletions internal/services/container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
container "github.com/scaleway/scaleway-sdk-go/api/container/v1beta1"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/dsf"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/httperrors"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality"
"github.com/scaleway/terraform-provider-scaleway/v2/internal/locality/regional"
Expand Down Expand Up @@ -170,6 +171,44 @@ func ResourceContainer() *schema.Resource {
Description: "Execution environment of the container.",
ValidateDiagFunc: verify.ValidateEnum[container.ContainerSandbox](),
},
"health_check": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "Health check configuration of the container.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
// TCP has not been implemented yet in the API SDK, that's why the parameter is not in the schema.
// See container.ContainerHealthCheckSpecTCPProbe.
"http": {
Type: schema.TypeSet,
Description: "HTTP health check configuration.",
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"path": {
Type: schema.TypeString,
Description: "Path to use for the HTTP health check.",
Required: true,
},
},
},
},
"failure_threshold": {
Type: schema.TypeInt,
Description: "Number of consecutive health check failures before considering the container unhealthy.",
Required: true,
},
"interval": {
Type: schema.TypeString,
Description: "Period between health checks.",
DiffSuppressFunc: dsf.Duration,
ValidateDiagFunc: verify.IsDuration(),
Required: true,
},
},
},
},
// computed
"status": {
Type: schema.TypeString,
Expand Down Expand Up @@ -280,6 +319,7 @@ func ResourceContainerRead(ctx context.Context, d *schema.ResourceData, m interf
_ = d.Set("deploy", scw.BoolPtr(*types.ExpandBoolPtr(d.Get("deploy"))))
_ = d.Set("http_option", co.HTTPOption)
_ = d.Set("sandbox", co.Sandbox)
_ = d.Set("health_check", flattenHealthCheck(co.HealthCheck))
_ = d.Set("region", co.Region.String())

return nil
Expand Down Expand Up @@ -375,6 +415,16 @@ func ResourceContainerUpdate(ctx context.Context, d *schema.ResourceData, m inte
req.Sandbox = container.ContainerSandbox(d.Get("sandbox").(string))
}

if d.HasChanges("health_check") {
healthCheck := d.Get("health_check")

healthCheckReq, errExpandHealthCheck := expandHealthCheck(healthCheck)
if errExpandHealthCheck != nil {
return diag.FromErr(errExpandHealthCheck)
}
req.HealthCheck = healthCheckReq
}

imageHasChanged := d.HasChanges("registry_sha256")
if imageHasChanged {
req.Redeploy = &imageHasChanged
Expand Down
38 changes: 38 additions & 0 deletions internal/services/container/container_data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,41 @@ func TestAccDataSourceContainer_Basic(t *testing.T) {
},
})
}

func TestAccDataSourceContainer_HealthCheck(t *testing.T) {
tt := acctest.NewTestTools(t)
defer tt.Cleanup()

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: isNamespaceDestroyed(tt),
Steps: []resource.TestStep{
{
Config: `
resource scaleway_container_namespace main {}

resource scaleway_container main {
namespace_id = scaleway_container_namespace.main.id
deploy = false
}

data scaleway_container main {
namespace_id = scaleway_container_namespace.main.id
container_id = scaleway_container.main.id
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
// Check default option returned by the API when you don't specify the health_check block.
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.failure_threshold", "30"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.interval", "10s"),
resource.TestCheckResourceAttr("data.scaleway_container.main", "health_check.#", "1"),
resource.TestCheckResourceAttr("data.scaleway_container.main", "health_check.0.failure_threshold", "30"),
resource.TestCheckResourceAttr("data.scaleway_container.main", "health_check.0.interval", "10s"),
),
},
},
})
}
54 changes: 54 additions & 0 deletions internal/services/container/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,60 @@ func TestAccContainer_Sandbox(t *testing.T) {
})
}

func TestAccContainer_HealthCheck(t *testing.T) {
tt := acctest.NewTestTools(t)
defer tt.Cleanup()
resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(t) },
ProviderFactories: tt.ProviderFactories,
CheckDestroy: isContainerDestroyed(tt),
Steps: []resource.TestStep{
{
Config: `
resource scaleway_container_namespace main {}

resource scaleway_container main {
namespace_id = scaleway_container_namespace.main.id
deploy = false
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
// Check default option returned by the API when you don't specify the health_check block.
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.failure_threshold", "30"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.interval", "10s"),
),
},
{
Config: `
resource scaleway_container_namespace main {}

resource scaleway_container main {
namespace_id = scaleway_container_namespace.main.id
deploy = false

health_check {
http {
path = "/test"
}
failure_threshold = 40
interval = "12s"
}
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.http.0.path", "/test"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.failure_threshold", "40"),
resource.TestCheckResourceAttr("scaleway_container.main", "health_check.0.interval", "12s"),
),
},
},
})
}

func isContainerPresent(tt *acctest.TestTools, n string) resource.TestCheckFunc {
return func(state *terraform.State) error {
rs, ok := state.RootModule().Resources[n]
Expand Down
98 changes: 98 additions & 0 deletions internal/services/container/helpers_container.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,107 @@ func setCreateContainerRequest(d *schema.ResourceData, region scw.Region) (*cont
req.Sandbox = container.ContainerSandbox(sandbox.(string))
}

if healthCheck, ok := d.GetOk("health_check"); ok {
healthCheckReq, errExpandHealthCheck := expandHealthCheck(healthCheck)
if errExpandHealthCheck != nil {
return nil, errExpandHealthCheck
}
req.HealthCheck = healthCheckReq
}

return req, nil
}

func expandHealthCheck(healthCheckSchema interface{}) (*container.ContainerHealthCheckSpec, error) {
healthCheck, ok := healthCheckSchema.(*schema.Set)
if !ok {
return &container.ContainerHealthCheckSpec{}, nil
}

for _, option := range healthCheck.List() {
rawOption, isRawOption := option.(map[string]interface{})
if !isRawOption {
continue
}

healthCheckSpec := &container.ContainerHealthCheckSpec{}
if http, ok := rawOption["http"].(*schema.Set); ok {
healthCheckSpec.HTTP = expendHealthCheckHTTP(http)
}

// Failure threshold is a required field and will be checked by TF.
healthCheckSpec.FailureThreshold = uint32(rawOption["failure_threshold"].(int))

if interval, ok := rawOption["interval"]; ok {
duration, err := types.ExpandDuration(interval)
if err != nil {
return nil, err
}
healthCheckSpec.Interval = scw.NewDurationFromTimeDuration(*duration)
}

return healthCheckSpec, nil
}

return &container.ContainerHealthCheckSpec{}, nil
}

func expendHealthCheckHTTP(healthCheckHTTPSchema interface{}) *container.ContainerHealthCheckSpecHTTPProbe {
healthCheckHTTP, ok := healthCheckHTTPSchema.(*schema.Set)
if !ok {
return &container.ContainerHealthCheckSpecHTTPProbe{}
}

for _, option := range healthCheckHTTP.List() {
rawOption, isRawOption := option.(map[string]interface{})
if !isRawOption {
continue
}

httpProbe := &container.ContainerHealthCheckSpecHTTPProbe{}
if path, ok := rawOption["path"].(string); ok {
httpProbe.Path = path
}

return httpProbe
}

return &container.ContainerHealthCheckSpecHTTPProbe{}
}

func flattenHealthCheck(healthCheck *container.ContainerHealthCheckSpec) interface{} {
if healthCheck == nil {
return nil
}

var interval *time.Duration
if healthCheck.Interval != nil {
interval = healthCheck.Interval.ToTimeDuration()
}

flattenedHealthCheck := []map[string]interface{}(nil)
flattenedHealthCheck = append(flattenedHealthCheck, map[string]interface{}{
"http": flattenHealthCheckHTTP(healthCheck.HTTP),
"failure_threshold": types.FlattenUint32Ptr(&healthCheck.FailureThreshold),
"interval": types.FlattenDuration(interval),
})

return flattenedHealthCheck
}

func flattenHealthCheckHTTP(healthCheckHTTP *container.ContainerHealthCheckSpecHTTPProbe) interface{} {
if healthCheckHTTP == nil {
return nil
}

flattenedHealthCheckHTTP := []map[string]interface{}(nil)
flattenedHealthCheckHTTP = append(flattenedHealthCheckHTTP, map[string]interface{}{
"path": types.FlattenStringPtr(&healthCheckHTTP.Path),
})

return flattenedHealthCheckHTTP
}

func expandContainerSecrets(secretsRawMap interface{}) []*container.Secret {
secretsMap := secretsRawMap.(map[string]interface{})
secrets := make([]*container.Secret, 0, len(secretsMap))
Expand Down
Loading
Loading