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(containers): add scaling_option block #2876

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
5 changes: 5 additions & 0 deletions docs/data-sources/container.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ In addition to all arguments above, the following attributes are exported:
- `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).
- `sandbox` - (Optional) Execution environment of the container.
- `scaling_option` - Configuration block used to decide when to scale up or down. Possible values:
- `concurrent_requests_threshold` - Scale depending on the number of concurrent requests being processed per container instance.
- `cpu_usage_threshold` - Scale depending on the CPU usage of a container instance.
- `memory_usage_threshold`- Scale depending on the memory usage of a container instance.

- `status` - The container status.

Expand Down
29 changes: 28 additions & 1 deletion docs/resources/container.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ The following arguments are supported:
- `failure_threshold` - Number of consecutive health check failures before considering the container unhealthy.
- `interval`- Period between health checks (in seconds).

- `scaling_option` - (Optional) Configuration block used to decide when to scale up or down. Possible values:
- `concurrent_requests_threshold` - Scale depending on the number of concurrent requests being processed per container instance.
- `cpu_usage_threshold` - Scale depending on the CPU usage of a container instance.
- `memory_usage_threshold`- Scale depending on the memory usage of a container instance.

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

- `deploy` - (Optional) Boolean indicating whether the container is in a production environment.
Expand Down Expand Up @@ -188,4 +193,26 @@ resource scaleway_container main {

~>**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.
Refer to the [Serverless Containers pricing](https://www.scaleway.com/en/docs/faq/serverless-containers/#prices) for more information.

## Scaling option configuration

Scaling option block configuration allows you to choose which parameter will scale up/down containers.
Options are number of concurrent requests, CPU or memory usage.
It replaces current `max_concurrency` that has been deprecated.

Example:

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

scaling_option {
concurrent_requests_threshold = 15
}
}
```

~>**Important**: A maximum of one of these parameters may be set. Also, when `cpu_usage_threshold` or `memory_usage_threshold` are used, `min_scale` can't be set to 0.
Refer to the [API Reference](https://www.scaleway.com/en/developers/api/serverless-containers/#path-containers-create-a-new-container) for more information.
38 changes: 38 additions & 0 deletions internal/services/container/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ func ResourceContainer() *schema.Resource {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Deprecated: "Use scaling_option.concurrent_requests_threshold instead. This attribute will be removed.",
Description: "The maximum the number of simultaneous requests your container can handle at the same time.",
ValidateFunc: validation.IntAtMost(containerMaxConcurrencyLimit),
},
Expand Down Expand Up @@ -209,6 +210,31 @@ func ResourceContainer() *schema.Resource {
},
},
},
"scaling_option": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "Configuration used to decide when to scale up or down.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"concurrent_requests_threshold": {
Type: schema.TypeInt,
Description: "Scale depending on the number of concurrent requests being processed per container instance.",
Optional: true,
},
"cpu_usage_threshold": {
Type: schema.TypeInt,
Description: "Scale depending on the CPU usage of a container instance.",
Optional: true,
},
"memory_usage_threshold": {
Type: schema.TypeInt,
Description: "Scale depending on the memory usage of a container instance.",
Optional: true,
},
},
},
},
// computed
"status": {
Type: schema.TypeString,
Expand Down Expand Up @@ -323,6 +349,7 @@ func ResourceContainerRead(ctx context.Context, d *schema.ResourceData, m interf
_ = d.Set("http_option", co.HTTPOption)
_ = d.Set("sandbox", co.Sandbox)
_ = d.Set("health_check", flattenHealthCheck(co.HealthCheck))
_ = d.Set("scaling_option", flattenScalingOption(co.ScalingOption))
_ = d.Set("region", co.Region.String())

return nil
Expand Down Expand Up @@ -429,6 +456,17 @@ func ResourceContainerUpdate(ctx context.Context, d *schema.ResourceData, m inte
req.HealthCheck = healthCheckReq
}

if d.HasChanges("scaling_option") {
scalingOption := d.Get("scaling_option")

scalingOptionReq, err := expandScalingOptions(scalingOption)
if err != nil {
return diag.FromErr(err)
}

req.ScalingOption = scalingOptionReq
}

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

func TestAccDataSourceContainer_ScalingOption(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 scaling_option block.
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.0.concurrent_requests_threshold", "50"),
resource.TestCheckResourceAttr("data.scaleway_container.main", "scaling_option.#", "1"),
resource.TestCheckResourceAttr("data.scaleway_container.main", "scaling_option.0.concurrent_requests_threshold", "50"),
),
},
},
})
}
89 changes: 89 additions & 0 deletions internal/services/container/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,95 @@ func TestAccContainer_HealthCheck(t *testing.T) {
})
}

