agentenv-framework 0.9.1254__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_env/__init__.py +0 -0
- agent_env/a2a_agent/__init__.py +23 -0
- agent_env/a2a_agent/a2a_agent.py +600 -0
- agent_env/a2a_agent/conversation_store.py +356 -0
- agent_env/a2a_agent/object_transfer.py +609 -0
- agent_env/a2a_agent/protocol.py +238 -0
- agent_env/a2a_agent/store.py +201 -0
- agent_env/a2a_agent/validator.py +901 -0
- agent_env/artifact/__init__.py +48 -0
- agent_env/artifact/artifact.py +74 -0
- agent_env/artifact/artifacts/__init__.py +0 -0
- agent_env/artifact/artifacts/cli.py +83 -0
- agent_env/artifact/artifacts/docker_image.py +457 -0
- agent_env/artifact/artifacts/environment.py +89 -0
- agent_env/artifact/artifacts/environment_universe.py +156 -0
- agent_env/artifact/artifacts/file.py +214 -0
- agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
- agent_env/artifact/artifacts/skill.py +206 -0
- agent_env/artifact/artifacts/vm_image.py +95 -0
- agent_env/artifact/ref.py +15 -0
- agent_env/artifact/registry.py +251 -0
- agent_env/artifact/store.py +295 -0
- agent_env/artifact/universe.py +38 -0
- agent_env/attribution.py +41 -0
- agent_env/bundle/__init__.py +4 -0
- agent_env/bundle/_fs.py +128 -0
- agent_env/bundle/authoring.py +239 -0
- agent_env/bundle/installed.py +175 -0
- agent_env/bundle/ledger.py +269 -0
- agent_env/bundle/materialize.py +204 -0
- agent_env/bundle/parse.py +594 -0
- agent_env/bundle/plan.py +414 -0
- agent_env/bundle/resolve.py +404 -0
- agent_env/bundle/run.py +361 -0
- agent_env/cli/__init__.py +69 -0
- agent_env/cli/__main__.py +10 -0
- agent_env/cli/_installers.py +576 -0
- agent_env/cli/_plugin_changes.py +947 -0
- agent_env/cli/a2a_agent/__init__.py +22 -0
- agent_env/cli/a2a_agent/add_skill.py +97 -0
- agent_env/cli/a2a_agent/deploy.py +60 -0
- agent_env/cli/a2a_agent/get.py +15 -0
- agent_env/cli/a2a_agent/get_instance.py +26 -0
- agent_env/cli/a2a_agent/put.py +78 -0
- agent_env/cli/a2a_agent/validate.py +56 -0
- agent_env/cli/artifact/__init__.py +20 -0
- agent_env/cli/artifact/cli.py +83 -0
- agent_env/cli/artifact/environment.py +44 -0
- agent_env/cli/artifact/environment_universe.py +163 -0
- agent_env/cli/artifact/file_artifact_universe.py +281 -0
- agent_env/cli/artifact/skill.py +128 -0
- agent_env/cli/banner.py +25 -0
- agent_env/cli/config.py +263 -0
- agent_env/cli/env/__init__.py +31 -0
- agent_env/cli/env/deploy.py +112 -0
- agent_env/cli/env/gateway.py +57 -0
- agent_env/cli/env/get_instance.py +40 -0
- agent_env/cli/env/mcp_server.py +410 -0
- agent_env/cli/env/multi.py +282 -0
- agent_env/cli/env/service_db.py +99 -0
- agent_env/cli/env/snapshot.py +35 -0
- agent_env/cli/env/state/__init__.py +6 -0
- agent_env/cli/env/state/init.py +108 -0
- agent_env/cli/env/state/teardown.py +44 -0
- agent_env/cli/env/website.py +216 -0
- agent_env/cli/env/website_browser.py +67 -0
- agent_env/cli/eval/__init__.py +16 -0
- agent_env/cli/eval/add_tasks.py +63 -0
- agent_env/cli/eval/create.py +49 -0
- agent_env/cli/eval/run.py +194 -0
- agent_env/cli/identity/__init__.py +5 -0
- agent_env/cli/identity/client_identity.py +37 -0
- agent_env/cli/plugin.py +438 -0
- agent_env/cli/run.py +285 -0
- agent_env/cli/task/__init__.py +21 -0
- agent_env/cli/task/create.py +109 -0
- agent_env/cli/task/get.py +17 -0
- agent_env/cli/task/get_instance.py +34 -0
- agent_env/cli/task/run.py +615 -0
- agent_env/cli/task/validate.py +31 -0
- agent_env/cli/up.py +123 -0
- agent_env/cli/utils.py +183 -0
- agent_env/config/__init__.py +50 -0
- agent_env/config/describe.py +1067 -0
- agent_env/config/errors.py +13 -0
- agent_env/config/loader.py +245 -0
- agent_env/config/model.py +154 -0
- agent_env/config/paths.py +25 -0
- agent_env/config/plugin_tables.py +101 -0
- agent_env/config/provenance.py +134 -0
- agent_env/config/runtime.py +1064 -0
- agent_env/config/snapshot.py +81 -0
- agent_env/entity_refs.py +186 -0
- agent_env/env/__init__.py +49 -0
- agent_env/env/env.py +433 -0
- agent_env/env/env_artifact_store.py +87 -0
- agent_env/env/envs/__init__.py +7 -0
- agent_env/env/envs/_deployment.py +281 -0
- agent_env/env/envs/gateway_server.py +32 -0
- agent_env/env/envs/mcp_server.py +387 -0
- agent_env/env/envs/multi_env.py +780 -0
- agent_env/env/envs/service_db/Dockerfile +20 -0
- agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
- agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
- agent_env/env/envs/service_db.py +92 -0
- agent_env/env/envs/website.py +294 -0
- agent_env/env/envs/website_browser/Dockerfile +40 -0
- agent_env/env/envs/website_browser/__init__.py +17 -0
- agent_env/env/envs/website_browser/entrypoint.sh +13 -0
- agent_env/env/gateway/Dockerfile +14 -0
- agent_env/env/gateway/__init__.py +37 -0
- agent_env/env/gateway/clock.py +184 -0
- agent_env/env/gateway/constants.py +190 -0
- agent_env/env/gateway/entrypoint.py +156 -0
- agent_env/env/gateway/gateway.py +1095 -0
- agent_env/env/gateway/get_time.py +60 -0
- agent_env/env/gateway/requirements.txt +4 -0
- agent_env/env/gateway/triggers.py +1193 -0
- agent_env/env/legacy_protocol.py +146 -0
- agent_env/env/registry.py +93 -0
- agent_env/env/snapshot_store.py +372 -0
- agent_env/env/store.py +411 -0
- agent_env/eval/__init__.py +14 -0
- agent_env/eval/eval.py +68 -0
- agent_env/eval/store.py +116 -0
- agent_env/examples/hello/README.md +9 -0
- agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
- agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
- agent_env/examples/hello/tasks/hello.json +10 -0
- agent_env/explorer/__init__.py +12 -0
- agent_env/explorer/app.py +277 -0
- agent_env/explorer/openapi_docs.py +242 -0
- agent_env/explorer/plugin.py +95 -0
- agent_env/explorer/routers/__init__.py +1 -0
- agent_env/explorer/routers/common.py +174 -0
- agent_env/explorer/routers/conversations.py +25 -0
- agent_env/explorer/routers/objects.py +112 -0
- agent_env/explorer/routers/runs.py +475 -0
- agent_env/plugins/__init__.py +59 -0
- agent_env/plugins/_cli.py +244 -0
- agent_env/plugins/_discovery.py +97 -0
- agent_env/plugins/_inventory.py +262 -0
- agent_env/plugins/_registration.py +268 -0
- agent_env/plugins/_report.py +47 -0
- agent_env/plugins/_requirements.py +55 -0
- agent_env/providers/__init__.py +37 -0
- agent_env/providers/env_providers/__init__.py +12 -0
- agent_env/providers/env_providers/constants.py +13 -0
- agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
- agent_env/providers/env_providers/env_provider.py +237 -0
- agent_env/providers/env_providers/env_server_provider.py +133 -0
- agent_env/providers/env_state/__init__.py +49 -0
- agent_env/providers/env_state/env_state_provider.py +554 -0
- agent_env/providers/env_state/local_postgres.py +390 -0
- agent_env/providers/env_state/store.py +112 -0
- agent_env/providers/sandbox_providers/__init__.py +29 -0
- agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
- agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
- agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
- agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
- agent_env/providers/sandbox_providers/e2b/template.py +158 -0
- agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
- agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
- agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
- agent_env/providers/sandbox_providers/sandbox.py +387 -0
- agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
- agent_env/py.typed +0 -0
- agent_env/runner/__init__.py +16 -0
- agent_env/runner/local_runner.py +190 -0
- agent_env/runner/runner.py +127 -0
- agent_env/runner/store.py +94 -0
- agent_env/store/__init__.py +126 -0
- agent_env/store/_google.py +68 -0
- agent_env/store/base.py +33 -0
- agent_env/store/document_store/__init__.py +60 -0
- agent_env/store/document_store/document_store.py +519 -0
- agent_env/store/document_store/dynamodb_document_store.py +306 -0
- agent_env/store/document_store/evaluation.py +199 -0
- agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
- agent_env/store/document_store/mongo_document_store.py +259 -0
- agent_env/store/document_store/sqlite_document_store.py +314 -0
- agent_env/store/ids.py +123 -0
- agent_env/store/image_store/__init__.py +34 -0
- agent_env/store/image_store/ecr_image_store.py +131 -0
- agent_env/store/image_store/google_credentials.py +113 -0
- agent_env/store/image_store/image_store.py +113 -0
- agent_env/store/image_store/local_registry_image_store.py +106 -0
- agent_env/store/image_store/oci_registry_credentials.py +196 -0
- agent_env/store/local_state.py +27 -0
- agent_env/store/object_store/__init__.py +24 -0
- agent_env/store/object_store/gcs_object_store.py +415 -0
- agent_env/store/object_store/local_object_store.py +143 -0
- agent_env/store/object_store/object_store.py +198 -0
- agent_env/store/object_store/s3_object_store.py +354 -0
- agent_env/store/query.py +112 -0
- agent_env/store/routing.py +609 -0
- agent_env/store/secret_store/__init__.py +19 -0
- agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
- agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
- agent_env/store/secret_store/local_secret_store.py +47 -0
- agent_env/store/secret_store/secret_store.py +19 -0
- agent_env/task/__init__.py +27 -0
- agent_env/task/interrupts.py +109 -0
- agent_env/task/registry.py +27 -0
- agent_env/task/step_journal.py +99 -0
- agent_env/task/store.py +940 -0
- agent_env/task/task.py +815 -0
- agent_env/task/teardown.py +142 -0
- agent_env/task_step/__init__.py +47 -0
- agent_env/task_step/context.py +195 -0
- agent_env/task_step/context_ops.py +224 -0
- agent_env/task_step/registry.py +182 -0
- agent_env/task_step/review_store.py +118 -0
- agent_env/task_step/snapshot_utils/__init__.py +2 -0
- agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
- agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
- agent_env/task_step/store.py +129 -0
- agent_env/task_step/task_step.py +173 -0
- agent_env/task_step/task_steps/__init__.py +27 -0
- agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
- agent_env/task_step/task_steps/add_skills.py +240 -0
- agent_env/task_step/task_steps/apply_server_config.py +288 -0
- agent_env/task_step/task_steps/collect_artifacts.py +940 -0
- agent_env/task_step/task_steps/deploy_agent.py +626 -0
- agent_env/task_step/task_steps/deploy_env.py +197 -0
- agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
- agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
- agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
- agent_env/task_step/task_steps/install_agent.py +376 -0
- agent_env/task_step/task_steps/load_artifact.py +775 -0
- agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
- agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
- agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
- agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
- agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
- agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
- agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
- agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
- agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
- agent_env/task_step/task_steps/peer_agents.py +92 -0
- agent_env/task_step/task_steps/prompt_agent.py +900 -0
- agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
- agent_env/task_step/task_steps/register_env_triggers.py +97 -0
- agent_env/task_step/task_steps/reset_env.py +71 -0
- agent_env/task_step/task_steps/review.py +152 -0
- agent_env/task_step/task_steps/run_code.py +461 -0
- agent_env/task_step/task_steps/run_code_runner.py +52 -0
- agent_env/task_step/task_steps/run_docker_container.py +380 -0
- agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
- agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
- agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
- agent_env/task_step/task_steps/snapshot_env.py +637 -0
- agent_env/task_step/task_steps/sync_env_clock.py +132 -0
- agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
- agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
- agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
- agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
- agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
- agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
- agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
- agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
- agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
- agent_env/task_step/thread_work.py +61 -0
- agent_env/utils/__init__.py +0 -0
- agent_env/utils/card_naming.py +108 -0
- agent_env/utils/deprecation.py +109 -0
- agent_env/utils/docker_build.py +29 -0
- agent_env/utils/exec_retry.py +77 -0
- agent_env/utils/litellm_attribution.py +59 -0
- agent_env/utils/paths.py +20 -0
- agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
- agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
- agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
- agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
- agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
- agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
- agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
"""Modal **VM-mode** sandbox provider — runs an entire env on ONE Modal VM sandbox.
|
|
2
|
+
|
|
3
|
+
This is the Modal analogue of a KubeVirt-style one-VM provider rather than of the
|
|
4
|
+
container-per-service ModalSandboxProvider. It provisions a single Modal VM sandbox
|
|
5
|
+
(`experimental_options={"vm_runtime": True}` → real Linux kernel + nested Docker),
|
|
6
|
+
so the gateway's VM path (`EnvironmentGatewayProvider._deploy_via_vm`) can `docker compose up`
|
|
7
|
+
the whole stack (postgres + N MCP servers + gateway) inside one box behind one tunnel.
|
|
8
|
+
|
|
9
|
+
Deliberately a *separate* class from ModalSandboxProvider (no shared base): the
|
|
10
|
+
container provider stays byte-for-byte unchanged, and because this is NOT an instance
|
|
11
|
+
of ModalSandboxProvider, `EnvironmentGatewayProvider._deploy_gateway` routes it to `_deploy_via_vm`
|
|
12
|
+
(not `_deploy_via_containers`) and the i6pn gate never fires — i6pn is a container-mode
|
|
13
|
+
east-west concern and is irrelevant here (one sandbox, one docker bridge).
|
|
14
|
+
|
|
15
|
+
Only the pure, stateless helpers are reused from modal_sandbox (no class coupling).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import logging
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import shlex
|
|
25
|
+
import time
|
|
26
|
+
from typing import Awaitable, Callable, ClassVar, Optional
|
|
27
|
+
|
|
28
|
+
import modal
|
|
29
|
+
|
|
30
|
+
from agent_env.providers.sandbox_providers.modal_sandbox import (
|
|
31
|
+
_ModalProcessAdapter,
|
|
32
|
+
_app_name_for_project,
|
|
33
|
+
_build_cost_attribution_tags,
|
|
34
|
+
_build_sandbox_tags,
|
|
35
|
+
_log_sandbox_started,
|
|
36
|
+
_resolve_app_base_name,
|
|
37
|
+
_tunnel_url,
|
|
38
|
+
_modal_network_kwargs,
|
|
39
|
+
)
|
|
40
|
+
from agent_env.attribution import Attribution
|
|
41
|
+
from agent_env.config import get_config
|
|
42
|
+
from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, VmSandbox
|
|
43
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_VM, SandboxProvider
|
|
44
|
+
|
|
45
|
+
logger = logging.getLogger(__name__)
|
|
46
|
+
|
|
47
|
+
# Ubuntu 22.04 + Docker engine + the compose v2 plugin baked in — the Modal-native
|
|
48
|
+
# equivalent of a KubeVirt containerdisk image with Docker pre-installed,
|
|
49
|
+
# matching its OS baseline so the two backends behave alike. Modal builds/caches this
|
|
50
|
+
# image (no ECR push / no auth — public base). `docker.io` is the engine; the compose v2
|
|
51
|
+
# plugin isn't in Ubuntu's repos, so we drop the release binary into the CLI-plugins dir.
|
|
52
|
+
# amd64: Modal VM sandboxes run x86_64, matching the linux-x86_64 compose binary.
|
|
53
|
+
_COMPOSE_VERSION = "v2.29.7"
|
|
54
|
+
_VM_IMAGE = (
|
|
55
|
+
modal.Image.from_registry("ubuntu:22.04")
|
|
56
|
+
.apt_install("docker.io", "curl", "aria2") # aria2: object downloads, see _DL_*
|
|
57
|
+
.run_commands(
|
|
58
|
+
"mkdir -p /usr/local/lib/docker/cli-plugins",
|
|
59
|
+
f"curl -sSL https://github.com/docker/compose/releases/download/{_COMPOSE_VERSION}/"
|
|
60
|
+
"docker-compose-linux-x86_64 -o /usr/local/lib/docker/cli-plugins/docker-compose",
|
|
61
|
+
"chmod +x /usr/local/lib/docker/cli-plugins/docker-compose",
|
|
62
|
+
)
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# The sandbox MAIN process. Two decoupled parts, both for robustness:
|
|
66
|
+
# 1. A best-effort log forwarder run as a *child* of this process — NOT a separate `exec`.
|
|
67
|
+
# Modal reaps an exec'd process tree when the exec call returns (that killed an earlier
|
|
68
|
+
# nohup'd forwarder); a child of the everlasting main process is not. It polls
|
|
69
|
+
# `docker ps` and, per container, streams `docker logs -f` (name-prefixed, `sed -u`
|
|
70
|
+
# unbuffered) to THIS process's stdout. Because the forwarder is a child it inherits
|
|
71
|
+
# that stdout, which Modal captures into the dashboard — so logs reach Modal with no
|
|
72
|
+
# intermediate file. There is therefore no second on-disk copy: Docker's own json-file
|
|
73
|
+
# logs (what `docker logs` reads) are the single on-disk copy, and they are size-capped
|
|
74
|
+
# at dockerd start (see _ensure_dockerd_running) so they can't fill the disk. Uses
|
|
75
|
+
# `docker ps -aq` (not `-q`) so containers that have already exited are also followed:
|
|
76
|
+
# `docker logs` persists after exit, and `docker logs -f` on an exited container just
|
|
77
|
+
# dumps its logs and returns. That keeps startup/crash logs of a short-lived or failed
|
|
78
|
+
# service (often the ones you need) instead of dropping them. New containers (compose
|
|
79
|
+
# services / the agent-api container) are picked up by the poll loop as they appear.
|
|
80
|
+
# 2. A keepalive that never exits, so liveness is fully decoupled from logging: if the
|
|
81
|
+
# forwarder child dies, this loop keeps the sandbox alive — equivalent to the previous
|
|
82
|
+
# `sleep infinity` main process. Logging can never take the env down.
|
|
83
|
+
_MAIN_SCRIPT = r'''
|
|
84
|
+
(
|
|
85
|
+
seen=""
|
|
86
|
+
while true; do
|
|
87
|
+
for c in $(docker ps -aq 2>/dev/null); do
|
|
88
|
+
case " $seen " in
|
|
89
|
+
*" $c "*) ;;
|
|
90
|
+
*)
|
|
91
|
+
seen="$seen $c"
|
|
92
|
+
n=$(docker inspect -f '{{.Name}}' "$c" 2>/dev/null | sed 's#^/##')
|
|
93
|
+
( docker logs -f --tail 200 --timestamps "$c" 2>&1 | sed -u "s/^/[$n] /" ) &
|
|
94
|
+
;;
|
|
95
|
+
esac
|
|
96
|
+
done
|
|
97
|
+
sleep 3
|
|
98
|
+
done
|
|
99
|
+
) &
|
|
100
|
+
while true; do sleep 3600; done
|
|
101
|
+
'''
|
|
102
|
+
_KEEPALIVE_CMD = ("sh", "-c", _MAIN_SCRIPT)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ModalVmSandbox(VmSandbox):
|
|
106
|
+
"""A Modal VM sandbox (vm_runtime) presented through the VmSandbox contract.
|
|
107
|
+
|
|
108
|
+
Subclasses VmSandbox so it inherits exec_script / load_docker_images / load_s3_file /
|
|
109
|
+
write_file_* unchanged — they are built on exec_with_output ->
|
|
110
|
+
exec + an in-VM Docker daemon, which this class provides. Only the Modal-specific
|
|
111
|
+
pieces (raw exec, terminate, dockerd startup) are implemented here.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
type = "modal_vm"
|
|
115
|
+
# Modal rejects an exec whose command exceeds ~48 KB, well under Linux's MAX_ARG_STRLEN.
|
|
116
|
+
_WFT_CHUNK_BYTES = 32 * 1024
|
|
117
|
+
|
|
118
|
+
def __init__(self, sb: modal.Sandbox, tunnel_urls: dict[int, str],
|
|
119
|
+
network_policy: NetworkPolicy | None = None):
|
|
120
|
+
self._sb = sb
|
|
121
|
+
self.sandbox_id = sb.object_id
|
|
122
|
+
self.tunnel_urls = tunnel_urls
|
|
123
|
+
self.vnc_url = None
|
|
124
|
+
self.mode = SANDBOX_MODE_VM
|
|
125
|
+
self.network_policy = network_policy
|
|
126
|
+
self._download_slots = asyncio.Semaphore(max(1, _dl_setting("PARALLEL_FILES", _DL_PARALLEL_FILES)))
|
|
127
|
+
|
|
128
|
+
async def terminate(self) -> None:
|
|
129
|
+
await self._sb.terminate.aio()
|
|
130
|
+
|
|
131
|
+
async def exec(self, *command: str):
|
|
132
|
+
# Modal VM sandboxes run as root and have no `sudo`; the inherited VmSandbox
|
|
133
|
+
# helpers prefix commands with "sudo" (sandbox.py). Strip it, exactly like
|
|
134
|
+
# LocalSandbox.exec does, so those helpers work unchanged.
|
|
135
|
+
cmd = [c for c in command if c != "sudo"]
|
|
136
|
+
process = await self._sb.exec.aio(*cmd, text=False)
|
|
137
|
+
return _ModalProcessAdapter(process)
|
|
138
|
+
|
|
139
|
+
async def setup_vm_for_gateway(self, exposed_ports: Optional[list[int]] = None) -> None:
|
|
140
|
+
"""Make the VM ready for the gateway deploy.
|
|
141
|
+
|
|
142
|
+
Unlike a containerdisk image that auto-starts dockerd via systemd, a Modal VM
|
|
143
|
+
sandbox does not start dockerd on its own, so we start it here. No iptables step:
|
|
144
|
+
ports are exposed via Modal `encrypted_ports` at create time, and Modal has no
|
|
145
|
+
host INPUT chain to open (contrast VmSandbox.setup_vm_for_gateway).
|
|
146
|
+
|
|
147
|
+
The container-log forwarder is NOT started here — it runs as a child of the
|
|
148
|
+
sandbox main process (see `_MAIN_SCRIPT`) so Modal can't reap it the way it reaps
|
|
149
|
+
a transient `exec`'d process when the exec call returns.
|
|
150
|
+
"""
|
|
151
|
+
await self._ensure_dockerd_running()
|
|
152
|
+
|
|
153
|
+
async def wait_for_vm(self) -> None:
|
|
154
|
+
# For a Modal VM, "ready" means the Docker daemon is reachable.
|
|
155
|
+
await self._ensure_dockerd_running()
|
|
156
|
+
|
|
157
|
+
async def _ensure_dockerd_running(self) -> None:
|
|
158
|
+
"""Start dockerd if needed, then poll `docker info` until ready (non-blocking).
|
|
159
|
+
|
|
160
|
+
Idempotent (safe on reconnect). Bounded by the inherited VmSandbox wall-clock
|
|
161
|
+
budget; never blocks the event loop (background-launch + asyncio.sleep poll).
|
|
162
|
+
"""
|
|
163
|
+
# Launch dockerd detached only if not already up. `nohup ... &` so it survives
|
|
164
|
+
# the exec session; the `if` keeps this idempotent across reconnects. The
|
|
165
|
+
# --log-driver/--log-opt daemon flags cap the json-file driver via rotation
|
|
166
|
+
# (max-size 30m x max-file 3 => ~90 MB/container, oldest dropped first) so a
|
|
167
|
+
# long-running env's container logs can't fill the 512 GiB rootfs. max-file>=2
|
|
168
|
+
# keeps a buffer of already-written log behind the live `docker logs -f` follower,
|
|
169
|
+
# so a follower briefly behind under load doesn't lose lines at a rotation. Passed
|
|
170
|
+
# as daemon args (not a daemon.json file) so nothing extra is written to disk —
|
|
171
|
+
# this is the single on-disk log copy (`docker logs` reads it; the forwarder
|
|
172
|
+
# streams from it to stdout without a second copy).
|
|
173
|
+
await self.exec_script(
|
|
174
|
+
"if ! docker info >/dev/null 2>&1; then "
|
|
175
|
+
"nohup dockerd "
|
|
176
|
+
"--log-driver json-file --log-opt max-size=30m --log-opt max-file=3 "
|
|
177
|
+
">/var/log/dockerd.log 2>&1 & fi"
|
|
178
|
+
)
|
|
179
|
+
deadline = time.monotonic() + self._VM_READY_TIMEOUT
|
|
180
|
+
attempts = 0
|
|
181
|
+
while time.monotonic() < deadline:
|
|
182
|
+
attempts += 1
|
|
183
|
+
exit_code, _, _ = await self.exec_with_output("docker", "info")
|
|
184
|
+
if exit_code == 0:
|
|
185
|
+
elapsed = self._VM_READY_TIMEOUT - max(0.0, deadline - time.monotonic())
|
|
186
|
+
logger.info(f"dockerd ready after {elapsed:.0f}s ({attempts} polls)")
|
|
187
|
+
return
|
|
188
|
+
await asyncio.sleep(self._VM_READY_POLL_INTERVAL)
|
|
189
|
+
_, log_tail, _ = await self.exec_with_output("tail", "-n", "40", "/var/log/dockerd.log")
|
|
190
|
+
raise RuntimeError(
|
|
191
|
+
f"dockerd not ready in Modal VM {self.sandbox_id} after {self._VM_READY_TIMEOUT}s "
|
|
192
|
+
f"({attempts} polls); /var/log/dockerd.log tail:\n{log_tail}"
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
async def _download_object_to_vm(self, object_url: str, vm_path: str) -> None:
|
|
196
|
+
"""Presigned objects go through aria2c (see _DL_*); a store that cannot presign keeps the base path."""
|
|
197
|
+
store = get_config().get_object_store()
|
|
198
|
+
signed = await asyncio.to_thread(store.signed_get_url, object_url)
|
|
199
|
+
signed_at = time.monotonic()
|
|
200
|
+
if signed is None:
|
|
201
|
+
await self._write_unsigned_object(store, object_url, vm_path)
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
async def url(attempt: int) -> str:
|
|
205
|
+
if attempt == 1 and time.monotonic() - signed_at < _FRESH_URL_SECONDS:
|
|
206
|
+
return signed
|
|
207
|
+
return await asyncio.to_thread(store.signed_get_url, object_url)
|
|
208
|
+
|
|
209
|
+
await self._download_ranged(url, vm_path, label=object_url.rsplit("/", 1)[-1])
|
|
210
|
+
|
|
211
|
+
async def _download_ranged(self, url_factory: Callable[[int], Awaitable[str]], vm_path: str, *, label: str) -> None:
|
|
212
|
+
"""Run the download script per attempt with the URL ``url_factory`` gives for it; 404 raises,
|
|
213
|
+
anything else retries. The first script to run clears any stale file at ``vm_path``."""
|
|
214
|
+
attempts = max(1, _dl_setting("ATTEMPTS", _DL_ATTEMPTS))
|
|
215
|
+
deadline = _dl_setting("DEADLINE_S", _DL_DEADLINE_S)
|
|
216
|
+
last = "no attempt made"
|
|
217
|
+
ran = False
|
|
218
|
+
async with self._download_slots:
|
|
219
|
+
for attempt in range(1, attempts + 1):
|
|
220
|
+
try:
|
|
221
|
+
url = await url_factory(attempt)
|
|
222
|
+
except Exception as e: # a failed re-sign costs this attempt, not the download
|
|
223
|
+
last = f"attempt {attempt}: signing failed: {type(e).__name__}: {str(e)[:300]}"
|
|
224
|
+
logger.warning(f"download {label}: {last}")
|
|
225
|
+
continue
|
|
226
|
+
script = _render_download_script(url, vm_path, fresh=not ran)
|
|
227
|
+
ran = True
|
|
228
|
+
try:
|
|
229
|
+
stdout = await asyncio.wait_for(self.exec_script(script, max_retries=1), timeout=deadline + 120)
|
|
230
|
+
except (asyncio.TimeoutError, RuntimeError) as e: # host-side wait expired / exec transport failed
|
|
231
|
+
last = f"attempt {attempt}: {type(e).__name__}: {str(e)[:300]}"
|
|
232
|
+
logger.warning(f"download {label}: {last}")
|
|
233
|
+
continue
|
|
234
|
+
parsed = _parse_download_summary(stdout)
|
|
235
|
+
if parsed is None:
|
|
236
|
+
last = f"attempt {attempt}: no summary line; output tail {stdout[-300:]!r}"
|
|
237
|
+
logger.warning(f"download {label}: {last}")
|
|
238
|
+
continue
|
|
239
|
+
rc, nbytes, seconds, msg = parsed
|
|
240
|
+
if rc == 0:
|
|
241
|
+
line = (f"download result=ok bytes={nbytes} seconds={seconds} "
|
|
242
|
+
f"mib_s={nbytes / max(seconds, 1) / 1024 ** 2:.1f} attempts={attempt} label={label}")
|
|
243
|
+
logger.info(line)
|
|
244
|
+
print(line, flush=True)
|
|
245
|
+
return
|
|
246
|
+
if _not_found(rc, msg):
|
|
247
|
+
raise RuntimeError(f"download {label}: object not found (aria2c rc={rc} {msg[:200]})")
|
|
248
|
+
last = f"attempt {attempt}: aria2c rc={rc}; {msg[:300]}"
|
|
249
|
+
logger.warning(f"download {label}: {last}")
|
|
250
|
+
logger.error(f"download result=failed attempts={attempts} label={label}")
|
|
251
|
+
await self._remove_vm_temp_file(vm_path)
|
|
252
|
+
await self._remove_vm_temp_file(vm_path + ".aria2")
|
|
253
|
+
raise RuntimeError(f"download {label} failed after {attempts} attempts: {last}")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class ModalVmSandboxProvider(SandboxProvider):
|
|
257
|
+
EGRESS_HOSTS: ClassVar[tuple[str, ...]] = ("*.modal.host", "*.w.modal.host")
|
|
258
|
+
|
|
259
|
+
@classmethod
|
|
260
|
+
def supports_network_policy(cls, policy: NetworkPolicy) -> bool:
|
|
261
|
+
return True
|
|
262
|
+
|
|
263
|
+
"""Provisions a single Modal VM sandbox per env (the VM-mode Modal backend)."""
|
|
264
|
+
|
|
265
|
+
def __init__(self, app_name: Optional[str] = None):
|
|
266
|
+
self._app_name = _resolve_app_base_name(app_name)
|
|
267
|
+
self._client: Optional[modal.Client] = None
|
|
268
|
+
# Per-attribution-scope Modal App, looked up on demand (billing aggregates per App).
|
|
269
|
+
# Self-contained copy of ModalSandboxProvider's client/app handling — intentionally
|
|
270
|
+
# NOT shared, so the container provider is untouched.
|
|
271
|
+
self._apps: dict[str, modal.App] = {}
|
|
272
|
+
|
|
273
|
+
async def _get_client(self) -> modal.Client:
|
|
274
|
+
if self._client is None:
|
|
275
|
+
from agent_env.config import get_config
|
|
276
|
+
token_id, token_secret = get_config().get_modal_credentials()
|
|
277
|
+
self._client = await modal.Client.from_credentials.aio(token_id, token_secret)
|
|
278
|
+
return self._client
|
|
279
|
+
|
|
280
|
+
async def _get_app(self, app_name: str, app_tags: Optional[dict[str, str]] = None) -> modal.App:
|
|
281
|
+
app = self._apps.get(app_name)
|
|
282
|
+
if app is None:
|
|
283
|
+
client = await self._get_client()
|
|
284
|
+
app = await modal.App.lookup.aio(app_name, create_if_missing=True, client=client)
|
|
285
|
+
if app_tags:
|
|
286
|
+
try:
|
|
287
|
+
await app.set_tags.aio(app_tags)
|
|
288
|
+
except Exception as e:
|
|
289
|
+
logger.warning(f"Failed to set tags on Modal app {app_name}: {type(e).__name__}: {e}")
|
|
290
|
+
self._apps[app_name] = app
|
|
291
|
+
return app
|
|
292
|
+
|
|
293
|
+
async def create_vm(
|
|
294
|
+
self,
|
|
295
|
+
*,
|
|
296
|
+
image: Optional[str] = None,
|
|
297
|
+
boot_mode: Optional[str] = None,
|
|
298
|
+
cpu: float = 0.5,
|
|
299
|
+
memory: int = 8192,
|
|
300
|
+
disk_size_gb: float = 10,
|
|
301
|
+
timeout: int = 3600 * 2,
|
|
302
|
+
exposed_ports: Optional[list[int]] = None,
|
|
303
|
+
setup_for_gateway: bool = True,
|
|
304
|
+
attribution: Optional[Attribution] = None,
|
|
305
|
+
priority: Optional[int] = None,
|
|
306
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
307
|
+
) -> ModalVmSandbox:
|
|
308
|
+
# image/boot_mode/disk_size_gb/priority accepted for interface parity but inert here.
|
|
309
|
+
# disk_size_gb: Modal has no disk-size knob on Sandbox.create; a VM sandbox's rootfs is
|
|
310
|
+
# fixed at the 512 GiB max. https://modal.com/docs/guide/vm-sandboxes
|
|
311
|
+
attribution = dict(attribution or {})
|
|
312
|
+
app_tags = _build_cost_attribution_tags(attribution)
|
|
313
|
+
app_name = _app_name_for_project(self._app_name, app_tags.get("project_id"))
|
|
314
|
+
app = await self._get_app(app_name, app_tags)
|
|
315
|
+
sandbox_tags = _build_sandbox_tags(attribution)
|
|
316
|
+
client = await self._get_client()
|
|
317
|
+
effective = self.effective_network_policy(network_policy)
|
|
318
|
+
ports = list(exposed_ports or [])
|
|
319
|
+
logger.info(
|
|
320
|
+
f"Creating Modal VM sandbox (vm_runtime; app={app_name}, tags={app_tags}, "
|
|
321
|
+
f"sandbox_tags={sandbox_tags}, "
|
|
322
|
+
f"ports={ports}, cpu={cpu}, memory={memory}MB, timeout={timeout}s, "
|
|
323
|
+
f"policy={effective.mode.value})"
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
# No retry around create: retrying a create can orphan a half-provisioned sandbox
|
|
327
|
+
# (retry_transient is documented for read-only calls only). Modal's client already
|
|
328
|
+
# retries RESOURCE_EXHAUSTED / queueing internally, which is the real high-load case.
|
|
329
|
+
try:
|
|
330
|
+
sb = await modal.Sandbox._experimental_create.aio(
|
|
331
|
+
*_KEEPALIVE_CMD,
|
|
332
|
+
app=app, image=_VM_IMAGE, cpu=cpu, memory=memory, timeout=timeout,
|
|
333
|
+
encrypted_ports=ports, experimental_options={"vm_runtime": True}, client=client,
|
|
334
|
+
tags=sandbox_tags or None,
|
|
335
|
+
**_modal_network_kwargs(effective),
|
|
336
|
+
)
|
|
337
|
+
except Exception as e:
|
|
338
|
+
raise RuntimeError(f"Modal VM sandbox create failed [{type(e).__name__}: {e}]") from e
|
|
339
|
+
|
|
340
|
+
sandbox: ModalVmSandbox | None = None
|
|
341
|
+
try:
|
|
342
|
+
tunnels = await sb.tunnels.aio(timeout=150)
|
|
343
|
+
tunnel_urls = {p: _tunnel_url(t) for p, t in tunnels.items()}
|
|
344
|
+
for p in ports:
|
|
345
|
+
if p not in tunnel_urls:
|
|
346
|
+
raise RuntimeError(f"No Modal tunnel for exposed port {p}; got {sorted(tunnel_urls)}")
|
|
347
|
+
sandbox = ModalVmSandbox(sb, tunnel_urls, network_policy=effective)
|
|
348
|
+
logger.info(f"Modal VM sandbox created: {sb.object_id} (tunnels={tunnel_urls})")
|
|
349
|
+
await _log_sandbox_started(
|
|
350
|
+
sb, app_name=app_name, sandbox_tags=sandbox_tags,
|
|
351
|
+
cpu=cpu, memory=memory, gpu=None,
|
|
352
|
+
)
|
|
353
|
+
if setup_for_gateway:
|
|
354
|
+
await sandbox.setup_vm_for_gateway(ports)
|
|
355
|
+
return sandbox
|
|
356
|
+
except BaseException:
|
|
357
|
+
try:
|
|
358
|
+
await sb.terminate.aio()
|
|
359
|
+
except Exception as e:
|
|
360
|
+
logger.warning(f"Failed to terminate Modal VM sandbox {sb.object_id} after failure: {e}")
|
|
361
|
+
raise
|
|
362
|
+
|
|
363
|
+
async def create_sandbox(
|
|
364
|
+
self,
|
|
365
|
+
*,
|
|
366
|
+
image_name: str,
|
|
367
|
+
port: int,
|
|
368
|
+
env: dict[str, str],
|
|
369
|
+
cpu: float = 0.5,
|
|
370
|
+
memory: int = 8192,
|
|
371
|
+
disk_size_gb: float = 10,
|
|
372
|
+
timeout: int = 3600 * 2,
|
|
373
|
+
attribution: Optional[Attribution] = None,
|
|
374
|
+
priority: Optional[int] = None,
|
|
375
|
+
network_policy: Optional[NetworkPolicy] = None,
|
|
376
|
+
) -> ModalVmSandbox:
|
|
377
|
+
# Like the other VM providers' create_sandbox: return a bare VM (image_name/env are
|
|
378
|
+
# ignored at create). The caller sees mode == "vm" and loads + runs the image
|
|
379
|
+
# itself (A2AAgent.deploy).
|
|
380
|
+
return await self.create_vm(
|
|
381
|
+
exposed_ports=[port], cpu=cpu, memory=memory, disk_size_gb=disk_size_gb,
|
|
382
|
+
timeout=timeout,
|
|
383
|
+
attribution=attribution,
|
|
384
|
+
priority=priority, network_policy=network_policy,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
async def get_sandbox(self, sandbox_id: str) -> ModalVmSandbox:
|
|
388
|
+
client = await self._get_client()
|
|
389
|
+
sb = await modal.Sandbox.from_id.aio(sandbox_id, client=client)
|
|
390
|
+
tunnels = await sb.tunnels.aio()
|
|
391
|
+
tunnel_urls = {p: _tunnel_url(t) for p, t in tunnels.items()}
|
|
392
|
+
# dockerd is already running on a live sandbox; do not re-run setup here.
|
|
393
|
+
return ModalVmSandbox(sb, tunnel_urls)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
# ── Object downloads (internal) ────────────────────────────────────────────────────
|
|
397
|
+
# Object downloads run as one aria2c per object: a pool of HTTP range connections with small pieces,
|
|
398
|
+
# so a single slow TCP flow only ever holds one piece instead of the whole object; resume via the
|
|
399
|
+
# .aria2 control file; bounded by `timeout`. Modal-only: this class owns _VM_IMAGE, so aria2c is
|
|
400
|
+
# present by construction. Defaults are overridable as AGENT_ENV_MODAL_VM_DOWNLOAD_<NAME>.
|
|
401
|
+
_DL_CONNECTIONS = 16 # range connections per object (aria2c's cap); throughput under loss scales with it
|
|
402
|
+
_DL_MIN_SPLIT_MIB = 4 # piece size: a slow connection's tail is one piece
|
|
403
|
+
_DL_SPEED_FLOOR_KIB_S = 0 # aria2c's --lowest-speed-limit aborts the whole download, not one connection; keep off
|
|
404
|
+
_FRESH_URL_SECONDS = 60 # a signed URL older than this is re-signed before its first attempt
|
|
405
|
+
_DL_ATTEMPTS = 3 # each with a freshly minted URL, resuming
|
|
406
|
+
_DL_PARALLEL_FILES = 4 # concurrent downloads per VM
|
|
407
|
+
_DL_DEADLINE_S = 1800 # wall clock per attempt
|
|
408
|
+
_DL_ENV_PREFIX = "AGENT_ENV_MODAL_VM_DOWNLOAD_"
|
|
409
|
+
_DL_SUMMARY = "AGENTENV_DOWNLOAD"
|
|
410
|
+
_DL_SUMMARY_RE = re.compile(rf"^{_DL_SUMMARY} rc=(-?\d+) bytes=(\d+) seconds=(\d+)(?: msg=(.*))?$")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def _dl_setting(name: str, default):
|
|
414
|
+
"""`default`, or its AGENT_ENV_MODAL_VM_DOWNLOAD_<name> override coerced to the same type."""
|
|
415
|
+
raw = os.environ.get(_DL_ENV_PREFIX + name)
|
|
416
|
+
if raw is None or raw == "":
|
|
417
|
+
return default
|
|
418
|
+
try:
|
|
419
|
+
return type(default)(raw)
|
|
420
|
+
except ValueError as e:
|
|
421
|
+
raise ValueError(f"{_DL_ENV_PREFIX}{name}={raw!r} is not a valid {type(default).__name__}") from e
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _render_download_script(url: str, vm_path: str, *, fresh: bool) -> str:
|
|
425
|
+
"""One `bash -c` script: aria2c under `timeout`; always exits 0 and reports through its last line."""
|
|
426
|
+
connections = max(1, min(16, _dl_setting("CONNECTIONS", _DL_CONNECTIONS)))
|
|
427
|
+
aria2 = (
|
|
428
|
+
f"timeout -k 15 {_dl_setting('DEADLINE_S', _DL_DEADLINE_S)} aria2c --console-log-level=warn"
|
|
429
|
+
" --summary-interval=0 --show-console-readout=false --download-result=hide --allow-overwrite=true --auto-file-renaming=false"
|
|
430
|
+
" --continue=true --file-allocation=none --remote-time=false --async-dns=false"
|
|
431
|
+
" --http-accept-gzip=false --max-file-not-found=2"
|
|
432
|
+
f" --max-connection-per-server={connections} --split={connections}"
|
|
433
|
+
f" --min-split-size={_dl_setting('MIN_SPLIT_MIB', _DL_MIN_SPLIT_MIB)}M"
|
|
434
|
+
f" --lowest-speed-limit={_dl_setting('SPEED_FLOOR_KIB_S', _DL_SPEED_FLOOR_KIB_S) * 1024}"
|
|
435
|
+
" --max-tries=8 --retry-wait=1 --timeout=60 --connect-timeout=10"
|
|
436
|
+
' --dir="$dir" --out="$name" "$url"'
|
|
437
|
+
)
|
|
438
|
+
return "\n".join([
|
|
439
|
+
"set +e",
|
|
440
|
+
"url=" + shlex.quote(url),
|
|
441
|
+
"out=" + shlex.quote(vm_path),
|
|
442
|
+
'dir=$(dirname "$out"); name=$(basename "$out"); log="$dir/.$name.download.log"',
|
|
443
|
+
'mkdir -p "$dir"; t0=$(date +%s)',
|
|
444
|
+
# The first attempt for an object must not --continue onto another object's bytes at the same path.
|
|
445
|
+
*(['rm -f "$out" "$out.aria2"'] if fresh else []),
|
|
446
|
+
f'{aria2} >"$log" 2>&1; rc=$?',
|
|
447
|
+
'bytes=$(wc -c <"$out" 2>/dev/null | tr -d " "); [ -n "$bytes" ] || bytes=0',
|
|
448
|
+
# Mask URLs and long tokens before truncating, or a tail starting mid-URL keeps a credential fragment.
|
|
449
|
+
"msg=$(tr '\\n\\r' ' ' <\"$log\" 2>/dev/null | sed -E 's#https?://[^[:space:]]+#<url>#g; s#[A-Za-z0-9%+/=_-]{40,}#<token>#g' | tail -c 400)",
|
|
450
|
+
'rm -f "$log"',
|
|
451
|
+
f'echo "{_DL_SUMMARY} rc=$rc bytes=$bytes seconds=$(( $(date +%s) - t0 )) msg=$msg"',
|
|
452
|
+
"exit 0",
|
|
453
|
+
])
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _parse_download_summary(stdout: str) -> Optional[tuple[int, int, int, str]]:
|
|
457
|
+
"""(rc, bytes, seconds, msg) from the script's last summary line; None if it never got there."""
|
|
458
|
+
for line in reversed(stdout.splitlines()):
|
|
459
|
+
if m := _DL_SUMMARY_RE.match(line.strip()):
|
|
460
|
+
return int(m[1]), int(m[2]), int(m[3]), (m[4] or "").strip()
|
|
461
|
+
return None
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _not_found(rc: int, msg: str) -> bool:
|
|
465
|
+
"""aria2c exit 3 = resource not found, 4 = --max-file-not-found reached."""
|
|
466
|
+
return rc in (3, 4) or "status=404" in msg
|