Create an Agent Sandbox Container Edition
You can create an Agent Sandbox Container Edition (sandbox) in an ACS cluster by installing the required add-ons, creating a warm pool, integrating an SDK, and configuring a domain name and certificate for a production environment.
Preparations
Create an ACS cluster, and activate the Agent Sandbox Container Edition Service.
If you already have a cluster, you must also upgrade the following to the required versions after you activate the service.
Upgrade the
acs-virtual-nodeadd-on to v2.17.0 or later.Upgrade the
Kube Schedulercomponent.Cluster version
Kube Schedulercomponent versionv1.28
v1.28.12-aliyun-1.4.6 or later
v1.30
v1.30.3-aliyun-1.6.2 or later
v1.31
v1.31.0-aliyun-1.5.2 or later
v1.32
v1.32.0-apsara.6.11.11.3187ac8f or later
Install add-ons
If the add-ons are already installed, upgrade the ack-agent-sandbox-controller add-on to v0.5.14-release.1 or later, and upgrade the ack-sandbox-manager add-on to v0.6.0 or later.
Log on to the ACS console. In the left navigation pane, click Clusters.
On the Clusters page, click the name of the target cluster. In the left navigation pane, choose Add-ons.
Install the ack-agent-sandbox-controller add-on.
When you install this component for the first time, you must grant the AliyunCSManagedAgentSandboxRole role permissions to access your cloud resources. You can use the default parameter settings. If you require higher concurrency, you can increase the resource specifications.
For more information about the features of this add-on, see ack-agent-sandbox-controller.
Install an Ingress controller add-on.
Install any Ingress controller add-on supported by ACS to access the
sandbox-managerService from outside the cluster. The following steps create an Internet-facing ALB instance as described in Install the ALB Ingress Controller.Prepare an E2B domain name. For more information about how to prepare a domain name, configure DNS resolution, and apply for a certificate, see Configure a domain name and certificate.
If you use ALB Ingress Controller, you must also add an HTTPS:443 listener configuration to both the ALB instance and the Ingress.
Install the ack-sandbox-manager add-on.
Configure the add-on parameters.
Set
classNametoalb(the IngressClass created by the Ingress controller that you installed in the previous step), setdomainto your actual domain name, and setadminApiKeyto a custom API key. Keep the other settings at their default values. After the add-on is installed, an Ingress is created in thesandbox-systemnamespace with the namesandbox-manager.
Create an Agent Sandbox Container Edition
Step 1: Create a warm pool by using SandboxSet
A warm pool is a set of pre-created Sandbox replicas managed by the SandboxSet CR. Applications obtain ready Sandboxes directly from the warm pool, which significantly improves delivery efficiency.
In the left-side navigation pane, click Custom Resources, choose the CRDs tab, and then click Create from YAML.
Use the following YAML to create a SandboxSet resource. ack-sandbox-manager automatically watches and identifies the resource, and initializes a sandbox template configuration named code-interpreter at the same time.
apiVersion: agents.kruise.io/v1alpha1 kind: SandboxSet metadata: name: code-interpreter namespace: default spec: runtimes: - name: csi # Supports CSI mounting. Newly created Sandboxes are injected with the corresponding Sidecar - name: agent-runtime # Injects environment management tools such as envd replicas: 4 template: metadata: labels: alibabacloud.com/acs: "true" alibabacloud.com/compute-class: agent-sandbox # Agent Sandbox instance type alibabacloud.com/compute-qos: default # Compute QoS: default spec: automountServiceAccountToken: false containers: - image: registry-cn-zhangjiakou-vpc.ack.aliyuncs.com/acs/code-interpreter:v1.6 # Replace with the region where your cluster is deployed imagePullPolicy: IfNotPresent name: sandbox resources: limits: cpu: "1" memory: 1Gi requests: cpu: "1" memory: 1Gi ephemeral-storage: 30Gi terminationGracePeriodSeconds: 30For more information about the fields and advanced configurations of the SandboxSet CRD, see Sandbox CRD field descriptions.
ImportantThe code-interpreter image is intended only for verification in test environments. If you want to deploy it in a production environment, you must perform the necessary security hardening. Expand the section below to view the detailed image instructions.
code-interpreterimage usage instructionsIn the left-side navigation pane, click Pods, select the corresponding namespace, and view the created
code-interpreterSandbox.You can run the
kubectl get sbscommand to view SandboxSet resources, whereAVAILABLEindicates the number of Sandboxes that are ready.
After a Sandbox is allocated, SandboxSet automatically triggers the replenishment process to maintain the number of instances in the warm pool.
Step 2: Obtain an Agent Sandbox Container Edition
E2B SDK method
You can use the E2B SDK to develop and deploy projects and view the results on the platform, including running code (run_code), reading and writing files (files.write/files.read), and running commands (commands.run). For more information about how to use the SDK, see Connect to Agent Sandbox Container Edition by using the E2B SDK.
Install Python in your local environment.
Install the E2B Python SDK.
pip install "e2b-code-interpreter" "e2b"Configure environment variables.
# Uses the default domain name configured when you installed the ack-sandbox-manager add-on. Do not include *. You can modify it based on your actual configuration. export E2B_DOMAIN=your.domain.com # Uses the default API key configured when you installed the ack-sandbox-manager add-on. You can modify it based on your actual configuration. export E2B_API_KEY=e2b_abcdef # The path to the CA certificate that the client must trust, as used in the steps to configure the domain name and certificate export SSL_CERT_FILE=/path/to/ca-fullchain.pemNoteReplace the value of the E2B_API_KEY variable with the value that you actually configured.
Save the following code as the
main.pyfile.# Import the E2B SDK from e2b_code_interpreter import Sandbox sbx: Sandbox = Sandbox.create(template="code-interpreter") print(f"sandbox id: {sbx.sandbox_id}") result = sbx.run_code("print('hello, world')") print(f"run code result: {result}") text = input("enter some text to be saved to file 'text.txt' inside sandbox: ") sbx.files.write("text.txt", text) print(f"read file from sandbox via files api: [{sbx.files.read('text.txt')}]") print(f"read file from sandbox via commands api: [{sbx.commands.run('cat text.txt')}]") input("press ENTER to kill the sandbox") print(sbx.kill())Run the
main.pyfile to create and verify the Sandbox.After the first prompt appears, enter text such as
acs agent sandbox, and then press ENTER. In the Pod namedcode-interpreter-29***, the text is written to the/home/user/text.txtfile:acs agent sandbox. If you press ENTER again, the current Sandbox is deleted.python main.pyExpected output:
sandbox id: default--code-interpreter-29*** run code result: Execution(Results: [], Logs: Logs(stdout: ['hello, world\n'], stderr: []), Error: None) enter some text to be saved to file 'text.txt' inside sandbox: acs agent sandbox read file from sandbox via files api: [acs agent sandbox] read file from sandbox via commands api: [CommandResult(stderr='', stdout='acs agent sandbox', exit_code=0, error='')] press ENTER to kill the sandbox True
SandboxClaim method
After the warm pool allocates a Sandbox, the automatic replenishment logic starts immediately to quickly backfill warm instances.
In the left-side navigation pane, click Custom Resources, choose the CRDs tab, and then click Create from YAML.
Use the following YAML to create a SandboxClaim resource to obtain a Sandbox.
apiVersion: agents.kruise.io/v1alpha1 kind: SandboxClaim metadata: name: code-interpreter # SandboxSet name namespace: default # SandboxSet namespace spec: templateName: code-interpreter # Specifies the name of the SandboxSet replicas: 1 # The number of sandboxes to obtain from the SandboxSet claimTimeout: 5m # Specifies the timeout period of the SandboxClaim ttlAfterCompleted: 15m # Specifies the TTL period after the SandboxClaim completes. After the task completes and the TTL period elapses, the SandboxClaim resource is deleted (the obtained sandbox is not deleted).In the left-side navigation pane, click Pods, select the
defaultnamespace, and view the newly obtained Sandbox namedcode-interpreter-xxxxx.You can run the
kubectl get sbx -l agents.kruise.io/claim-name=code-interpretercommand to obtain the Sandbox status.
Developers can also manage Sandbox resources by using the Kubernetes SDK.
Replace the Agent Sandbox Container Edition container image
E2B SDK method
Refer to the following Python code. Replace <YOUR_IMAGE> with the actual image address. After a Sandbox is taken from the warm pool, the metadata parameter is used to replace the container image with the specified image.
from e2b_code_interpreter import Sandbox
# timeout: the default duration is 300 seconds
sbx = Sandbox.create(template="some-template", timeout=300, metadata={
# Replace the image of the sandbox container in place with the specified image
"e2b.agents.kruise.io/image": "<YOUR_IMAGE>"
})Sandboxes support image caching (Image Cache) to accelerate image pulls. You can use the Annotation ops.alibabacloud.com/update-with-image-cache to control when the image cache is used. The valid values and applicable scenarios are as follows:
false(default): Uses the image cache when the warm pool scales out . In this mode, the image cache is not used for subsequent image updates. This mode applies to scenarios where the updated image shares many layers with the warm pool image and can be largely reused.true: Uses the image cache during image updates. In this mode, the cache is not used when the warm pool scales out. This mode applies to scenarios where the warm pool uses a lightweight placeholder image, or where the target image for the update is large.
SandboxClaim method
Replace the following <YOUR_IMAGE> with the actual image address.
apiVersion: agents.kruise.io/v1alpha1
kind: SandboxClaim
metadata:
name: my-sandbox-claim
namespace: default
spec:
templateName: code-interpreter # Specifies the name of the SandboxSet warm pool
replicas: 1
claimTimeout: 5m
ttlAfterCompleted: 15m
inplaceUpdate:
# The target image to update to
image: <YOUR_IMAGE> # Replace with the actual image addressSpecify the Agent Sandbox Container Edition resource specifications
In-place vertical scaling (VPA) is supported when a Sandbox is allocated from the warm pool. A pre-warmed sandbox instance with lower specifications can be upgraded to the specifications required by your workload without the Pod being rebuilt, which balances fast provisioning from the warm pool with the differentiated resource requirements of your workload.
Only CPU adjustments are currently supported. Memory and other resources are ignored, and only the main container is adjusted. For more information about the limits and usage notes, see In-place vertical scaling for containers based on CPU metrics.
If the cluster version is earlier than 1.32, you must go to the Add-ons page and set the feature gate of Kube API Server to
InPlacePodVerticalScaling=trueto enable in-place resource resizing.
Step 1: Enable in-place resource resizing for SandboxSet
In the spec.template.metadata.annotations of the SandboxSet, add scaling.alibabacloud.com/enable-inplace-resource-resize: "true" to allow Sandboxes in the warm pool to perform in-place VPA when they are allocated.
The following example creates only a warm pool with smaller specifications. You can specify specifications to dynamically scale out during subsequent allocations.
apiVersion: agents.kruise.io/v1alpha1
kind: SandboxSet
metadata:
name: code-interpreter
spec:
template:
metadata:
annotations:
# When a Sandbox is allocated from the warm pool, allow in-place VPA
scaling.alibabacloud.com/enable-inplace-resource-resize: "true"
spec:
containers:
- name: interpreter
image: xxx
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: 500m
memory: 1Gi
replicas: 5 # The number of warm instancesStep 2: Declare the target resource specifications during allocation
When you allocate an Agent Sandbox Container Edition from the warm pool, you can dynamically scale the CPU to the specified specifications in the following two ways:
E2B SDK method
In Sandbox.create, use the agreed keys in metadata to declare the target CPU specifications.
from e2b_code_interpreter import Sandbox
sbx = Sandbox.create(template="code-interpreter", metadata={
"e2b.agents.kruise.io/cpu-request": "1000m",
"e2b.agents.kruise.io/cpu-limit": "1000m"
})SandboxClaim method
Declare the target resource specifications in the spec.inplaceUpdate.resources field of SandboxClaim.
apiVersion: agents.kruise.io/v1alpha1
kind: SandboxClaim
metadata:
name: code-interpreter-vpa-claim
namespace: default
spec:
templateName: code-interpreter
replicas: 1
claimTimeout: 5m
ttlAfterCompleted: 15m
inplaceUpdate: # Declare the target resource specifications
resources:
requests:
cpu: 1000m
limits:
cpu: 1000mDelete an Agent Sandbox Container Edition
To completely remove an instance, you can delete the sandbox in the following ways.
E2B SDK method
Delete a sandbox instance through the E2B SDK: replace the following <YOUR_SANDBOX_ID> with the actual sandbox id.
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.connect("<YOUR_SANDBOX_ID>")
sandbox.kill()Sandbox CR method
# Before you run the command, replace <NAMESPACE> with the namespace of the resource and <RESOURCE_NAME> with the actual CR name
kubectl -n <NAMESPACE> delete sandbox <RESOURCE_NAME>Configure a domain name and certificate
Prepare a domain name
For more information, see Add or delete an Authoritative Zone. Configure the domain names your.domain.com and *.your.domain.com, and resolve them to the address of the Ingress. If access is entirely within the ACS cluster, you can also directly use the in-cluster Headless Service address: sandbox-manager.sandbox-system.svc.cluster.local.
Apply for a certificate
The E2B client must request the backend over the HTTPS protocol. In production scenarios, we recommend that you use the following methods to apply for a certificate.
(Recommended) Method 1: Manage certificates by using cert-manager
Method 2: Use a self-signed certificate
Method 3: Use an official certificate (Let's Encrypt as an example)
DNS resolution
Run the following command to view the endpoint information:
kubectl get ingress sandbox-manager -o jsonpath='{range .status.loadBalancer.ingress[*]}{.hostname}{.ip}{"\n"}{end}' -n sandbox-systemBased on the endpoint information in the output, configure DNS resolution for the domain name your.domain.com or *.your.domain.com. For more information about DNS resolution, see Quick links.
If the output is an IP address (such as
47.114.***.***), resolve the host record*.your.domain.comto that IP address as an A record.If the output is a domain name (such as
alb-*****62roo70i*****.cn-hangzhou.alb.aliyuncsslb.com), resolve the host record*.your.domain.comto the corresponding domain name as a CNAME record.If multiple endpoints are output, you can resolve the record to any one of the endpoints, or configure round-robin for all endpoints.
FAQ
The ack-agent-sandbox-controller add-on fails to install. Error message: RAM Role AliyunCSManagedAgentSandboxRole is not granted
Go to the Resource Access Management (RAM) Roles page, search for AliyunCSManagedAgentSandboxRole, and then click the role name to open the role details page.
On the role details page, select AliyunCSManagedAgentSandboxRolePolicy, and then click Remove Permission.
Grant the permissions again. Click the authorization link.
Sandbox creation times out or returns an errore2b create sandbox: status 500
For various reasons, errors may occur while a sandbox is being obtained, which causes the allocation of a sandbox from the warm pool to fail. By default, Sandbox Manager and SandboxClaim Controller delete the sandbox on which an error occurred and retry allocating a new sandbox. If you need to retain the failed Sandbox instance and its corresponding Pod for troubleshooting, you can add the following parameters when you obtain the sandbox to skip the deletion:
E2B SDK method
In Sandbox.create, use the agreed keys in metadata to declare the target CPU specifications.
from e2b_code_interpreter import Sandbox
sbx = Sandbox.create(template="some-template", timeout=3000, metadata={
"e2b.agents.kruise.io/reserve-failed-sandbox": "true"
})SandboxClaim method
Declare the target resource specifications in the spec.inplaceUpdate.resources field of SandboxClaim.
apiVersion: agents.kruise.io/v1alpha1
kind: SandboxClaim
metadata:
name: code-interpreter-vpa-claim
namespace: default
spec:
templateName: code-interpreter
replicas: 1
reserveFailedSandbox: true