func TestAccContainer_ScalingOption(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 scaling_option block.
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.0.concurrent_requests_threshold", "50"),
),
},
{
Config: `
resource scaleway_container_namespace main {}

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

scaling_option {
concurrent_requests_threshold = 15
}
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.0.concurrent_requests_threshold", "15"),
),
},
{
Config: `
resource scaleway_container_namespace main {}

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

min_scale = 1

scaling_option {
cpu_usage_threshold = 72
}
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.#", "1"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.0.cpu_usage_threshold", "72"),
),
},

{
Config: `
resource scaleway_container_namespace main {}

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

min_scale = 1

scaling_option {
memory_usage_threshold = 66
}
}
`,
Check: resource.ComposeTestCheckFunc(
isContainerPresent(tt, "scaleway_container.main"),
resource.TestCheckResourceAttr("scaleway_container.main", "scaling_option.0.memory_usage_threshold", "66"),
),
},
},
})
}

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

if scalingOption, ok := d.GetOk("scaling_option"); ok {
scalingOptionReq, err := expandScalingOptions(scalingOption)
if err != nil {
return nil, err
}

req.ScalingOption = scalingOptionReq
}

return req, nil
}

Expand Down Expand Up @@ -220,6 +229,61 @@ func flattenHealthCheckHTTP(healthCheckHTTP *container.ContainerHealthCheckSpecH
return flattenedHealthCheckHTTP
}

func expandScalingOptions(scalingOptionSchema interface{}) (*container.ContainerScalingOption, error) {
scalingOption, ok := scalingOptionSchema.(*schema.Set)
if !ok {
return &container.ContainerScalingOption{}, nil
}

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

setFields := 0

cso := &container.ContainerScalingOption{}
if concurrentRequestThresold, ok := rawOption["concurrent_requests_threshold"].(int); ok && concurrentRequestThresold != 0 {
cso.ConcurrentRequestsThreshold = scw.Uint32Ptr(uint32(concurrentRequestThresold))
setFields++
}

if cpuUsageThreshold, ok := rawOption["cpu_usage_threshold"].(int); ok && cpuUsageThreshold != 0 {
cso.CPUUsageThreshold = scw.Uint32Ptr(uint32(cpuUsageThreshold))
setFields++
}

if memoryUsageThreshold, ok := rawOption["memory_usage_threshold"].(int); ok && memoryUsageThreshold != 0 {
cso.MemoryUsageThreshold = scw.Uint32Ptr(uint32(memoryUsageThreshold))
setFields++
}

if setFields > 1 {
return &container.ContainerScalingOption{}, errors.New("a maximum of one scaling option can be set")
}

return cso, nil
}

return &container.ContainerScalingOption{}, nil
}

func flattenScalingOption(scalingOption *container.ContainerScalingOption) interface{} {
if scalingOption == nil {
return nil
}

flattenedScalingOption := []map[string]interface{}(nil)
flattenedScalingOption = append(flattenedScalingOption, map[string]interface{}{
"concurrent_requests_threshold": types.FlattenUint32Ptr(scalingOption.ConcurrentRequestsThreshold),
"cpu_usage_threshold": types.FlattenUint32Ptr(scalingOption.CPUUsageThreshold),
"memory_usage_threshold": types.FlattenUint32Ptr(scalingOption.MemoryUsageThreshold),
})

return flattenedScalingOption
}

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