diff --git a/README.md b/README.md index 55e39e93..866b16c0 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,15 @@ There are three main resources created by these templates: * K8s Control Plane + minimal worker node set * Postgres DB (will be used for your Plural Console instance) +On AWS, GCP and Azure it also sets up devboxes, Plural's sandboxed coding-agent environments, on the management cluster: + +* `terraform/mgmt/cluster/devbox.tf`: a node pool for the sandboxes, which keeps one node running and grows with demand, a bucket for their snapshots, and workload identities to reach it. On AWS the pool is a [Karpenter](https://karpenter.sh) `NodePool` with nested virtualization on (`services/devbox/karpenter.yaml.liquid`), and this file holds Karpenter's IAM, the node role's access entry and the interruption queue. A `NodeOverlay` beside the `NodePool` tells Karpenter its nodes will have `ate.dev/kvm`, which microvm workers request but atelet only advertises once a node runs; it needs the `nodeOverlay` feature gate the Karpenter values turn on. On Azure it's a `NodePool` for AKS's [node auto-provisioning](https://learn.microsoft.com/en-us/azure/aks/node-auto-provisioning) (managed Karpenter), which this file turns on. It runs beside the autoscaled `blue` and `green` pools through the subscription's `AllowClusterAutoscalerAndNAP` feature, which this file registers, so the first apply needs an identity allowed to register features (e.g. subscription Owner or Contributor). Both clouds launch each node in the zone its sandbox's home disk is in, which the cluster autoscaler can't do for a pool spanning zones +* `bootstrap/devbox`: [Agent Substrate](https://github.com/agent-substrate/substrate), the sandbox runtime, Karpenter on AWS, the devbox `NodePool` on AWS and Azure, and a `devbox` DevboxRunner (`services/devbox`) + +Each devbox's `/home/dev` is its own cloud disk (EBS, Persistent Disk or Azure managed disk) from Agent Substrate's block driver, DevboxRunners' default home storage. It needs the cloud's disk CSI driver and the VolumeSnapshot API, which the cluster stacks turn on: the `aws-ebs-csi-driver` and `snapshot-controller` EKS add-ons, GKE's Persistent Disk CSI driver, and AKS's disk driver and snapshot controller. + +To leave them out, set `devbox_enabled = false` on the `mgmt` module and delete `bootstrap/devbox`. + Our defaults are meant to be tweaked, feel free to reference the documentation of the underlying modules if you want to make a cluster private, or modify our CIDR range defaults if you want to VPC peer. diff --git a/helm/agent-substrate.yaml.liquid b/helm/agent-substrate.yaml.liquid new file mode 100644 index 00000000..a1ce5d6c --- /dev/null +++ b/helm/agent-substrate.yaml.liquid @@ -0,0 +1,72 @@ +# Agent Substrate on the management cluster. Values reference: +# https://github.com/pluralsh/console/blob/master/charts/agent-substrate/values.yaml + +# Wires Substrate to the deployment operator's devbox-gateway in plrl-deploy-operator and makes the operator's +# ServiceAccount a bootstrap owner, so it can create atespaces. +devboxes: + enabled: true + +otel: + endpoint: "" + +# Substrate keeps its state in a CloudNativePG cluster in ate-system, with the operator bundled. +cloudnative-pg: + enabled: true + +# Substrate workers only run on the devbox pool, so atelet only needs to run there too. It doesn't tolerate the +# plural.sh/devbox-disk startup taint, so it waits for devbox-disk-prep. +atelet: + nodeSelector: + plural.sh/devbox-pool: devbox + +# Devbox homes (spec.home.storage: Block) are one cloud disk each from the cluster's own disk CSI +# driver, seeded and moved between zones through VolumeSnapshots, which the mgmt stack makes sure the cluster serves. +# The operator runs a WorkerPool per zone of the devbox nodes and keeps each devbox in its disk's zone. +block: + enabled: true +{% if configuration.cloud == 'aws' %} + provider: ebs.csi.aws.com + parameters: + type: gp3 +{% elsif configuration.cloud == 'gcp' %} + provider: pd.csi.storage.gke.io + parameters: + type: pd-balanced +{% elsif configuration.cloud == 'azure' %} + provider: disk.csi.azure.com + parameters: + skuName: Premium_LRS +{% endif %} + +{% if configuration.cloud == 'aws' %} +# ate-api-server and atelet reach S3 through EKS Pod Identity associations made by the mgmt stack. +objectStore: + backend: s3 + snapshotLocation: {{ imports["mgmt"].devbox_snapshot_location }} + s3: + region: {{ configuration.region }} +{% elsif configuration.cloud == 'gcp' %} +apiServer: + snapshotTransferServiceAccount: {{ imports["mgmt"].devbox_transfer_service_account }} + serviceAccount: + annotations: + iam.gke.io/gcp-service-account: {{ imports["mgmt"].devbox_api_server_service_account }} + +objectStore: + backend: gcs + snapshotLocation: {{ imports["mgmt"].devbox_snapshot_location }} +{% elsif configuration.cloud == 'azure' %} +objectStore: + backend: azureBlob + snapshotLocation: {{ imports["mgmt"].devbox_snapshot_location }} + azureBlob: + image: + # built from agent-substrate-plugins/objectstore-azure-blob d960af4 by console's objectstore-azure-blob workflow + tag: sha-d960af4 + accountUrl: {{ imports["mgmt"].devbox_account_url }} + containers: + - snapshots + tenantId: {{ imports["mgmt"].devbox_tenant_id }} + nodeClientId: {{ imports["mgmt"].devbox_node_client_id }} + controlClientId: {{ imports["mgmt"].devbox_control_client_id }} +{% endif %} diff --git a/helm/karpenter.yaml.liquid b/helm/karpenter.yaml.liquid new file mode 100644 index 00000000..3e2aeb24 --- /dev/null +++ b/helm/karpenter.yaml.liquid @@ -0,0 +1,23 @@ +# Karpenter on the management cluster, which runs the devbox node pool. Values reference: +# https://github.com/aws/karpenter-provider-aws/blob/main/charts/karpenter/values.yaml +replicas: 2 + +settings: + clusterName: {{ imports["mgmt"].cluster_name }} + clusterEndpoint: {{ imports["mgmt"].cluster_endpoint }} + interruptionQueue: {{ imports["mgmt"].devbox_karpenter_queue }} + featureGates: + # The devbox pool's NodeOverlay tells Karpenter its nodes will have ate.dev/kvm. + nodeOverlay: true + +# the mgmt stack's Pod Identity association grants this ServiceAccount the controller's role +serviceAccount: + name: karpenter + +controller: + resources: + requests: + cpu: 250m + memory: 512Mi + limits: + memory: 1Gi diff --git a/services/devbox/devbox-runner.yaml.liquid b/services/devbox/devbox-runner.yaml.liquid new file mode 100644 index 00000000..cad15a4d --- /dev/null +++ b/services/devbox/devbox-runner.yaml.liquid @@ -0,0 +1,51 @@ +# The default devbox. One worker always runs, since building the devbox template needs one, and the pool grows +# with demand. Add SCM connections, repositories, egress rules or cloud identities here. +# Reference: https://github.com/pluralsh/console/blob/master/go/deployment-operator/docs/api.md#devboxrunner +apiVersion: deployments.plural.sh/v1alpha1 +kind: DevboxRunner +metadata: + name: devbox +spec: + agents: + - type: claude + default: true + - type: codex + - type: opencode + - type: gemini + - type: pi + scmConnections: + - plural + autonomy: + default: manual + max: full + browser: + enabled: true + # each devbox's /home/dev is its own cloud disk from agent-substrate's block driver, in one zone + home: + storage: Block + resources: + cpu: "2" + memory: 4Gi + disk: 20Gi + workerPool: + autoscaling: + minReplicas: 1 + maxReplicas: {{ configuration.maxWorkers }} + spareInstances: 1 + diskSize: {{ configuration.diskSize }} + sandboxClass: gvisor + nodeSelector: + plural.sh/devbox-pool: {{ configuration.pool }} + tolerations: + # lets the cluster autoscaler size the pool from its template; atelet still waits for the disk + - key: plural.sh/devbox-disk + operator: Exists + effect: NoSchedule +{% if configuration.cloud == 'aws' or configuration.cloud == 'azure' %} + # keeps Karpenter from draining a node out from under running sandboxes + podAnnotations: + karpenter.sh/do-not-disrupt: "true" +{% endif %} + resources: + requests: {cpu: "{{ configuration.workerCpu }}", memory: {{ configuration.workerMemory }}} + limits: {cpu: "{{ configuration.workerCpu }}", memory: {{ configuration.workerMemory }}} diff --git a/services/devbox/disk-prep.yaml.liquid b/services/devbox/disk-prep.yaml.liquid new file mode 100644 index 00000000..b5bf86a2 --- /dev/null +++ b/services/devbox/disk-prep.yaml.liquid @@ -0,0 +1,119 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: devbox-nodes +--- +# GKE only admits node- and cluster-critical pods outside kube-system in a namespace with a quota for them +apiVersion: v1 +kind: ResourceQuota +metadata: + name: disk-prep-critical-pods + namespace: devbox-nodes +spec: + hard: + pods: 1G + scopeSelector: + matchExpressions: + - operator: In + scopeName: PriorityClass + values: + - system-node-critical + - system-cluster-critical +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: devbox-disk-prep + namespace: devbox-nodes +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: devbox-disk-prep +rules: +- apiGroups: [""] + resources: ["nodes"] + verbs: ["get", "update"] +# restarts pods on the node that started before /var/lib/ate was mounted +- apiGroups: [""] + resources: ["pods"] + verbs: ["list", "delete"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: devbox-disk-prep +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: devbox-disk-prep +subjects: +- kind: ServiceAccount + name: devbox-disk-prep + namespace: devbox-nodes +--- +# devbox-disk-prep ships in the agent-harness base image. On a node's first boot it formats the disks whose model +# matches DISK_MODEL (RAID0 when there are several) as XFS, mounts them at /var/lib/ate and lifts the +# plural.sh/devbox-disk startup taint. Afterwards it only reassembles and remounts. +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: devbox-disk-prep + namespace: devbox-nodes +spec: + selector: + matchLabels: + app.kubernetes.io/name: devbox-disk-prep + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 25% + template: + metadata: + labels: + app.kubernetes.io/name: devbox-disk-prep + spec: + serviceAccountName: devbox-disk-prep + priorityClassName: system-node-critical + nodeSelector: + plural.sh/devbox-pool: {{ configuration.pool }} + tolerations: + - operator: Exists + containers: + - name: disk-prep + image: {{ configuration.diskPrepImage }} + command: ["/devbox-disk-prep"] + env: + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - name: DISK_MODEL + value: "{{ configuration.diskModel }}" + securityContext: + privileged: true + runAsUser: 0 + runAsGroup: 0 + readinessProbe: + exec: + command: ["test", "-f", "/tmp/ready"] + periodSeconds: 10 + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + memory: 128Mi + volumeMounts: + - name: host + mountPath: /host + mountPropagation: Bidirectional + - name: dev + mountPath: /dev + volumes: + - name: host + hostPath: + path: / + - name: dev + hostPath: + path: /dev diff --git a/services/devbox/karpenter.yaml.liquid b/services/devbox/karpenter.yaml.liquid new file mode 100644 index 00000000..af65d11a --- /dev/null +++ b/services/devbox/karpenter.yaml.liquid @@ -0,0 +1,140 @@ +{% if configuration.cloud == 'aws' or configuration.cloud == 'azure' %} +{% if configuration.cloud == 'aws' %} +apiVersion: karpenter.k8s.aws/v1 +kind: EC2NodeClass +metadata: + name: {{ configuration.pool }} +spec: + amiSelectorTerms: + - alias: al2023@latest + role: {{ imports["mgmt"].devbox_node_role }} + subnetSelectorTerms: +{% assign subnets = imports["mgmt"].devbox_subnet_ids | split: "," %} +{% for subnet in subnets %} + - id: {{ subnet }} +{% endfor %} + securityGroupSelectorTerms: + - id: {{ imports["mgmt"].devbox_node_security_group_id }} + # Lets the pool run microvm sandboxes as well as gVisor. Karpenter only picks instance types that support it. + cpuOptions: + nestedVirtualization: enabled + metadataOptions: + httpEndpoint: enabled + httpTokens: required + httpPutResponseHopLimit: 1 + blockDeviceMappings: + - deviceName: /dev/xvda + ebs: + volumeSize: 100Gi + volumeType: gp3 + encrypted: true + deleteOnTermination: true + # mounted at /var/lib/ate by devbox-disk-prep + - deviceName: /dev/xvdb + ebs: + volumeSize: {{ configuration.dataDiskSize }} + volumeType: gp3 + encrypted: true + deleteOnTermination: true + tags: + plural.sh/devbox-pool: {{ configuration.pool }} +{% else %} +# AKS node auto-provisioning (managed Karpenter), which the mgmt stack turns on (terraform/mgmt/cluster/devbox.tf) +apiVersion: karpenter.azure.com/v1beta1 +kind: AKSNodeClass +metadata: + name: {{ configuration.pool }} +spec: + imageFamily: Ubuntu + # also holds /var/lib/ate + osDiskSizeGB: {{ configuration.bootDiskSize }} + osDiskType: Managed + # Azure has no nested virtualization switch: the VM size brings it, and Trusted Launch takes it away. With it the pool + # can run microvm sandboxes as well as gVisor. + security: + trustedLaunch: + secureBoot: false + vtpm: false + tags: + plural-devbox-pool: {{ configuration.pool }} +{% endif %} +--- +apiVersion: karpenter.sh/v1 +kind: NodePool +metadata: + name: {{ configuration.pool }} +spec: + template: + metadata: + labels: + plural.sh/devbox-pool: {{ configuration.pool }} +{% if configuration.cloud == 'azure' %} + # lets NAP account for the Cilium agent on each node + kubernetes.azure.com/ebpf-dataplane: cilium +{% endif %} + spec: + nodeClassRef: +{% if configuration.cloud == 'aws' %} + group: karpenter.k8s.aws + kind: EC2NodeClass +{% else %} + group: karpenter.azure.com + kind: AKSNodeClass +{% endif %} + name: {{ configuration.pool }} + taints: + - key: ate.dev/sandboxClass + value: gvisor + effect: NoSchedule + # lifted by devbox-disk-prep once /var/lib/ate is ready + startupTaints: + - key: plural.sh/devbox-disk + value: pending + effect: NoSchedule +{% if configuration.cloud == 'azure' %} + - key: node.cilium.io/agent-not-ready + value: "true" + effect: NoExecute +{% endif %} + requirements: + - key: kubernetes.io/arch + operator: In + values: ["amd64"] + - key: karpenter.sh/capacity-type + operator: In + values: ["on-demand"] + # one instance type, since gVisor snapshots need a single CPU model across the pool; it must support nested + # virtualization + - key: node.kubernetes.io/instance-type + operator: In + values: ["{{ configuration.instanceType }}"] + # Sandboxes are stateful between snapshots: never expire nodes, and give atelet time to suspend actors when a + # node is drained. + expireAfter: Never + terminationGracePeriod: 1h + disruption: + consolidationPolicy: WhenEmpty + consolidateAfter: 15m + budgets: + - nodes: "10%" + limits: + cpu: "{{ configuration.maxCpu }}" +{% if configuration.cloud == 'aws' %} +--- +# Karpenter only launches a node for a pod whose requests the instance type covers, and ate.dev/kvm (which microvm +# workers request) only appears once atelet's device plugin runs on the node, so the pool would never scale up for +# one. The count is the one atelet advertises; it is a placeholder, not a limit. Needs Karpenter's NodeOverlay feature +# gate (helm/karpenter.yaml.liquid). +apiVersion: karpenter.sh/v1alpha1 +kind: NodeOverlay +metadata: + name: {{ configuration.pool }}-kvm +spec: + requirements: + - key: karpenter.sh/nodepool + operator: In + values: ["{{ configuration.pool }}"] + capacity: + ate.dev/kvm: "4096" +{% endif %} +{% endif %} diff --git a/setup/devbox/agent-substrate.yaml b/setup/devbox/agent-substrate.yaml new file mode 100644 index 00000000..4b4e5109 --- /dev/null +++ b/setup/devbox/agent-substrate.yaml @@ -0,0 +1,38 @@ +[[- if or (eq .Provider "aws") (eq .Provider "gcp") (eq .Provider "azure") ]] +# Agent Substrate, the sandbox runtime devboxes run on. Its snapshot storage and identities come from the mgmt +# stack (terraform/mgmt/cluster/devbox.tf). +apiVersion: deployments.plural.sh/v1alpha1 +kind: ServiceDeployment +metadata: + name: agent-substrate + namespace: infra +spec: + name: agent-substrate + # Substrate's binaries default their in-cluster addresses and SPIFFE IDs to ate-system, so the chart only renders there. + namespace: ate-system + git: + folder: helm + ref: [[ or .Context.Branch "main" ]] + repositoryRef: + kind: GitRepository + name: infra + namespace: infra + helm: + version: "0.1.1" + chart: agent-substrate + release: ate + url: oci://ghcr.io/pluralsh/charts + valuesFiles: + - agent-substrate.yaml.liquid + imports: + - stackRef: + name: mgmt + namespace: infra + configuration: + cloud: [[ .Provider ]] + region: [[ .Region ]] + clusterRef: + kind: Cluster + name: mgmt + namespace: infra +[[- end ]] diff --git a/setup/devbox/devbox-nodes.yaml b/setup/devbox/devbox-nodes.yaml new file mode 100644 index 00000000..06120662 --- /dev/null +++ b/setup/devbox/devbox-nodes.yaml @@ -0,0 +1,62 @@ +[[- if or (eq .Provider "aws") (eq .Provider "gcp") (eq .Provider "azure") ]] +# The devbox node pool's disk prep and the DevboxRunner the deployment operator turns into Substrate workers and +# console devboxes. On AWS and Azure the node pool is a Karpenter NodePool here (on Azure AKS's node auto-provisioning, +# which the mgmt stack turns on); on GCP it's in the mgmt stack (terraform/mgmt/cluster/devbox.tf). +apiVersion: deployments.plural.sh/v1alpha1 +kind: ServiceDeployment +metadata: + name: devbox-nodes + namespace: infra +spec: + name: devbox-nodes + namespace: devbox-nodes + git: + folder: services/devbox + ref: [[ or .Context.Branch "main" ]] + repositoryRef: + kind: GitRepository + name: infra + namespace: infra + dependencies: + # the DevboxRunner needs Substrate's WorkerPool API + - name: agent-substrate + [[- if eq .Provider "aws" ]] + # the NodePool and EC2NodeClass need Karpenter's CRDs + - name: karpenter + imports: + - stackRef: + name: mgmt + namespace: infra + [[- end ]] + configuration: + cloud: [[ .Provider ]] + pool: devbox + diskPrepImage: ghcr.io/pluralsh/agent-harness-base:0.6.77 + [[- if eq .Provider "aws" ]] + # the gp3 data volume at /dev/xvdb; elsewhere /var/lib/ate stays on the boot disk and disk prep only lifts the + # startup taint (console rejects an empty configuration value, so diskModel is left out) + diskModel: "Elastic Block Store" + dataDiskSize: 200Gi + # one type, since gVisor snapshots need a single CPU model; it must support nested virtualization + instanceType: m7i.2xlarge + # caps the pool at 5 of those nodes + maxCpu: "40" + [[- end ]] + [[- if eq .Provider "azure" ]] + # also holds /var/lib/ate + bootDiskSize: "250" + # one size, since gVisor snapshots need a single CPU model; Dsv5 supports nested virtualization + instanceType: Standard_D8s_v5 + # caps the pool at 5 of those nodes + maxCpu: "40" + [[- end ]] + # every pool's default machine has 8 vCPUs and 32GiB, so one worker per node fits below its allocatable resources + workerCpu: "7" + workerMemory: 24Gi + diskSize: 200Gi + maxWorkers: "5" + clusterRef: + kind: Cluster + name: mgmt + namespace: infra +[[- end ]] diff --git a/setup/devbox/karpenter.yaml b/setup/devbox/karpenter.yaml new file mode 100644 index 00000000..3af1d428 --- /dev/null +++ b/setup/devbox/karpenter.yaml @@ -0,0 +1,35 @@ +[[- if eq .Provider "aws" ]] +# Karpenter, which runs the devbox node pool (services/devbox/karpenter.yaml.liquid). Its IAM, Pod Identity +# association and interruption queue come from the mgmt stack (terraform/mgmt/cluster/devbox.tf). +apiVersion: deployments.plural.sh/v1alpha1 +kind: ServiceDeployment +metadata: + name: karpenter + namespace: infra +spec: + name: karpenter + namespace: karpenter + git: + folder: helm + ref: [[ or .Context.Branch "main" ]] + repositoryRef: + kind: GitRepository + name: infra + namespace: infra + helm: + # 1.13 is the first with EC2NodeClass cpuOptions.nestedVirtualization + version: "1.13.0" + chart: karpenter + release: karpenter + url: oci://public.ecr.aws/karpenter + valuesFiles: + - karpenter.yaml.liquid + imports: + - stackRef: + name: mgmt + namespace: infra + clusterRef: + kind: Cluster + name: mgmt + namespace: infra +[[- end ]] diff --git a/templates/providers/bootstrap/azure.tf b/templates/providers/bootstrap/azure.tf index 603cf07f..2237b747 100644 --- a/templates/providers/bootstrap/azure.tf +++ b/templates/providers/bootstrap/azure.tf @@ -14,6 +14,10 @@ terraform { source = "hashicorp/azurerm" version = ">=3.51.0, < 4.0" } + azapi = { + source = "Azure/azapi" + version = ">= 1.13, < 2.0" + } curl = { source = "anschoewe/curl" version = "1.0.2" @@ -56,6 +60,12 @@ provider "azurerm" { tenant_id = "{{ .Context.TenantId }}" } +# turns on node auto-provisioning for devboxes (terraform/mgmt/cluster/devbox.tf) +provider "azapi" { + subscription_id = "{{ .Context.SubscriptionId }}" + tenant_id = "{{ .Context.TenantId }}" +} + provider "kubernetes" { host = "https://${module.mgmt.cluster.cluster_fqdn}" cluster_ca_certificate = base64decode(module.mgmt.cluster.cluster_ca_certificate) diff --git a/templates/setup/providers/aws.tf b/templates/setup/providers/aws.tf index 0f2b391c..000f172c 100644 --- a/templates/setup/providers/aws.tf +++ b/templates/setup/providers/aws.tf @@ -11,3 +11,32 @@ module "mgmt" { deletion_protection = "${var.deletion_protection}" } + +# read by the devbox services in bootstrap/devbox through the mgmt stack's outputs +output "devbox_snapshot_location" { + value = module.mgmt.devbox_snapshot_location +} + +output "cluster_name" { + value = module.mgmt.cluster_name +} + +output "cluster_endpoint" { + value = module.mgmt.cluster_endpoint +} + +output "devbox_karpenter_queue" { + value = module.mgmt.devbox_karpenter_queue +} + +output "devbox_node_role" { + value = module.mgmt.devbox_node_role +} + +output "devbox_subnet_ids" { + value = module.mgmt.devbox_subnet_ids +} + +output "devbox_node_security_group_id" { + value = module.mgmt.devbox_node_security_group_id +} diff --git a/templates/setup/providers/azure.tf b/templates/setup/providers/azure.tf index 7eaa10a2..d5e380d1 100644 --- a/templates/setup/providers/azure.tf +++ b/templates/setup/providers/azure.tf @@ -4,4 +4,24 @@ module "mgmt" { cluster_name = "{{ .Cluster }}" location = "{{ .Region }}" create_db = {{ .RequireDB }} -} \ No newline at end of file +} +# read by the devbox services in bootstrap/devbox through the mgmt stack's outputs +output "devbox_snapshot_location" { + value = module.mgmt.devbox_snapshot_location +} + +output "devbox_account_url" { + value = module.mgmt.devbox_account_url +} + +output "devbox_tenant_id" { + value = module.mgmt.devbox_tenant_id +} + +output "devbox_node_client_id" { + value = module.mgmt.devbox_node_client_id +} + +output "devbox_control_client_id" { + value = module.mgmt.devbox_control_client_id +} diff --git a/templates/setup/providers/gcp.tf b/templates/setup/providers/gcp.tf index f5f527d6..ddfc4406 100644 --- a/templates/setup/providers/gcp.tf +++ b/templates/setup/providers/gcp.tf @@ -21,3 +21,16 @@ module "mgmt" { network = "${var.network}" subnetwork = "${var.subnetwork}" } + +# read by the devbox services in bootstrap/devbox through the mgmt stack's outputs +output "devbox_snapshot_location" { + value = module.mgmt.devbox_snapshot_location +} + +output "devbox_api_server_service_account" { + value = module.mgmt.devbox_api_server_service_account +} + +output "devbox_transfer_service_account" { + value = module.mgmt.devbox_transfer_service_account +} diff --git a/terraform/clouds/aws/devbox.tf b/terraform/clouds/aws/devbox.tf new file mode 100644 index 00000000..8c384c05 --- /dev/null +++ b/terraform/clouds/aws/devbox.tf @@ -0,0 +1,129 @@ +# Plural devboxes: Karpenter, which runs the node pool for Agent Substrate's workers, the bucket Substrate keeps +# actor snapshots in, and the EKS Pod Identity roles ate-api-server and atelet reach it with. Devbox homes are EBS +# volumes from the EBS CSI driver, snapshotted through the snapshot-controller add-on (runtime.tf). The services in bootstrap/devbox install Karpenter, Substrate and the DevboxRunner on top; +# the devbox NodePool and EC2NodeClass are in services/devbox. +# +# Karpenter rather than a managed node group: a node group spanning zones is one Auto Scaling group whose zone the +# cluster autoscaler can't choose, while Karpenter launches each node in the zone its pending worker needs. It also +# turns on nested virtualization, which EKS drops from managed node groups' launch templates, so the pool can run +# microvm sandboxes as well as gVisor. + +variable "devbox_enabled" { + type = bool + default = true +} + +locals { + devbox = var.devbox_enabled ? 1 : 0 + devbox_roles = var.devbox_enabled ? toset(["ate-api-server", "atelet"]) : toset([]) +} + +module "devbox_karpenter" { + count = local.devbox + source = "terraform-aws-modules/eks/aws//modules/karpenter" + version = "~> 20.37" + + cluster_name = module.eks.cluster_name + enable_v1_permissions = true + + namespace = "karpenter" + service_account = "karpenter" + create_pod_identity_association = true + + queue_name = substr("${var.cluster_name}-karpenter", 0, 80) + + node_iam_role_name = substr("${var.cluster_name}-devbox", 0, 64) + node_iam_role_use_name_prefix = false + # Karpenter's nodes authenticate their kubelet through this access entry; without it they launch but never register. + create_access_entry = true + node_iam_role_additional_policies = { + AmazonSSMManagedInstanceCore = "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonSSMManagedInstanceCore" + } +} + +resource "aws_s3_bucket" "devbox" { + count = local.devbox + bucket_prefix = substr("${var.cluster_name}-ate-", 0, 37) + # snapshots only outlive their devboxes, which go with the cluster + force_destroy = true +} + +resource "aws_s3_bucket_public_access_block" "devbox" { + count = local.devbox + bucket = aws_s3_bucket.devbox[0].id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +data "aws_iam_policy_document" "devbox_assume" { + statement { + actions = ["sts:AssumeRole", "sts:TagSession"] + principals { + type = "Service" + identifiers = ["pods.eks.amazonaws.com"] + } + } +} + +data "aws_iam_policy_document" "devbox_bucket" { + count = local.devbox + + statement { + actions = ["s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads"] + resources = [aws_s3_bucket.devbox[0].arn] + } + + statement { + actions = [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject", + "s3:AbortMultipartUpload", + "s3:ListMultipartUploadParts", + ] + resources = ["${aws_s3_bucket.devbox[0].arn}/*"] + } +} + +resource "aws_iam_role" "devbox" { + for_each = local.devbox_roles + name = substr("${var.cluster_name}-${each.key}", 0, 64) + assume_role_policy = data.aws_iam_policy_document.devbox_assume.json +} + +resource "aws_iam_role_policy" "devbox" { + for_each = local.devbox_roles + name = "substrate-snapshots" + role = aws_iam_role.devbox[each.key].id + policy = data.aws_iam_policy_document.devbox_bucket[0].json +} + +resource "aws_eks_pod_identity_association" "devbox" { + for_each = local.devbox_roles + cluster_name = module.eks.cluster_name + namespace = "ate-system" + service_account = each.key + role_arn = aws_iam_role.devbox[each.key].arn +} + +output "devbox_snapshot_location" { + value = try("s3://${aws_s3_bucket.devbox[0].id}/substrate/", "") +} + +output "devbox_karpenter_queue" { + value = try(module.devbox_karpenter[0].queue_name, "") +} + +output "devbox_node_role" { + value = try(module.devbox_karpenter[0].node_iam_role_name, "") +} + +output "devbox_subnet_ids" { + value = join(",", module.vpc.private_subnets) +} + +output "devbox_node_security_group_id" { + value = module.eks.node_security_group_id +} diff --git a/terraform/clouds/aws/eks.tf b/terraform/clouds/aws/eks.tf index e64108d0..fab34549 100644 --- a/terraform/clouds/aws/eks.tf +++ b/terraform/clouds/aws/eks.tf @@ -50,6 +50,9 @@ module "eks" { create_kms_key = true + # Access entries only, no aws-auth ConfigMap. EKS creates the managed node groups' entries; Karpenter's devbox node + # role gets one from its module (devbox.tf). + authentication_mode = "API" enable_cluster_creator_admin_permissions = false access_entries = { @@ -83,6 +86,19 @@ module "eks" { data.aws_iam_session_context.current.issuer_arn ], var.additional_kms_administrators) + # the module only opens DNS and ephemeral ports between nodes; Agent Substrate's workers reach ate-api-server, + # atenet-router and atenet-egress on 443 on other nodes + node_security_group_additional_rules = { + ingress_self_https = { + description = "Node to node HTTPS" + protocol = "tcp" + from_port = 443 + to_port = 443 + type = "ingress" + self = true + } + } + # EKS Managed Node Group(s) eks_managed_node_group_defaults = var.node_group_defaults eks_managed_node_groups = local.full_node_groups diff --git a/terraform/clouds/aws/runtime.tf b/terraform/clouds/aws/runtime.tf index 4347634b..ed83bfce 100644 --- a/terraform/clouds/aws/runtime.tf +++ b/terraform/clouds/aws/runtime.tf @@ -15,6 +15,10 @@ module "eks_blueprints_addons" { defaultStorageClass = { enabled = true } + # the node plugin mounts devbox homes on the devbox pool, whose nodes carry sandbox and disk-prep taints + node = { + tolerateAllTaints = true + } }) } coredns = { @@ -30,11 +34,20 @@ module "eks_blueprints_addons" { eks-pod-identity-agent = { most_recent = true } + # serves the VolumeSnapshot API devbox homes, EBS volumes, are seeded and moved between zones through + snapshot-controller = { + most_recent = true + } } # mostly need this module to install the lb controller here. enable_aws_load_balancer_controller = true enable_cluster_autoscaler = true + # the module's default chart lacks the RBAC newer autoscalers need (DRA and VolumeAttachments), which stalls + # them before they ever scale + cluster_autoscaler = { + chart_version = "9.60.0" + } enable_metrics_server = true depends_on = [ diff --git a/terraform/clouds/aws/variables.tf b/terraform/clouds/aws/variables.tf index 76829f83..0098ed34 100644 --- a/terraform/clouds/aws/variables.tf +++ b/terraform/clouds/aws/variables.tf @@ -25,12 +25,12 @@ variable "create_db" { variable "kubernetes_version" { type = string - default = "1.36" + default = "1.37" } variable "next_kubernetes_version" { type = string - default = "1.36" + default = "1.37" } @@ -128,4 +128,4 @@ variable "monitoring_role" { variable "additional_kms_administrators" { type = list(string) default = [ ] -} \ No newline at end of file +} diff --git a/terraform/clouds/azure/aks.tf b/terraform/clouds/azure/aks.tf index 436084c3..81d7d5b7 100644 --- a/terraform/clouds/azure/aks.tf +++ b/terraform/clouds/azure/aks.tf @@ -41,4 +41,9 @@ module "aks" { workload_identity_enabled = var.workload_identity_enabled oidc_issuer_enabled = var.workload_identity_enabled + + # devbox homes are Azure managed disks, seeded and moved between zones through VolumeSnapshots + storage_profile_enabled = true + storage_profile_disk_driver_enabled = true + storage_profile_snapshot_controller_enabled = true } diff --git a/terraform/clouds/azure/devbox.tf b/terraform/clouds/azure/devbox.tf new file mode 100644 index 00000000..5069fe81 --- /dev/null +++ b/terraform/clouds/azure/devbox.tf @@ -0,0 +1,148 @@ +# Plural devboxes: node auto-provisioning (AKS's managed Karpenter) for Agent Substrate's gVisor workers, the storage +# account Substrate keeps actor snapshots in, and the Workload Identity identities that reach it. Devbox homes are Azure +# managed disks. The services in bootstrap/devbox add the devbox NodePool and AKSNodeClass, Substrate and the +# DevboxRunner on top. Needs workload_identity_enabled. + +variable "devbox_enabled" { + type = bool + default = true +} + +locals { + devbox = var.devbox_enabled ? 1 : 0 + # Storage account names are 3-24 lowercase alphanumerics and globally unique. + devbox_account_prefix = substr(replace(lower("ate${var.cluster_name}"), "/[^a-z0-9]/", ""), 0, 16) + # The objectstore-azure-blob plugin runs next to atelet (node) and ate-api-server (control), each as its own Entra + # identity federated to that pod's ServiceAccount. + devbox_identities = var.devbox_enabled ? { + node = "atelet" + control = "ate-api-server" + } : {} +} + +data "azurerm_client_config" "devbox" {} + +# Devbox nodes come from node auto-provisioning, which launches each one in the zone its worker's home disk is in. The +# cluster autoscaler can't: a pool spanning zones is one scale set that picks the zone itself. NAP runs beside the +# autoscaled blue and green pools only with this subscription feature; the devbox NodePool's taint and label keep the +# two from scaling for the same pods. +resource "azapi_resource_action" "devbox_nap_feature" { + count = local.devbox + type = "Microsoft.Features/providers/features@2021-07-01" + resource_id = "/subscriptions/${data.azurerm_client_config.devbox.subscription_id}/providers/Microsoft.Features/providers/Microsoft.ContainerService/features/AllowClusterAutoscalerAndNAP" + action = "register" + method = "POST" + response_export_values = ["properties.state"] +} + +# Registering takes a few minutes and azapi 1.x, which the AKS module pins, can't poll it. If AKS still rejects NAP +# below, apply again. +resource "time_sleep" "devbox_nap_feature" { + count = local.devbox + create_duration = azapi_resource_action.devbox_nap_feature[0].output.properties.state == "Registered" ? "0s" : "10m" +} + +# picks up the feature in the resource provider, as `az provider register` does +resource "azapi_resource_action" "devbox_nap_provider" { + count = local.devbox + type = "Microsoft.Resources/providers@2021-04-01" + resource_id = "/subscriptions/${data.azurerm_client_config.devbox.subscription_id}/providers/Microsoft.ContainerService" + action = "register" + method = "POST" + + depends_on = [time_sleep.devbox_nap_feature] +} + +# No default NodePools: they're untainted, so NAP would add nodes for the same pending pods as the cluster autoscaler. +# The only NodePool is the devbox one in services/devbox. +resource "azapi_update_resource" "devbox_nap" { + count = local.devbox + type = "Microsoft.ContainerService/managedClusters@2025-10-01" + resource_id = module.aks.aks_id + + body = { + properties = { + nodeProvisioningProfile = { + mode = "Auto" + defaultNodePools = "None" + } + } + } + + timeouts { + create = "40m" + update = "40m" + } + + # NAP joins nodes to the cluster's subnet as the cluster identity, which needs to read and join it + depends_on = [azapi_resource_action.devbox_nap_provider, azurerm_role_assignment.aks-network-identity-ssi] +} + +resource "random_string" "devbox" { + count = local.devbox + length = 8 + upper = false + special = false +} + +resource "azurerm_storage_account" "devbox" { + count = local.devbox + name = "${local.devbox_account_prefix}${random_string.devbox[0].result}" + resource_group_name = local.resource_group.name + location = local.resource_group.location + account_tier = "Standard" + account_replication_type = "LRS" + min_tls_version = "TLS1_2" + allow_nested_items_to_be_public = false +} + +resource "azurerm_storage_container" "devbox" { + count = local.devbox + name = "snapshots" + storage_account_name = azurerm_storage_account.devbox[0].name + container_access_type = "private" +} + +resource "azurerm_user_assigned_identity" "devbox" { + for_each = local.devbox_identities + name = "${var.cluster_name}-${each.value}" + resource_group_name = local.resource_group.name + location = local.resource_group.location +} + +resource "azurerm_federated_identity_credential" "devbox" { + for_each = local.devbox_identities + name = "ate-system-${each.value}" + resource_group_name = local.resource_group.name + parent_id = azurerm_user_assigned_identity.devbox[each.key].id + audience = ["api://AzureADTokenExchange"] + issuer = module.aks.oidc_issuer_url + subject = "system:serviceaccount:ate-system:${each.value}" +} + +resource "azurerm_role_assignment" "devbox" { + for_each = local.devbox_identities + scope = azurerm_storage_account.devbox[0].id + role_definition_name = "Storage Blob Data Contributor" + principal_id = azurerm_user_assigned_identity.devbox[each.key].principal_id +} + +output "devbox_snapshot_location" { + value = try("azblob://${azurerm_storage_container.devbox[0].name}/substrate/", "") +} + +output "devbox_account_url" { + value = try(trimsuffix(azurerm_storage_account.devbox[0].primary_blob_endpoint, "/"), "") +} + +output "devbox_tenant_id" { + value = data.azurerm_client_config.devbox.tenant_id +} + +output "devbox_node_client_id" { + value = try(azurerm_user_assigned_identity.devbox["node"].client_id, "") +} + +output "devbox_control_client_id" { + value = try(azurerm_user_assigned_identity.devbox["control"].client_id, "") +} diff --git a/terraform/clouds/azure/providers.tf b/terraform/clouds/azure/providers.tf index 6bf643f0..fc381369 100644 --- a/terraform/clouds/azure/providers.tf +++ b/terraform/clouds/azure/providers.tf @@ -6,5 +6,14 @@ terraform { source = "hashicorp/azurerm" version = ">=3.51.0, < 4.0" } + # 1.x, as the AKS module pins it + azapi = { + source = "Azure/azapi" + version = ">= 1.13, < 2.0" + } + time = { + source = "hashicorp/time" + version = ">= 0.9" + } } -} \ No newline at end of file +} diff --git a/terraform/clouds/azure/variables.tf b/terraform/clouds/azure/variables.tf index 54ad0f34..1e879685 100644 --- a/terraform/clouds/azure/variables.tf +++ b/terraform/clouds/azure/variables.tf @@ -15,7 +15,7 @@ variable "create_db" { variable "kubernetes_version" { type = string - default = "1.36" + default = "1.37" } variable "next_kubernetes_version" { @@ -108,4 +108,4 @@ variable "node_pools" { enable_auto_scaling = true } } -} \ No newline at end of file +} diff --git a/terraform/clouds/gcp/devbox.tf b/terraform/clouds/gcp/devbox.tf new file mode 100644 index 00000000..1b377076 --- /dev/null +++ b/terraform/clouds/gcp/devbox.tf @@ -0,0 +1,173 @@ +# Plural devboxes: a node pool for Agent Substrate's gVisor workers, the bucket Substrate keeps actor snapshots in, +# and the Workload Identity service accounts that reach it. Devbox homes are Persistent Disks in the pool's zone. The +# services in bootstrap/devbox install Substrate and the DevboxRunner on top. + +variable "devbox_enabled" { + type = bool + default = true +} + +variable "devbox_machine_type" { + type = string + default = "n2-standard-8" +} + +# gVisor snapshots need a single CPU model across the pool, so it runs in one zone on one CPU platform. +variable "devbox_min_cpu_platform" { + type = string + default = "Intel Ice Lake" +} + +variable "devbox_max_nodes" { + type = number + default = 5 +} + +variable "devbox_boot_disk_size" { + type = number + default = 250 + description = "size in GiB of the boot disk, which also holds /var/lib/ate" +} + +locals { + devbox = var.devbox_enabled ? 1 : 0 + # Service account ids are 6-30 characters, so the cluster part is capped. + devbox_suffix = trim(substr(replace(lower(var.cluster_name), "/[^a-z0-9-]/", "-"), 0, 18), "-") + devbox_bucket_members = var.devbox_enabled ? { + api = google_service_account.devbox_api_server[0].email + transfer = google_service_account.devbox_transfer[0].email + } : {} +} + +data "google_compute_zones" "devbox" { + project = var.project_id + region = var.region +} + +resource "google_container_node_pool" "devbox" { + count = local.devbox + name = "devbox" + project = var.project_id + location = var.region + cluster = module.gke.name + node_locations = [data.google_compute_zones.devbox.names[0]] + initial_node_count = 1 + + # Block homes make the deployment operator run a WorkerPool per zone of the nodes matching the pool's label, or + # of every node before one does. The pool always keeps a node, so the operator finds its zone rather than the + # zones of the other pools, where no devbox node can start. The runner's minimum worker needs a whole node anyway. + autoscaling { + total_min_node_count = 1 + total_max_node_count = var.devbox_max_nodes + location_policy = "ANY" + } + + management { + auto_repair = true + auto_upgrade = true + } + + node_config { + machine_type = var.devbox_machine_type + min_cpu_platform = var.devbox_min_cpu_platform + image_type = "UBUNTU_CONTAINERD" + disk_size_gb = var.devbox_boot_disk_size + disk_type = "pd-balanced" + service_account = module.gke.service_account + oauth_scopes = ["https://www.googleapis.com/auth/cloud-platform"] + + labels = { + "plural.sh/devbox-pool" = "devbox" + } + + taint { + key = "ate.dev/sandboxClass" + value = "gvisor" + effect = "NO_SCHEDULE" + } + + # lifted by devbox-disk-prep; /var/lib/ate stays on the boot disk, so there's nothing to format + taint { + key = "plural.sh/devbox-disk" + value = "pending" + effect = "NO_SCHEDULE" + } + + workload_metadata_config { + mode = "GKE_METADATA" + } + + shielded_instance_config { + enable_secure_boot = true + } + } + + lifecycle { + ignore_changes = [initial_node_count] + } +} + +resource "google_storage_bucket" "devbox" { + count = local.devbox + project = var.project_id + name = trim(substr("${var.project_id}-${local.devbox_suffix}-ate", 0, 63), "-") + location = var.region + uniform_bucket_level_access = true + public_access_prevention = "enforced" + # snapshots only outlive their devboxes, which go with the cluster + force_destroy = true +} + +resource "google_service_account" "devbox_api_server" { + count = local.devbox + project = var.project_id + account_id = "ate-api-${local.devbox_suffix}" + display_name = "Agent Substrate ate-api-server on ${var.cluster_name}" +} + +# ate-api-server impersonates this account for every snapshot transfer, with credentials scoped to one actor, so +# atelet itself needs no access to the bucket. +resource "google_service_account" "devbox_transfer" { + count = local.devbox + project = var.project_id + account_id = "ate-xfer-${local.devbox_suffix}" + display_name = "Agent Substrate snapshot transfers on ${var.cluster_name}" +} + +resource "google_service_account_iam_member" "devbox_api_server_workload_identity" { + count = local.devbox + service_account_id = google_service_account.devbox_api_server[0].name + role = "roles/iam.workloadIdentityUser" + member = "serviceAccount:${var.project_id}.svc.id.goog[ate-system/ate-api-server]" +} + +resource "google_service_account_iam_member" "devbox_transfer_token_creator" { + count = local.devbox + service_account_id = google_service_account.devbox_transfer[0].name + role = "roles/iam.serviceAccountTokenCreator" + member = "serviceAccount:${google_service_account.devbox_api_server[0].email}" +} + +resource "google_storage_bucket_iam_member" "devbox" { + for_each = var.devbox_enabled ? { + "api-object-admin" = { role = "roles/storage.objectAdmin", sa = "api" } + "api-bucket-viewer" = { role = "roles/storage.bucketViewer", sa = "api" } + "transfer-object-admin" = { role = "roles/storage.objectAdmin", sa = "transfer" } + "transfer-bucket-viewer" = { role = "roles/storage.bucketViewer", sa = "transfer" } + } : {} + bucket = google_storage_bucket.devbox[0].name + role = each.value.role + member = "serviceAccount:${local.devbox_bucket_members[each.value.sa]}" +} + +output "devbox_snapshot_location" { + value = try("gs://${google_storage_bucket.devbox[0].name}/substrate/", "") +} + +output "devbox_api_server_service_account" { + value = try(google_service_account.devbox_api_server[0].email, "") +} + +output "devbox_transfer_service_account" { + value = try(google_service_account.devbox_transfer[0].email, "") +} diff --git a/terraform/clouds/gcp/gke.tf b/terraform/clouds/gcp/gke.tf index a3e7804e..17a5f8dc 100644 --- a/terraform/clouds/gcp/gke.tf +++ b/terraform/clouds/gcp/gke.tf @@ -48,6 +48,9 @@ module "gke" { datapath_provider = "ADVANCED_DATAPATH" + # devbox homes are Persistent Disks, which the driver also snapshots through the VolumeSnapshot API GKE serves with it + gce_pd_csi_driver = true + release_channel = "UNSPECIFIED" depends_on = [ diff --git a/terraform/clouds/gcp/variables.tf b/terraform/clouds/gcp/variables.tf index f3fc5880..044dff1c 100644 --- a/terraform/clouds/gcp/variables.tf +++ b/terraform/clouds/gcp/variables.tf @@ -15,12 +15,12 @@ variable "deletion_protection" { variable "kubernetes_version" { type = string - default = "1.36" + default = "1.37" } variable "next_kubernetes_version" { type = string - default = "1.36" + default = "1.37" } variable "node_pools" { diff --git a/terraform/modules/clusters/aws/addons.tf b/terraform/modules/clusters/aws/addons.tf index 0bd7c951..4bfa016d 100644 --- a/terraform/modules/clusters/aws/addons.tf +++ b/terraform/modules/clusters/aws/addons.tf @@ -27,6 +27,10 @@ module "addons" { kube-proxy = { most_recent = true } + # lets workloads such as Agent Substrate get AWS credentials through EKS Pod Identity + eks-pod-identity-agent = { + most_recent = true + } } # mostly need this module to install the lb controller here. diff --git a/terraform/modules/clusters/aws/eks.tf b/terraform/modules/clusters/aws/eks.tf index d85df83e..c3bb4de1 100644 --- a/terraform/modules/clusters/aws/eks.tf +++ b/terraform/modules/clusters/aws/eks.tf @@ -8,11 +8,16 @@ locals { module "eks" { source = "terraform-aws-modules/eks/aws" - version = "~> 19.0" + version = "~> 20.0" cluster_name = var.cluster cluster_version = var.kubernetes_version + # Nodes and principals authenticate through EKS access entries; EKS creates the managed node groups' entries, and + # the identity applying this stack, which registers the cluster with Plural below, gets a cluster admin one. + authentication_mode = "API_AND_CONFIG_MAP" + enable_cluster_creator_admin_permissions = true + cluster_endpoint_public_access = var.public vpc_id = local.vpc.vpc_id diff --git a/terraform/modules/clusters/aws/variables.tf b/terraform/modules/clusters/aws/variables.tf index 79952a5f..c8c35c13 100644 --- a/terraform/modules/clusters/aws/variables.tf +++ b/terraform/modules/clusters/aws/variables.tf @@ -23,7 +23,7 @@ variable "public" { variable "kubernetes_version" { type = string - default = "1.36" + default = "1.37" } variable "vpc_cidr" { diff --git a/terraform/modules/clusters/aws/versions.tf b/terraform/modules/clusters/aws/versions.tf index 3f54857c..a64eeb5a 100644 --- a/terraform/modules/clusters/aws/versions.tf +++ b/terraform/modules/clusters/aws/versions.tf @@ -1,10 +1,10 @@ terraform { - required_version = ">= 1.0" + required_version = ">= 1.3" required_providers { aws = { source = "hashicorp/aws" - version = "< 6.0.0" + version = ">= 5.34, < 6.0.0" } plural = {