feat(aws): run, find, stop and watch workspace tasks
aws/tasks.rs: TaskApi (+ SdkTaskApi) with RunTask, DescribeTasks (tags), ListTasks by family, StopTask and a GetLogEvents tail. find_or_run reuses the project's live task only when its tags name the caller and the project, and otherwise runs the exact family:revision with the three ownership tags (FARGATE, or the FARGATE_SPOT capacity provider for Spot), with a client token so SDK retries cannot start a second task. wait_ready polls with injectable timing and fails with the stop reason and the last 50 log lines. Quota refusals become AwsError::QuotaExceeded and are never retried. classify_stop maps stop codes per the spec. host/watch.rs: ExitSource::Aws polls an injected project-to-task lookup every 15 s, per connection+region+cluster, 100 tasks per call; a group that can't be asked is skipped. has_exited's Agent arm is unchanged (R3). container_watch::run/spawn take their ExitSource. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
30d6b26a42
commit
e43ed26e20
11 files changed
+1767
-13
No files matched your search
@@ -29,6 +29,11 @@ pub enum AwsError {
|
||||
StateBucketTaken {
|
||||
bucket: String,
|
||||
},
|
||||
/// An account limit (Fargate vCPUs, tasks, ...) refused the request.
|
||||
/// Never retried; `message` says what to do.
|
||||
QuotaExceeded {
|
||||
message: String,
|
||||
},
|
||||
Other {
|
||||
message: String,
|
||||
},
|
||||
@@ -63,7 +68,9 @@ impl std::fmt::Display for AwsError {
|
||||
"The state bucket name \"{bucket}\" is already taken by another AWS account, so \
|
||||
Triple-C can't keep OpenTofu state there"
|
||||
),
|
||||
AwsError::Other { message } => f.write_str(message),
|
||||
AwsError::QuotaExceeded { message } | AwsError::Other { message } => {
|
||||
f.write_str(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,9 @@ pub mod permissions;
|
||||
pub mod policies;
|
||||
#[cfg(test)]
|
||||
mod policy_eval;
|
||||
// Used by the AWS host (phase 5, Task 6); until then only by its tests.
|
||||
#[allow(dead_code)]
|
||||
pub mod tasks;
|
||||
pub mod tofu;
|
||||
pub mod tofu_modules;
|
||||
// Used by the AWS host (phase 5, Task 6); until then only by its tests.
|
||||
|
||||
@@ -0,0 +1,686 @@
|
||||
//! A project's ECS task: find the one already running, or run one; wait
|
||||
//! until it is ready; stop it; and read why it stopped.
|
||||
//!
|
||||
//! **A task is trusted by its tags, not its family.** Family names are built
|
||||
//! from a 12-character id prefix and any workspace user may register into any
|
||||
//! `triple-c-*` family, so a task listed under the project's family is reused
|
||||
//! only when DescribeTasks shows the caller's own `triple-c:owner` (which only
|
||||
//! the caller can set, at RunTask) and this project's `triple-c:project`.
|
||||
//!
|
||||
//! **RunTask names an exact revision.** Never a bare family: "the latest
|
||||
//! revision" of a family is whatever anyone registered last.
|
||||
//!
|
||||
//! **A quota refusal is final.** Fargate's vCPU limit (and its kin) surface as
|
||||
//! [`AwsError::QuotaExceeded`] with a message saying what to do; nothing here
|
||||
//! retries a RunTask, and the SDK's own retries are made idempotent by a
|
||||
//! client token.
|
||||
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
use aws_config::SdkConfig;
|
||||
use aws_sdk_ecs::operation::run_task::RunTaskInput;
|
||||
use aws_sdk_ecs::types::{
|
||||
AssignPublicIp, AwsVpcConfiguration, CapacityProviderStrategyItem, DesiredStatus, LaunchType,
|
||||
ManagedAgentName, NetworkConfiguration, Tag, Task, TaskField,
|
||||
};
|
||||
|
||||
use super::environments::EnvironmentInfo;
|
||||
use super::error::{classify_sdk_error, AwsError};
|
||||
pub use super::tofu_modules::task_log_stream;
|
||||
use super::workspace::{workspace_tags, CONTAINER_NAME, TAG_OWNER, TAG_PROJECT};
|
||||
|
||||
/// The `reason` StopTask records when the app stops a task.
|
||||
pub const STOP_REASON: &str = "Stopped from Triple-C";
|
||||
/// Log lines shown when a task stops before it is ready.
|
||||
pub const LOG_TAIL_LINES: i32 = 50;
|
||||
const SPOT_PROVIDER: &str = "FARGATE_SPOT";
|
||||
/// DescribeTasks takes at most 100 tasks per call.
|
||||
const DESCRIBE_BATCH: usize = 100;
|
||||
/// ListTasks pages read per status; a project has one task, so this is slack.
|
||||
const MAX_LIST_PAGES: usize = 5;
|
||||
|
||||
fn other(message: impl Into<String>) -> AwsError {
|
||||
AwsError::Other {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app needs to know about a task.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TaskInfo {
|
||||
pub arn: String,
|
||||
/// `PROVISIONING`, `PENDING`, `ACTIVATING`, `RUNNING`, `DEACTIVATING`,
|
||||
/// `STOPPING`, `DEPROVISIONING`, `STOPPED`.
|
||||
pub last_status: String,
|
||||
pub desired_status: String,
|
||||
/// `HEALTHY`, `UNHEALTHY`, `UNKNOWN`.
|
||||
pub health: Option<String>,
|
||||
/// ECS `stopCode` (`EssentialContainerExited`, `SpotInterruption`, ...).
|
||||
pub stop_code: Option<String>,
|
||||
pub stopped_reason: Option<String>,
|
||||
pub task_definition_arn: String,
|
||||
/// The `workspace` container's runtime id (needed for an SSM target).
|
||||
pub runtime_id: Option<String>,
|
||||
/// The `workspace` container's ExecuteCommandAgent is RUNNING.
|
||||
pub exec_agent_running: bool,
|
||||
/// Its `triple-c:owner` / `triple-c:project` tags (DescribeTasks with
|
||||
/// TAGS; RunTask's answer carries the tags it was given).
|
||||
pub owner: Option<String>,
|
||||
pub project: Option<String>,
|
||||
}
|
||||
|
||||
impl TaskInfo {
|
||||
fn is_stopping(&self) -> bool {
|
||||
self.last_status == "STOPPED" || self.desired_status == "STOPPED"
|
||||
}
|
||||
/// On its way up or up, and meant to stay that way.
|
||||
fn is_live(&self) -> bool {
|
||||
self.desired_status == "RUNNING"
|
||||
&& matches!(
|
||||
self.last_status.as_str(),
|
||||
"PROVISIONING" | "PENDING" | "ACTIVATING" | "RUNNING"
|
||||
)
|
||||
}
|
||||
fn is_ready(&self) -> bool {
|
||||
self.last_status == "RUNNING" && self.exec_agent_running && self.runtime_id.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_value(tags: &[Tag], key: &str) -> Option<String> {
|
||||
tags.iter()
|
||||
.find(|t| t.key() == Some(key))
|
||||
.and_then(|t| t.value())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// An SDK task as a [`TaskInfo`]. The container facts come from the
|
||||
/// `workspace` container only.
|
||||
pub(crate) fn task_info(t: &Task) -> TaskInfo {
|
||||
let workspace = t
|
||||
.containers()
|
||||
.iter()
|
||||
.find(|c| c.name() == Some(CONTAINER_NAME));
|
||||
TaskInfo {
|
||||
arn: t.task_arn().unwrap_or_default().to_string(),
|
||||
last_status: t.last_status().unwrap_or_default().to_string(),
|
||||
desired_status: t.desired_status().unwrap_or_default().to_string(),
|
||||
health: t.health_status().map(|h| h.as_str().to_string()),
|
||||
stop_code: t.stop_code().map(|c| c.as_str().to_string()),
|
||||
stopped_reason: t.stopped_reason().map(str::to_string),
|
||||
task_definition_arn: t.task_definition_arn().unwrap_or_default().to_string(),
|
||||
runtime_id: workspace.and_then(|c| c.runtime_id()).map(str::to_string),
|
||||
exec_agent_running: workspace.is_some_and(|c| {
|
||||
c.managed_agents().iter().any(|a| {
|
||||
a.name() == Some(&ManagedAgentName::ExecuteCommandAgent)
|
||||
&& a.last_status() == Some("RUNNING")
|
||||
})
|
||||
}),
|
||||
owner: tag_value(t.tags(), TAG_OWNER),
|
||||
project: tag_value(t.tags(), TAG_PROJECT),
|
||||
}
|
||||
}
|
||||
|
||||
/// What running and watching tasks asks AWS. Like `WorkspaceApi`, each
|
||||
/// method returns a `Send` future and an impl may write them as `async fn`;
|
||||
/// the decisions are made by the functions below, so a fake exercises them.
|
||||
pub trait TaskApi: Send + Sync {
|
||||
/// RunTask. A quota refusal is [`AwsError::QuotaExceeded`].
|
||||
fn run_task(
|
||||
&self,
|
||||
req: RunTaskInput,
|
||||
) -> impl Future<Output = Result<TaskInfo, AwsError>> + Send;
|
||||
/// DescribeTasks (with tags). Tasks ECS no longer knows are left out.
|
||||
fn describe(
|
||||
&self,
|
||||
cluster: &str,
|
||||
arns: &[String],
|
||||
) -> impl Future<Output = Result<Vec<TaskInfo>, AwsError>> + Send;
|
||||
/// ListTasks of exactly `family`, desired status RUNNING and PENDING.
|
||||
fn list_project_tasks(
|
||||
&self,
|
||||
cluster: &str,
|
||||
family: &str,
|
||||
) -> impl Future<Output = Result<Vec<String>, AwsError>> + Send;
|
||||
fn stop_task(
|
||||
&self,
|
||||
cluster: &str,
|
||||
arn: &str,
|
||||
reason: &str,
|
||||
) -> impl Future<Output = Result<(), AwsError>> + Send;
|
||||
/// The last `limit` lines of a log stream, oldest first. A stream (or
|
||||
/// group) that does not exist is no lines, not an error.
|
||||
fn log_tail(
|
||||
&self,
|
||||
group: &str,
|
||||
stream: &str,
|
||||
limit: i32,
|
||||
) -> impl Future<Output = Result<Vec<String>, AwsError>> + Send;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- run request
|
||||
|
||||
/// The RunTask request: the exact revision, on the environment's cluster and
|
||||
/// network, with ECS Exec on and exactly the `tags` given (no propagation,
|
||||
/// no ECS-managed tags, no overrides — P1). Spot runs on the `FARGATE_SPOT`
|
||||
/// capacity provider with no launch type (the two are exclusive).
|
||||
pub fn run_task_request(
|
||||
env: &EnvironmentInfo,
|
||||
task_def_arn: &str,
|
||||
spot: bool,
|
||||
tags: &[(String, String)],
|
||||
) -> RunTaskInput {
|
||||
const BUILT: &str = "every required field is set";
|
||||
let mut req = RunTaskInput::builder()
|
||||
.cluster(&env.cluster_arn)
|
||||
.task_definition(task_def_arn)
|
||||
.count(1)
|
||||
.enable_execute_command(true)
|
||||
.network_configuration(
|
||||
NetworkConfiguration::builder()
|
||||
.awsvpc_configuration(
|
||||
AwsVpcConfiguration::builder()
|
||||
.set_subnets(Some(env.subnet_ids.clone()))
|
||||
.security_groups(&env.security_group_id)
|
||||
.assign_public_ip(if env.assign_public_ip {
|
||||
AssignPublicIp::Enabled
|
||||
} else {
|
||||
AssignPublicIp::Disabled
|
||||
})
|
||||
.build()
|
||||
.expect(BUILT),
|
||||
)
|
||||
.build(),
|
||||
)
|
||||
.set_tags(Some(
|
||||
tags.iter()
|
||||
.map(|(k, v)| Tag::builder().key(k).value(v).build())
|
||||
.collect(),
|
||||
))
|
||||
// SDK retries of this call must not start a second task.
|
||||
.client_token(uuid::Uuid::new_v4().to_string());
|
||||
req = if spot {
|
||||
req.capacity_provider_strategy(
|
||||
CapacityProviderStrategyItem::builder()
|
||||
.capacity_provider(SPOT_PROVIDER)
|
||||
.weight(1)
|
||||
.build()
|
||||
.expect(BUILT),
|
||||
)
|
||||
} else {
|
||||
req.launch_type(LaunchType::Fargate)
|
||||
};
|
||||
req.build().expect(BUILT)
|
||||
}
|
||||
|
||||
/// The family of `arn:...:task-definition/<family>:<revision>`, when the
|
||||
/// revision is a number. `None` for a bare family or anything else.
|
||||
pub fn revision_family(arn: &str) -> Option<&str> {
|
||||
if !arn.starts_with("arn:") {
|
||||
return None;
|
||||
}
|
||||
let (_, rest) = arn.rsplit_once(":task-definition/")?;
|
||||
let (family, rev) = rest.rsplit_once(':')?;
|
||||
(!family.is_empty()
|
||||
&& !family.contains('/')
|
||||
&& !rev.is_empty()
|
||||
&& rev.bytes().all(|c| c.is_ascii_digit()))
|
||||
.then_some(family)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- find or run
|
||||
|
||||
/// The project's live task (provisioning through running, not being
|
||||
/// stopped), owned by the caller and tagged with this project. A RUNNING
|
||||
/// one is preferred.
|
||||
pub async fn find_project_task<A: TaskApi>(
|
||||
api: &A,
|
||||
cluster: &str,
|
||||
family: &str,
|
||||
owner_user_id: &str,
|
||||
project_id: &str,
|
||||
) -> Result<Option<TaskInfo>, AwsError> {
|
||||
let arns = api.list_project_tasks(cluster, family).await?;
|
||||
if arns.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut mine: Vec<TaskInfo> = Vec::new();
|
||||
for chunk in arns.chunks(DESCRIBE_BATCH) {
|
||||
mine.extend(api.describe(cluster, chunk).await?.into_iter().filter(|t| {
|
||||
t.owner.as_deref() == Some(owner_user_id)
|
||||
&& t.project.as_deref() == Some(project_id)
|
||||
&& revision_family(&t.task_definition_arn) == Some(family)
|
||||
&& t.is_live()
|
||||
}));
|
||||
}
|
||||
mine.sort_by_key(|t| t.last_status != "RUNNING");
|
||||
Ok(mine.into_iter().next())
|
||||
}
|
||||
|
||||
/// What [`find_or_run`] did.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TaskStart {
|
||||
pub task: TaskInfo,
|
||||
/// An existing task was found (nothing was run). Its agent token is the
|
||||
/// one it started with — see [`find_project_task`] in the report for
|
||||
/// why a caller should look before rotating the token.
|
||||
pub reused: bool,
|
||||
}
|
||||
|
||||
/// The project's live task if there is one (Review Focus 2: never a second
|
||||
/// task for a project), else RunTask with the exact `task_def_arn`.
|
||||
pub async fn find_or_run<A: TaskApi>(
|
||||
api: &A,
|
||||
env: &EnvironmentInfo,
|
||||
owner_user_id: &str,
|
||||
project_id: &str,
|
||||
task_def_arn: &str,
|
||||
spot: bool,
|
||||
) -> Result<TaskStart, AwsError> {
|
||||
let family = revision_family(task_def_arn).ok_or_else(|| {
|
||||
other(format!(
|
||||
"\"{task_def_arn}\" is not an exact task definition revision"
|
||||
))
|
||||
})?;
|
||||
if !family.starts_with("triple-c-") {
|
||||
return Err(other(format!(
|
||||
"\"{task_def_arn}\" is not a Triple-C task definition"
|
||||
)));
|
||||
}
|
||||
if let Some(task) =
|
||||
find_project_task(api, &env.cluster_arn, family, owner_user_id, project_id).await?
|
||||
{
|
||||
return Ok(TaskStart { task, reused: true });
|
||||
}
|
||||
let tags = workspace_tags(owner_user_id, project_id, &env.name);
|
||||
let task = api
|
||||
.run_task(run_task_request(env, task_def_arn, spot, &tags))
|
||||
.await?;
|
||||
Ok(TaskStart {
|
||||
task,
|
||||
reused: false,
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ quotas
|
||||
|
||||
/// Whether an AWS message says an account limit or quota was hit.
|
||||
pub fn looks_like_quota(text: &str) -> bool {
|
||||
let t = text.to_lowercase();
|
||||
[
|
||||
"you've reached the limit",
|
||||
"you\u{2019}ve reached the limit",
|
||||
"limitexceeded",
|
||||
"limit exceeded",
|
||||
"quota",
|
||||
]
|
||||
.iter()
|
||||
.any(|s| t.contains(s))
|
||||
}
|
||||
|
||||
/// The error for a RunTask refused on a quota.
|
||||
pub fn quota_error(detail: &str) -> AwsError {
|
||||
AwsError::QuotaExceeded {
|
||||
message: format!(
|
||||
"AWS would not start the task because an account limit was reached: {detail}. \
|
||||
Stop another workspace, or ask an administrator to raise the Fargate quota \
|
||||
(Service Quotas, AWS Fargate) for this region. Triple-C does not retry."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// `e` as a quota error when its message is one; otherwise unchanged.
|
||||
pub fn quota_or(e: AwsError) -> AwsError {
|
||||
match e {
|
||||
AwsError::Other { ref message } if looks_like_quota(message) => quota_error(message),
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_quota_error(e: &AwsError) -> bool {
|
||||
matches!(e, AwsError::QuotaExceeded { .. })
|
||||
}
|
||||
|
||||
/// RunTask's answer: its one task, or an error from its `failures`
|
||||
/// (`(reason, detail)`), a quota one when they say so.
|
||||
pub fn run_task_outcome(
|
||||
tasks: Vec<TaskInfo>,
|
||||
failures: Vec<(Option<String>, Option<String>)>,
|
||||
) -> Result<TaskInfo, AwsError> {
|
||||
if let Some(task) = tasks.into_iter().find(|t| !t.arn.is_empty()) {
|
||||
return Ok(task);
|
||||
}
|
||||
let text = failures
|
||||
.iter()
|
||||
.map(|(r, d)| match (r, d) {
|
||||
(Some(r), Some(d)) => format!("{r} ({d})"),
|
||||
(Some(r), None) => r.clone(),
|
||||
(None, Some(d)) => d.clone(),
|
||||
(None, None) => "unknown failure".into(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
if text.is_empty() {
|
||||
return Err(other("ecs:RunTask returned no task and no failure"));
|
||||
}
|
||||
if looks_like_quota(&text) {
|
||||
return Err(quota_error(&text));
|
||||
}
|
||||
Err(other(format!("ECS could not start the task: {text}")))
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- wait
|
||||
|
||||
/// How [`wait_ready`] polls. Injectable so tests don't wait.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct WaitTiming {
|
||||
pub interval: Duration,
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for WaitTiming {
|
||||
fn default() -> Self {
|
||||
WaitTiming {
|
||||
interval: Duration::from_secs(5),
|
||||
timeout: Duration::from_secs(6 * 60),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a project's task logs go: the environment's log group and the
|
||||
/// project's `awslogs-stream-prefix` (Task 4's `log_stream_prefix`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TaskLogs {
|
||||
pub group: String,
|
||||
pub stream_prefix: String,
|
||||
}
|
||||
|
||||
fn describe_timeout(t: Duration) -> String {
|
||||
let secs = t.as_secs();
|
||||
if secs >= 60 && secs % 60 == 0 {
|
||||
let m = secs / 60;
|
||||
format!("{m} minute{}", if m == 1 { "" } else { "s" })
|
||||
} else {
|
||||
format!("{secs} seconds")
|
||||
}
|
||||
}
|
||||
|
||||
/// Poll until the task is RUNNING with its exec agent up and a runtime id
|
||||
/// (what an SSM session needs), calling `progress` with each look. A task
|
||||
/// that stops (or is being stopped) fails with its reason and the last
|
||||
/// [`LOG_TAIL_LINES`] lines of its log; one that never gets there fails
|
||||
/// after `timing.timeout` with its last status. The task is left as it is
|
||||
/// either way: stopping it is the caller's call.
|
||||
pub async fn wait_ready<A: TaskApi>(
|
||||
api: &A,
|
||||
cluster: &str,
|
||||
arn: &str,
|
||||
logs: &TaskLogs,
|
||||
timing: WaitTiming,
|
||||
progress: impl Fn(&TaskInfo),
|
||||
) -> Result<TaskInfo, AwsError> {
|
||||
let deadline = tokio::time::Instant::now() + timing.timeout;
|
||||
let wanted = [arn.to_string()];
|
||||
loop {
|
||||
let Some(t) = api
|
||||
.describe(cluster, &wanted)
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|t| t.arn == arn)
|
||||
else {
|
||||
return Err(other(format!(
|
||||
"The task {arn} is no longer known to ECS; start the project again"
|
||||
)));
|
||||
};
|
||||
progress(&t);
|
||||
if t.is_stopping() {
|
||||
return Err(stopped_error(api, logs, &t).await);
|
||||
}
|
||||
if t.is_ready() {
|
||||
return Ok(t);
|
||||
}
|
||||
if tokio::time::Instant::now() + timing.interval > deadline {
|
||||
return Err(other(format!(
|
||||
"The task did not become ready within {} (last status {}{}). It may still \
|
||||
be starting; check the ECS console, or stop the project and start it again.",
|
||||
describe_timeout(timing.timeout),
|
||||
t.last_status,
|
||||
if t.last_status == "RUNNING" && !t.exec_agent_running {
|
||||
", ECS Exec agent not running yet"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
)));
|
||||
}
|
||||
tokio::time::sleep(timing.interval).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn stopped_error<A: TaskApi>(api: &A, logs: &TaskLogs, t: &TaskInfo) -> AwsError {
|
||||
let reason = t
|
||||
.stopped_reason
|
||||
.clone()
|
||||
.unwrap_or_else(|| "no reason given".into());
|
||||
let code = t
|
||||
.stop_code
|
||||
.as_deref()
|
||||
.map(|c| format!(" ({c})"))
|
||||
.unwrap_or_default();
|
||||
let stream = task_log_stream(&logs.stream_prefix, &t.arn);
|
||||
let tail = match api.log_tail(&logs.group, &stream, LOG_TAIL_LINES).await {
|
||||
Ok(lines) if lines.is_empty() => "\n(The task wrote no log lines.)".to_string(),
|
||||
Ok(lines) => format!("\nLast log lines:\n{}", lines.join("\n")),
|
||||
Err(e) => format!("\n(Its log could not be read: {e})"),
|
||||
};
|
||||
other(format!(
|
||||
"The task stopped before it was ready: {reason}{code}.{tail}"
|
||||
))
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------- stop / watch
|
||||
|
||||
/// Why a task stopped, as the app reports it (spec, "Lifecycle and status").
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum StopKind {
|
||||
/// Exited on its own (the essential container ended, idle stop, or AWS
|
||||
/// retired it).
|
||||
Exited,
|
||||
/// A Fargate Spot interruption (P8).
|
||||
Spot,
|
||||
/// Never got going: the project goes to Error with this reason.
|
||||
FailedToStart(String),
|
||||
/// Stopped by someone (the app, the console, the CLI).
|
||||
UserInitiated,
|
||||
}
|
||||
|
||||
pub fn classify_stop(info: &TaskInfo) -> StopKind {
|
||||
match info.stop_code.as_deref() {
|
||||
Some("SpotInterruption") => StopKind::Spot,
|
||||
Some("TaskFailedToStart") => StopKind::FailedToStart(
|
||||
info.stopped_reason
|
||||
.clone()
|
||||
.filter(|r| !r.trim().is_empty())
|
||||
.unwrap_or_else(|| "The task failed to start".into()),
|
||||
),
|
||||
Some("UserInitiated") => StopKind::UserInitiated,
|
||||
_ => StopKind::Exited,
|
||||
}
|
||||
}
|
||||
|
||||
/// Of `arns`, the ones that are STOPPED or that ECS no longer knows (it
|
||||
/// forgets stopped tasks after about an hour). A task merely being stopped
|
||||
/// is not yet reported. For the AWS death watch.
|
||||
pub async fn stopped_among<A: TaskApi>(
|
||||
api: &A,
|
||||
cluster: &str,
|
||||
arns: &[String],
|
||||
) -> Result<Vec<String>, AwsError> {
|
||||
let mut stopped = Vec::new();
|
||||
for chunk in arns.chunks(DESCRIBE_BATCH) {
|
||||
let known = api.describe(cluster, chunk).await?;
|
||||
for arn in chunk {
|
||||
match known.iter().find(|t| &t.arn == arn) {
|
||||
Some(t) if t.last_status != "STOPPED" => {}
|
||||
_ => stopped.push(arn.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(stopped)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- real API
|
||||
|
||||
/// The real thing, from a connection's `SdkConfig`.
|
||||
pub struct SdkTaskApi {
|
||||
ecs: aws_sdk_ecs::Client,
|
||||
logs: aws_sdk_cloudwatchlogs::Client,
|
||||
}
|
||||
|
||||
impl SdkTaskApi {
|
||||
pub fn new(cfg: &SdkConfig) -> Self {
|
||||
SdkTaskApi {
|
||||
ecs: aws_sdk_ecs::Client::new(cfg),
|
||||
logs: aws_sdk_cloudwatchlogs::Client::new(cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskApi for SdkTaskApi {
|
||||
async fn run_task(&self, req: RunTaskInput) -> Result<TaskInfo, AwsError> {
|
||||
const ACTION: &str = "ecs:RunTask";
|
||||
// The fluent builder takes no whole input; copy every field.
|
||||
let out = self
|
||||
.ecs
|
||||
.run_task()
|
||||
.set_capacity_provider_strategy(req.capacity_provider_strategy)
|
||||
.set_cluster(req.cluster)
|
||||
.set_count(req.count)
|
||||
.set_enable_ecs_managed_tags(req.enable_ecs_managed_tags)
|
||||
.set_enable_execute_command(req.enable_execute_command)
|
||||
.set_group(req.group)
|
||||
.set_launch_type(req.launch_type)
|
||||
.set_network_configuration(req.network_configuration)
|
||||
.set_overrides(req.overrides)
|
||||
.set_placement_constraints(req.placement_constraints)
|
||||
.set_placement_strategy(req.placement_strategy)
|
||||
.set_platform_version(req.platform_version)
|
||||
.set_propagate_tags(req.propagate_tags)
|
||||
.set_reference_id(req.reference_id)
|
||||
.set_started_by(req.started_by)
|
||||
.set_tags(req.tags)
|
||||
.set_task_definition(req.task_definition)
|
||||
.set_client_token(req.client_token)
|
||||
.set_volume_configurations(req.volume_configurations)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| quota_or(classify_sdk_error(ACTION, &e)))?;
|
||||
run_task_outcome(
|
||||
out.tasks().iter().map(task_info).collect(),
|
||||
out.failures()
|
||||
.iter()
|
||||
.map(|f| (f.reason().map(String::from), f.detail().map(String::from)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn describe(&self, cluster: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
|
||||
const ACTION: &str = "ecs:DescribeTasks";
|
||||
let mut out = Vec::new();
|
||||
for chunk in arns.chunks(DESCRIBE_BATCH) {
|
||||
let page = self
|
||||
.ecs
|
||||
.describe_tasks()
|
||||
.cluster(cluster)
|
||||
.set_tasks(Some(chunk.to_vec()))
|
||||
.include(TaskField::Tags)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error(ACTION, &e))?;
|
||||
out.extend(page.tasks().iter().map(task_info));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
async fn list_project_tasks(
|
||||
&self,
|
||||
cluster: &str,
|
||||
family: &str,
|
||||
) -> Result<Vec<String>, AwsError> {
|
||||
const ACTION: &str = "ecs:ListTasks";
|
||||
let mut found: Vec<String> = Vec::new();
|
||||
for status in [DesiredStatus::Running, DesiredStatus::Pending] {
|
||||
let mut token: Option<String> = None;
|
||||
for _ in 0..MAX_LIST_PAGES {
|
||||
let page = self
|
||||
.ecs
|
||||
.list_tasks()
|
||||
.cluster(cluster)
|
||||
.family(family)
|
||||
.desired_status(status.clone())
|
||||
.set_next_token(token.take())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error(ACTION, &e))?;
|
||||
for a in page.task_arns() {
|
||||
if !found.contains(a) {
|
||||
found.push(a.clone());
|
||||
}
|
||||
}
|
||||
match page.next_token() {
|
||||
Some(t) => token = Some(t.to_string()),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
async fn stop_task(&self, cluster: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
|
||||
const ACTION: &str = "ecs:StopTask";
|
||||
self.ecs
|
||||
.stop_task()
|
||||
.cluster(cluster)
|
||||
.task(arn)
|
||||
.reason(reason)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error(ACTION, &e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn log_tail(
|
||||
&self,
|
||||
group: &str,
|
||||
stream: &str,
|
||||
limit: i32,
|
||||
) -> Result<Vec<String>, AwsError> {
|
||||
const ACTION: &str = "logs:GetLogEvents";
|
||||
let out = self
|
||||
.logs
|
||||
.get_log_events()
|
||||
.log_group_name(group)
|
||||
.log_stream_name(stream)
|
||||
.start_from_head(false)
|
||||
.limit(limit)
|
||||
.send()
|
||||
.await;
|
||||
match out {
|
||||
Ok(page) => Ok(page
|
||||
.events()
|
||||
.iter()
|
||||
.filter_map(|e| e.message())
|
||||
.map(str::to_string)
|
||||
.collect()),
|
||||
Err(e)
|
||||
if e.as_service_error()
|
||||
.is_some_and(|s| s.is_resource_not_found_exception()) =>
|
||||
{
|
||||
Ok(Vec::new())
|
||||
}
|
||||
Err(e) => Err(classify_sdk_error(ACTION, &e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,721 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use aws_sdk_ecs::types::{
|
||||
AssignPublicIp, Container, LaunchType, ManagedAgent, ManagedAgentName, Tag, Task, TaskStopCode,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::aws::environments::EnvironmentInfo;
|
||||
use crate::aws::tofu_modules::{log_stream_prefix, owner_key};
|
||||
|
||||
const ACCOUNT: &str = "111122223333";
|
||||
const REGION: &str = "eu-west-1";
|
||||
const USER: &str = "AROAEXAMPLEID:alice@example.com";
|
||||
const OTHER: &str = "AROAOTHERID:mallory";
|
||||
const PROJECT_ID: &str = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";
|
||||
const FAMILY: &str = "triple-c-dev-abcdef012345-0f1e2d3c-4b5";
|
||||
|
||||
fn cluster() -> String {
|
||||
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:cluster/triple-c-dev")
|
||||
}
|
||||
|
||||
fn td_arn(rev: u32) -> String {
|
||||
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}:{rev}")
|
||||
}
|
||||
|
||||
fn task_arn(id: &str) -> String {
|
||||
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task/triple-c-dev/{id}")
|
||||
}
|
||||
|
||||
fn env_info() -> EnvironmentInfo {
|
||||
EnvironmentInfo {
|
||||
schema: 1,
|
||||
name: "dev".into(),
|
||||
template_version: 1,
|
||||
cluster_arn: cluster(),
|
||||
security_group_id: "sg-0123456789abcdef0".into(),
|
||||
subnet_ids: vec!["subnet-0a".into(), "subnet-0b".into()],
|
||||
assign_public_ip: true,
|
||||
kms_key_arn: format!("arn:aws:kms:{REGION}:{ACCOUNT}:key/1234"),
|
||||
log_group: "/triple-c/dev".into(),
|
||||
network_mode: "public".into(),
|
||||
tenancy: "strict".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn info(id: &str, last: &str) -> TaskInfo {
|
||||
TaskInfo {
|
||||
arn: task_arn(id),
|
||||
last_status: last.into(),
|
||||
desired_status: if last == "STOPPED" {
|
||||
"STOPPED"
|
||||
} else {
|
||||
"RUNNING"
|
||||
}
|
||||
.into(),
|
||||
health: None,
|
||||
stop_code: None,
|
||||
stopped_reason: None,
|
||||
task_definition_arn: td_arn(3),
|
||||
runtime_id: None,
|
||||
exec_agent_running: false,
|
||||
owner: Some(USER.into()),
|
||||
project: Some(PROJECT_ID.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ready(id: &str) -> TaskInfo {
|
||||
TaskInfo {
|
||||
runtime_id: Some(format!("{id}-123")),
|
||||
exec_agent_running: true,
|
||||
..info(id, "RUNNING")
|
||||
}
|
||||
}
|
||||
|
||||
/// A scripted `TaskApi`: `listed` answers ListTasks, `described` answers
|
||||
/// every DescribeTasks in turn (the last one repeats), `run` answers RunTask.
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
listed: Vec<String>,
|
||||
described: Mutex<Vec<Vec<TaskInfo>>>,
|
||||
run: Mutex<Option<Result<TaskInfo, AwsError>>>,
|
||||
logs: Vec<String>,
|
||||
calls: Mutex<Vec<String>>,
|
||||
run_requests: Mutex<Vec<RunTaskInput>>,
|
||||
log_requests: Mutex<Vec<(String, String, i32)>>,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
fn calls(&self) -> Vec<String> {
|
||||
self.calls.lock().unwrap().clone()
|
||||
}
|
||||
fn describing(self, answers: Vec<Vec<TaskInfo>>) -> Self {
|
||||
*self.described.lock().unwrap() = answers;
|
||||
self
|
||||
}
|
||||
fn running(self, r: Result<TaskInfo, AwsError>) -> Self {
|
||||
*self.run.lock().unwrap() = Some(r);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskApi for Fake {
|
||||
async fn run_task(&self, req: RunTaskInput) -> Result<TaskInfo, AwsError> {
|
||||
self.calls.lock().unwrap().push("run".into());
|
||||
self.run_requests.lock().unwrap().push(req);
|
||||
self.run
|
||||
.lock()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.unwrap_or_else(|| Ok(info("new", "PROVISIONING")))
|
||||
}
|
||||
async fn describe(&self, cluster: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(format!("describe {cluster} {}", arns.join(",")));
|
||||
let mut d = self.described.lock().unwrap();
|
||||
let answer = if d.len() > 1 {
|
||||
d.remove(0)
|
||||
} else {
|
||||
d.first().cloned().unwrap_or_default()
|
||||
};
|
||||
Ok(answer
|
||||
.into_iter()
|
||||
.filter(|t| arns.contains(&t.arn))
|
||||
.collect())
|
||||
}
|
||||
async fn list_project_tasks(
|
||||
&self,
|
||||
cluster: &str,
|
||||
family: &str,
|
||||
) -> Result<Vec<String>, AwsError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(format!("list {cluster} {family}"));
|
||||
Ok(self.listed.clone())
|
||||
}
|
||||
async fn stop_task(&self, _cluster: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push(format!("stop {arn} {reason}"));
|
||||
Ok(())
|
||||
}
|
||||
async fn log_tail(
|
||||
&self,
|
||||
group: &str,
|
||||
stream: &str,
|
||||
limit: i32,
|
||||
) -> Result<Vec<String>, AwsError> {
|
||||
self.log_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((group.into(), stream.into(), limit));
|
||||
Ok(self.logs.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn tags() -> Vec<(String, String)> {
|
||||
crate::aws::workspace::workspace_tags(USER, PROJECT_ID, "dev")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ run request
|
||||
|
||||
#[test]
|
||||
fn on_demand_runs_fargate_on_the_environment_network_with_exec_and_the_three_tags() {
|
||||
let req = run_task_request(&env_info(), &td_arn(3), false, &tags());
|
||||
assert_eq!(req.cluster(), Some(cluster().as_str()));
|
||||
assert_eq!(req.task_definition(), Some(td_arn(3).as_str()));
|
||||
assert_eq!(req.launch_type(), Some(&LaunchType::Fargate));
|
||||
assert!(req.capacity_provider_strategy().is_empty());
|
||||
assert_eq!(req.enable_execute_command(), Some(true));
|
||||
assert_eq!(req.count(), Some(1));
|
||||
let vpc = req
|
||||
.network_configuration()
|
||||
.and_then(|n| n.awsvpc_configuration())
|
||||
.expect("awsvpc");
|
||||
assert_eq!(vpc.subnets(), ["subnet-0a", "subnet-0b"]);
|
||||
assert_eq!(vpc.security_groups(), ["sg-0123456789abcdef0"]);
|
||||
assert_eq!(vpc.assign_public_ip(), Some(&AssignPublicIp::Enabled));
|
||||
let got: Vec<(String, String)> = req
|
||||
.tags()
|
||||
.iter()
|
||||
.map(|t| (t.key().unwrap().to_string(), t.value().unwrap().to_string()))
|
||||
.collect();
|
||||
assert_eq!(got, tags());
|
||||
// Nothing project-shaped rides along (P1), and tags are given, not propagated.
|
||||
assert!(req.overrides().is_none());
|
||||
assert!(req.propagate_tags().is_none());
|
||||
assert!(req.enable_ecs_managed_tags().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_uses_the_fargate_spot_capacity_provider_and_no_launch_type() {
|
||||
let req = run_task_request(&env_info(), &td_arn(3), true, &tags());
|
||||
assert_eq!(req.launch_type(), None);
|
||||
let strategy = req.capacity_provider_strategy();
|
||||
assert_eq!(strategy.len(), 1);
|
||||
assert_eq!(strategy[0].capacity_provider(), "FARGATE_SPOT");
|
||||
assert_eq!(strategy[0].weight(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_environment_gets_no_public_ip() {
|
||||
let mut env = env_info();
|
||||
env.assign_public_ip = false;
|
||||
let req = run_task_request(&env, &td_arn(3), false, &tags());
|
||||
let vpc = req
|
||||
.network_configuration()
|
||||
.unwrap()
|
||||
.awsvpc_configuration()
|
||||
.unwrap();
|
||||
assert_eq!(vpc.assign_public_ip(), Some(&AssignPublicIp::Disabled));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ find or run
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_existing_running_task_is_reused_and_nothing_is_run() {
|
||||
let api = Fake {
|
||||
listed: vec![task_arn("t1")],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![ready("t1")]]);
|
||||
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(4), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(got.reused);
|
||||
assert_eq!(got.task.arn, task_arn("t1"));
|
||||
assert!(!api.calls().contains(&"run".to_string()));
|
||||
assert_eq!(api.calls()[0], format!("list {} {FAMILY}", cluster()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pending_task_is_reused_too() {
|
||||
let api = Fake {
|
||||
listed: vec![task_arn("t1")],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![info("t1", "PENDING")]]);
|
||||
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(got.reused);
|
||||
assert_eq!(got.task.last_status, "PENDING");
|
||||
assert!(!api.calls().contains(&"run".to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_task_of_another_owner_or_project_in_the_family_is_never_reused() {
|
||||
let mut foreign = info("theirs", "RUNNING");
|
||||
foreign.owner = Some(OTHER.into());
|
||||
let mut other_project = info("other-project", "RUNNING");
|
||||
other_project.project = Some("ffffffff-0000-0000-0000-000000000000".into());
|
||||
let mut untagged = info("untagged", "RUNNING");
|
||||
untagged.owner = None;
|
||||
untagged.project = None;
|
||||
let api = Fake {
|
||||
listed: vec![
|
||||
task_arn("theirs"),
|
||||
task_arn("other-project"),
|
||||
task_arn("untagged"),
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![foreign, other_project, untagged]]);
|
||||
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!got.reused);
|
||||
assert_eq!(got.task.arn, task_arn("new"));
|
||||
assert_eq!(api.calls().last().unwrap(), "run");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_task_already_stopping_is_not_reused() {
|
||||
let mut stopping = info("t1", "RUNNING");
|
||||
stopping.desired_status = "STOPPED".into();
|
||||
let api = Fake {
|
||||
listed: vec![task_arn("t1"), task_arn("t2")],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![stopping, info("t2", "DEPROVISIONING")]]);
|
||||
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!got.reused);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_running_task_is_preferred_over_a_pending_one() {
|
||||
let api = Fake {
|
||||
listed: vec![task_arn("p"), task_arn("r")],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![info("p", "PENDING"), ready("r")]]);
|
||||
let got = find_project_task(&api, &cluster(), FAMILY, USER, PROJECT_ID)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(got.arn, task_arn("r"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_listed_means_no_describe_and_a_run_with_the_exact_revision_and_tags() {
|
||||
let api = Fake::default();
|
||||
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(7), true)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!got.reused);
|
||||
assert_eq!(api.calls().len(), 2, "{:?}", api.calls());
|
||||
let reqs = api.run_requests.lock().unwrap();
|
||||
assert_eq!(reqs[0].task_definition(), Some(td_arn(7).as_str()));
|
||||
assert_eq!(reqs[0].launch_type(), None);
|
||||
let keys: Vec<&str> = reqs[0].tags().iter().filter_map(|t| t.key()).collect();
|
||||
assert_eq!(
|
||||
keys,
|
||||
["triple-c:environment", "triple-c:owner", "triple-c:project"]
|
||||
);
|
||||
assert_eq!(
|
||||
reqs[0]
|
||||
.tags()
|
||||
.iter()
|
||||
.find(|t| t.key() == Some("triple-c:owner"))
|
||||
.unwrap()
|
||||
.value(),
|
||||
Some(USER)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bare_family_or_foreign_arn_is_refused_before_any_call() {
|
||||
let api = Fake::default();
|
||||
for bad in [
|
||||
FAMILY.to_string(),
|
||||
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}"),
|
||||
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}:latest"),
|
||||
"arn:aws:ecs:eu-west-1:1:task-definition/someone-else:1".to_string(),
|
||||
] {
|
||||
let err = find_or_run(&api, &env_info(), USER, PROJECT_ID, &bad, false)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, AwsError::Other { .. }), "{bad}: {err:?}");
|
||||
}
|
||||
assert!(api.calls().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_quota_refusal_is_reported_once_without_retrying() {
|
||||
let api = Fake::default().running(Err(quota_error(
|
||||
"You've reached the limit on the number of vCPUs you can run concurrently",
|
||||
)));
|
||||
let err = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(is_quota_error(&err));
|
||||
let text = err.to_string();
|
||||
assert!(text.contains("limit"), "{text}");
|
||||
assert!(text.contains("quota"), "{text}");
|
||||
assert!(text.contains("vCPUs"), "{text}");
|
||||
assert_eq!(
|
||||
api.calls().iter().filter(|c| *c == "run").count(),
|
||||
1,
|
||||
"no retry"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ quota mapping
|
||||
|
||||
#[test]
|
||||
fn quota_texts_are_recognised_and_others_are_not() {
|
||||
for q in [
|
||||
"You've reached the limit on the number of vCPUs you can run concurrently",
|
||||
"You\u{2019}ve reached the limit on the number of tasks you can run concurrently",
|
||||
"LimitExceededException: too many",
|
||||
"Service quota exceeded for Fargate On-Demand vCPU",
|
||||
"limit exceeded",
|
||||
] {
|
||||
assert!(looks_like_quota(q), "{q}");
|
||||
}
|
||||
for not in [
|
||||
"Capacity is unavailable at this time. Please try again later",
|
||||
"AccessDeniedException: not authorized",
|
||||
"CannotPullContainerError",
|
||||
] {
|
||||
assert!(!looks_like_quota(not), "{not}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_mapping_turns_other_errors_into_quota_errors_and_leaves_the_rest() {
|
||||
let q = quota_or(AwsError::Other {
|
||||
message: "ClientException: You've reached the limit on the number of vCPUs".into(),
|
||||
});
|
||||
assert!(is_quota_error(&q));
|
||||
// The frontend's `quota_exceeded` kind (lib/types.ts).
|
||||
let v = serde_json::to_value(&q).unwrap();
|
||||
assert_eq!(v["kind"], "quota_exceeded");
|
||||
assert!(v["message"].as_str().unwrap().contains("vCPUs"));
|
||||
let denied = AwsError::AccessDenied {
|
||||
action: "ecs:RunTask".into(),
|
||||
message: "limit".into(),
|
||||
};
|
||||
assert_eq!(quota_or(denied.clone()), denied);
|
||||
assert!(!is_quota_error(&AwsError::Other {
|
||||
message: "x".into()
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_task_failures_become_errors_and_quota_failures_quota_errors() {
|
||||
let ok = run_task_outcome(vec![info("a", "PROVISIONING")], vec![]).unwrap();
|
||||
assert_eq!(ok.arn, task_arn("a"));
|
||||
let err = run_task_outcome(
|
||||
vec![],
|
||||
vec![(Some("RESOURCE:ENI".into()), Some("no ENIs left".into()))],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(!is_quota_error(&err));
|
||||
assert!(err.to_string().contains("RESOURCE:ENI"), "{err}");
|
||||
assert!(err.to_string().contains("no ENIs left"), "{err}");
|
||||
let err = run_task_outcome(
|
||||
vec![],
|
||||
vec![(
|
||||
Some("You've reached the limit on the number of tasks you can run concurrently".into()),
|
||||
None,
|
||||
)],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(is_quota_error(&err));
|
||||
let err = run_task_outcome(vec![], vec![]).unwrap_err();
|
||||
assert!(err.to_string().contains("no task"), "{err}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ wait
|
||||
|
||||
fn timing() -> WaitTiming {
|
||||
WaitTiming {
|
||||
interval: Duration::from_secs(5),
|
||||
timeout: Duration::from_secs(360),
|
||||
}
|
||||
}
|
||||
|
||||
fn logs() -> TaskLogs {
|
||||
TaskLogs {
|
||||
group: "/triple-c/dev".into(),
|
||||
stream_prefix: log_stream_prefix(&owner_key(REGION, USER), PROJECT_ID),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn wait_polls_until_running_with_the_exec_agent_and_a_runtime_id() {
|
||||
let mut half = info("t1", "RUNNING");
|
||||
half.runtime_id = Some("rt".into());
|
||||
let api = Fake::default().describing(vec![
|
||||
vec![info("t1", "PROVISIONING")],
|
||||
vec![info("t1", "PENDING")],
|
||||
vec![half],
|
||||
vec![ready("t1")],
|
||||
]);
|
||||
let seen = Mutex::new(Vec::new());
|
||||
let t0 = tokio::time::Instant::now();
|
||||
let got = wait_ready(
|
||||
&api,
|
||||
&cluster(),
|
||||
&task_arn("t1"),
|
||||
&logs(),
|
||||
timing(),
|
||||
|t: &TaskInfo| seen.lock().unwrap().push(t.last_status.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(got, ready("t1"));
|
||||
assert_eq!(
|
||||
*seen.lock().unwrap(),
|
||||
["PROVISIONING", "PENDING", "RUNNING", "RUNNING"]
|
||||
);
|
||||
assert_eq!(t0.elapsed(), Duration::from_secs(15));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_task_that_stops_while_waiting_reports_its_reason_and_last_log_lines() {
|
||||
let mut stopped = info("t1", "STOPPED");
|
||||
stopped.stop_code = Some("EssentialContainerExited".into());
|
||||
stopped.stopped_reason = Some("Essential container in task exited".into());
|
||||
let api = Fake {
|
||||
logs: vec!["Triple-C: starting".into(), "fatal: boom".into()],
|
||||
..Default::default()
|
||||
}
|
||||
.describing(vec![vec![info("t1", "PENDING")], vec![stopped]]);
|
||||
let err = wait_ready(
|
||||
&api,
|
||||
&cluster(),
|
||||
&task_arn("t1"),
|
||||
&logs(),
|
||||
timing(),
|
||||
|_: &TaskInfo| {},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let text = err.to_string();
|
||||
assert!(
|
||||
text.contains("Essential container in task exited"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("Triple-C: starting\nfatal: boom"), "{text}");
|
||||
let reqs = api.log_requests.lock().unwrap();
|
||||
assert_eq!(
|
||||
*reqs,
|
||||
[(
|
||||
"/triple-c/dev".to_string(),
|
||||
format!("{}/workspace/t1", logs().stream_prefix),
|
||||
50
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_task_being_stopped_fails_the_wait_at_once() {
|
||||
let mut stopping = info("t1", "RUNNING");
|
||||
stopping.desired_status = "STOPPED".into();
|
||||
stopping.stop_code = Some("SpotInterruption".into());
|
||||
stopping.stopped_reason = Some("Your Spot Task was interrupted.".into());
|
||||
let api = Fake::default().describing(vec![vec![stopping]]);
|
||||
let err = wait_ready(
|
||||
&api,
|
||||
&cluster(),
|
||||
&task_arn("t1"),
|
||||
&logs(),
|
||||
timing(),
|
||||
|_: &TaskInfo| {},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("Your Spot Task was interrupted."),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_task_that_never_gets_ready_times_out_with_its_last_status() {
|
||||
let api = Fake::default().describing(vec![vec![info("t1", "PENDING")]]);
|
||||
let t0 = tokio::time::Instant::now();
|
||||
let err = wait_ready(
|
||||
&api,
|
||||
&cluster(),
|
||||
&task_arn("t1"),
|
||||
&logs(),
|
||||
timing(),
|
||||
|_: &TaskInfo| {},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(t0.elapsed() >= Duration::from_secs(360));
|
||||
assert!(t0.elapsed() < Duration::from_secs(366));
|
||||
let text = err.to_string();
|
||||
assert!(text.contains("6 minutes"), "{text}");
|
||||
assert!(text.contains("PENDING"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_task_that_vanishes_is_an_error_not_a_hang() {
|
||||
let api = Fake::default().describing(vec![vec![]]);
|
||||
let err = wait_ready(
|
||||
&api,
|
||||
&cluster(),
|
||||
&task_arn("t1"),
|
||||
&logs(),
|
||||
timing(),
|
||||
|_: &TaskInfo| {},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("no longer"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_wait_is_five_seconds_for_six_minutes() {
|
||||
let t = WaitTiming::default();
|
||||
assert_eq!(t.interval, Duration::from_secs(5));
|
||||
assert_eq!(t.timeout, Duration::from_secs(360));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ stop / logs
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_passes_the_reason() {
|
||||
let api = Fake::default();
|
||||
api.stop_task(&cluster(), &task_arn("t1"), STOP_REASON)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
api.calls(),
|
||||
[format!("stop {} Stopped from Triple-C", task_arn("t1"))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_log_stream_is_prefix_container_task_id() {
|
||||
assert_eq!(
|
||||
task_log_stream("abc/p", &task_arn("0123abcd")),
|
||||
"abc/p/workspace/0123abcd"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stopped_among_reports_stopped_and_vanished_tasks_only() {
|
||||
let api = Fake::default().describing(vec![vec![
|
||||
ready("up"),
|
||||
info("down", "STOPPED"),
|
||||
info("pending", "PENDING"),
|
||||
]]);
|
||||
let arns = vec![
|
||||
task_arn("up"),
|
||||
task_arn("down"),
|
||||
task_arn("pending"),
|
||||
task_arn("gone"),
|
||||
];
|
||||
let mut got = stopped_among(&api, &cluster(), &arns).await.unwrap();
|
||||
got.sort();
|
||||
assert_eq!(got, [task_arn("down"), task_arn("gone")]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ classify
|
||||
|
||||
#[test]
|
||||
fn classify_stop_follows_the_spec_table() {
|
||||
let with = |code: Option<&str>, reason: Option<&str>| TaskInfo {
|
||||
stop_code: code.map(String::from),
|
||||
stopped_reason: reason.map(String::from),
|
||||
..info("t", "STOPPED")
|
||||
};
|
||||
assert_eq!(
|
||||
classify_stop(&with(Some("EssentialContainerExited"), None)),
|
||||
StopKind::Exited
|
||||
);
|
||||
assert_eq!(
|
||||
classify_stop(&with(Some("SpotInterruption"), None)),
|
||||
StopKind::Spot
|
||||
);
|
||||
assert_eq!(
|
||||
classify_stop(&with(
|
||||
Some("TaskFailedToStart"),
|
||||
Some("CannotPullContainerError: nope")
|
||||
)),
|
||||
StopKind::FailedToStart("CannotPullContainerError: nope".into())
|
||||
);
|
||||
assert!(matches!(
|
||||
classify_stop(&with(Some("TaskFailedToStart"), None)),
|
||||
StopKind::FailedToStart(r) if !r.is_empty()
|
||||
));
|
||||
assert_eq!(
|
||||
classify_stop(&with(Some("UserInitiated"), Some("Stopped from Triple-C"))),
|
||||
StopKind::UserInitiated
|
||||
);
|
||||
assert_eq!(
|
||||
classify_stop(&with(Some("TerminationNotice"), None)),
|
||||
StopKind::Exited
|
||||
);
|
||||
assert_eq!(
|
||||
classify_stop(&with(Some("ServiceSchedulerInitiated"), None)),
|
||||
StopKind::Exited
|
||||
);
|
||||
assert_eq!(classify_stop(&with(None, None)), StopKind::Exited);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ SDK mapping
|
||||
|
||||
#[test]
|
||||
fn task_info_reads_the_workspace_container_and_its_exec_agent() {
|
||||
let task = Task::builder()
|
||||
.task_arn(task_arn("t1"))
|
||||
.last_status("RUNNING")
|
||||
.desired_status("RUNNING")
|
||||
.health_status(aws_sdk_ecs::types::HealthStatus::Healthy)
|
||||
.stop_code(TaskStopCode::SpotInterruption)
|
||||
.stopped_reason("r")
|
||||
.task_definition_arn(td_arn(3))
|
||||
.containers(
|
||||
Container::builder()
|
||||
.name("sidecar")
|
||||
.runtime_id("wrong")
|
||||
.build(),
|
||||
)
|
||||
.containers(
|
||||
Container::builder()
|
||||
.name("workspace")
|
||||
.runtime_id("rt-1")
|
||||
.managed_agents(
|
||||
ManagedAgent::builder()
|
||||
.name(ManagedAgentName::ExecuteCommandAgent)
|
||||
.last_status("RUNNING")
|
||||
.build(),
|
||||
)
|
||||
.build(),
|
||||
)
|
||||
.tags(Tag::builder().key("triple-c:owner").value(USER).build())
|
||||
.tags(
|
||||
Tag::builder()
|
||||
.key("triple-c:project")
|
||||
.value(PROJECT_ID)
|
||||
.build(),
|
||||
)
|
||||
.build();
|
||||
let i = task_info(&task);
|
||||
assert_eq!(i.arn, task_arn("t1"));
|
||||
assert_eq!(i.health.as_deref(), Some("HEALTHY"));
|
||||
assert_eq!(i.stop_code.as_deref(), Some("SpotInterruption"));
|
||||
assert_eq!(i.runtime_id.as_deref(), Some("rt-1"));
|
||||
assert!(i.exec_agent_running);
|
||||
assert_eq!(i.owner.as_deref(), Some(USER));
|
||||
assert_eq!(i.project.as_deref(), Some(PROJECT_ID));
|
||||
|
||||
let bare = task_info(&Task::builder().task_arn("x").last_status("PENDING").build());
|
||||
assert!(!bare.exec_agent_running);
|
||||
assert_eq!(bare.runtime_id, None);
|
||||
assert_eq!(bare.owner, None);
|
||||
}
|
||||
@@ -198,6 +198,14 @@ pub fn log_stream_prefix(owner_key: &str, project_id: &str) -> String {
|
||||
format!("{owner_key}/{}", project_component(project_id))
|
||||
}
|
||||
|
||||
/// The awslogs stream of a task's `workspace` container:
|
||||
/// `<prefix>/<container>/<task-id>`, the task id being the last segment of
|
||||
/// its ARN.
|
||||
pub fn task_log_stream(stream_prefix: &str, task_arn: &str) -> String {
|
||||
let task_id = task_arn.rsplit('/').next().unwrap_or(task_arn);
|
||||
format!("{stream_prefix}/workspace/{task_id}")
|
||||
}
|
||||
|
||||
/// The `creation_token` of the user's file system (the onboarding module's
|
||||
/// `local.name`).
|
||||
pub fn user_file_system_token(env: &str, owner_key: &str) -> String {
|
||||
|
||||
@@ -143,11 +143,11 @@ async fn unless_cancelled<T>(
|
||||
/// (see [`STABLE_AFTER`]).
|
||||
async fn watch_once(
|
||||
store: &ProjectsStore,
|
||||
source: &ExitSource,
|
||||
cancel: &mut watch::Receiver<bool>,
|
||||
sweep_reason: ExitReason,
|
||||
on_change: &impl Fn(&Project, ExitReason),
|
||||
) -> Option<bool> {
|
||||
let source = ExitSource::Docker;
|
||||
if !unless_cancelled(cancel, source.reachable()).await? {
|
||||
return Some(false);
|
||||
}
|
||||
@@ -187,6 +187,7 @@ async fn watch_once(
|
||||
/// test can drive it without a Tauri app.
|
||||
pub(crate) async fn run(
|
||||
store: Arc<ProjectsStore>,
|
||||
source: ExitSource,
|
||||
mut cancel: watch::Receiver<bool>,
|
||||
on_change: impl Fn(&Project, ExitReason),
|
||||
) {
|
||||
@@ -197,7 +198,7 @@ pub(crate) async fn run(
|
||||
let mut sweep_reason = ExitReason::FoundStopped;
|
||||
let mut failures: u32 = 0;
|
||||
loop {
|
||||
let Some(healthy) = watch_once(&store, &mut cancel, sweep_reason, &on_change).await else {
|
||||
let Some(healthy) = watch_once(&store, &source, &mut cancel, sweep_reason, &on_change).await else {
|
||||
return;
|
||||
};
|
||||
sweep_reason = ExitReason::Exited;
|
||||
@@ -209,14 +210,16 @@ pub(crate) async fn run(
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the watcher for the life of the app.
|
||||
/// Start a watcher on `source` for the life of the app. One per host kind:
|
||||
/// Docker's event stream, and (Task 6) the AWS task poll.
|
||||
pub fn spawn(
|
||||
app: AppHandle,
|
||||
store: Arc<ProjectsStore>,
|
||||
source: ExitSource,
|
||||
cancel: watch::Receiver<bool>,
|
||||
) -> tauri::async_runtime::JoinHandle<()> {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
run(store, cancel, |p, reason| {
|
||||
run(store, source, cancel, |p, reason| {
|
||||
log::warn!(
|
||||
"Project '{}' ({}): its container stopped without the app asking ({:?}) — marking Stopped",
|
||||
p.name,
|
||||
@@ -270,6 +273,48 @@ mod tests {
|
||||
assert_eq!(unless_cancelled(&mut rx, async { 1 }).await, None);
|
||||
}
|
||||
|
||||
/// The AWS source drives the same loop: it is "reachable" without a
|
||||
/// ping, polls its lookup every interval, and gives way to cancellation.
|
||||
/// No project is Running, so nothing is confirmed (and nothing reaches
|
||||
/// Docker or AWS).
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_aws_source_polls_its_lookup_until_cancelled() {
|
||||
use crate::host::watch::{AwsTaskLookup, AwsWatch, TaskGroup, WatchedTask};
|
||||
use futures_util::future::BoxFuture;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct Lookup(AtomicUsize);
|
||||
impl AwsTaskLookup for Lookup {
|
||||
fn running_tasks(&self) -> Vec<WatchedTask> {
|
||||
self.0.fetch_add(1, Ordering::SeqCst);
|
||||
Vec::new()
|
||||
}
|
||||
fn stopped<'a>(
|
||||
&'a self,
|
||||
_: &'a TaskGroup,
|
||||
_: &'a [String],
|
||||
) -> BoxFuture<'a, Result<Vec<String>, String>> {
|
||||
Box::pin(async { Ok(Vec::new()) })
|
||||
}
|
||||
}
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("triple-c-watch-aws-{}", uuid::Uuid::new_v4().simple()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let store = Arc::new(ProjectsStore::over_file_for_test(dir.join("projects.json"), Vec::new()));
|
||||
let lookup = Arc::new(Lookup(AtomicUsize::new(0)));
|
||||
let source = ExitSource::Aws(AwsWatch::every(lookup.clone(), Duration::from_secs(15)));
|
||||
let (cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let watcher = tokio::spawn(run(store, source, cancel_rx, |_, _| panic!("nothing stopped")));
|
||||
tokio::time::sleep(Duration::from_secs(46)).await;
|
||||
assert_eq!(lookup.0.load(Ordering::SeqCst), 3);
|
||||
let _ = cancel_tx.send(true);
|
||||
tokio::time::timeout(Duration::from_secs(1), watcher)
|
||||
.await
|
||||
.expect("stops at once")
|
||||
.unwrap();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
/// End to end against a real daemon: a Running project whose container is
|
||||
/// killed from outside the app is flipped to Stopped and reported as a live
|
||||
/// exit; one found already stopped on the first look is reported as such;
|
||||
@@ -302,7 +347,7 @@ mod tests {
|
||||
|
||||
let (cancel_tx, cancel_rx) = watch::channel(false);
|
||||
let (seen_tx, mut seen_rx) = tokio::sync::mpsc::unbounded_channel::<(String, ExitReason)>();
|
||||
let watcher = tokio::spawn(run(store.clone(), cancel_rx, move |p, why| {
|
||||
let watcher = tokio::spawn(run(store.clone(), ExitSource::Docker, cancel_rx, move |p, why| {
|
||||
let _ = seen_tx.send((p.id.clone(), why));
|
||||
}));
|
||||
let first = tokio::time::timeout(Duration::from_secs(10), seen_rx.recv()).await;
|
||||
|
||||
@@ -3,21 +3,143 @@
|
||||
//! reported dead (replayable from a point in time), and a positive-exit check
|
||||
//! used to confirm each report before anything changes.
|
||||
//!
|
||||
//! Docker pushes `die` events. An AWS host will have no push stream from the
|
||||
//! app's point of view; its [`deaths`] will be a `DescribeTasks` poll that
|
||||
//! yields stopped tasks, which `container_watch` handles the same way because
|
||||
//! every report is confirmed with [`ContainerTarget::has_exited`] anyway.
|
||||
//! Docker pushes `die` events. AWS has no push stream from the app's point of
|
||||
//! view; its [`ExitSource::deaths`] is a `DescribeTasks` poll (every 15 s) over
|
||||
//! the tasks of Running AWS projects that yields the stopped ones, which
|
||||
//! `container_watch` handles the same way because every report is confirmed
|
||||
//! with [`ContainerTarget::has_exited`] anyway.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::future::BoxFuture;
|
||||
use futures_util::{Stream, StreamExt};
|
||||
use std::pin::Pin;
|
||||
|
||||
use super::ContainerTarget;
|
||||
use crate::docker;
|
||||
|
||||
/// Which host's deaths to watch. One variant today.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
/// How often the AWS watch asks ECS (spec, "Lifecycle and status").
|
||||
pub const AWS_POLL_INTERVAL: Duration = Duration::from_secs(15);
|
||||
|
||||
/// Which host's deaths to watch.
|
||||
#[derive(Clone)]
|
||||
pub enum ExitSource {
|
||||
Docker,
|
||||
// Constructed by the AWS host (phase 5, Task 6); until then only by tests.
|
||||
#[allow(dead_code)]
|
||||
Aws(AwsWatch),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ExitSource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ExitSource::Docker => f.write_str("Docker"),
|
||||
ExitSource::Aws(w) => write!(f, "Aws(every {:?})", w.interval),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a task's DescribeTasks goes: the connection and region its
|
||||
/// credentials and endpoint come from, and the cluster.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct TaskGroup {
|
||||
pub connection_id: String,
|
||||
pub region: String,
|
||||
pub cluster_arn: String,
|
||||
}
|
||||
|
||||
/// A Running AWS project's task, and the target a death is reported as.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WatchedTask {
|
||||
pub target: ContainerTarget,
|
||||
pub group: TaskGroup,
|
||||
pub task_arn: String,
|
||||
}
|
||||
|
||||
/// The project-to-task lookup the AWS watch runs on, injected so it can be
|
||||
/// faked (Task 6 backs it with the tunnel registry / project store and
|
||||
/// `aws::tasks::stopped_among`).
|
||||
pub trait AwsTaskLookup: Send + Sync {
|
||||
/// The tasks of the projects that are Running now. Read on every poll.
|
||||
fn running_tasks(&self) -> Vec<WatchedTask>;
|
||||
/// Of `arns` (all in `group`, at most 100), the ones that are STOPPED or
|
||||
/// gone. `Err` when ECS could not be asked.
|
||||
fn stopped<'a>(
|
||||
&'a self,
|
||||
group: &'a TaskGroup,
|
||||
arns: &'a [String],
|
||||
) -> BoxFuture<'a, Result<Vec<String>, String>>;
|
||||
}
|
||||
|
||||
/// The AWS death poll: a lookup and how often to run it.
|
||||
#[derive(Clone)]
|
||||
pub struct AwsWatch {
|
||||
lookup: Arc<dyn AwsTaskLookup>,
|
||||
interval: Duration,
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // Task 6
|
||||
impl AwsWatch {
|
||||
pub fn new(lookup: Arc<dyn AwsTaskLookup>) -> Self {
|
||||
Self::every(lookup, AWS_POLL_INTERVAL)
|
||||
}
|
||||
pub fn every(lookup: Arc<dyn AwsTaskLookup>, interval: Duration) -> Self {
|
||||
AwsWatch { lookup, interval }
|
||||
}
|
||||
}
|
||||
|
||||
/// DescribeTasks' batch limit.
|
||||
const DESCRIBE_BATCH: usize = 100;
|
||||
|
||||
/// One poll: the targets of Running projects whose task stopped. Tasks are
|
||||
/// asked about per group (connection + region + cluster), 100 at a time. A
|
||||
/// group that can't be asked (expired SSO, network) is logged and skipped —
|
||||
/// it confirms nothing, and the other groups are still watched; the next
|
||||
/// poll asks again.
|
||||
pub async fn poll_stopped(lookup: &dyn AwsTaskLookup) -> Vec<ContainerTarget> {
|
||||
let mut groups: HashMap<TaskGroup, Vec<WatchedTask>> = HashMap::new();
|
||||
for t in lookup.running_tasks() {
|
||||
groups.entry(t.group.clone()).or_default().push(t);
|
||||
}
|
||||
let mut dead = Vec::new();
|
||||
for (group, tasks) in groups {
|
||||
for chunk in tasks.chunks(DESCRIBE_BATCH) {
|
||||
let arns: Vec<String> = chunk.iter().map(|t| t.task_arn.clone()).collect();
|
||||
match lookup.stopped(&group, &arns).await {
|
||||
Ok(stopped) => dead.extend(
|
||||
chunk
|
||||
.iter()
|
||||
.filter(|t| stopped.contains(&t.task_arn))
|
||||
.map(|t| t.target.clone()),
|
||||
),
|
||||
Err(e) => log::warn!(
|
||||
"Container watch: could not check AWS tasks in {} ({}): {e}",
|
||||
group.region,
|
||||
group.cluster_arn
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
dead
|
||||
}
|
||||
|
||||
/// Polls forever, `interval` apart (the first after one interval: the
|
||||
/// watcher sweeps on connect), yielding each stopped task's target.
|
||||
fn aws_deaths(watch: AwsWatch) -> DeathStream {
|
||||
Box::pin(futures_util::stream::unfold(
|
||||
(watch, VecDeque::new()),
|
||||
|(watch, mut queue)| async move {
|
||||
loop {
|
||||
if let Some(t) = queue.pop_front() {
|
||||
return Some((Ok(t), (watch, queue)));
|
||||
}
|
||||
tokio::time::sleep(watch.interval).await;
|
||||
queue.extend(poll_stopped(&*watch.lookup).await);
|
||||
}
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
pub type DeathStream = Pin<Box<dyn Stream<Item = Result<ContainerTarget, String>> + Send>>;
|
||||
@@ -28,6 +150,9 @@ impl ExitSource {
|
||||
pub async fn reachable(&self) -> bool {
|
||||
match self {
|
||||
ExitSource::Docker => docker::events::ping().await,
|
||||
// No one endpoint to ping: each poll asks every group, and a
|
||||
// group that fails is skipped rather than ending the stream.
|
||||
ExitSource::Aws(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +163,9 @@ impl ExitSource {
|
||||
ExitSource::Docker => Box::pin(
|
||||
docker::events::container_deaths(since).map(|r| r.map(ContainerTarget::docker)),
|
||||
),
|
||||
// ECS has no replay: a task that stopped while the stream was
|
||||
// down is still STOPPED (or gone) on the next poll.
|
||||
ExitSource::Aws(watch) => aws_deaths(watch.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,3 +186,151 @@ impl ContainerTarget {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn group(conn: &str, region: &str) -> TaskGroup {
|
||||
TaskGroup {
|
||||
connection_id: conn.into(),
|
||||
region: region.into(),
|
||||
cluster_arn: format!("arn:aws:ecs:{region}:111122223333:cluster/triple-c-dev"),
|
||||
}
|
||||
}
|
||||
|
||||
fn task(n: usize, g: &TaskGroup) -> WatchedTask {
|
||||
WatchedTask {
|
||||
target: ContainerTarget::docker(format!("target-{:012}", n)),
|
||||
group: g.clone(),
|
||||
task_arn: format!("arn:aws:ecs:{}:111122223333:task/triple-c-dev/t{n}", g.region),
|
||||
}
|
||||
}
|
||||
|
||||
/// Running tasks are fixed; `dead` are the stopped ARNs; a group whose
|
||||
/// region is `failing` errors. Every `stopped` call is recorded.
|
||||
struct FakeLookup {
|
||||
tasks: Mutex<Vec<WatchedTask>>,
|
||||
dead: Vec<String>,
|
||||
failing: &'static str,
|
||||
asked: Mutex<Vec<(TaskGroup, usize)>>,
|
||||
polls: Mutex<usize>,
|
||||
}
|
||||
|
||||
impl FakeLookup {
|
||||
fn new(tasks: Vec<WatchedTask>, dead: Vec<String>) -> Self {
|
||||
FakeLookup {
|
||||
tasks: Mutex::new(tasks),
|
||||
dead,
|
||||
failing: "",
|
||||
asked: Mutex::new(Vec::new()),
|
||||
polls: Mutex::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsTaskLookup for FakeLookup {
|
||||
fn running_tasks(&self) -> Vec<WatchedTask> {
|
||||
*self.polls.lock().unwrap() += 1;
|
||||
self.tasks.lock().unwrap().clone()
|
||||
}
|
||||
fn stopped<'a>(
|
||||
&'a self,
|
||||
group: &'a TaskGroup,
|
||||
arns: &'a [String],
|
||||
) -> BoxFuture<'a, Result<Vec<String>, String>> {
|
||||
Box::pin(async move {
|
||||
self.asked.lock().unwrap().push((group.clone(), arns.len()));
|
||||
if group.region == self.failing {
|
||||
return Err("SSO session expired".into());
|
||||
}
|
||||
Ok(arns.iter().filter(|a| self.dead.contains(a)).cloned().collect())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_poll_asks_each_group_once_and_reports_only_stopped_tasks() {
|
||||
let (a, b) = (group("c1", "eu-west-1"), group("c2", "us-east-1"));
|
||||
let tasks = vec![task(1, &a), task(2, &b), task(3, &a)];
|
||||
let dead = vec![tasks[0].task_arn.clone(), tasks[1].task_arn.clone()];
|
||||
let lookup = FakeLookup::new(tasks.clone(), dead);
|
||||
let mut got = poll_stopped(&lookup).await;
|
||||
got.sort_by(|x, y| x.id().cmp(y.id()));
|
||||
assert_eq!(got, vec![tasks[0].target.clone(), tasks[1].target.clone()]);
|
||||
let mut asked = lookup.asked.lock().unwrap().clone();
|
||||
asked.sort_by(|x, y| x.0.region.cmp(&y.0.region));
|
||||
assert_eq!(asked, vec![(a, 2), (b, 1)]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_group_that_cannot_be_asked_confirms_nothing_and_the_others_still_report() {
|
||||
let (a, b) = (group("c1", "eu-west-1"), group("c2", "us-east-1"));
|
||||
let tasks = vec![task(1, &a), task(2, &b)];
|
||||
let dead = tasks.iter().map(|t| t.task_arn.clone()).collect();
|
||||
let mut lookup = FakeLookup::new(tasks.clone(), dead);
|
||||
lookup.failing = "eu-west-1";
|
||||
assert_eq!(poll_stopped(&lookup).await, vec![tasks[1].target.clone()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tasks_are_described_a_hundred_at_a_time() {
|
||||
let a = group("c1", "eu-west-1");
|
||||
let lookup = FakeLookup::new((0..250).map(|n| task(n, &a)).collect(), Vec::new());
|
||||
assert!(poll_stopped(&lookup).await.is_empty());
|
||||
let sizes: Vec<usize> = lookup.asked.lock().unwrap().iter().map(|(_, n)| *n).collect();
|
||||
assert_eq!(sizes, vec![100, 100, 50]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_running_aws_projects_means_no_aws_calls() {
|
||||
let lookup = FakeLookup::new(Vec::new(), Vec::new());
|
||||
assert!(poll_stopped(&lookup).await.is_empty());
|
||||
assert!(lookup.asked.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_aws_stream_polls_every_interval_and_yields_each_death() {
|
||||
let a = group("c1", "eu-west-1");
|
||||
let tasks = vec![task(1, &a), task(2, &a)];
|
||||
let lookup = Arc::new(FakeLookup::new(
|
||||
tasks.clone(),
|
||||
vec![tasks[0].task_arn.clone(), tasks[1].task_arn.clone()],
|
||||
));
|
||||
let source = ExitSource::Aws(AwsWatch::new(lookup.clone()));
|
||||
assert!(source.reachable().await);
|
||||
let mut deaths = source.deaths(0);
|
||||
let t0 = tokio::time::Instant::now();
|
||||
let first = deaths.next().await.unwrap().unwrap();
|
||||
assert_eq!(t0.elapsed(), AWS_POLL_INTERVAL, "the first poll waits one interval");
|
||||
let second = deaths.next().await.unwrap().unwrap();
|
||||
assert_eq!(t0.elapsed(), AWS_POLL_INTERVAL, "one poll, both reported");
|
||||
let mut got = vec![first, second];
|
||||
got.sort_by(|x, y| x.id().cmp(y.id()));
|
||||
assert_eq!(got, vec![tasks[0].target.clone(), tasks[1].target.clone()]);
|
||||
assert_eq!(*lookup.polls.lock().unwrap(), 1);
|
||||
|
||||
// Once the projects are no longer Running, polls go on and report nothing.
|
||||
lookup.tasks.lock().unwrap().clear();
|
||||
let quiet = tokio::time::timeout(AWS_POLL_INTERVAL * 3 + Duration::from_secs(1), deaths.next()).await;
|
||||
assert!(quiet.is_err(), "nothing to report");
|
||||
assert_eq!(*lookup.polls.lock().unwrap(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_aws_poll_runs_every_fifteen_seconds() {
|
||||
assert_eq!(AWS_POLL_INTERVAL, Duration::from_secs(15));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_agent_target_never_confirms_an_exit_on_its_own() {
|
||||
// R3: Task 6 wires the tunnel registry into this arm.
|
||||
let ep = crate::host::agent::AgentEndpoint::new(
|
||||
url::Url::parse("http://127.0.0.1:47901").unwrap(),
|
||||
"fake-token",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!ContainerTarget::Agent(ep).has_exited().await);
|
||||
}
|
||||
}
|
||||
@@ -329,6 +329,7 @@ pub fn run() {
|
||||
lifecycle_setup.track(container_watch::spawn(
|
||||
app.handle().clone(),
|
||||
projects_store_setup.clone(),
|
||||
crate::host::watch::ExitSource::Docker,
|
||||
lifecycle_setup.cancellation(),
|
||||
));
|
||||
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { toAwsError } from "./aws-error";
|
||||
import { awsErrorMessage, toAwsError } from "./aws-error";
|
||||
|
||||
describe("toAwsError", () => {
|
||||
it("passes a tagged AwsError through", () => {
|
||||
const e = { kind: "sso_expired", profile: "dev" };
|
||||
expect(toAwsError(e)).toBe(e);
|
||||
});
|
||||
it("passes a quota error through with its message", () => {
|
||||
const e = { kind: "quota_exceeded", message: "An account limit was reached" };
|
||||
expect(toAwsError(e)).toBe(e);
|
||||
expect(awsErrorMessage(toAwsError(e))).toBe("An account limit was reached");
|
||||
});
|
||||
it("wraps strings and Errors as other", () => {
|
||||
expect(toAwsError("boom")).toEqual({ kind: "other", message: "boom" });
|
||||
expect(toAwsError(new Error("bad"))).toEqual({ kind: "other", message: "bad" });
|
||||
|
||||
@@ -8,6 +8,7 @@ const KINDS: Record<AwsError["kind"], true> = {
|
||||
invalid_credentials: true,
|
||||
access_denied: true,
|
||||
state_bucket_taken: true,
|
||||
quota_exceeded: true,
|
||||
other: true,
|
||||
};
|
||||
|
||||
|
||||
@@ -1184,6 +1184,7 @@ export type AwsError =
|
||||
| { kind: "invalid_credentials"; message: string }
|
||||
| { kind: "access_denied"; action: string; message: string }
|
||||
| { kind: "state_bucket_taken"; bucket: string }
|
||||
| { kind: "quota_exceeded"; message: string }
|
||||
| { kind: "other"; message: string };
|
||||
|
||||
export interface CallerIdentity {
|
||||
|
||||
Reference in new issue
Block a user