Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(fleets): make pool sizing modes exclusive (#6724)

r33drichards287f98780b72
diff --git a/libs/fleet/terraform-provider-fleets/MIGRATION.md b/libs/fleet/terraform-provider-fleets/MIGRATION.md
index dc83632906..632d20a429 100644
--- a/libs/fleet/terraform-provider-fleets/MIGRATION.md
+++ b/libs/fleet/terraform-provider-fleets/MIGRATION.md
@@ -4,10 +4,11 @@
APIs and OAuth environment variables remain unchanged. `fleets_pool` now backs
each pool with the native `osgym.cua.ai/v1alpha1` CRDs — an
`OSGymSandboxWarmPool` and the `OSGymSandboxTemplate` it references — in place
-of the removed legacy pool CRD. The resource arguments are unchanged; the
-`phase`, `total_count`, `available_count`, and `claimed_count` attributes it
-used to export are replaced by `template_name`, `current_replicas`, and
-`ready_replicas`.
+of the removed legacy pool CRD. Apart from the pool sizing-mode change
+described below, the resource arguments for this Cyclops-to-Fleets migration
+are unchanged; the `phase`, `total_count`, `available_count`, and
+`claimed_count` attributes it used to export are replaced by `template_name`,
+`current_replicas`, and `ready_replicas`.
| Previous surface | Fleets surface | Migration |
| --- | --- | --- |
@@ -23,3 +24,25 @@ the old provider address, run `terraform state replace-provider
registry.terraform.io/trycua/cyclops registry.terraform.io/trycua/fleets`
before planning. Back up state and review the plan before applying either
command.
+
+## Choosing a pool sizing mode
+
+New provider releases require exactly one of `replicas` or `autoscaling`.
+Existing autoscaled configurations that set both must remove `replicas`:
+
+```terraform
+resource "fleets_pool" "linux" {
+ # replicas = 0 # remove this line
+
+ autoscaling {
+ min_pool_size = 0
+ initial_pool_size = 1
+ max_pool_size = 5
+ }
+}
+```
+
+Static pools keep `replicas` and omit `autoscaling`. In autoscaling mode, do
+not configure `replicas`; it reports the current pool target after apply and
+refresh. Review the plan before changing modes because switching to static sets
+the pool to the configured `replicas` value.
diff --git a/libs/fleet/terraform-provider-fleets/docs/resources/pool.md b/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
index 24a53512a5..946434fdeb 100644
--- a/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
+++ b/libs/fleet/terraform-provider-fleets/docs/resources/pool.md
@@ -8,32 +8,39 @@ description: |-
Creates an `OSGymSandboxWarmPool`, the `OSGymSandboxTemplate` it references (named `<pool>-template`), and their same-named namespace. Destroy removes all three. Import IDs are pool names.
+## Static pool
+
```terraform
-resource "fleets_pool" "linux" {
- name = "training-linux"
+resource "fleets_pool" "linux_static" {
+ name = "training-linux-static"
replicas = 3
cpu_cores = 4
memory = "8Gi"
container_disk_image = "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest"
+}
+```
+
+## Autoscaled pool
+
+```terraform
+resource "fleets_pool" "linux_autoscaled" {
+ name = "training-linux-autoscaled"
+ cpu_cores = 4
+ memory = "8Gi"
+ container_disk_image = "296062593712.dkr.ecr.us-west-2.amazonaws.com/osgym-workspace:latest"
autoscaling {
min_pool_size = 0
initial_pool_size = 3
max_pool_size = 20
}
-
- service {
- name = "ssh"
- target_port = 22
- protocol = "TCP"
- }
}
```
## Arguments
- `name` - Pool and namespace DNS label. Changing it replaces the resource.
-- `replicas` - Desired warm pool size.
+- `replicas` - Static desired warm pool size. Exactly one of `replicas` or `autoscaling` must be configured. In autoscaling mode, do not configure it; after apply and refresh it reports the current pool target.
- `cpu_cores` - Virtual CPUs per sandbox.
- `memory` - Kubernetes memory quantity per sandbox.
- `container_disk_image` - OCI containerDisk or runtime image.
@@ -42,11 +49,14 @@ resource "fleets_pool" "linux" {
- `firmware` - `bios` or `efi`; defaults to `bios`.
- `readiness_probe_json` / `liveness_probe_json` - Kubernetes probe objects encoded as JSON.
- `service` - Repeatable service with `name`, `target_port`, and optional `protocol`.
-- `autoscaling` - Optional claim-driven autoscaling limits.
+- `autoscaling` - Claim-driven autoscaling limits. Exactly one of `replicas` or `autoscaling` is required.
+- `autoscaling.min_pool_size` - Minimum warm pool size while autoscaling is enabled.
+- `autoscaling.initial_pool_size` - Initial pool target when autoscaling starts.
+- `autoscaling.max_pool_size` - Maximum autoscaled pool size; defaults to `50` when omitted.
## Read-only Attributes
-`namespace` and `template_name` identify the objects Fleet created. `current_replicas` and `ready_replicas` are the warm pool's `status.replicas` and `status.readyReplicas`.
+`namespace` and `template_name` identify the objects Fleet created. In autoscaling mode, `replicas` reports the current pool target so scaling changes remain visible in Terraform state. `current_replicas` and `ready_replicas` report the number of current and ready sandboxes.
## Import
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json b/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
index d27aee77c3..8d90bcb323 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/generate/pool_mapping.json
@@ -26,7 +26,7 @@
"name": "replicas",
"go_name": "Replicas",
"value_type": "int64",
- "mode": "required",
+ "mode": "optional_computed",
"cr": "warmpool",
"crd_path": "spec.replicas"
},
@@ -182,7 +182,7 @@
"name": "max_pool_size",
"go_name": "MaxPoolSize",
"value_type": "int64",
- "mode": "required",
+ "mode": "optional_computed",
"crd_path": "maxPoolSize"
}
],
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
index 008c467f31..dab6da2b3e 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_generated.go
@@ -54,7 +54,7 @@ func poolResourceSchema() schema.Schema {
"id": schema.StringAttribute{Computed: true},
"name": schema.StringAttribute{Required: true, Description: "DNS label used for both pool and namespace.", Validators: []validator.String{stringvalidator.LengthBetween(1, 63), stringvalidator.RegexMatches(dnsLabelRegex, "must be a lowercase DNS label")}, PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()}},
"namespace": schema.StringAttribute{Computed: true},
- "replicas": schema.Int64Attribute{Required: true, Description: "Desired number of pre-warmed OSGymSandboxes.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
+ "replicas": schema.Int64Attribute{Optional: true, Computed: true, Description: "Desired number of pre-warmed OSGymSandboxes.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
"cpu_cores": schema.Int64Attribute{Required: true, Validators: []validator.Int64{int64validator.AtLeast(1)}},
"memory": schema.StringAttribute{Required: true},
"container_disk_image": schema.StringAttribute{Required: true, Description: "KubeVirt containerDisk OCI image (runtime=kubevirt) or the sandbox pod image ref (runtime=macos/gvisor)."},
@@ -76,7 +76,7 @@ func poolResourceSchema() schema.Schema {
"autoscaling": schema.SingleNestedBlock{Attributes: map[string]schema.Attribute{
"min_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "ScaledObject minReplicaCount — the durable warm\nfloor kept while the extension is enabled. 0 lets\nthe pool scale to zero when there are no claims.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
"initial_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "One-time warm head-start: the pool-operator seeds\nspec.replicas to this when the pool is created so\nthe first claims bind without a cold start. KEDA\nthen owns spec.replicas; the value decays toward\nthe live claim demand (floored at minPoolSize)\nonce KEDA begins polling.", Validators: []validator.Int64{int64validator.AtLeast(0)}},
- "max_pool_size": schema.Int64Attribute{Required: true, Description: "ScaledObject maxReplicaCount — hard ceiling.", Validators: []validator.Int64{int64validator.AtLeast(1)}},
+ "max_pool_size": schema.Int64Attribute{Optional: true, Computed: true, Description: "ScaledObject maxReplicaCount — hard ceiling.", Validators: []validator.Int64{int64validator.AtLeast(1)}},
}},
},
}
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
index 95a55492a3..2eb21fc840 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource.go
@@ -23,11 +23,21 @@ import (
// OSGymSandboxTemplate it references, both named after the pool.
const templateNameSuffix = "-template"
+const defaultMaxPoolSize uint32 = 50
+
+const (
+ poolScalingModeDiagnosticSummary = "Invalid pool scaling configuration"
+ poolScalingModeExactlyOneMessage = "exactly one of replicas or autoscaling must be configured"
+ poolScalingModeUnknownAtApplyMessage = "replicas and autoscaling must be known before apply"
+)
+
type poolResource struct {
client *fleet_sdk.CyclopsClient
legacyType bool
}
+var _ resource.ResourceWithValidateConfig = (*poolResource)(nil)
+
func NewPoolResource() resource.Resource { return &poolResource{} }
func NewLegacyPoolResource() resource.Resource { return &poolResource{legacyType: true} }
@@ -54,12 +64,67 @@ func (r *poolResource) Configure(_ context.Context, req resource.ConfigureReques
r.client = apiClient
}
+func (r *poolResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
+ var config poolResourceModel
+ resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
+ if resp.Diagnostics.HasError() {
+ return
+ }
+ if err := validatePoolScalingModeDuringPlan(config); err != nil {
+ addPoolScalingModeDiagnostic(&resp.Diagnostics, err)
+ }
+}
+
+func validatePoolScalingModeDuringPlan(config poolResourceModel) error {
+ if config.Replicas.IsUnknown() || config.Autoscaling.IsUnknown() {
+ return nil
+ }
+ if config.Replicas.IsNull() == config.Autoscaling.IsNull() {
+ return errors.New(poolScalingModeExactlyOneMessage)
+ }
+ return nil
+}
+
+func validatePoolScalingModeAtApply(config, plan poolResourceModel) error {
+ replicasPresent, replicasKnown := resolvedConfigurationPresence(config.Replicas, plan.Replicas)
+ autoscalingPresent, autoscalingKnown := resolvedConfigurationPresence(config.Autoscaling, plan.Autoscaling)
+ if !replicasKnown || !autoscalingKnown {
+ return errors.New(poolScalingModeUnknownAtApplyMessage)
+ }
+ if replicasPresent == autoscalingPresent {
+ return errors.New(poolScalingModeExactlyOneMessage)
+ }
+ return nil
+}
+
+func resolvedConfigurationPresence(config, plan attr.Value) (present, known bool) {
+ if config.IsNull() {
+ return false, true
+ }
+ if !config.IsUnknown() {
+ return true, true
+ }
+ if plan.IsUnknown() {
+ return false, false
+ }
+ return !plan.IsNull(), true
+}
+
+func addPoolScalingModeDiagnostic(diagnostics *diag.Diagnostics, err error) {
+ diagnostics.AddError(poolScalingModeDiagnosticSummary, err.Error())
+}
+
func (r *poolResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
- var plan poolResourceModel
+ var config, plan poolResourceModel
+ resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
+ if err := validatePoolScalingModeAtApply(config, plan); err != nil {
+ addPoolScalingModeDiagnostic(&resp.Diagnostics, err)
+ return
+ }
poolRequest := plan.toSDKCreatePoolRequest(ctx, &resp.Diagnostics)
templateRequest := plan.toSDKCreateTemplateRequest(ctx, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
@@ -118,8 +183,16 @@ func (r *poolResource) Read(ctx context.Context, req resource.ReadRequest, resp
}
func (r *poolResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
- var plan, state poolResourceModel
+ var config, plan, state poolResourceModel
+ resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
+ if resp.Diagnostics.HasError() {
+ return
+ }
+ if err := validatePoolScalingModeAtApply(config, plan); err != nil {
+ addPoolScalingModeDiagnostic(&resp.Diagnostics, err)
+ return
+ }
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
@@ -223,18 +296,23 @@ func (m poolResourceModel) toSDKPool(ctx context.Context, diagnostics *diag.Diag
}
func (m poolResourceModel) toSDKPoolSpec(ctx context.Context, diagnostics *diag.Diagnostics) cyclops_sdk_schema.OsGymSandboxWarmPoolSpec {
+ replicas := uint32(m.Replicas.ValueInt64())
var autoscaling *cyclops_sdk_schema.WarmPoolAutoscaling
var autoscalingValue autoscalingModel
if objectValue(ctx, m.Autoscaling, &autoscalingValue, diagnostics) {
minPoolSize := uint32(autoscalingValue.MinPoolSize.ValueInt64())
initialPoolSize := uint32(autoscalingValue.InitialPoolSize.ValueInt64())
- maxPoolSize := uint32(autoscalingValue.MaxPoolSize.ValueInt64())
+ maxPoolSize := defaultMaxPoolSize
+ if !autoscalingValue.MaxPoolSize.IsNull() && !autoscalingValue.MaxPoolSize.IsUnknown() {
+ maxPoolSize = uint32(autoscalingValue.MaxPoolSize.ValueInt64())
+ }
autoscaling = &cyclops_sdk_schema.WarmPoolAutoscaling{
MinPoolSize: &minPoolSize, InitialPoolSize: &initialPoolSize, MaxPoolSize: &maxPoolSize,
}
+ replicas = initialPoolSize
}
return cyclops_sdk_schema.OsGymSandboxWarmPoolSpec{
- Replicas: uint32(m.Replicas.ValueInt64()),
+ Replicas: replicas,
SandboxTemplateRef: cyclops_sdk_schema.SandboxTemplateRef{Name: m.templateName()},
Autoscaling: autoscaling,
}
@@ -336,8 +414,8 @@ func (m *poolResourceModel) fromSDKPool(pool fleet_sdk.Pool, diagnostics *diag.D
m.ID = types.StringValue(pool.Metadata.Name)
m.Name = types.StringValue(pool.Metadata.Name)
m.Namespace = types.StringValue(pool.Metadata.Namespace)
- m.Replicas = types.Int64Value(int64(pool.Spec.Replicas))
m.TemplateName = types.StringValue(pool.Spec.SandboxTemplateRef.Name)
+ m.Replicas = types.Int64Value(int64(pool.Spec.Replicas))
if pool.Spec.Autoscaling == nil {
m.Autoscaling = types.ObjectNull(autoscalingObjectType())
} else {
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
index 68318d0d1b..d101be28a7 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_resource_acc_test.go
@@ -10,13 +10,17 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "regexp"
"strings"
+ "sync/atomic"
"testing"
"github.com/hashicorp/terraform-plugin-framework/providerserver"
"github.com/hashicorp/terraform-plugin-go/tfprotov6"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
+ "github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/hashicorp/terraform-plugin-testing/terraform"
+ "github.com/hashicorp/terraform-plugin-testing/tfjsonpath"
fleetsprovider "github.com/trycua/terraform-provider-fleets/internal/provider"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -64,7 +68,7 @@ func TestAccPoolLifecycle(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- apiServer := newCyclopsTestServer(t, clientset, dynamicClient)
+ apiServer := newCyclopsTestServer(t, clientset, dynamicClient, nil)
defer apiServer.Close()
providerConfig := fmt.Sprintf(`
@@ -102,7 +106,6 @@ provider "fleets" {
resource.TestCheckResourceAttr("fleets_pool.test", "replicas", "1"),
resource.TestCheckResourceAttr("fleets_pool.test", "container_disk_image", "example.invalid/cyclops/e2e:latest"),
resource.TestCheckResourceAttr("fleets_pool.test", "service.#", "1"),
- resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.max_pool_size", "5"),
),
},
{
@@ -117,10 +120,153 @@ provider "fleets" {
ImportState: true,
ImportStateVerify: true,
},
+ {
+ Config: providerConfig + autoscaledPoolConfig("16Gi"),
+ Check: resource.ComposeAggregateTestCheckFunc(
+ resource.TestCheckResourceAttr("fleets_pool.test", "memory", "16Gi"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.min_pool_size", "0"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.initial_pool_size", "1"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.max_pool_size", "5"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "replicas", "1"),
+ setWarmPoolReplicas(dynamicClient, 15),
+ ),
+ },
+ {
+ RefreshState: true,
+ Check: resource.ComposeAggregateTestCheckFunc(
+ resource.TestCheckResourceAttr("fleets_pool.test", "replicas", "15"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.min_pool_size", "0"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.initial_pool_size", "1"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "autoscaling.max_pool_size", "5"),
+ ),
+ },
+ {
+ Config: providerConfig + poolConfig(3, "24Gi"),
+ Check: resource.ComposeAggregateTestCheckFunc(
+ resource.TestCheckResourceAttr("fleets_pool.test", "id", "terraform-e2e"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "replicas", "3"),
+ resource.TestCheckNoResourceAttr("fleets_pool.test", "autoscaling"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "cpu_cores", "2"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "memory", "24Gi"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "container_disk_image", "example.invalid/cyclops/e2e:latest"),
+ resource.TestCheckResourceAttr("fleets_pool.test", "service.#", "1"),
+ ),
+ },
},
})
}
+func TestAccPoolUnknownResolvedModesRejected(t *testing.T) {
+ if os.Getenv("TF_ACC") == "" {
+ t.Skip("TF_ACC must be set for acceptance tests")
+ }
+ if os.Getenv("KUBEBUILDER_ASSETS") == "" {
+ t.Skip("KUBEBUILDER_ASSETS must point to envtest binaries")
+ }
+
+ testEnvironment := &envtest.Environment{
+ CRDDirectoryPaths: []string{"../../../../clusters/base/osgym/crd.yaml"},
+ ErrorIfCRDPathMissing: true,
+ }
+ config, err := testEnvironment.Start()
+ if err != nil {
+ t.Fatalf("start envtest: %v", err)
+ }
+ t.Cleanup(func() {
+ if err := testEnvironment.Stop(); err != nil {
+ t.Errorf("stop envtest: %v", err)
+ }
+ })
+
+ clientset, err := kubernetes.NewForConfig(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dynamicClient, err := dynamic.NewForConfig(config)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mutationCount atomic.Int32
+ apiServer := newCyclopsTestServer(t, clientset, dynamicClient, &mutationCount)
+ defer apiServer.Close()
+
+ providerConfig := fmt.Sprintf(`
+provider "fleets" {
+ endpoint = %q
+ client_id = "terraform-e2e"
+ client_secret = "terraform-secret"
+ token_url = %q
+}
+`, apiServer.URL, apiServer.URL+"/token")
+
+ tests := map[string]string{
+ "both present": unknownBothPoolConfig(),
+ "neither present": unknownNeitherPoolConfig(),
+ }
+ for name, poolConfig := range tests {
+ t.Run(name, func(t *testing.T) {
+ mutationCount.Store(0)
+ resource.Test(t, resource.TestCase{
+ ProtoV6ProviderFactories: map[string]func() (tfprotov6.ProviderServer, error){
+ "fleets": providerserver.NewProtocol6WithError(fleetsprovider.New("test")()),
+ },
+ Steps: []resource.TestStep{
+ {
+ Config: providerConfig + poolConfig,
+ ExpectError: regexp.MustCompile(`(?s)Invalid pool scaling configuration.*exactly one of replicas or autoscaling must be configured`),
+ ConfigPlanChecks: resource.ConfigPlanChecks{
+ PreApply: []plancheck.PlanCheck{
+ plancheck.ExpectUnknownValue("fleets_pool.test", tfjsonpath.New("replicas")),
+ },
+ },
+ },
+ },
+ })
+ if got := mutationCount.Load(); got != 0 {
+ t.Fatalf("API mutation requests = %d, want 0", got)
+ }
+ })
+ }
+}
+
+func unknownBothPoolConfig() string {
+ return `
+resource "terraform_data" "mode" {
+ input = 2
+}
+
+resource "fleets_pool" "test" {
+ name = "terraform-e2e"
+ replicas = terraform_data.mode.output
+ cpu_cores = 2
+ memory = "4Gi"
+ container_disk_image = "example.invalid/cyclops/e2e:latest"
+
+ autoscaling {
+ min_pool_size = 0
+ initial_pool_size = 1
+ max_pool_size = 5
+ }
+}
+`
+}
+
+func unknownNeitherPoolConfig() string {
+ return `
+resource "terraform_data" "mode" {
+ input = null
+}
+
+resource "fleets_pool" "test" {
+ name = "terraform-e2e"
+ replicas = terraform_data.mode.output
+ cpu_cores = 2
+ memory = "4Gi"
+ container_disk_image = "example.invalid/cyclops/e2e:latest"
+}
+`
+}
+
func poolConfig(replicas int, memory string) string {
return fmt.Sprintf(`
resource "fleets_pool" "test" {
@@ -130,6 +276,23 @@ resource "fleets_pool" "test" {
memory = %q
container_disk_image = "example.invalid/cyclops/e2e:latest"
+ service {
+ name = "ssh"
+ target_port = 22
+ protocol = "TCP"
+ }
+}
+`, replicas, memory)
+}
+
+func autoscaledPoolConfig(memory string) string {
+ return fmt.Sprintf(`
+resource "fleets_pool" "test" {
+ name = "terraform-e2e"
+ cpu_cores = 2
+ memory = %q
+ container_disk_image = "example.invalid/cyclops/e2e:latest"
+
autoscaling {
min_pool_size = 0
initial_pool_size = 1
@@ -142,10 +305,10 @@ resource "fleets_pool" "test" {
protocol = "TCP"
}
}
-`, replicas, memory)
+`, memory)
}
-func newCyclopsTestServer(t *testing.T, clientset *kubernetes.Clientset, dynamicClient dynamic.Interface) *httptest.Server {
+func newCyclopsTestServer(t *testing.T, clientset *kubernetes.Clientset, dynamicClient dynamic.Interface, mutationCount *atomic.Int32) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/token" {
@@ -161,6 +324,9 @@ func newCyclopsTestServer(t *testing.T, clientset *kubernetes.Clientset, dynamic
http.Error(w, "missing bearer token", http.StatusUnauthorized)
return
}
+ if mutationCount != nil && (r.Method == http.MethodPost || r.Method == http.MethodPatch || r.Method == http.MethodDelete) {
+ mutationCount.Add(1)
+ }
ctx := r.Context()
if r.URL.Path == "/api/namespaces" && r.Method == http.MethodPost {
@@ -232,6 +398,16 @@ func newCyclopsTestServer(t *testing.T, clientset *kubernetes.Clientset, dynamic
}))
}
+func setWarmPoolReplicas(dynamicClient dynamic.Interface, replicas int64) resource.TestCheckFunc {
+ return func(*terraform.State) error {
+ body := []byte(fmt.Sprintf(`{"spec":{"replicas":%d}}`, replicas))
+ _, err := dynamicClient.Resource(warmPoolGVR).
+ Namespace("terraform-e2e").
+ Patch(context.Background(), "terraform-e2e", types.MergePatchType, body, metav1.PatchOptions{})
+ return err
+ }
+}
+
func namespaceObject(name string) *corev1.Namespace {
return &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}
}
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
index faf2eef995..b12e415d1a 100644
--- a/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_sdk_test.go
@@ -4,6 +4,7 @@ import (
"context"
"testing"
+ "github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/trycua/cloud/cyclops-cs/sdk-bindings/go-uniffi/cyclops_sdk_schema"
@@ -27,6 +28,14 @@ func examplePoolModel() poolResourceModel {
}
}
+func testAutoscalingValue(initial int64) types.Object {
+ return types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Value(initial),
+ "max_pool_size": types.Int64Value(5),
+ })
+}
+
func TestPoolResourceModelToSDKCreatePoolRequest(t *testing.T) {
model := examplePoolModel()
@@ -59,6 +68,109 @@ func TestPoolResourceModelToSDKCreatePoolRequest(t *testing.T) {
}
}
+func TestPoolResourceModelToSDKAutoscalingUsesInitialPoolSize(t *testing.T) {
+ model := examplePoolModel()
+ model.Replicas = types.Int64Null()
+ model.Autoscaling = testAutoscalingValue(3)
+
+ var diagnostics diag.Diagnostics
+ request := model.toSDKCreatePoolRequest(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if request.Spec.Replicas != 3 {
+ t.Fatalf("replicas = %d, want initial_pool_size 3", request.Spec.Replicas)
+ }
+ if request.Spec.Autoscaling == nil {
+ t.Fatal("autoscaling was not serialized")
+ }
+ if request.Spec.Autoscaling.MaxPoolSize == nil || *request.Spec.Autoscaling.MaxPoolSize != 5 {
+ t.Fatalf("max_pool_size = %v, want 5", request.Spec.Autoscaling.MaxPoolSize)
+ }
+}
+
+func TestPoolResourceModelToSDKAutoscalingNullInitialPoolSizeUsesZero(t *testing.T) {
+ model := examplePoolModel()
+ model.Replicas = types.Int64Null()
+ model.Autoscaling = types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Null(),
+ "max_pool_size": types.Int64Value(5),
+ })
+
+ var diagnostics diag.Diagnostics
+ request := model.toSDKCreatePoolRequest(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if request.Spec.Replicas != 0 {
+ t.Fatalf("replicas = %d, want zero for null initial_pool_size", request.Spec.Replicas)
+ }
+}
+
+func TestPoolResourceModelToSDKAutoscalingUnknownInitialPoolSizeUsesZero(t *testing.T) {
+ model := examplePoolModel()
+ model.Replicas = types.Int64Null()
+ model.Autoscaling = types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Unknown(),
+ "max_pool_size": types.Int64Value(5),
+ })
+
+ var diagnostics diag.Diagnostics
+ request := model.toSDKCreatePoolRequest(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if request.Spec.Replicas != 0 {
+ t.Fatalf("replicas = %d, want zero for unknown initial_pool_size", request.Spec.Replicas)
+ }
+}
+
+func TestPoolResourceModelToSDKAutoscalingNullMaxPoolSizeUsesDefault(t *testing.T) {
+ model := examplePoolModel()
+ model.Replicas = types.Int64Null()
+ model.Autoscaling = types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Value(3),
+ "max_pool_size": types.Int64Null(),
+ })
+
+ var diagnostics diag.Diagnostics
+ request := model.toSDKCreatePoolRequest(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if request.Spec.Autoscaling == nil || request.Spec.Autoscaling.MaxPoolSize == nil {
+ t.Fatal("autoscaling max_pool_size was not serialized")
+ }
+ if *request.Spec.Autoscaling.MaxPoolSize != 50 {
+ t.Fatalf("max_pool_size = %d, want default 50", *request.Spec.Autoscaling.MaxPoolSize)
+ }
+}
+
+func TestPoolResourceModelToSDKAutoscalingUnknownMaxPoolSizeUsesDefault(t *testing.T) {
+ model := examplePoolModel()
+ model.Replicas = types.Int64Null()
+ model.Autoscaling = types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Value(3),
+ "max_pool_size": types.Int64Unknown(),
+ })
+
+ var diagnostics diag.Diagnostics
+ request := model.toSDKCreatePoolRequest(context.Background(), &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if request.Spec.Autoscaling == nil || request.Spec.Autoscaling.MaxPoolSize == nil {
+ t.Fatal("autoscaling max_pool_size was not serialized")
+ }
+ if *request.Spec.Autoscaling.MaxPoolSize != 50 {
+ t.Fatalf("max_pool_size = %d, want default 50", *request.Spec.Autoscaling.MaxPoolSize)
+ }
+}
+
func TestPoolResourceModelToSDKCreateTemplateRequest(t *testing.T) {
model := examplePoolModel()
@@ -128,6 +240,9 @@ func TestPoolResourceModelFromSDKObjects(t *testing.T) {
if model.TemplateName.ValueString() != "example-template" {
t.Fatalf("template_name = %q", model.TemplateName.ValueString())
}
+ if model.Replicas.ValueInt64() != 2 {
+ t.Fatalf("replicas = %d, want 2", model.Replicas.ValueInt64())
+ }
if model.CurrentReplicas.ValueInt64() != 2 || model.ReadyReplicas.ValueInt64() != 1 {
t.Fatalf("status replicas = %d, ready = %d", model.CurrentReplicas.ValueInt64(), model.ReadyReplicas.ValueInt64())
}
@@ -139,6 +254,45 @@ func TestPoolResourceModelFromSDKObjects(t *testing.T) {
}
}
+func TestPoolResourceModelFromSDKAutoscalingPreservesLiveReplicas(t *testing.T) {
+ minPoolSize := uint32(0)
+ initialPoolSize := uint32(2)
+ maxPoolSize := uint32(5)
+ pool := fleet_sdk.Pool{
+ Metadata: fleet_sdk.ResourceMetadata{Namespace: "example", Name: "example"},
+ Spec: cyclops_sdk_schema.OsGymSandboxWarmPoolSpec{
+ Replicas: 4,
+ SandboxTemplateRef: cyclops_sdk_schema.SandboxTemplateRef{Name: "example-template"},
+ Autoscaling: &cyclops_sdk_schema.WarmPoolAutoscaling{
+ MinPoolSize: &minPoolSize, InitialPoolSize: &initialPoolSize, MaxPoolSize: &maxPoolSize,
+ },
+ },
+ }
+
+ var model poolResourceModel
+ var diagnostics diag.Diagnostics
+ model.fromSDKPool(pool, &diagnostics)
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if model.Replicas.ValueInt64() != 4 {
+ t.Fatalf("replicas = %d, want live autoscaled target 4", model.Replicas.ValueInt64())
+ }
+ if model.Autoscaling.IsNull() {
+ t.Fatal("autoscaling was not preserved")
+ }
+ var autoscaling autoscalingModel
+ if !objectValue(context.Background(), model.Autoscaling, &autoscaling, &diagnostics) {
+ t.Fatal("autoscaling could not be decoded")
+ }
+ if diagnostics.HasError() {
+ t.Fatalf("unexpected diagnostics: %v", diagnostics)
+ }
+ if autoscaling.MinPoolSize.ValueInt64() != 0 || autoscaling.InitialPoolSize.ValueInt64() != 2 || autoscaling.MaxPoolSize.ValueInt64() != 5 {
+ t.Fatalf("autoscaling = min %d, initial %d, max %d; want min 0, initial 2, max 5", autoscaling.MinPoolSize.ValueInt64(), autoscaling.InitialPoolSize.ValueInt64(), autoscaling.MaxPoolSize.ValueInt64())
+ }
+}
+
func TestPoolResourceModelFromSDKTemplateClearsMissingTemplate(t *testing.T) {
model := examplePoolModel()
diff --git a/libs/fleet/terraform-provider-fleets/internal/provider/pool_validation_test.go b/libs/fleet/terraform-provider-fleets/internal/provider/pool_validation_test.go
new file mode 100644
index 0000000000..810b9f7771
--- /dev/null
+++ b/libs/fleet/terraform-provider-fleets/internal/provider/pool_validation_test.go
@@ -0,0 +1,112 @@
+package provider
+
+import (
+ "testing"
+
+ "github.com/hashicorp/terraform-plugin-framework/attr"
+ "github.com/hashicorp/terraform-plugin-framework/types"
+)
+
+func TestValidatePoolScalingModeDuringPlan(t *testing.T) {
+ autoscaling := testValidationAutoscalingValue()
+
+ tests := []struct {
+ name string
+ replicas types.Int64
+ autoscaling types.Object
+ wantError bool
+ }{
+ {name: "static", replicas: types.Int64Value(2), autoscaling: types.ObjectNull(autoscalingObjectType())},
+ {name: "autoscaled", replicas: types.Int64Null(), autoscaling: autoscaling},
+ {name: "both", replicas: types.Int64Value(2), autoscaling: autoscaling, wantError: true},
+ {name: "neither", replicas: types.Int64Null(), autoscaling: types.ObjectNull(autoscalingObjectType()), wantError: true},
+ {name: "unknown replicas", replicas: types.Int64Unknown(), autoscaling: types.ObjectNull(autoscalingObjectType())},
+ {name: "unknown autoscaling", replicas: types.Int64Null(), autoscaling: types.ObjectUnknown(autoscalingObjectType())},
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ config := poolResourceModel{Replicas: test.replicas, Autoscaling: test.autoscaling}
+ err := validatePoolScalingModeDuringPlan(config)
+ if (err != nil) != test.wantError {
+ t.Fatalf("validatePoolScalingModeDuringPlan() error = %v, wantError %t", err, test.wantError)
+ }
+ })
+ }
+}
+
+func TestValidatePoolScalingModeAtApply(t *testing.T) {
+ autoscaling := testValidationAutoscalingValue()
+ nullAutoscaling := types.ObjectNull(autoscalingObjectType())
+
+ tests := []struct {
+ name string
+ config poolResourceModel
+ plan poolResourceModel
+ wantError string
+ }{
+ {
+ name: "static",
+ config: poolResourceModel{Replicas: types.Int64Value(2), Autoscaling: nullAutoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Value(2), Autoscaling: nullAutoscaling},
+ },
+ {
+ name: "autoscaled with computed live replicas",
+ config: poolResourceModel{Replicas: types.Int64Null(), Autoscaling: autoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Value(15), Autoscaling: autoscaling},
+ },
+ {
+ name: "both",
+ config: poolResourceModel{Replicas: types.Int64Value(2), Autoscaling: autoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Value(2), Autoscaling: autoscaling},
+ wantError: poolScalingModeExactlyOneMessage,
+ },
+ {
+ name: "neither",
+ config: poolResourceModel{Replicas: types.Int64Null(), Autoscaling: nullAutoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Unknown(), Autoscaling: nullAutoscaling},
+ wantError: poolScalingModeExactlyOneMessage,
+ },
+ {
+ name: "unknown replicas resolve present beside autoscaling",
+ config: poolResourceModel{Replicas: types.Int64Unknown(), Autoscaling: autoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Value(2), Autoscaling: autoscaling},
+ wantError: poolScalingModeExactlyOneMessage,
+ },
+ {
+ name: "unknown replicas resolve null without autoscaling",
+ config: poolResourceModel{Replicas: types.Int64Unknown(), Autoscaling: nullAutoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Null(), Autoscaling: nullAutoscaling},
+ wantError: poolScalingModeExactlyOneMessage,
+ },
+ {
+ name: "unknown replicas remain unresolved",
+ config: poolResourceModel{Replicas: types.Int64Unknown(), Autoscaling: nullAutoscaling},
+ plan: poolResourceModel{Replicas: types.Int64Unknown(), Autoscaling: nullAutoscaling},
+ wantError: poolScalingModeUnknownAtApplyMessage,
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ err := validatePoolScalingModeAtApply(test.config, test.plan)
+ if test.wantError == "" {
+ if err != nil {
+ t.Fatalf("validatePoolScalingModeAtApply() error = %v", err)
+ }
+ return
+ }
+ if err == nil || err.Error() != test.wantError {
+ t.Fatalf("validatePoolScalingModeAtApply() error = %v, want %q", err, test.wantError)
+ }
+ })
+ }
+}
+
+func testValidationAutoscalingValue() types.Object {
+ return types.ObjectValueMust(autoscalingObjectType(), map[string]attr.Value{
+ "min_pool_size": types.Int64Value(0),
+ "initial_pool_size": types.Int64Value(1),
+ "max_pool_size": types.Int64Value(5),
+ })
+}