Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bc3d16bfb6 | |||
| 7617e1f87c | |||
| 299a7704c2 | |||
| a52602186d | |||
| 57aa866144 | |||
| ac96c6451e | |||
| 39664957fe | |||
| 1b00488b7c | |||
| dfbfa4d2a7 | |||
| 5dd9a1e346 | |||
| 00b3af3813 | |||
| d8d7dd021b | |||
| eaf5ca6ade | |||
| cc64729599 | |||
| 9f17f72cc3 | |||
| d8d94a773d | |||
| 957579c8b7 | |||
| d9a1a36dc8 | |||
| 5d4b010710 | |||
| 2486869b6b | |||
| 327173c8f6 | |||
| dcb007f8b8 | |||
| 607ac0803b | |||
| a9df81a294 | |||
| fa3327bf71 | |||
| 83aafc0325 | |||
| 24314f4432 | |||
| e90978ae94 | |||
| 21625c5a1b | |||
| 2e0a438d70 | |||
| ccdf32335d | |||
| cbb95ba26c | |||
| 90d5dc9427 |
@@ -1,21 +1,17 @@
|
||||
<p align="center">
|
||||
<img src="docs/assets/floci-black.svg#gh-light-mode-only" alt="Floci" width="500" />
|
||||
<img src="docs/assets/floci-white.svg#gh-dark-mode-only" alt="Floci" width="500" />
|
||||
<img src="docs/assets/thecloud-logo.png" alt="TheCloud" width="160" />
|
||||
</p>
|
||||
|
||||
<h1 align="center">TheCloud AWS runtime</h1>
|
||||
|
||||
<p align="center">
|
||||
<strong>Any Cloud. Locally.</strong><br />
|
||||
Light, fluffy, and always free<br />
|
||||
The local AWS emulator behind TheCloud.<br />
|
||||
No account. No auth token. No feature gates. Just <code>docker compose up</code>.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/floci-io/floci/releases/latest"><img src="https://img.shields.io/github/v/release/floci-io/floci?label=latest%20release&color=blue" alt="Latest Release"></a>
|
||||
<a href="https://github.com/floci-io/floci/actions/workflows/release.yml"><img src="https://img.shields.io/github/actions/workflow/status/floci-io/floci/release.yml?label=build" alt="Build Status"></a>
|
||||
<a href="https://hub.docker.com/r/floci/floci"><img src="https://img.shields.io/docker/pulls/floci/floci?label=docker%20pulls" alt="Docker Pulls"></a>
|
||||
<a href="https://hub.docker.com/r/floci/floci"><img src="https://img.shields.io/docker/image-size/floci/floci/latest?label=image%20size" alt="Docker Image Size"></a>
|
||||
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/license-MIT-green" alt="License: MIT"></a>
|
||||
<a href="https://github.com/floci-io/floci/stargazers"><img src="https://img.shields.io/github/stars/floci-io/floci?style=flat" alt="GitHub Stars"></a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -24,41 +20,43 @@
|
||||
<a href="#supported-services">Services</a> ·
|
||||
<a href="#sdk-integration">SDKs</a> ·
|
||||
<a href="#testcontainers">Testcontainers</a> ·
|
||||
<a href="#migrating-from-localstack">Migration</a> ·
|
||||
<a href="https://floci.io/floci/">Docs</a>
|
||||
<a href="#migrating-from-localstack">Migration</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## What is Floci?
|
||||
## What is this?
|
||||
|
||||
Floci is a free, open-source local AWS emulator for development, testing, and CI.
|
||||
TheCloud's AWS runtime is a local AWS emulator for development, testing, and CI. It is the runtime behind [TheCloud](https://gitea.zacksolutions.dev/Zakaria/floci-ui), a self-hosted cloud console.
|
||||
|
||||
It gives you AWS-shaped services on your machine without requiring a cloud account, an auth token, or paid feature gates. Point your AWS SDK, CLI, Terraform, CDK, OpenTofu, or test suite at `http://localhost:4566` and keep your existing workflows.
|
||||
It gives you AWS-shaped services on your machine without a cloud account, an auth token, or paid feature gates. Point your AWS SDK, CLI, Terraform, CDK, OpenTofu, or test suite at `http://localhost:4566` and keep your existing workflows.
|
||||
|
||||
Already using LocalStack? Floci is a drop-in replacement: swap the image and keep going. See [Migrating from LocalStack](#migrating-from-localstack).
|
||||
It is a fork of the open-source [Floci](https://github.com/floci-io/floci) emulator. Upstream fixes are brought in by cherry-picking from Floci's `main`, alongside TheCloud's own changes, for example:
|
||||
|
||||
Floci is the AWS member of the [Floci](https://github.com/floci-io) emulator family, named after [floccus](https://en.wikipedia.org/wiki/Cirrocumulus_floccus), the cloud formation that looks like popcorn.
|
||||
- Cognito hosted login with identity-provider buttons, and `PreventUserExistenceErrors` honoured on app clients.
|
||||
- CloudFront distributions served at `<id>.cloudfront.localhost`.
|
||||
- SES delivering real email through an SMTP relay that signs in with a password (Gmail app passwords work).
|
||||
- HTTP API JWT authorizers that verify tokens from this runtime's own Cognito pools.
|
||||
|
||||
| Emulator | Cloud | Port |
|
||||
|---|---|:---:|
|
||||
| **[floci](https://github.com/floci-io/floci)** | **AWS** | **4566** |
|
||||
| [floci-az](https://github.com/floci-io/floci-az) | Azure | 4577 |
|
||||
| [floci-gcp](https://github.com/floci-io/floci-gcp) | GCP | 4588 |
|
||||
| [floci-oci](https://github.com/floci-io/floci-oci) | OCI | 4599 |
|
||||
Companion runtimes for other clouds come from upstream: [floci-az](https://github.com/floci-io/floci-az) for Azure on port 4577 and [floci-gcp](https://github.com/floci-io/floci-gcp) for GCP on port 4588.
|
||||
|
||||
## Quick Start
|
||||
|
||||
The fastest way to run Floci is with the official [CLI](https://github.com/floci-io/floci-cli)
|
||||
Build and start the runtime from this repository:
|
||||
|
||||
```bash
|
||||
floci start
|
||||
git clone https://gitea.zacksolutions.dev/Zakaria/FlociClone.git
|
||||
cd FlociClone
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
Export the AWS environment variables:
|
||||
|
||||
```bash
|
||||
eval $(floci env)
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
export AWS_DEFAULT_REGION=us-east-1
|
||||
export AWS_ACCESS_KEY_ID=test
|
||||
export AWS_SECRET_ACCESS_KEY=test
|
||||
```
|
||||
|
||||
Use your existing AWS tools normally:
|
||||
@@ -75,121 +73,41 @@ aws dynamodb create-table \
|
||||
aws dynamodb list-tables
|
||||
```
|
||||
|
||||
### Watch it run
|
||||
|
||||
This short demo shows the CLI flow: start Floci, export the local AWS environment, run standard AWS CLI commands, and stop the emulator.
|
||||
|
||||
https://github.com/user-attachments/assets/b55714dc-ef36-40ae-a734-cd2cadc288a8
|
||||
|
||||
All AWS services are available at `http://localhost:4566`. Any region works. Credentials can be any non-empty values unless you explicitly enable stricter service-specific auth checks.
|
||||
|
||||
<details>
|
||||
<summary>Prefer Docker Compose?</summary>
|
||||
<summary>Prefer <code>docker run</code>, or dev mode?</summary>
|
||||
|
||||
Create a `compose.yaml` file:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
ports:
|
||||
- "4566:4566"
|
||||
```
|
||||
|
||||
Start Floci:
|
||||
Build the image, then run it with the Docker socket so container-backed services work:
|
||||
|
||||
```bash
|
||||
docker compose up
|
||||
docker build -f docker/Dockerfile -t floci-floci:latest .
|
||||
docker run -d --name floci -p 4566:4566 \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
floci-floci:latest
|
||||
```
|
||||
|
||||
Then configure your AWS environment manually:
|
||||
Or run it in Quarkus dev mode, which needs JDK 25:
|
||||
|
||||
```bash
|
||||
export AWS_ENDPOINT_URL=http://localhost:4566
|
||||
export AWS_DEFAULT_REGION=us-east-1
|
||||
export AWS_ACCESS_KEY_ID=test
|
||||
export AWS_SECRET_ACCESS_KEY=test
|
||||
./mvnw quarkus:dev
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using the old <code>hectorvent/floci</code> image?</summary>
|
||||
|
||||
Update your image name:
|
||||
|
||||
```yaml
|
||||
# Before
|
||||
image: hectorvent/floci:latest
|
||||
|
||||
# After
|
||||
image: floci/floci:latest
|
||||
```
|
||||
|
||||
The old `hectorvent/floci` repository no longer receives updates.
|
||||
|
||||
</details>
|
||||
|
||||
## Web Console
|
||||
|
||||
Floci ships a browser console for inspecting the resources in your local emulator.
|
||||
[TheCloud](https://gitea.zacksolutions.dev/Zakaria/floci-ui) is the console for this runtime. It runs as its own app on port 4500, talks to the runtime at `FLOCI_ENDPOINT`, and covers the services listed in its README.
|
||||
|
||||
**Open it at:** `http://localhost:4566/_floci/ui`
|
||||
|
||||
Nothing runs at boot. The first request pulls the console image, starts it as a sidecar container on Floci's Docker network, hands it Floci's own reachable address plus the standard AWS environment, polls its health endpoint, and redirects the browser once it reports it can reach Floci. The sidecar's port is bound by Docker, so it needs no `ports:` entry of your own, and its logs are streamed into CloudWatch Logs under `/floci/ui`.
|
||||
|
||||
Starting a container needs the Docker socket:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
ports:
|
||||
- "4566:4566"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
The runtime can also start a console for you as a sidecar container on first visit to `http://localhost:4566/_floci/ui`. That needs the Docker socket, and the image is set with `FLOCI_SERVICES_UI_IMAGE`; point it at your TheCloud build to use it.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_UI_ENABLED` | `true` | Enable the console sidecar |
|
||||
| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
|
||||
| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run, for example `floci/floci-ui:local` for a local TheCloud build |
|
||||
| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
|
||||
| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
|
||||
| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
|
||||
|
||||
### Running a different console
|
||||
|
||||
The console is not fixed to the one Floci ships. Any console implementing the [Floci console contract](https://floci.io/floci/ui/console-contract/) runs with nothing but an image name: listen on the port in `PORT`, serve `GET /api/health`, talk to Floci at `AWS_ENDPOINT_URL`.
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
FLOCI_SERVICES_UI_IMAGE: acme/my-console:1.0
|
||||
```
|
||||
|
||||
A console that differs from the contract's defaults says so in its own `io.floci.console.*` image labels, so its operators do not have to. [StackPort](https://github.com/DaviReisVieira/stackport), for example, listens on 8080 rather than 4500; on an image that predates the labels, say it by hand:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
FLOCI_SERVICES_UI_IMAGE: davireis/stackport:latest
|
||||
FLOCI_SERVICES_UI_CONTAINER_NAME: floci-stackport
|
||||
FLOCI_SERVICES_UI_PORT: "8080"
|
||||
FLOCI_SERVICES_UI_INTERNAL_PORT: "8080"
|
||||
```
|
||||
|
||||
[Floci Dash](https://github.com/ofsazib/floci-dash) is another. It honours `PORT`, so only the two things it does differ on need naming:
|
||||
|
||||
```yaml
|
||||
environment:
|
||||
FLOCI_SERVICES_UI_IMAGE: ghcr.io/ofsazib/floci-dash:latest
|
||||
FLOCI_SERVICES_UI_CONTAINER_NAME: floci-dash
|
||||
FLOCI_SERVICES_UI_ENDPOINT_ENV: FLOCI_URL
|
||||
FLOCI_SERVICES_UI_STATUS_PATH: /api/healthz
|
||||
```
|
||||
|
||||
The endpoint itself is never configured by hand: Floci resolves its own reachable address at start time and injects it as `AWS_ENDPOINT_URL`.
|
||||
|
||||
Full reference: [Web Console](https://floci.io/floci/ui/) and [Console Contract v1](https://floci.io/floci/ui/console-contract/).
|
||||
| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when the runtime stops |
|
||||
|
||||
## Features
|
||||
|
||||
@@ -212,14 +130,7 @@ Lambda, RDS, Neptune, ElastiCache, MSK, MSK Connect, ECS, EC2, EKS, OpenSearch,
|
||||
|
||||
Point standard AWS clients at `http://localhost:4566`. Existing credentials, regions, SDKs, CLI commands, and IaC workflows stay familiar.
|
||||
|
||||
Terraform can provision AWS-shaped resources locally through Floci using the standard HashiCorp AWS provider. See the [Terraform with Floci guide](docs/getting-started/terraform.md) for provider configuration, resource examples, and optional emulated S3 state.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Fast enough for CI</strong></summary>
|
||||
|
||||
The native image starts in milliseconds and keeps idle memory low, making it practical for local development and test pipelines.
|
||||
Terraform can provision AWS-shaped resources locally through this runtime using the standard HashiCorp AWS provider. See the [Terraform guide](docs/getting-started/terraform.md) for provider configuration, resource examples, and optional emulated S3 state.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -230,36 +141,13 @@ Choose from in-memory, persistent, hybrid, and write-ahead log storage depending
|
||||
|
||||
</details>
|
||||
|
||||
## Why Floci?
|
||||
|
||||
LocalStack's community edition [sunset in March 2026](https://blog.localstack.cloud/the-road-ahead-for-localstack/), requiring auth tokens and freezing security updates. Floci is the no-strings-attached alternative.
|
||||
|
||||
| Capability | Floci | LocalStack Community |
|
||||
|---|:---:|:---:|
|
||||
| Auth token required | No | Yes |
|
||||
| Security updates | Yes | Frozen |
|
||||
| Startup time | ~24 ms | ~3.3 s |
|
||||
| Idle memory | ~13 MiB | ~143 MiB |
|
||||
| Docker image size | ~90 MB | ~1.0 GB |
|
||||
| License | MIT | Restricted |
|
||||
| API Gateway v2 / HTTP API | Yes | No |
|
||||
| Cognito | Yes | No |
|
||||
| RDS, ElastiCache, MSK, MSK Connect | Real Docker | No |
|
||||
| Neptune (graph DB + Gremlin WebSocket) | Real Docker | No |
|
||||
| DocumentDB (MongoDB-compatible) | Real Docker | No |
|
||||
| ECS, EC2, EKS | Real Docker | No |
|
||||
| CodeBuild | Real Docker execution | No |
|
||||
| Native binary | ~40 MB | No |
|
||||
|
||||
**Broad AWS coverage. Free forever.** See the [Services Overview](https://floci.io/floci/services/) for the full list of emulated services.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Client["AWS SDK / CLI"]
|
||||
|
||||
subgraph Floci ["Floci, port 4566"]
|
||||
subgraph Runtime ["TheCloud AWS runtime, port 4566"]
|
||||
Router["HTTP Router\nJAX-RS / Vert.x"]
|
||||
|
||||
subgraph Stateless ["Stateless Services"]
|
||||
@@ -288,7 +176,7 @@ flowchart LR
|
||||
|
||||
## Supported Services
|
||||
|
||||
Floci supports local emulation for application services, data services, eventing, identity, infrastructure, billing, and container-backed workloads.
|
||||
The runtime emulates application services, data services, eventing, identity, infrastructure, billing, and container-backed workloads.
|
||||
|
||||
| Category | Services |
|
||||
|---|---|
|
||||
@@ -303,7 +191,7 @@ Floci supports local emulation for application services, data services, eventing
|
||||
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Pricing Calculator, BCM Data Exports |
|
||||
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
|
||||
|
||||
For operation-level compatibility, see the [Services Overview](https://floci.io/floci/services/).
|
||||
For operation-level detail, see upstream Floci's [Services Overview](https://floci.io/floci/services/); it can list upstream work this fork has not picked up yet.
|
||||
|
||||
<details>
|
||||
<summary>Detailed service notes</summary>
|
||||
@@ -378,7 +266,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points |
|
||||
| AWS FIS | In-process | All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services |
|
||||
| AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging |
|
||||
| Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to |
|
||||
| Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable accounts in the runtime and member accounts can read the organization they belong to |
|
||||
| CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records |
|
||||
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging |
|
||||
| WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) |
|
||||
@@ -389,7 +277,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| Textract | In-process stub | API-compatible stubs, dummy block data, async job simulation |
|
||||
| Transcribe | In-process stub | Transcription jobs and custom vocabularies; jobs complete immediately, no real audio processing |
|
||||
| Pricing | In-process with static snapshot | Product discovery, attributes, price list files, pagination |
|
||||
| Cost Explorer | In-process | Cost synthesized from Floci resource state and pricing snapshots |
|
||||
| Cost Explorer | In-process | Cost synthesized from the runtime's resource state and pricing snapshots |
|
||||
| Cost and Usage Reports | In-process with floci-duck sidecar | CUR 2.0 and FOCUS 1.2 columns, account-scoped storage, Parquet emission |
|
||||
| BCM Pricing Calculator | In-process | Workload estimate create, usage pricing, read, and delete lifecycle |
|
||||
| BCM Data Exports | In-process | Export lifecycle, executions, update and delete operations |
|
||||
@@ -398,7 +286,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
|
||||
## Real Docker Integration
|
||||
|
||||
Floci uses real Docker containers when in-process emulation would reduce fidelity. This applies to stateful databases, connection-heavy protocols, runtimes, and build systems.
|
||||
The runtime uses real Docker containers when in-process emulation would reduce fidelity. This applies to stateful databases, connection-heavy protocols, runtimes, and build systems.
|
||||
|
||||
| Service | Default image | What is real |
|
||||
|---|---|---|
|
||||
@@ -416,12 +304,12 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit
|
||||
| EC2 | AMI-mapped Linux images | Linux containers, SSH key injection, UserData, IMDS, IAM credentials |
|
||||
| ECS | User-specified task image | Container lifecycle, start, stop, health checks |
|
||||
| EKS | `rancher/k3s:latest` | Kubernetes API server via k3s |
|
||||
| MWAA | `apache/airflow:<version>-python3.12` + `postgres:16-alpine` | Real Apache Airflow (LocalExecutor: scheduler + webserver) with its own Postgres metadata DB; webserver/CLI reachable via Floci's proxy |
|
||||
| MWAA | `apache/airflow:<version>-python3.12` + `postgres:16-alpine` | Real Apache Airflow (LocalExecutor: scheduler + webserver) with its own Postgres metadata DB; webserver/CLI reachable via the runtime's proxy |
|
||||
| CodeBuild | User-specified environment image | Buildspec execution, log streaming, S3 artifact upload |
|
||||
| OpenSearch | `opensearchproject/opensearch:2` | Full OpenSearch engine with REST API |
|
||||
| ECR | `registry:2` | OCI-compatible registry for docker push and docker pull |
|
||||
| Verified Permissions | `floci/floci-sidecar-cedar:1.1.0` | Cedar 4 policy parsing, schema validation and authorization decisions, via a [Floci sidecar](https://github.com/floci-io/floci-sidecars) |
|
||||
| AppSync | `floci/floci-sidecar-graphql:0.2.0` | graphql-java schema validation, query planning and execution, via a [Floci sidecar](https://github.com/floci-io/floci-sidecars) |
|
||||
| Verified Permissions | `floci/floci-sidecar-cedar:1.1.0` | Cedar 4 policy parsing, schema validation and authorization decisions, via an upstream [Floci sidecar](https://github.com/floci-io/floci-sidecars) |
|
||||
| AppSync | `floci/floci-sidecar-graphql:0.2.0` | graphql-java schema validation, query planning and execution, via an upstream [Floci sidecar](https://github.com/floci-io/floci-sidecars) |
|
||||
|
||||
Docker-backed services require the Docker socket:
|
||||
|
||||
@@ -430,7 +318,7 @@ docker run -d --name floci \
|
||||
-p 4566:4566 \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-u root \
|
||||
floci/floci:latest
|
||||
floci-floci:latest
|
||||
```
|
||||
|
||||
### Overriding default images
|
||||
@@ -454,7 +342,7 @@ docker run -d --name floci \
|
||||
|
||||
## Persistence and Storage Modes
|
||||
|
||||
Floci can trade speed for durability depending on the workflow. Configure the default mode with `FLOCI_STORAGE_MODE`, or override storage per service.
|
||||
The runtime can trade speed for durability depending on the workflow. Configure the default mode with `FLOCI_STORAGE_MODE`, or override storage per service.
|
||||
|
||||
| Mode | Behavior | Best for | Durability |
|
||||
|---|---|---|:---:|
|
||||
@@ -465,22 +353,22 @@ Floci can trade speed for durability depending on the workflow. Configure the de
|
||||
|
||||
Use `memory` for fast test runs. Use `hybrid` when you want state preserved across container restarts without much overhead.
|
||||
|
||||
For more detail, see the [Storage Configuration documentation](https://floci.io/floci/configuration/storage/).
|
||||
For more detail, see upstream Floci's [Storage Configuration documentation](https://floci.io/floci/configuration/storage/).
|
||||
|
||||
## Multi-Account Isolation
|
||||
|
||||
Floci supports per-account resource isolation with no extra setup. If `AWS_ACCESS_KEY_ID` is exactly 12 digits, Floci uses it as the account ID. Resources created by one account are invisible to another.
|
||||
The runtime supports per-account resource isolation with no extra setup. If `AWS_ACCESS_KEY_ID` is exactly 12 digits, it is used as the account ID. Resources created by one account are invisible to another.
|
||||
|
||||
```bash
|
||||
AWS_ACCESS_KEY_ID=111111111111 aws sqs create-queue --queue-name orders
|
||||
AWS_ACCESS_KEY_ID=222222222222 aws sqs create-queue --queue-name orders
|
||||
```
|
||||
|
||||
Any other key format, such as `test` or `AKIA...`, causes Floci to fall back to `FLOCI_DEFAULT_ACCOUNT_ID`, which defaults to `000000000000`.
|
||||
Any other key format, such as `test` or `AKIA...`, falls back to `FLOCI_DEFAULT_ACCOUNT_ID`, which defaults to `000000000000`.
|
||||
|
||||
STS temporary credentials are routed too: credentials from `AssumeRole` resolve to the assumed role's account, so the cross-account assume-role-then-provision pattern works locally. Resolution precedence is 12-digit AKID → temporary-session lookup → `FLOCI_DEFAULT_ACCOUNT_ID`.
|
||||
|
||||
See the [Multi-Account Isolation docs](https://floci.io/floci/configuration/multi-account/).
|
||||
See upstream Floci's [Multi-Account Isolation docs](https://floci.io/floci/configuration/multi-account/).
|
||||
|
||||
## SDK Integration
|
||||
|
||||
@@ -526,7 +414,7 @@ client = boto3.client(
|
||||
|
||||
client.put_parameter(
|
||||
Name="/demo/app/message",
|
||||
Value="hello from floci",
|
||||
Value="hello from TheCloud",
|
||||
Type="String",
|
||||
Overwrite=True,
|
||||
)
|
||||
@@ -552,7 +440,7 @@ const client = new SQSClient({
|
||||
await client.send(
|
||||
new SendMessageCommand({
|
||||
QueueUrl: "http://localhost:4566/000000000000/demo-queue",
|
||||
MessageBody: "hello from floci",
|
||||
MessageBody: "hello from TheCloud",
|
||||
}),
|
||||
);
|
||||
```
|
||||
@@ -613,7 +501,7 @@ use aws_sdk_secretsmanager::Client;
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
|
||||
.region(Region::new("us-east-1"))
|
||||
.credentials_provider(Credentials::new("test", "test", None, None, "floci"))
|
||||
.credentials_provider(Credentials::new("test", "test", None, None, "thecloud"))
|
||||
.endpoint_url("http://localhost:4566")
|
||||
.load()
|
||||
.await;
|
||||
@@ -623,7 +511,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
client
|
||||
.create_secret()
|
||||
.name("demo/secret")
|
||||
.secret_string("hello from floci")
|
||||
.secret_string("hello from TheCloud")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -649,7 +537,7 @@ aws --endpoint-url http://localhost:4566 s3 ls
|
||||
|
||||
## Testcontainers
|
||||
|
||||
Floci has Testcontainers modules for starting isolated Floci instances directly from tests. This avoids shared state, manual daemon setup, and port conflicts.
|
||||
Upstream Floci publishes Testcontainers modules for starting isolated instances directly from tests. This avoids shared state, manual daemon setup, and port conflicts. They start upstream's `floci/floci` image by default, so they test against upstream Floci rather than this fork unless you give them your own image.
|
||||
|
||||
For Testcontainers 1.x, use the versions as indicated in the table below.
|
||||
|
||||
@@ -767,7 +655,7 @@ def test_s3_create_bucket():
|
||||
|
||||
## Compatibility Testing
|
||||
|
||||
The [`compatibility-tests`](./compatibility-tests/) directory validates Floci across SDKs and tooling workflows.
|
||||
The [`compatibility-tests`](./compatibility-tests/) directory validates the runtime across SDKs and tooling workflows.
|
||||
|
||||
| Module | Language / Tool | SDK / Client | Tests |
|
||||
|---|---|---|---:|
|
||||
@@ -784,22 +672,19 @@ The [`compatibility-tests`](./compatibility-tests/) directory validates Floci ac
|
||||
|
||||
## Migrating from LocalStack
|
||||
|
||||
Floci is a drop-in replacement for LocalStack Community. The port, credentials, SDK configuration, and CLI endpoint pattern work the same way. Swap the image and keep going.
|
||||
The runtime is a drop-in replacement for LocalStack Community. The port, credentials, SDK configuration, and CLI endpoint pattern work the same way. Swap the image and keep going.
|
||||
|
||||
```yaml
|
||||
# Before
|
||||
image: localstack/localstack
|
||||
|
||||
# After, standard image
|
||||
image: floci/floci:latest
|
||||
|
||||
# After, if init scripts need AWS CLI or boto3
|
||||
image: floci/floci:latest-compat
|
||||
# After, your local build of this repository
|
||||
image: floci-floci:latest
|
||||
```
|
||||
|
||||
LocalStack environment variables are translated automatically:
|
||||
|
||||
| LocalStack | Floci equivalent |
|
||||
| LocalStack | Equivalent |
|
||||
|---|---|
|
||||
| `LOCALSTACK_HOST` | `FLOCI_HOSTNAME` |
|
||||
| `PERSISTENCE=1` | `FLOCI_STORAGE_MODE=persistent` |
|
||||
@@ -809,43 +694,23 @@ LocalStack environment variables are translated automatically:
|
||||
|
||||
Init scripts mounted under `/etc/localstack/init/` run unchanged. The `/_localstack/init` and `/_localstack/health` endpoints are still served. Once the emulator is up, the log also ends with a LocalStack-style `Ready.` line, so tooling that watches the log for it, such as the default wait strategy of Testcontainers' `LocalStackContainer`, works unchanged. Set `LOCALSTACK_PARITY=false` to opt out of automatic translation.
|
||||
|
||||
See the [full migration guide](https://floci.io/floci/getting-started/migrate-from-localstack/).
|
||||
See upstream Floci's [full migration guide](https://floci.io/floci/getting-started/migrate-from-localstack/).
|
||||
|
||||
## Image Tags
|
||||
## Building and Updating
|
||||
|
||||
Every tag combines a variant and a channel.
|
||||
The image is built from this repository; nothing is published to Docker Hub:
|
||||
|
||||
| Channel | Standard | Baseline (ARM64 only) | Compat with AWS CLI and boto3 |
|
||||
|---|---|---|---|
|
||||
| Release, floating | `latest` | `latest-baseline` | `latest-compat` |
|
||||
| Release, pinned | `x.y.z` | `x.y.z-baseline` | `x.y.z-compat` |
|
||||
| Nightly, floating | `nightly` | — | `nightly-compat` |
|
||||
| Nightly, dated | `nightly-mmddyyyy` | — | `nightly-mmddyyyy-compat` |
|
||||
|
||||
Use `latest` for stable releases, a pinned version for reproducible builds, and `nightly` to track `main`.
|
||||
|
||||
```yaml
|
||||
# Recommended
|
||||
image: floci/floci:latest
|
||||
|
||||
# Includes AWS CLI and boto3
|
||||
image: floci/floci:latest-compat
|
||||
|
||||
# ARM64 baseline for Raspberry Pi 4 / pre-LSE cores
|
||||
image: floci/floci:latest-baseline
|
||||
|
||||
# Pinned release
|
||||
image: floci/floci:x.y.z
|
||||
|
||||
# Track main
|
||||
image: floci/floci:nightly
|
||||
```bash
|
||||
docker build -f docker/Dockerfile -t floci-floci:latest .
|
||||
```
|
||||
|
||||
### Release train
|
||||
Tests run with Maven and JDK 25:
|
||||
|
||||
Stable releases ship on the **1st and 3rd Tuesday of each month**. Between trains, `floci/floci:nightly` tracks `main`. Every merged fix is available the next day, and dated `nightly-mmddyyyy` tags let you pin a specific night's build.
|
||||
```bash
|
||||
./mvnw test
|
||||
```
|
||||
|
||||
Versions are derived from Conventional Commits by [semantic-release](https://github.com/semantic-release/semantic-release); `CHANGELOG.md` is generated, never hand-edited. Releases are cut from `main` only: there are no maintenance branches.
|
||||
Upstream fixes come in by cherry-picking commits from Floci's `main` onto a branch, which then goes through review like any other change.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -853,26 +718,26 @@ All settings are overridable through environment variables with the `FLOCI_` pre
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_PORT` | `4566` | Port exposed by the Floci API |
|
||||
| `FLOCI_PORT` | `4566` | Port the runtime's API listens on |
|
||||
| `FLOCI_DEFAULT_REGION` | `us-east-1` | Default AWS region |
|
||||
| `FLOCI_DEFAULT_ACCOUNT_ID` | `000000000000` | Default AWS account ID |
|
||||
| `FLOCI_BASE_URL` | `http://localhost:4566` | Base URL used when Floci returns service URLs |
|
||||
| `FLOCI_HOSTNAME` | Unset | Hostname used in returned URLs when Floci runs inside Docker Compose |
|
||||
| `FLOCI_BASE_URL` | `http://localhost:4566` | Base URL used in service URLs the runtime returns |
|
||||
| `FLOCI_HOSTNAME` | Unset | Hostname used in returned URLs when the runtime runs inside Docker Compose |
|
||||
| `FLOCI_STORAGE_MODE` | `memory` | Storage mode: `memory`, `persistent`, `hybrid`, or `wal` |
|
||||
| `FLOCI_STORAGE_PERSISTENT_PATH` | `./data` | Directory used for persisted state |
|
||||
| `FLOCI_SERVICES_LAMBDA_ECR_BASE_URI` | `public.ecr.aws` | ECR base URI used when pulling Lambda runtime images (legacy name `FLOCI_ECR_BASE_URI` still works) |
|
||||
| `FLOCI_SERVICES_S3_ENFORCE_AUTH` | `false` | Enforce S3 public/private read access and reject unknown signed S3 access keys |
|
||||
|
||||
Full reference: [configuration docs](https://floci.io/floci/configuration/advanced/application-yml)
|
||||
Full reference: [`src/main/resources/application.yml`](src/main/resources/application.yml), and upstream Floci's [configuration docs](https://floci.io/floci/configuration/advanced/application-yml).
|
||||
|
||||
### Multi-container Docker Compose
|
||||
|
||||
When your application runs in a different container, set `FLOCI_HOSTNAME` to the Floci service name so returned URLs, such as SQS `QueueUrl` values, resolve correctly.
|
||||
When your application runs in a different container, set `FLOCI_HOSTNAME` to the runtime's service name so returned URLs, such as SQS `QueueUrl` values, resolve correctly.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
floci:
|
||||
image: floci/floci:latest
|
||||
image: floci-floci:latest
|
||||
ports:
|
||||
- "4566:4566"
|
||||
environment:
|
||||
@@ -887,59 +752,6 @@ services:
|
||||
|
||||
Without this, services may return URLs using `localhost`, which points to the wrong container from the application container.
|
||||
|
||||
## Community
|
||||
|
||||
Join the Floci community on [Slack](https://join.slack.com/t/floci/shared_invite/zt-3tjn02s3q-A00kEjJ1cZxsg_imTfy6Cw) or [GitHub Discussions](https://github.com/orgs/floci-io/discussions). Feature ideas, compatibility questions, design tradeoffs, and rough proposals are welcome.
|
||||
|
||||
## Sponsors
|
||||
|
||||
Floci is independent open source, funded by the people and companies who use it.
|
||||
Sponsorship buys gratitude and nothing else: every emulated service is free for
|
||||
everyone, forever, and no sponsor gets features, priority, or roadmap influence
|
||||
that the rest of the Flock does not.
|
||||
|
||||
### 🥇 Gold
|
||||
|
||||
Large logo with top placement in the emulator READMEs and on floci.io, plus a
|
||||
mention in release notes.
|
||||
|
||||
[IceGuard](https://github.com/iceguard) · [Softmax](https://softmax.com/)
|
||||
|
||||
### 🥈 Silver
|
||||
|
||||
Logo in the emulator READMEs and on floci.io, plus a mention in release notes.
|
||||
|
||||
*Your logo here. [Become a sponsor](https://github.com/sponsors/floci-io).*
|
||||
|
||||
### 🥉 Community
|
||||
|
||||
Name in the emulator READMEs, a sponsor badge on GitHub, and our sincere thanks.
|
||||
|
||||
[AutoScout24](https://www.autoscout24.com) · [Nexxion AI](https://nexxion.ai/)
|
||||
|
||||
Every sponsor, including the Friends of the Flock who support Floci outside these
|
||||
tiers, is listed in [THANKS.md](https://github.com/floci-io/.github/blob/main/THANKS.md).
|
||||
|
||||
**[Sponsor Floci](https://github.com/sponsors/floci-io)**
|
||||
|
||||
## Star History
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.star-history.com/?repos=floci-io%2Ffloci&type=date&legend=top-left">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=floci-io/floci&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=floci-io/floci&type=date&legend=top-left" />
|
||||
<img width="600" alt="Star History Chart" src="https://api.star-history.com/chart?repos=floci-io/floci&type=date&legend=top-left" />
|
||||
</picture>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/floci-io/floci/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=floci-io/floci&max=100&columns=20" />
|
||||
</a>
|
||||
|
||||
## License
|
||||
|
||||
MIT. Use it however you want.
|
||||
MIT. TheCloud's AWS runtime is a fork of [Floci](https://github.com/floci-io/floci); thanks to the Floci contributors and sponsors whose work it builds on.
|
||||
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.ComparisonOperator;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.Metric;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.MetricAlarm;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.MetricDataQuery;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.MetricStat;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;
|
||||
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("CloudWatch - Metric-math alarm definitions")
|
||||
class CloudWatchMetricMathAlarmTest {
|
||||
|
||||
private CloudWatchClient cloudWatch;
|
||||
private String alarmName;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
cloudWatch = TestFixtures.cloudWatchClient();
|
||||
alarmName = TestFixtures.uniqueName("sdk-metric-math-alarm");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
try {
|
||||
cloudWatch.deleteAlarms(request -> request.alarmNames(alarmName));
|
||||
} finally {
|
||||
cloudWatch.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void metricsRoundTripWithoutInventingSingleMetricFields() {
|
||||
List<MetricDataQuery> metrics = metrics();
|
||||
putMathAlarm(metrics);
|
||||
assertMathAlarm(metrics);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesReplaceQueriesAndSwitchBackToASingleMetric() {
|
||||
putSingleMetricAlarm(300);
|
||||
List<MetricDataQuery> original = metrics();
|
||||
putMathAlarm(original);
|
||||
assertMathAlarm(original);
|
||||
|
||||
List<MetricDataQuery> replacement = List.of(
|
||||
original.get(0).toBuilder().expression("errors / requests").label("Ratio").build(),
|
||||
original.get(1), original.get(2));
|
||||
putMathAlarm(replacement);
|
||||
assertMathAlarm(replacement);
|
||||
|
||||
putSingleMetricAlarm(120);
|
||||
MetricAlarm alarm = describe();
|
||||
assertThat(alarm.hasMetrics()).isFalse();
|
||||
assertThat(alarm.period()).isEqualTo(120);
|
||||
assertThat(alarm.metricName()).isEqualTo("5xx");
|
||||
assertThat(alarm.namespace()).isEqualTo("AWS/ApiGateway");
|
||||
}
|
||||
|
||||
private void putMathAlarm(List<MetricDataQuery> metrics) {
|
||||
cloudWatch.putMetricAlarm(request -> request.alarmName(alarmName)
|
||||
.comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)
|
||||
.evaluationPeriods(2).threshold(5.0).metrics(metrics));
|
||||
}
|
||||
|
||||
private void putSingleMetricAlarm(int period) {
|
||||
cloudWatch.putMetricAlarm(request -> request.alarmName(alarmName)
|
||||
.comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)
|
||||
.evaluationPeriods(2).threshold(5.0).namespace("AWS/ApiGateway")
|
||||
.metricName("5xx").statistic(Statistic.SUM).period(period));
|
||||
}
|
||||
|
||||
private MetricAlarm describe() {
|
||||
List<MetricAlarm> alarms = cloudWatch.describeAlarms(request -> request.alarmNames(alarmName)).metricAlarms();
|
||||
assertThat(alarms).hasSize(1);
|
||||
return alarms.get(0);
|
||||
}
|
||||
|
||||
private void assertMathAlarm(List<MetricDataQuery> metrics) {
|
||||
MetricAlarm alarm = describe();
|
||||
assertThat(alarm.metrics()).containsExactlyElementsOf(metrics);
|
||||
assertThat(alarm.period()).isNull();
|
||||
assertThat(alarm.metricName()).isNull();
|
||||
assertThat(alarm.namespace()).isNull();
|
||||
assertThat(alarm.statistic()).isNull();
|
||||
assertThat(alarm.extendedStatistic()).isNull();
|
||||
assertThat(alarm.unit()).isNull();
|
||||
assertThat(alarm.hasDimensions()).isFalse();
|
||||
assertThat(alarm.evaluationPeriods()).isEqualTo(2);
|
||||
assertThat(alarm.threshold()).isEqualTo(5.0);
|
||||
}
|
||||
|
||||
private static List<MetricDataQuery> metrics() {
|
||||
return List.of(
|
||||
MetricDataQuery.builder().id("rate").expression("100 * errors / requests")
|
||||
.returnData(true).period(300).label("Error <rate> & requests").build(),
|
||||
MetricDataQuery.builder().id("errors").returnData(false).accountId("123456789012")
|
||||
.metricStat(MetricStat.builder().period(300).stat("Sum").unit(StandardUnit.COUNT)
|
||||
.metric(Metric.builder().namespace("AWS/ApiGateway").metricName("5xx")
|
||||
.dimensions(Dimension.builder().name("ApiName").value("api<&>").build())
|
||||
.build()).build()).build(),
|
||||
MetricDataQuery.builder().id("requests").returnData(false)
|
||||
.metricStat(MetricStat.builder().period(300).stat("Sum")
|
||||
.metric(Metric.builder().namespace("AWS/ApiGateway").metricName("Count").build())
|
||||
.build()).build());
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import software.amazon.awssdk.services.cloudwatch.model.*;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@@ -185,4 +186,67 @@ class CloudWatchTest {
|
||||
);
|
||||
assertThat(noMatch.datapoints()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PutMetricData stores datums nested under EntityMetricData")
|
||||
void testPutMetricDataWithEntityMetricData() {
|
||||
String namespace = "JavaTestEntityMetricData";
|
||||
Instant now = Instant.now();
|
||||
|
||||
cloudWatchClient.putMetricData(request -> request
|
||||
.namespace(namespace)
|
||||
.metricData(datum -> datum
|
||||
.metricName("TopLevel")
|
||||
.value(1.0)
|
||||
.timestamp(now))
|
||||
.entityMetricData(entityMetricData -> entityMetricData
|
||||
.entity(entity -> entity
|
||||
.keyAttributes(Map.of(
|
||||
"Type", "AWS::Resource",
|
||||
"ResourceType", "AWS::EC2::Instance",
|
||||
"Identifier", "i-0123456789abcdef0")))
|
||||
.metricData(MetricDatum.builder()
|
||||
.metricName("mem_used_percent")
|
||||
.value(6.5)
|
||||
.unit(StandardUnit.PERCENT)
|
||||
.storageResolution(60)
|
||||
.timestamp(now)
|
||||
.dimensions(Dimension.builder().name("host").value("h1").build())
|
||||
.build()))
|
||||
.strictEntityValidation(false)
|
||||
);
|
||||
|
||||
ListMetricsResponse listed = cloudWatchClient.listMetrics(request -> request.namespace(namespace));
|
||||
assertThat(listed.metrics())
|
||||
.extracting(Metric::metricName)
|
||||
.containsExactlyInAnyOrder("TopLevel", "mem_used_percent");
|
||||
|
||||
GetMetricStatisticsResponse stats = cloudWatchClient.getMetricStatistics(request -> request
|
||||
.namespace(namespace)
|
||||
.metricName("mem_used_percent")
|
||||
.dimensions(Dimension.builder().name("host").value("h1").build())
|
||||
.startTime(now.minus(1, ChronoUnit.HOURS))
|
||||
.endTime(now.plus(1, ChronoUnit.MINUTES))
|
||||
.period(3600)
|
||||
.statistics(Statistic.SUM)
|
||||
);
|
||||
assertThat(stats.datapoints()).hasSize(1);
|
||||
assertThat(stats.datapoints().get(0).sum()).isEqualTo(6.5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("PutMetricData without MetricName throws MissingRequiredParameterException")
|
||||
void testPutMetricDataWithoutMetricNameIsRejected() {
|
||||
String namespace = "JavaTestMissingMetricName";
|
||||
|
||||
assertThatThrownBy(() -> cloudWatchClient.putMetricData(request -> request
|
||||
.namespace(namespace)
|
||||
.entityMetricData(entityMetricData -> entityMetricData
|
||||
.metricData(MetricDatum.builder().value(1.0).build()))))
|
||||
.isInstanceOf(MissingRequiredParameterException.class)
|
||||
.satisfies(e -> assertThat(((MissingRequiredParameterException) e).awsErrorDetails().errorCode())
|
||||
.isEqualTo("MissingParameter"));
|
||||
|
||||
assertThat(cloudWatchClient.listMetrics(request -> request.namespace(namespace)).metrics()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,8 @@ class TestCloudWatchAlarms:
|
||||
|
||||
alarm = next(a for a in alarms if a["AlarmName"] == alarm_name)
|
||||
assert alarm["StateValue"] == "INSUFFICIENT_DATA"
|
||||
assert response["CompositeAlarms"] == []
|
||||
assert response["LogAlarms"] == []
|
||||
finally:
|
||||
cloudwatch_client.delete_alarms(AlarmNames=[alarm_name])
|
||||
|
||||
|
||||
@@ -12,6 +12,11 @@ services:
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- ./data:/app/data
|
||||
# Optional SES SMTP relay settings (FLOCI_SERVICES_SES_SMTP_*), kept outside the repo
|
||||
# because they hold a password. Without the file, sent emails stay in the SES mailbox.
|
||||
env_file:
|
||||
- path: ${HOME}/.config/thecloud/ses-smtp.env
|
||||
required: false
|
||||
environment:
|
||||
FLOCI_SERVICES_DOCKER_NETWORK: floci_default
|
||||
FLOCI_SERVICES_RDS_PROXY_BASE_PORT: "7001"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 91 KiB |
@@ -160,7 +160,7 @@ cross-resource references.
|
||||
| Kinesis Data Firehose | `DeliveryStream` |
|
||||
| IoT Core | `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
|
||||
| CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |
|
||||
| CloudWatch | `Alarm`, `Dashboard` |
|
||||
| CloudWatch | `Alarm`, `CompositeAlarm`, `Dashboard`. Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. |
|
||||
| CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` |
|
||||
| WAFv2 | `WebACL` |
|
||||
| Config | `ConfigRule` |
|
||||
|
||||
@@ -311,6 +311,7 @@ aws logs put-retention-policy \
|
||||
| `GetMetricStatistics` | Get metric statistics (Average, Sum, etc.) |
|
||||
| `GetMetricData` | Query metrics with math expressions |
|
||||
| `PutMetricAlarm` | Create a metric alarm |
|
||||
| `PutCompositeAlarm` | Create or update a composite alarm rule |
|
||||
| `DescribeAlarms` | List alarms |
|
||||
| `DeleteAlarms` | Delete alarms |
|
||||
| `SetAlarmState` | Manually set alarm state |
|
||||
@@ -331,6 +332,31 @@ aws logs put-retention-policy \
|
||||
Metric streams are stored as definitions with their `running` or `stopped` state. Floci never
|
||||
delivers metrics to the Firehose delivery stream a metric stream names.
|
||||
|
||||
Composite alarms support boolean rules over alarm states. Request `AlarmTypes` containing
|
||||
`CompositeAlarm` when describing them; the default describes metric alarms. Composite
|
||||
action lists are stored but not executed. Action suppression is not implemented and is
|
||||
rejected with `ValidationError`.
|
||||
|
||||
### SNS alarm actions
|
||||
|
||||
State transitions publish to same-account standard SNS topics in `AlarmActions`, `OKActions`, or
|
||||
`InsufficientDataActions`, including transitions from `SetAlarmState`. Unchanged states and
|
||||
`ActionsEnabled=false` suppress notifications. Scaling action retries remain independent.
|
||||
Failures are logged per target without blocking other targets. Notifications include a
|
||||
single-metric `Trigger`; durable retries, FIFO topics, and metric-math payloads are not covered.
|
||||
|
||||
### Metric-math alarm definitions
|
||||
|
||||
`PutMetricAlarm` stores the `Metrics` query definitions and `DescribeAlarms` returns them over
|
||||
both JSON and Query protocols. Expressions, labels, `ReturnData`, account IDs, query periods,
|
||||
and nested metric statistics (including dimensions and units) survive storage reloads.
|
||||
Metric-math alarm responses omit the single-metric fields, including top-level `Period`.
|
||||
Updating an alarm replaces its metric definition, so changing between `Metrics` and a single
|
||||
metric does not retain the previous definition.
|
||||
|
||||
This is management-plane support: the alarm evaluator currently evaluates only single-metric
|
||||
alarms, not metric-math expressions. `SetAlarmState` remains available for manual transitions.
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1040,6 +1040,18 @@ public interface EmulatorConfig {
|
||||
interface EfsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/**
|
||||
* Serve every mount target over NFSv4.1 at its own address on the VPC's Docker network,
|
||||
* from a privileged helper container running the kernel NFS server, so an EC2 instance
|
||||
* can mount the file system as on AWS. Needs VPC networks ({@code floci.services.ec2.vpc-networks}).
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean nfsServers();
|
||||
|
||||
/** Image of the NFS server; the default is built locally from Floci's own recipe on first use. */
|
||||
@WithDefault("floci/efs-nfs-server:local")
|
||||
String nfsServerImage();
|
||||
}
|
||||
|
||||
interface LightsailServiceConfig {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The message AWS's Smithy validation layer answers when a request breaks its model's constraints:
|
||||
* "1 validation error detected: a" or "N validation errors detected: a; b", each violation reading
|
||||
* "Value at 'path' failed to satisfy constraint: ...". The wording is Smithy's, shared by every
|
||||
* service built on it; only the error code differs by protocol.
|
||||
*/
|
||||
public final class SmithyValidationErrors {
|
||||
|
||||
private SmithyValidationErrors() {}
|
||||
|
||||
/**
|
||||
* The message for one or more violations. An empty list is the caller's bug, so it fails rather
|
||||
* than answering "0 validation errors"; check {@code isEmpty()} before throwing.
|
||||
*/
|
||||
public static String message(List<String> violations) {
|
||||
if (violations.isEmpty()) {
|
||||
throw new IllegalArgumentException("no violations to report");
|
||||
}
|
||||
String count = violations.size() == 1
|
||||
? "1 validation error detected: "
|
||||
: violations.size() + " validation errors detected: ";
|
||||
return count + String.join("; ", violations);
|
||||
}
|
||||
|
||||
/** The violation for a required member the request leaves out. */
|
||||
public static String notNull(String path) {
|
||||
return "Value null at '" + path + "' failed to satisfy constraint: Member must not be null";
|
||||
}
|
||||
|
||||
/** The 400 error carrying {@link #message} under the protocol's validation error code. */
|
||||
public static AwsException exception(String errorCode, List<String> violations) {
|
||||
return new AwsException(errorCode, message(violations), 400);
|
||||
}
|
||||
|
||||
public static AwsException exception(String errorCode, String violation) {
|
||||
return exception(errorCode, List.of(violation));
|
||||
}
|
||||
|
||||
/** The code most JSON services use, on both the awsJson and the restJson protocols. */
|
||||
public static AwsException validationException(List<String> violations) {
|
||||
return exception("ValidationException", violations);
|
||||
}
|
||||
|
||||
public static AwsException validationException(String violation) {
|
||||
return validationException(List.of(violation));
|
||||
}
|
||||
|
||||
/** The awsQuery protocol's code. */
|
||||
public static AwsException validationError(List<String> violations) {
|
||||
return exception("ValidationError", violations);
|
||||
}
|
||||
|
||||
public static AwsException validationError(String violation) {
|
||||
return validationError(List.of(violation));
|
||||
}
|
||||
|
||||
/** The code of REST JSON services that model their validation failure as BadRequestException. */
|
||||
public static AwsException badRequest(List<String> violations) {
|
||||
return exception("BadRequestException", violations);
|
||||
}
|
||||
|
||||
public static AwsException badRequest(String violation) {
|
||||
return badRequest(List.of(violation));
|
||||
}
|
||||
|
||||
/** The violation for a number outside {@code min} to {@code max}, or {@code null} for one inside. */
|
||||
public static String outOfRange(String path, long value, long min, long max) {
|
||||
if (value < min) {
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must have value greater than or equal to " + min;
|
||||
}
|
||||
if (value > max) {
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must have value less than or equal to " + max;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The violation for a value outside its enum, listing the allowed values in the model's order. */
|
||||
public static String notInEnum(String value, String path, List<String> allowed) {
|
||||
return "Value '" + value + "' at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must satisfy enum value set: " + allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The violation for a list holding a value outside its members' enum. The list is checked as a
|
||||
* whole, so the whole list is the offending value and the enum constraint is nested.
|
||||
*/
|
||||
public static String notAllInEnum(List<String> values, String path, List<String> allowed) {
|
||||
return "Value '" + values + "' at '" + path + "' failed to satisfy constraint: "
|
||||
+ "Member must satisfy constraint: [Member must satisfy enum value set: " + allowed + "]";
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,14 @@ public class EmbeddedDnsServer {
|
||||
// localhost.floci.io → localhost.floci.io, *.localhost.floci.io
|
||||
public static final List<String> BUILTIN_SUFFIXES = List.of(DEFAULT_SUFFIX, LOCALSTACK_SUFFIX);
|
||||
|
||||
/** Answers A queries for names a service owns, such as an EFS file system's DNS name. */
|
||||
@FunctionalInterface
|
||||
public interface NameResolver {
|
||||
Optional<String> resolve(String name);
|
||||
}
|
||||
|
||||
private final List<NameResolver> resolvers = new java.util.concurrent.CopyOnWriteArrayList<>();
|
||||
|
||||
private volatile String serverIp;
|
||||
private final SequencedSet<String> suffixes = new LinkedHashSet<>();
|
||||
private volatile List<String> upstreamDnsServers = List.of();
|
||||
@@ -163,11 +171,30 @@ public class EmbeddedDnsServer {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Adds names a service answers for; a name no resolver knows is forwarded upstream as before. */
|
||||
public void addResolver(NameResolver resolver) {
|
||||
resolvers.add(resolver);
|
||||
}
|
||||
|
||||
Optional<String> resolveARecord(String name, String myIp) {
|
||||
if (matchesSuffix(name)) {
|
||||
return Optional.of(myIp);
|
||||
}
|
||||
return resolveEc2PrivateDnsName(name);
|
||||
Optional<String> ec2Name = resolveEc2PrivateDnsName(name);
|
||||
if (ec2Name.isPresent()) {
|
||||
return ec2Name;
|
||||
}
|
||||
for (NameResolver resolver : resolvers) {
|
||||
try {
|
||||
Optional<String> address = resolver.resolve(name);
|
||||
if (address.isPresent()) {
|
||||
return address;
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("DNS resolver failed for {0}: {1}", name, e.getMessage());
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<String> resolveEc2PrivateDnsName(String name) {
|
||||
|
||||
@@ -362,6 +362,20 @@ public class ContainerBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a named volume mount of one directory inside the volume, given relative to its root.
|
||||
* The directory must already exist; Docker refuses to start the container otherwise.
|
||||
*/
|
||||
public Builder withNamedVolumeSubpath(String volumeName, String subpath, String containerPath, boolean readOnly) {
|
||||
this.mounts.add(new Mount()
|
||||
.withType(MountType.VOLUME)
|
||||
.withSource(volumeName)
|
||||
.withTarget(containerPath)
|
||||
.withReadOnly(readOnly)
|
||||
.withVolumeOptions(new SubpathVolumeOptions(subpath)));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inherits every volume declared by another container.
|
||||
*/
|
||||
|
||||
+74
-9
@@ -34,6 +34,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -588,6 +589,77 @@ public class ContainerLifecycleManager {
|
||||
rootPermissions.ifPresent(p -> script.append("chmod ").append(p).append(' ').append(mount).append(" && "));
|
||||
script.append("true");
|
||||
|
||||
Integer status = runVolumeHelper(volumeName, mount, initImage, List.of("sh", "-c", script.toString()));
|
||||
if (status == null || status != 0) {
|
||||
// Throw so the caller leaves the volume unmemoised and retries on the next launch,
|
||||
// rather than leaving it root:root 0755 with no further attempt.
|
||||
throw new IllegalStateException("shared-volume init for " + volumeName
|
||||
+ " exited with status " + status + " (cmd: " + script + ")");
|
||||
}
|
||||
LOG.infov("Initialised shared volume {0} root (cmd: {1})", volumeName, script);
|
||||
}
|
||||
|
||||
/** Owner and permissions for a directory created inside a shared volume (EFS {@code CreationInfo}). */
|
||||
public record DirectoryCreation(long ownerUid, long ownerGid, String permissions) {
|
||||
public DirectoryCreation {
|
||||
if (permissions == null || !permissions.matches("^[0-7]{3,4}$")) {
|
||||
throw new IllegalArgumentException("permissions must be 3-4 octal digits: " + permissions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Walks the path one directory at a time so that every directory it creates, not only the
|
||||
// last, gets the owner and permissions, as EFS does for an access point's root directory.
|
||||
private static final String ENSURE_DIRECTORY_SCRIPT = """
|
||||
set -f
|
||||
cd /floci-shared-volume || exit 2
|
||||
[ -d "$1" ] && exit 0
|
||||
[ "$#" -eq 4 ] || exit 3
|
||||
p=
|
||||
IFS=/
|
||||
for part in $1; do
|
||||
[ -n "$part" ] || continue
|
||||
p="${p:+$p/}$part"
|
||||
if [ ! -d "$p" ]; then
|
||||
mkdir "$p" && chown "$2:$3" "$p" && chmod "$4" "$p" || exit 1
|
||||
fi
|
||||
done
|
||||
""";
|
||||
|
||||
/**
|
||||
* Ensures {@code relativePath} exists inside the named volume, emulating how Amazon EFS creates
|
||||
* an access point's root directory on first use: each missing directory on the path is created
|
||||
* with {@code creation}'s owner and permissions. When the directory is missing and
|
||||
* {@code creation} is empty nothing is created and this returns false, since EFS then refuses
|
||||
* the mount. The volume itself must already exist.
|
||||
*/
|
||||
public boolean ensureSharedVolumeDirectory(String volumeName, String relativePath,
|
||||
Optional<DirectoryCreation> creation, String initImage) {
|
||||
if (relativePath == null || relativePath.isBlank() || relativePath.startsWith("/")
|
||||
|| List.of(relativePath.split("/")).contains("..")) {
|
||||
throw new IllegalArgumentException("directory must be relative to the volume root: " + relativePath);
|
||||
}
|
||||
String memoKey = volumeName + "/" + relativePath;
|
||||
if (initializedSharedVolumes.containsKey(memoKey)) {
|
||||
return true;
|
||||
}
|
||||
List<String> cmd = new ArrayList<>(List.of("sh", "-c", ENSURE_DIRECTORY_SCRIPT, "sh", relativePath));
|
||||
creation.ifPresent(c -> cmd.addAll(List.of(
|
||||
Long.toString(c.ownerUid()), Long.toString(c.ownerGid()), c.permissions())));
|
||||
Integer status = runVolumeHelper(volumeName, "/floci-shared-volume", initImage, cmd);
|
||||
if (status != null && status == 3) {
|
||||
return false;
|
||||
}
|
||||
if (status == null || status != 0) {
|
||||
throw new IllegalStateException("creating " + relativePath + " in volume " + volumeName
|
||||
+ " exited with status " + status);
|
||||
}
|
||||
initializedSharedVolumes.put(memoKey, Boolean.TRUE);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Runs a one-off helper container with the volume mounted at {@code mount}; returns its exit status. */
|
||||
private Integer runVolumeHelper(String volumeName, String mount, String initImage, List<String> cmd) {
|
||||
String image = (initImage != null && !initImage.isBlank()) ? initImage : "busybox:stable";
|
||||
imageCacheService.ensureImageExists(image);
|
||||
|
||||
@@ -595,22 +667,15 @@ public class ContainerLifecycleManager {
|
||||
new Mount().withType(MountType.VOLUME).withSource(volumeName).withTarget(mount)));
|
||||
CreateContainerResponse created = dockerClient.createContainerCmd(image)
|
||||
.withHostConfig(hostConfig)
|
||||
.withCmd("sh", "-c", script.toString())
|
||||
.withCmd(cmd.toArray(String[]::new))
|
||||
.withLabels(ContainerStorageHelper.defaultLabels(config))
|
||||
.exec();
|
||||
String helperId = created.getId();
|
||||
try {
|
||||
startContainer(helperId);
|
||||
Integer status = dockerClient.waitContainerCmd(helperId)
|
||||
return dockerClient.waitContainerCmd(helperId)
|
||||
.exec(new WaitContainerResultCallback())
|
||||
.awaitStatusCode(60, TimeUnit.SECONDS);
|
||||
if (status == null || status != 0) {
|
||||
// Throw so the caller leaves the volume unmemoised and retries on the next launch,
|
||||
// rather than leaving it root:root 0755 with no further attempt.
|
||||
throw new IllegalStateException("shared-volume init for " + volumeName
|
||||
+ " exited with status " + status + " (cmd: " + script + ")");
|
||||
}
|
||||
LOG.infov("Initialised shared volume {0} root (cmd: {1})", volumeName, script);
|
||||
} finally {
|
||||
try {
|
||||
dockerClient.removeContainerCmd(helperId).withForce(true).exec();
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.github.dockerjava.api.model.VolumeOptions;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* {@link VolumeOptions} with the {@code Subpath} field (Docker Engine API 1.45+), which mounts one
|
||||
* directory of a named volume instead of its root. docker-java 3.7 does not model the field yet.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class SubpathVolumeOptions extends VolumeOptions {
|
||||
|
||||
@JsonProperty("Subpath")
|
||||
private final String subpath;
|
||||
|
||||
public SubpathVolumeOptions(String subpath) {
|
||||
this.subpath = subpath;
|
||||
}
|
||||
|
||||
public String getSubpath() {
|
||||
return subpath;
|
||||
}
|
||||
}
|
||||
@@ -563,8 +563,10 @@ public class AcmJsonHandler {
|
||||
|
||||
private CertificateOptions parseOptions(JsonNode optionsNode) {
|
||||
if (optionsNode.isMissingNode()) return null;
|
||||
String ctPref = optionsNode.path("CertificateTransparencyLoggingPreference").asText("ENABLED");
|
||||
return new CertificateOptions(ctPref, "DISABLED");
|
||||
String ctPref = parseOptionValue(optionsNode, "CertificateTransparencyLoggingPreference");
|
||||
String export = parseOptionValue(optionsNode, "Export");
|
||||
// An exportable public certificate is requested with Export ENABLED, and keeps it for life.
|
||||
return new CertificateOptions(ctPref != null ? ctPref : "ENABLED", export != null ? export : "DISABLED");
|
||||
}
|
||||
|
||||
private List<CertificateStatus> parseCertificateStatuses(JsonNode node) {
|
||||
|
||||
+26
@@ -4,8 +4,10 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.SsrfProtection;
|
||||
import io.github.hectorvent.floci.services.cognito.CognitoService;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
@@ -37,6 +39,7 @@ import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Verifies the RS256 signature of a token presented to an HTTP API v2 JWT authorizer, the same
|
||||
@@ -66,8 +69,27 @@ public class JwtSignatureVerifier implements AutoCloseable {
|
||||
private final CloseableHttpClient httpClient;
|
||||
private final boolean allowPrivateNetworkTargets;
|
||||
private final Map<String, CachedJwks> jwksCache = new ConcurrentHashMap<>();
|
||||
private Function<String, Optional<Map<String, RSAPublicKey>>> localIssuerKeys = issuer -> Optional.empty();
|
||||
|
||||
/**
|
||||
* An issuer that is one of this emulator's own Cognito pools is served at Floci's base URL, which
|
||||
* is plain HTTP on a hostname such as {@code localhost} or a Compose service name, so the HTTPS
|
||||
* and address rules below would refuse to fetch it. Its keys are read from the pool instead:
|
||||
* they are the same keys the pool publishes at its JWKS URL.
|
||||
*/
|
||||
@Inject
|
||||
public JwtSignatureVerifier(ObjectMapper objectMapper, EmulatorConfig config, Instance<CognitoService> cognito) {
|
||||
this(objectMapper, config);
|
||||
withLocalIssuerKeys(issuer -> cognito.isResolvable()
|
||||
? cognito.get().localIssuerKeys(issuer) : Optional.empty());
|
||||
}
|
||||
|
||||
/** Where the keys of in-process issuers come from; package-private so tests can stand one in. */
|
||||
JwtSignatureVerifier withLocalIssuerKeys(Function<String, Optional<Map<String, RSAPublicKey>>> localIssuerKeys) {
|
||||
this.localIssuerKeys = localIssuerKeys;
|
||||
return this;
|
||||
}
|
||||
|
||||
public JwtSignatureVerifier(ObjectMapper objectMapper, EmulatorConfig config) {
|
||||
this(objectMapper, SystemDefaultDnsResolver.INSTANCE,
|
||||
config.security().allowPrivateJwtTargets());
|
||||
@@ -162,6 +184,10 @@ public class JwtSignatureVerifier implements AutoCloseable {
|
||||
}
|
||||
|
||||
private RSAPublicKey resolveKey(String issuer, String kid) throws JwtVerificationException {
|
||||
Optional<Map<String, RSAPublicKey>> local = localIssuerKeys.apply(issuer);
|
||||
if (local.isPresent()) {
|
||||
return local.get().get(kid);
|
||||
}
|
||||
CachedJwks cached = jwksCache.get(issuer);
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
RSAPublicKey key = cached.keysByKid().get(kid);
|
||||
|
||||
@@ -47,7 +47,7 @@ public class AthenaJsonHandler {
|
||||
resultConfiguration = mapper.treeToValue(request.get("ResultConfiguration"), ResultConfiguration.class);
|
||||
}
|
||||
|
||||
String id = athenaService.startQueryExecution(query, workGroup, context, resultConfiguration);
|
||||
String id = athenaService.startQueryExecution(query, workGroup, context, resultConfiguration, region);
|
||||
yield Response.ok(Map.of("QueryExecutionId", id)).build();
|
||||
}
|
||||
case "GetQueryExecution" -> {
|
||||
@@ -62,7 +62,7 @@ public class AthenaJsonHandler {
|
||||
}
|
||||
case "ListQueryExecutions" -> {
|
||||
yield Response.ok(Map.of("QueryExecutionIds",
|
||||
athenaService.listQueryExecutions().stream()
|
||||
athenaService.listQueryExecutions(request.has("WorkGroup") ? request.get("WorkGroup").asText() : null).stream()
|
||||
.map(QueryExecution::getQueryExecutionId).toList())).build();
|
||||
}
|
||||
case "StopQueryExecution" -> {
|
||||
|
||||
@@ -59,6 +59,9 @@ public class AthenaService {
|
||||
public static final String DEFAULT_CATALOG = "AwsDataCatalog";
|
||||
private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results";
|
||||
private static final String DEFAULT_WORKGROUP = "primary";
|
||||
private static final Pattern ENGINE_FAILURE = Pattern.compile("^floci-duck \\w+ returned HTTP \\d+: (\\{.*})$", Pattern.DOTALL);
|
||||
private static final com.fasterxml.jackson.databind.ObjectMapper FAILURE_READER = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
private static final Pattern TRAILING_SEMICOLONS = Pattern.compile("[\\s;]+$");
|
||||
private static final String DEFAULT_ENGINE_VERSION = "Athena engine version 3";
|
||||
private static final long MIN_BYTES_SCANNED_CUTOFF_PER_QUERY = 10_000_000L;
|
||||
private static final String WORKGROUP_RESOURCE = "workgroup/";
|
||||
@@ -122,6 +125,20 @@ public class AthenaService {
|
||||
String workGroup,
|
||||
QueryExecutionContext context,
|
||||
ResultConfiguration resultConfiguration) {
|
||||
return startQueryExecution(query, workGroup, context, resultConfiguration, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a query in a workgroup. As in AWS, the workgroup's result location applies when the
|
||||
* request names none, and always when the workgroup enforces its configuration; an unknown
|
||||
* workgroup is refused. A null region skips the workgroup lookup.
|
||||
*/
|
||||
public String startQueryExecution(String query,
|
||||
String workGroup,
|
||||
QueryExecutionContext context,
|
||||
ResultConfiguration resultConfiguration,
|
||||
String region) {
|
||||
WorkGroupConfiguration workGroupConfiguration = region == null ? null : workGroupFor(region, workGroup).getConfiguration();
|
||||
String id = UUID.randomUUID().toString();
|
||||
String database = context != null && context.getDatabase() != null ? context.getDatabase() : "default";
|
||||
QueryExecutionContext resolvedContext = context != null ? context : new QueryExecutionContext();
|
||||
@@ -135,7 +152,7 @@ public class AthenaService {
|
||||
// directory prefix — the same key is written and returned to the client.
|
||||
// Statements that do not return rows must not be wrapped in a result COPY.
|
||||
String outputLocation = producesResultRows(query)
|
||||
? resolveOutputLocation(resultConfiguration, id)
|
||||
? resolveOutputLocation(resultConfiguration, workGroupConfiguration, id)
|
||||
: null;
|
||||
ResultConfiguration resolvedResult = outputLocation != null
|
||||
? new ResultConfiguration(outputLocation)
|
||||
@@ -177,7 +194,7 @@ public class AthenaService {
|
||||
if (outputLocation != null) {
|
||||
ensureOutputBucket(outputLocation);
|
||||
}
|
||||
duckClient.execute(query, setupDdl, outputLocation);
|
||||
duckClient.execute(withoutTrailingSemicolons(query), setupDdl, outputLocation);
|
||||
return null;
|
||||
}).onSuccess(v -> {
|
||||
markSucceeded(id, execution);
|
||||
@@ -214,6 +231,16 @@ public class AthenaService {
|
||||
return queryStore.scan(k -> true);
|
||||
}
|
||||
|
||||
/** A workgroup's queries, most recent first, as ListQueryExecutions returns them. */
|
||||
public List<QueryExecution> listQueryExecutions(String workGroup) {
|
||||
String name = workGroup == null || workGroup.isBlank() ? DEFAULT_WORKGROUP : workGroup;
|
||||
return queryStore.scan(k -> true).stream()
|
||||
.filter(execution -> name.equals(execution.getWorkGroup() == null ? DEFAULT_WORKGROUP : execution.getWorkGroup()))
|
||||
.sorted(Comparator.comparing((QueryExecution execution) -> execution.getStatus().getSubmissionDateTime(),
|
||||
Comparator.nullsLast(Comparator.naturalOrder())).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void stopQueryExecution(String id) {
|
||||
QueryExecution execution = getQueryExecution(id);
|
||||
execution.getStatus().setState(QueryExecutionState.CANCELLED);
|
||||
@@ -531,6 +558,15 @@ public class AthenaService {
|
||||
return properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Athena accepts one statement with or without a closing semicolon. The engine wraps the
|
||||
* statement in {@code COPY (...) TO ...}, where a semicolon is a syntax error, so it is
|
||||
* dropped before the query is handed over.
|
||||
*/
|
||||
static String withoutTrailingSemicolons(String query) {
|
||||
return query == null ? null : TRAILING_SEMICOLONS.matcher(query).replaceFirst("");
|
||||
}
|
||||
|
||||
private static boolean producesResultRows(String query) {
|
||||
return RESULT_STATEMENT_PATTERN.matcher(statementText(query)).find();
|
||||
}
|
||||
@@ -576,17 +612,53 @@ public class AthenaService {
|
||||
|
||||
private void markFailed(String id, QueryExecution execution, Throwable failure) {
|
||||
execution.getStatus().setState(QueryExecutionState.FAILED);
|
||||
execution.getStatus().setStateChangeReason(failure.getMessage());
|
||||
execution.getStatus().setStateChangeReason(failureReason(failure.getMessage()));
|
||||
queryStore.put(id, execution);
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine's own explanation of a failed query, as Athena reports it: without the HTTP
|
||||
* envelope of the engine call, and without the echoed statement, which shows the
|
||||
* internal {@code COPY ... TO} wrapper rather than the query that was sent.
|
||||
*/
|
||||
static String failureReason(String message) {
|
||||
if (message == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher envelope = ENGINE_FAILURE.matcher(message);
|
||||
if (!envelope.matches()) {
|
||||
return message;
|
||||
}
|
||||
try {
|
||||
String engineMessage = FAILURE_READER.readTree(envelope.group(1)).path("message").asText("");
|
||||
if (engineMessage.isBlank()) {
|
||||
return message;
|
||||
}
|
||||
int echo = engineMessage.indexOf("\n\nLINE ");
|
||||
return (echo >= 0 ? engineMessage.substring(0, echo) : engineMessage).strip();
|
||||
} catch (Exception e) {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
private record CreateDatabaseDdl(String name, boolean ifNotExists, String comment,
|
||||
String location, Map<String, String> properties) {
|
||||
}
|
||||
|
||||
private String resolveOutputLocation(ResultConfiguration rc, String queryId) {
|
||||
String base = (rc != null && rc.getOutputLocation() != null && !rc.getOutputLocation().isBlank())
|
||||
private String resolveOutputLocation(ResultConfiguration rc, WorkGroupConfiguration workGroupConfiguration, String queryId) {
|
||||
String requested = rc != null && rc.getOutputLocation() != null && !rc.getOutputLocation().isBlank()
|
||||
? rc.getOutputLocation()
|
||||
: null;
|
||||
String workGroupLocation = workGroupConfiguration != null
|
||||
&& workGroupConfiguration.getResultConfiguration() != null
|
||||
&& workGroupConfiguration.getResultConfiguration().getOutputLocation() != null
|
||||
&& !workGroupConfiguration.getResultConfiguration().getOutputLocation().isBlank()
|
||||
? workGroupConfiguration.getResultConfiguration().getOutputLocation()
|
||||
: null;
|
||||
boolean enforced = workGroupConfiguration != null && Boolean.TRUE.equals(workGroupConfiguration.getEnforceWorkGroupConfiguration());
|
||||
String base = enforced && workGroupLocation != null ? workGroupLocation
|
||||
: requested != null ? requested
|
||||
: workGroupLocation != null ? workGroupLocation
|
||||
: "s3://" + DEFAULT_OUTPUT_BUCKET + "/results/";
|
||||
return base.endsWith("/") ? base + queryId + ".csv" : base + "/" + queryId + ".csv";
|
||||
}
|
||||
@@ -692,6 +764,12 @@ public class AthenaService {
|
||||
return engineVersion;
|
||||
}
|
||||
|
||||
private WorkGroup workGroupFor(String region, String name) {
|
||||
return name == null || name.isBlank() || DEFAULT_WORKGROUP.equals(name)
|
||||
? primaryWorkGroup(region)
|
||||
: requireWorkGroup(region, name);
|
||||
}
|
||||
|
||||
private WorkGroup primaryWorkGroup(String region) {
|
||||
return workGroupStore.get(workGroupKey(region, DEFAULT_WORKGROUP)).orElseGet(() -> {
|
||||
WorkGroup workGroup = new WorkGroup();
|
||||
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchCompositeAlarmCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final String TYPE = "AWS::CloudWatch::CompositeAlarm";
|
||||
private static final String SNAPSHOT = "FlociCompositeAlarmSnapshot";
|
||||
private static final String TAG_KEYS = "FlociCompositeAlarmTagKeys";
|
||||
private static final String EXPLICIT_NAME = "FlociCompositeAlarmExplicitName";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private final CloudWatchMetricsService service;
|
||||
|
||||
public CloudWatchCompositeAlarmCfnProvisioner(CloudWatchMetricsService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TYPE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) {
|
||||
for (String unsupported : List.of("ActionsSuppressor", "ActionsSuppressorWaitPeriod",
|
||||
"ActionsSuppressorExtensionPeriod")) {
|
||||
if (props.has(unsupported)) {
|
||||
throw new AwsException("ValidationError", "Composite action suppression is not supported", 400);
|
||||
}
|
||||
}
|
||||
if (resource.getAttributes().containsKey(SNAPSHOT)) {
|
||||
throw new AwsException("ResourceConflictException", "Alarm update cleanup is still pending", 400);
|
||||
}
|
||||
String explicit = ctx.resolveOptional(props, "AlarmName");
|
||||
boolean removedName = explicit == null && "true".equals(resource.getAttributes().get(EXPLICIT_NAME));
|
||||
String name = removedName ? ctx.generatePhysicalName(resource.getLogicalId(), 255, false)
|
||||
: ctx.stablePhysicalName(explicit, resource.getLogicalId(), 255, false);
|
||||
CompositeAlarm alarm = new CompositeAlarm();
|
||||
alarm.setAlarmName(name);
|
||||
alarm.setAlarmDescription(ctx.resolveOptional(props, "AlarmDescription"));
|
||||
alarm.setAlarmRule(ctx.resolveOptional(props, "AlarmRule"));
|
||||
alarm.setActionsEnabled(!"false".equals(ctx.resolveOptional(props, "ActionsEnabled")));
|
||||
alarm.setTags(ctx.resolveTags(props, "Tags"));
|
||||
actions(props, "AlarmActions", ctx, alarm.getAlarmActions());
|
||||
actions(props, "OKActions", ctx, alarm.getOkActions());
|
||||
actions(props, "InsufficientDataActions", ctx, alarm.getInsufficientDataActions());
|
||||
Map<String, String> desiredTags = Map.copyOf(alarm.getTags());
|
||||
Map<String, String> priorAttributes = Map.copyOf(resource.getAttributes());
|
||||
boolean inPlace = ctx.reusesPriorEntity(name);
|
||||
String updateSnapshot = null;
|
||||
if (inPlace) {
|
||||
ObjectNode snapshot = MAPPER.createObjectNode().put("region", ctx.region()).put("name", name);
|
||||
List<CompositeAlarm> previous = service.describeCompositeAlarms(List.of(name), null, ctx.region());
|
||||
if (!previous.isEmpty()) {
|
||||
snapshot.set("alarm", MAPPER.valueToTree(previous.getFirst()));
|
||||
}
|
||||
snapshot.set("attributes", MAPPER.valueToTree(priorAttributes));
|
||||
Set<String> changedKeys = new TreeSet<>(desiredTags.keySet());
|
||||
changedKeys.addAll(tagKeys(resource.getAttributes().get(TAG_KEYS)));
|
||||
snapshot.set("changedTagKeys", MAPPER.valueToTree(changedKeys));
|
||||
updateSnapshot = snapshot.toString();
|
||||
}
|
||||
service.putCompositeAlarm(alarm, ctx.region(), inPlace);
|
||||
if (inPlace) {
|
||||
resource.getAttributes().put(SNAPSHOT, updateSnapshot);
|
||||
reconcileTags(alarm.getAlarmArn(), tagKeys(priorAttributes.get(TAG_KEYS)), desiredTags, ctx.region());
|
||||
}
|
||||
resource.getAttributes().put(TAG_KEYS, MAPPER.valueToTree(desiredTags.keySet()).toString());
|
||||
resource.setPhysicalId(name);
|
||||
resource.getAttributes().put("Arn", alarm.getAlarmArn());
|
||||
resource.getAttributes().put(EXPLICIT_NAME, Boolean.toString(explicit != null));
|
||||
ReplacementCleanup.record(resource, ctx, priorAttributes);
|
||||
}
|
||||
|
||||
private static void actions(JsonNode props, String field, ProvisionContext ctx, List<String> target) {
|
||||
JsonNode values = ctx.engine().resolveNode(props.path(field));
|
||||
if (values != null && values.isArray()) {
|
||||
values.forEach(value -> target.add(value.asText()));
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> tagKeys(String json) {
|
||||
Set<String> keys = new TreeSet<>();
|
||||
if (json != null) {
|
||||
try {
|
||||
MAPPER.readTree(json).forEach(value -> keys.add(value.asText()));
|
||||
} catch (JsonProcessingException error) {
|
||||
throw new IllegalStateException("Cannot read composite alarm tag ownership", error);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
private void reconcileTags(String arn, Set<String> owned, Map<String, String> desired, String region) {
|
||||
List<String> removed = owned.stream().filter(key -> !desired.containsKey(key)).toList();
|
||||
if (!removed.isEmpty()) {
|
||||
service.untagResource(arn, removed, region);
|
||||
}
|
||||
if (!desired.isEmpty()) {
|
||||
service.tagResource(arn, desired, region);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String type, String physicalId, String region) {
|
||||
service.deleteAlarms(List.of(physicalId), region);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainsFailedUpdateState(StackResource resource) {
|
||||
return resource.getAttributes().containsKey(SNAPSHOT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
if (ReplacementCleanup.rollback(resource, this::delete)) {
|
||||
return true;
|
||||
}
|
||||
String raw = resource.getAttributes().get(SNAPSHOT);
|
||||
if (raw == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
JsonNode snapshot = MAPPER.readTree(raw);
|
||||
String region = snapshot.path("region").asText();
|
||||
if (snapshot.has("alarm")) {
|
||||
CompositeAlarm original = MAPPER.treeToValue(snapshot.get("alarm"), CompositeAlarm.class);
|
||||
Map<String, String> originalTags = Map.copyOf(original.getTags());
|
||||
service.putCompositeAlarm(original, region);
|
||||
Set<String> changed = tagKeys(snapshot.path("changedTagKeys").toString());
|
||||
reconcileTags(original.getAlarmArn(), changed, originalTags.entrySet().stream()
|
||||
.filter(entry -> changed.contains(entry.getKey()))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)), region);
|
||||
} else {
|
||||
delete(TYPE, snapshot.path("name").asText(), region);
|
||||
}
|
||||
resource.getAttributes().clear();
|
||||
snapshot.path("attributes").fields().forEachRemaining(entry ->
|
||||
resource.getAttributes().put(entry.getKey(), entry.getValue().asText()));
|
||||
} catch (JsonProcessingException error) {
|
||||
throw new IllegalStateException("Cannot read composite alarm rollback state", error);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
if (resource.getAttributes().containsKey(SNAPSHOT) && !ReplacementCleanup.hasReplacement(resource)) {
|
||||
return new UpdateCleanupResult(true, true, null, 0, null);
|
||||
}
|
||||
return ReplacementCleanup.complete(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(SNAPSHOT);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
}
|
||||
+18
@@ -9,9 +9,11 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The replacement lifecycle for provisioners whose replacing update simply creates the new entity
|
||||
@@ -121,6 +123,22 @@ public final class ReplacementCleanup {
|
||||
return cleanup != null && cleanup.path("displaced").size() > 0;
|
||||
}
|
||||
|
||||
/** The physical IDs of replaced resources this resource still has to delete. */
|
||||
static Set<String> owedPhysicalIds(StackResource r) {
|
||||
Set<String> owed = new HashSet<>();
|
||||
ObjectNode cleanup = read(r);
|
||||
if (cleanup == null) {
|
||||
return owed;
|
||||
}
|
||||
for (JsonNode entry : cleanup.path("displaced")) {
|
||||
String physicalId = entry.path("physicalId").asText(null);
|
||||
if (physicalId != null) {
|
||||
owed.add(physicalId);
|
||||
}
|
||||
}
|
||||
return owed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The entity the cleanup is working on, or null when none is owed or {@code UpdateReplacePolicy:
|
||||
* Retain} keeps it. The engine announces one physical id per resource, so a resource owing more
|
||||
|
||||
+63
-10
@@ -179,29 +179,82 @@ public class CloudWatchDashboardsService {
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
return findByArn(resourceArn, region).map(Dashboard::getTags).orElse(Map.of());
|
||||
return requireDashboard(resourceArn, region).getTags();
|
||||
}
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(dashboard -> {
|
||||
dashboard.getTags().putAll(tags);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
});
|
||||
Dashboard dashboard = requireDashboard(resourceArn, region);
|
||||
dashboard.getTags().putAll(tags);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
}
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(dashboard -> {
|
||||
tagKeys.forEach(dashboard.getTags()::remove);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
});
|
||||
Dashboard dashboard = requireDashboard(resourceArn, region);
|
||||
tagKeys.forEach(dashboard.getTags()::remove);
|
||||
dashboardStore.put(key(region, dashboard.getDashboardName()), dashboard);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the dashboard an ARN names, or reports that nothing does. The tag operations
|
||||
* declare {@code ResourceNotFoundException}, which is a different shape from the
|
||||
* {@code ResourceNotFound} that {@code GetDashboard} declares,
|
||||
* so this is not the {@link #notFound(String)} used by the rest of this service.
|
||||
*/
|
||||
private Dashboard requireDashboard(String resourceArn, String region) {
|
||||
return findByArn(resourceArn, region).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException",
|
||||
"Dashboard does not exist: " + resourceArn, 404));
|
||||
}
|
||||
|
||||
private java.util.Optional<Dashboard> findByArn(String resourceArn, String region) {
|
||||
return dashboardStore.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(d -> d.getDashboardArn() != null && d.getDashboardArn().equals(resourceArn))
|
||||
.filter(d -> namesDashboard(resourceArn, d.getDashboardArn()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code candidate} is an ARN for the dashboard whose own ARN is {@code stored}.
|
||||
*
|
||||
* <p>Both the region-ful and the regionless form resolve, deliberately, because the two
|
||||
* disagree here and a caller may hold either. Dashboards are a global resource and AWS
|
||||
* documents their ARN without a region on both the TagResource and the ListTagsForResource
|
||||
* pages, {@code arn:aws:cloudwatch::<account-id>:dashboard/<dashboard-name>}, while Floci
|
||||
* mints a region-ful one. That divergence used to be invisible on this path: an ARN
|
||||
* matching nothing was a silent success answering an empty tag map. Now that it is an
|
||||
* error, a caller sending the documented ARN for a dashboard that exists would be told the
|
||||
* dashboard does not, so the lookup accepts both shapes.
|
||||
*
|
||||
* <p>What Floci mints is left alone here on purpose. Clients may already hold the ARNs it
|
||||
* has handed out, so bringing the minted shape into line with AWS is a separate change
|
||||
* from making the lookup tolerant, and only the second one is needed to keep this path
|
||||
* correct.
|
||||
*
|
||||
* <p>Only an absent region is accepted in place of the dashboard's own, so an ARN naming
|
||||
* some other region is still a miss rather than resolving to a same-named dashboard
|
||||
* elsewhere.
|
||||
*/
|
||||
private static boolean namesDashboard(String candidate, String stored) {
|
||||
if (candidate == null || stored == null) {
|
||||
return false;
|
||||
}
|
||||
return candidate.equals(stored) || candidate.equals(withoutRegion(stored));
|
||||
}
|
||||
|
||||
/**
|
||||
* Blanks the region field of an ARN, turning
|
||||
* {@code arn:aws:cloudwatch:us-east-1:123:dashboard/x} into
|
||||
* {@code arn:aws:cloudwatch::123:dashboard/x}. An ARN with fewer than six fields is
|
||||
* returned unchanged, since there is no region field to blank.
|
||||
*/
|
||||
private static String withoutRegion(String arn) {
|
||||
String[] fields = arn.split(":", 6);
|
||||
if (fields.length < 6) {
|
||||
return arn;
|
||||
}
|
||||
fields[3] = "";
|
||||
return String.join(":", fields);
|
||||
}
|
||||
|
||||
private static String key(String region, String dashboardName) {
|
||||
return region + "::" + dashboardName;
|
||||
}
|
||||
|
||||
+2
-1
@@ -275,9 +275,10 @@ public class AlarmEvaluator {
|
||||
|
||||
private static boolean isEvaluable(MetricAlarm alarm) {
|
||||
return alarm.getRegion() != null
|
||||
&& alarm.getMetrics().isEmpty()
|
||||
&& alarm.getNamespace() != null && !alarm.getNamespace().isBlank()
|
||||
&& alarm.getMetricName() != null && !alarm.getMetricName().isBlank()
|
||||
&& alarm.getPeriod() > 0
|
||||
&& alarm.getPeriod() != null && alarm.getPeriod() > 0
|
||||
&& alarm.getEvaluationPeriods() > 0
|
||||
&& alarm.getComparisonOperator() != null;
|
||||
}
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** Publishes SNS actions once per state transition, independently of scaling action retries. */
|
||||
@ApplicationScoped
|
||||
public class AlarmSnsNotifier {
|
||||
|
||||
/** The names CloudWatch writes in the alarm message's Region field; other regions use their ID. */
|
||||
private static final Map<String, String> REGION_NAMES = Map.ofEntries(
|
||||
Map.entry("us-east-1", "US East (N. Virginia)"),
|
||||
Map.entry("us-east-2", "US East (Ohio)"),
|
||||
Map.entry("us-west-1", "US West (N. California)"),
|
||||
Map.entry("us-west-2", "US West (Oregon)"),
|
||||
Map.entry("ca-central-1", "Canada (Central)"),
|
||||
Map.entry("ca-west-1", "Canada West (Calgary)"),
|
||||
Map.entry("sa-east-1", "South America (Sao Paulo)"),
|
||||
Map.entry("eu-west-1", "EU (Ireland)"),
|
||||
Map.entry("eu-west-2", "EU (London)"),
|
||||
Map.entry("eu-west-3", "EU (Paris)"),
|
||||
Map.entry("eu-central-1", "EU (Frankfurt)"),
|
||||
Map.entry("eu-central-2", "EU (Zurich)"),
|
||||
Map.entry("eu-north-1", "EU (Stockholm)"),
|
||||
Map.entry("eu-south-1", "EU (Milan)"),
|
||||
Map.entry("eu-south-2", "EU (Spain)"),
|
||||
Map.entry("me-south-1", "Middle East (Bahrain)"),
|
||||
Map.entry("me-central-1", "Middle East (UAE)"),
|
||||
Map.entry("il-central-1", "Israel (Tel Aviv)"),
|
||||
Map.entry("af-south-1", "Africa (Cape Town)"),
|
||||
Map.entry("ap-east-1", "Asia Pacific (Hong Kong)"),
|
||||
Map.entry("ap-south-1", "Asia Pacific (Mumbai)"),
|
||||
Map.entry("ap-south-2", "Asia Pacific (Hyderabad)"),
|
||||
Map.entry("ap-northeast-1", "Asia Pacific (Tokyo)"),
|
||||
Map.entry("ap-northeast-2", "Asia Pacific (Seoul)"),
|
||||
Map.entry("ap-northeast-3", "Asia Pacific (Osaka)"),
|
||||
Map.entry("ap-southeast-1", "Asia Pacific (Singapore)"),
|
||||
Map.entry("ap-southeast-2", "Asia Pacific (Sydney)"),
|
||||
Map.entry("ap-southeast-3", "Asia Pacific (Jakarta)"),
|
||||
Map.entry("ap-southeast-4", "Asia Pacific (Melbourne)"));
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AlarmSnsNotifier.class);
|
||||
private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ROOT).withZone(ZoneOffset.UTC);
|
||||
private final SnsService snsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AlarmSnsNotifier(SnsService snsService, ObjectMapper objectMapper) {
|
||||
this.snsService = snsService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
record Notification(String topicArn, String message, String subject, String region) {}
|
||||
|
||||
List<Notification> prepareTransition(MetricAlarm alarm, String oldState) {
|
||||
if (!alarm.isActionsEnabled() || alarm.getStateValue().equals(oldState)) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> actions = switch (alarm.getStateValue()) {
|
||||
case "ALARM" -> alarm.getAlarmActions();
|
||||
case "OK" -> alarm.getOkActions();
|
||||
case "INSUFFICIENT_DATA" -> alarm.getInsufficientDataActions();
|
||||
default -> List.of();
|
||||
};
|
||||
if (actions == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Notification> notifications = new ArrayList<>();
|
||||
for (String action : actions) {
|
||||
if (!AwsArnUtils.isArnFor(action, "sns")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
AwsArnUtils.Arn topic = AwsArnUtils.parse(action);
|
||||
String subject = alarm.getStateValue() + ": \"" + alarm.getAlarmName() + "\"";
|
||||
if (subject.length() > 100) {
|
||||
subject = subject.substring(0, 100);
|
||||
}
|
||||
notifications.add(new Notification(action, message(alarm, oldState), subject, topic.region()));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv(e, "Unable to publish alarm {0} state {1} to SNS action {2}",
|
||||
alarm.getAlarmName(), alarm.getStateValue(), action);
|
||||
}
|
||||
}
|
||||
return notifications;
|
||||
}
|
||||
|
||||
void publish(List<Notification> notifications) {
|
||||
for (Notification notification : notifications) {
|
||||
try {
|
||||
snsService.publish(notification.topicArn(), null, notification.message(),
|
||||
notification.subject(), notification.region());
|
||||
} catch (Exception error) {
|
||||
LOG.warnv(error, "Unable to publish alarm transition {0} to SNS action {1}",
|
||||
notification.subject(), notification.topicArn());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String message(MetricAlarm alarm, String oldState) throws JsonProcessingException {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(alarm.getAlarmArn());
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("AlarmName", alarm.getAlarmName());
|
||||
payload.put("AlarmDescription", alarm.getAlarmDescription());
|
||||
payload.put("AWSAccountId", arn.accountId());
|
||||
payload.put("AlarmConfigurationUpdatedTimestamp", timestamp(alarm.getAlarmConfigurationUpdatedTimestamp()));
|
||||
payload.put("NewStateValue", alarm.getStateValue());
|
||||
payload.put("NewStateReason", alarm.getStateReason());
|
||||
payload.put("StateChangeTime", timestamp(alarm.getStateUpdatedTimestamp()));
|
||||
payload.put("Region", REGION_NAMES.getOrDefault(arn.region(), arn.region()));
|
||||
payload.put("AlarmArn", alarm.getAlarmArn());
|
||||
payload.put("OldStateValue", oldState);
|
||||
payload.put("OKActions", alarm.getOkActions());
|
||||
payload.put("AlarmActions", alarm.getAlarmActions());
|
||||
payload.put("InsufficientDataActions", alarm.getInsufficientDataActions());
|
||||
Map<String, Object> trigger = new LinkedHashMap<>();
|
||||
trigger.put("MetricName", alarm.getMetricName());
|
||||
trigger.put("Namespace", alarm.getNamespace());
|
||||
trigger.put("StatisticType", "Statistic");
|
||||
trigger.put("Statistic", alarm.getStatistic() != null
|
||||
? alarm.getStatistic().toUpperCase(Locale.ROOT) : null);
|
||||
trigger.put("Unit", alarm.getUnit());
|
||||
trigger.put("Dimensions", alarm.getDimensions());
|
||||
trigger.put("Period", alarm.getPeriod());
|
||||
trigger.put("EvaluationPeriods", alarm.getEvaluationPeriods());
|
||||
if (alarm.getDatapointsToAlarm() != null) {
|
||||
trigger.put("DatapointsToAlarm", alarm.getDatapointsToAlarm());
|
||||
}
|
||||
trigger.put("ComparisonOperator", alarm.getComparisonOperator());
|
||||
trigger.put("Threshold", alarm.getThreshold());
|
||||
trigger.put("TreatMissingData", alarm.getTreatMissingData());
|
||||
trigger.put("EvaluateLowSampleCountPercentile", alarm.getEvaluateLowSampleCountPercentile() != null
|
||||
? alarm.getEvaluateLowSampleCountPercentile() : "");
|
||||
payload.put("Trigger", trigger);
|
||||
return objectMapper.writeValueAsString(payload);
|
||||
}
|
||||
|
||||
private String timestamp(long epochSeconds) {
|
||||
return TIMESTAMP_FORMAT.format(Instant.ofEpochSecond(epochSeconds));
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
/**
|
||||
* A CloudWatch error whose Query code and JSON shape name differ.
|
||||
*
|
||||
* <p>CloudWatch is awsQueryCompatible: the Query {@code <Code>} and the
|
||||
* {@code x-amzn-query-error} header carry the {@code awsQueryError} code
|
||||
* ({@code MissingParameter}), while a JSON 1.0 or CBOR body's {@code __type} names the
|
||||
* model shape ({@code MissingRequiredParameterException}). The AWS SDK v2 picks the typed
|
||||
* exception from {@code __type}, so the code alone yields a generic {@code CloudWatchException}.
|
||||
* Keeping {@link #getErrorCode()} as the Query code and overriding {@link #jsonType()}
|
||||
* reproduces both surfaces.
|
||||
*/
|
||||
class CloudWatchMetricsException extends AwsException {
|
||||
|
||||
private final String jsonType;
|
||||
|
||||
private CloudWatchMetricsException(String errorCode, String jsonType, String message, int httpStatus) {
|
||||
super(errorCode, message, httpStatus);
|
||||
this.jsonType = jsonType;
|
||||
}
|
||||
|
||||
static CloudWatchMetricsException missingParameter(String parameter) {
|
||||
return new CloudWatchMetricsException("MissingParameter", "MissingRequiredParameterException",
|
||||
"The parameter " + parameter + " is required.", 400);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String jsonType() {
|
||||
return jsonType;
|
||||
}
|
||||
}
|
||||
+127
-38
@@ -5,13 +5,21 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -56,6 +64,7 @@ public class CloudWatchMetricsJsonHandler {
|
||||
case "ListMetrics" -> handleListMetrics(request, region);
|
||||
case "GetMetricStatistics" -> handleGetMetricStatistics(request, region);
|
||||
case "PutMetricAlarm" -> handlePutMetricAlarm(request, region);
|
||||
case "PutCompositeAlarm" -> handlePutCompositeAlarm(request, region);
|
||||
case "DescribeAlarms" -> handleDescribeAlarms(request, region);
|
||||
case "DeleteAlarms" -> handleDeleteAlarms(request, region);
|
||||
case "SetAlarmState" -> handleSetAlarmState(request, region);
|
||||
@@ -81,10 +90,14 @@ public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
private Response handlePutMetricData(JsonNode request, String region) {
|
||||
String namespace = request.path("Namespace").asText();
|
||||
LOG.infov("JSON PutMetricData raw: {0}", request);
|
||||
List<MetricDatum> datums = parseMetricDataJson(request.path("MetricData"));
|
||||
LOG.infov("JSON PutMetricData parsed {0} datums, sums={1}", datums.size(),
|
||||
datums.stream().map(d -> d.getMetricName() + "=" + d.getSum()).toList());
|
||||
List<MetricDatum> datums = parseMetricDataJson(request.path("MetricData"), "MetricData");
|
||||
int entityIndex = 0;
|
||||
for (JsonNode entityMetricData : request.path("EntityMetricData")) {
|
||||
entityIndex++;
|
||||
datums.addAll(parseMetricDataJson(entityMetricData.path("MetricData"),
|
||||
"EntityMetricData.member." + entityIndex + ".MetricData"));
|
||||
}
|
||||
LOG.debugv("JSON PutMetricData parsed {0} datums for namespace {1}", datums.size(), namespace);
|
||||
metricsService.putMetricData(namespace, datums, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
@@ -151,12 +164,17 @@ public class CloudWatchMetricsJsonHandler {
|
||||
|
||||
private Response handlePutMetricAlarm(JsonNode request, String region) {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName(request.path("AlarmName").asText());
|
||||
alarm.setAlarmDescription(request.path("AlarmDescription").asText(null));
|
||||
parseAlarmFields(request, alarm);
|
||||
alarm.setMetricName(request.path("MetricName").asText(null));
|
||||
alarm.setNamespace(request.path("Namespace").asText(null));
|
||||
alarm.setStatistic(request.path("Statistic").asText(null));
|
||||
alarm.setPeriod(request.path("Period").asInt(60));
|
||||
JsonNode metrics = request.path("Metrics");
|
||||
if (metrics.isArray()) {
|
||||
for (JsonNode query : metrics) {
|
||||
alarm.getMetrics().add(objectMapper.convertValue(query, AlarmMetricDataQuery.class));
|
||||
}
|
||||
}
|
||||
alarm.setPeriod(alarm.getMetrics().isEmpty() ? request.path("Period").asInt(60) : null);
|
||||
alarm.setUnit(request.path("Unit").asText(null));
|
||||
alarm.setEvaluationPeriods(request.path("EvaluationPeriods").asInt(1));
|
||||
alarm.setDatapointsToAlarm(request.hasNonNull("DatapointsToAlarm")
|
||||
@@ -164,9 +182,33 @@ public class CloudWatchMetricsJsonHandler {
|
||||
alarm.setThreshold(request.path("Threshold").asDouble(0));
|
||||
alarm.setComparisonOperator(request.path("ComparisonOperator").asText(null));
|
||||
alarm.setTreatMissingData(request.path("TreatMissingData").asText(null));
|
||||
alarm.setActionsEnabled(request.path("ActionsEnabled").asBoolean(true));
|
||||
alarm.setDimensions(parseDimensionsJson(request.path("Dimensions")));
|
||||
|
||||
metricsService.putMetricAlarm(alarm, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handlePutCompositeAlarm(JsonNode request, String region) {
|
||||
rejectSuppressor(request);
|
||||
CompositeAlarm alarm = new CompositeAlarm();
|
||||
parseAlarmFields(request, alarm);
|
||||
alarm.setAlarmRule(request.path("AlarmRule").asText(null));
|
||||
metricsService.putCompositeAlarm(alarm, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private static void rejectSuppressor(JsonNode request) {
|
||||
if (request.has("ActionsSuppressor") || request.has("ActionsSuppressorWaitPeriod")
|
||||
|| request.has("ActionsSuppressorExtensionPeriod")) {
|
||||
throw new AwsException("ValidationError", "Composite action suppression is not supported", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private void parseAlarmFields(JsonNode request, Alarm alarm) {
|
||||
alarm.setAlarmName(request.path("AlarmName").asText());
|
||||
alarm.setAlarmDescription(request.path("AlarmDescription").asText(null));
|
||||
alarm.setActionsEnabled(request.path("ActionsEnabled").asBoolean(true));
|
||||
|
||||
JsonNode alarmActions = request.path("AlarmActions");
|
||||
if (alarmActions.isArray()) {
|
||||
alarmActions.forEach(a -> alarm.getAlarmActions().add(a.asText()));
|
||||
@@ -187,8 +229,6 @@ public class CloudWatchMetricsJsonHandler {
|
||||
alarm.setTags(tags);
|
||||
}
|
||||
|
||||
metricsService.putMetricAlarm(alarm, region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleDescribeAlarms(JsonNode request, String region) {
|
||||
@@ -199,32 +239,42 @@ public class CloudWatchMetricsJsonHandler {
|
||||
}
|
||||
String prefix = request.has("AlarmNamePrefix") ? request.path("AlarmNamePrefix").asText() : null;
|
||||
|
||||
List<MetricAlarm> alarms = metricsService.describeAlarms(alarmNames, prefix, region);
|
||||
List<String> types = new ArrayList<>();
|
||||
request.path("AlarmTypes").forEach(value -> types.add(value.asText()));
|
||||
metricsService.validateAlarmTypes(types);
|
||||
List<MetricAlarm> alarms = types.isEmpty() || types.contains("MetricAlarm")
|
||||
? metricsService.describeAlarms(alarmNames, prefix, region) : List.of();
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray("MetricAlarms");
|
||||
for (MetricAlarm a : alarms) {
|
||||
ObjectNode node = arr.addObject();
|
||||
node.put("AlarmName", a.getAlarmName());
|
||||
if (a.getAlarmArn() != null) node.put("AlarmArn", a.getAlarmArn());
|
||||
if (a.getAlarmDescription() != null) node.put("AlarmDescription", a.getAlarmDescription());
|
||||
ArrayNode alarmActions = node.putArray("AlarmActions");
|
||||
a.getAlarmActions().forEach(alarmActions::add);
|
||||
ArrayNode okActions = node.putArray("OKActions");
|
||||
a.getOkActions().forEach(okActions::add);
|
||||
ArrayNode insufficientDataActions = node.putArray("InsufficientDataActions");
|
||||
a.getInsufficientDataActions().forEach(insufficientDataActions::add);
|
||||
if (a.getMetricName() != null) node.put("MetricName", a.getMetricName());
|
||||
if (a.getNamespace() != null) node.put("Namespace", a.getNamespace());
|
||||
if (a.getStatistic() != null) node.put("Statistic", a.getStatistic());
|
||||
ArrayNode dimensions = node.putArray("Dimensions");
|
||||
a.getDimensions().forEach(d -> {
|
||||
ObjectNode dimNode = dimensions.addObject();
|
||||
dimNode.put("Name", d.name());
|
||||
dimNode.put("Value", d.value());
|
||||
});
|
||||
node.put("Period", a.getPeriod());
|
||||
if (a.getUnit() != null) node.put("Unit", a.getUnit());
|
||||
describeAlarmFields(node, a);
|
||||
if (!a.getMetrics().isEmpty()) {
|
||||
node.set("Metrics", objectMapper.valueToTree(a.getMetrics()));
|
||||
} else {
|
||||
if (a.getMetricName() != null) {
|
||||
node.put("MetricName", a.getMetricName());
|
||||
}
|
||||
if (a.getNamespace() != null) {
|
||||
node.put("Namespace", a.getNamespace());
|
||||
}
|
||||
if (a.getStatistic() != null) {
|
||||
node.put("Statistic", a.getStatistic());
|
||||
}
|
||||
ArrayNode dimensions = node.putArray("Dimensions");
|
||||
a.getDimensions().forEach(d -> {
|
||||
ObjectNode dimNode = dimensions.addObject();
|
||||
dimNode.put("Name", d.name());
|
||||
dimNode.put("Value", d.value());
|
||||
});
|
||||
if (a.getPeriod() != null) {
|
||||
node.put("Period", a.getPeriod());
|
||||
}
|
||||
if (a.getUnit() != null) {
|
||||
node.put("Unit", a.getUnit());
|
||||
}
|
||||
}
|
||||
node.put("EvaluationPeriods", a.getEvaluationPeriods());
|
||||
if (a.getDatapointsToAlarm() != null) {
|
||||
node.put("DatapointsToAlarm", a.getDatapointsToAlarm());
|
||||
@@ -232,15 +282,48 @@ public class CloudWatchMetricsJsonHandler {
|
||||
node.put("Threshold", a.getThreshold());
|
||||
if (a.getComparisonOperator() != null) node.put("ComparisonOperator", a.getComparisonOperator());
|
||||
if (a.getTreatMissingData() != null) node.put("TreatMissingData", a.getTreatMissingData());
|
||||
node.put("ActionsEnabled", a.isActionsEnabled());
|
||||
if (a.getStateValue() != null) node.put("StateValue", a.getStateValue());
|
||||
if (a.getStateReason() != null) node.put("StateReason", a.getStateReason());
|
||||
if (a.getStateReasonData() != null) node.put("StateReasonData", a.getStateReasonData());
|
||||
node.put("StateUpdatedTimestamp", a.getStateUpdatedTimestamp());
|
||||
|
||||
}
|
||||
ArrayNode composites = response.putArray("CompositeAlarms");
|
||||
if (types.contains("CompositeAlarm")) {
|
||||
for (CompositeAlarm alarm : metricsService.describeCompositeAlarms(alarmNames, prefix, region)) {
|
||||
ObjectNode node = composites.addObject();
|
||||
describeAlarmFields(node, alarm);
|
||||
node.put("AlarmRule", alarm.getAlarmRule());
|
||||
}
|
||||
}
|
||||
response.putArray("LogAlarms");
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private void describeAlarmFields(ObjectNode node, Alarm a) {
|
||||
node.put("AlarmName", a.getAlarmName());
|
||||
if (a.getAlarmArn() != null) {
|
||||
node.put("AlarmArn", a.getAlarmArn());
|
||||
}
|
||||
if (a.getAlarmDescription() != null) {
|
||||
node.put("AlarmDescription", a.getAlarmDescription());
|
||||
}
|
||||
ArrayNode alarmActions = node.putArray("AlarmActions");
|
||||
a.getAlarmActions().forEach(alarmActions::add);
|
||||
ArrayNode okActions = node.putArray("OKActions");
|
||||
a.getOkActions().forEach(okActions::add);
|
||||
ArrayNode insufficientDataActions = node.putArray("InsufficientDataActions");
|
||||
a.getInsufficientDataActions().forEach(insufficientDataActions::add);
|
||||
node.put("ActionsEnabled", a.isActionsEnabled());
|
||||
if (a.getStateValue() != null) {
|
||||
node.put("StateValue", a.getStateValue());
|
||||
}
|
||||
if (a.getStateReason() != null) {
|
||||
node.put("StateReason", a.getStateReason());
|
||||
}
|
||||
if (a.getStateReasonData() != null) {
|
||||
node.put("StateReasonData", a.getStateReasonData());
|
||||
}
|
||||
node.put("StateUpdatedTimestamp", a.getStateUpdatedTimestamp());
|
||||
node.put("AlarmConfigurationUpdatedTimestamp", a.getAlarmConfigurationUpdatedTimestamp());
|
||||
}
|
||||
|
||||
private Response handleDeleteAlarms(JsonNode request, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
JsonNode namesNode = request.path("AlarmNames");
|
||||
@@ -586,12 +669,18 @@ public class CloudWatchMetricsJsonHandler {
|
||||
return configurations;
|
||||
}
|
||||
|
||||
private List<MetricDatum> parseMetricDataJson(JsonNode node) {
|
||||
private List<MetricDatum> parseMetricDataJson(JsonNode node, String listPath) {
|
||||
List<MetricDatum> datums = new ArrayList<>();
|
||||
if (!node.isArray()) return datums;
|
||||
int index = 0;
|
||||
for (JsonNode item : node) {
|
||||
index++;
|
||||
JsonNode metricName = item.path("MetricName");
|
||||
if (!metricName.isTextual() || metricName.asText().isEmpty()) {
|
||||
throw CloudWatchMetricsException.missingParameter(listPath + ".member." + index + ".MetricName");
|
||||
}
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(item.path("MetricName").asText());
|
||||
datum.setMetricName(metricName.asText());
|
||||
datum.setValue(item.path("Value").asDouble(0));
|
||||
datum.setUnit(item.path("Unit").asText(null));
|
||||
JsonNode ts = item.path("Timestamp");
|
||||
|
||||
+207
-70
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
@@ -7,10 +8,17 @@ import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.model.Dashboard;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStream;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamFilter;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.model.MetricStreamStatisticsConfiguration;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.AlarmMetricDataQuery;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -25,11 +33,16 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jboss.logging.Logger;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchMetricsQueryHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsQueryHandler.class);
|
||||
private static final Pattern ENTITY_METRIC_DATA_MEMBER = Pattern.compile("EntityMetricData\\.member\\.(\\d{1,9})\\.");
|
||||
|
||||
private CloudWatchMetricsService metricsService;
|
||||
private final CloudWatchDashboardsService dashboardsService;
|
||||
@@ -52,6 +65,7 @@ public class CloudWatchMetricsQueryHandler {
|
||||
case "GetMetricStatistics" -> handleGetMetricStatistics(params, region);
|
||||
case "GetMetricData" -> handleGetMetricData(params, region);
|
||||
case "PutMetricAlarm" -> handlePutMetricAlarm(params, region);
|
||||
case "PutCompositeAlarm" -> handlePutCompositeAlarm(params, region);
|
||||
case "DescribeAlarms" -> handleDescribeAlarms(params, region);
|
||||
case "DeleteAlarms" -> handleDeleteAlarms(params, region);
|
||||
case "SetAlarmState" -> handleSetAlarmState(params, region);
|
||||
@@ -153,7 +167,8 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.elem("Unit", dp.unit()).end("member");
|
||||
}
|
||||
xml.end("Datapoints");
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricStatistics", AwsNamespaces.CW, xml.build())).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("GetMetricStatistics",
|
||||
AwsNamespaces.CW, xml.build())).build();
|
||||
}
|
||||
|
||||
private Response handleGetMetricData(MultivaluedMap<String, String> params, String region) {
|
||||
@@ -237,6 +252,26 @@ public class CloudWatchMetricsQueryHandler {
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("PutMetricAlarm", null)).build();
|
||||
}
|
||||
|
||||
private Response handlePutCompositeAlarm(MultivaluedMap<String, String> params, String region) {
|
||||
if (params.containsKey("ActionsSuppressor") || params.containsKey("ActionsSuppressorWaitPeriod")
|
||||
|| params.containsKey("ActionsSuppressorExtensionPeriod")) {
|
||||
throw new AwsException("ValidationError", "Composite action suppression is not supported", 400);
|
||||
}
|
||||
CompositeAlarm alarm = new CompositeAlarm();
|
||||
parseAlarmFields(params, alarm);
|
||||
alarm.setAlarmRule(params.getFirst("AlarmRule"));
|
||||
metricsService.putCompositeAlarm(alarm, region);
|
||||
return Response.ok(AwsQueryResponse.envelopeNoResult("PutCompositeAlarm", null)).build();
|
||||
}
|
||||
|
||||
private static List<String> alarmMembers(MultivaluedMap<String, String> params, String key) {
|
||||
List<String> values = new ArrayList<>();
|
||||
for (int i = 1; params.getFirst(key + ".member." + i) != null; i++) {
|
||||
values.add(params.getFirst(key + ".member." + i));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private Response handleDescribeAlarms(MultivaluedMap<String, String> params, String region) {
|
||||
List<String> alarmNames = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
@@ -246,13 +281,24 @@ public class CloudWatchMetricsQueryHandler {
|
||||
}
|
||||
String prefix = params.getFirst("AlarmNamePrefix");
|
||||
|
||||
List<MetricAlarm> alarms = metricsService.describeAlarms(alarmNames, prefix, region);
|
||||
List<String> types = alarmMembers(params, "AlarmTypes");
|
||||
metricsService.validateAlarmTypes(types);
|
||||
List<MetricAlarm> alarms = types.isEmpty() || types.contains("MetricAlarm")
|
||||
? metricsService.describeAlarms(alarmNames, prefix, region) : List.of();
|
||||
|
||||
var xml = new XmlBuilder().start("MetricAlarms");
|
||||
for (MetricAlarm a : alarms) {
|
||||
toAlarmXml(xml, a);
|
||||
}
|
||||
xml.end("MetricAlarms");
|
||||
xml.end("MetricAlarms").start("CompositeAlarms");
|
||||
if (types.contains("CompositeAlarm")) {
|
||||
for (CompositeAlarm alarm : metricsService.describeCompositeAlarms(alarmNames, prefix, region)) {
|
||||
xml.start("member");
|
||||
describeAlarmFields(xml, alarm);
|
||||
xml.elem("AlarmRule", alarm.getAlarmRule()).end("member");
|
||||
}
|
||||
}
|
||||
xml.end("CompositeAlarms").start("LogAlarms").end("LogAlarms");
|
||||
return Response.ok(AwsQueryResponse.envelope("DescribeAlarms", null, xml.build())).build();
|
||||
}
|
||||
|
||||
@@ -590,42 +636,63 @@ public class CloudWatchMetricsQueryHandler {
|
||||
// ──────────────────────────── Parsing Helpers ────────────────────────────
|
||||
|
||||
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params) {
|
||||
LOG.infov("Query PutMetricData params: {0}", params);
|
||||
List<MetricDatum> datums = parseMetricData(params, "MetricData");
|
||||
// An empty EntityMetricData entry serializes to no keys, so its index is absent
|
||||
// while later entries keep theirs: iterate the indexes present, not 1..first gap.
|
||||
SortedSet<Integer> entityIndexes = new TreeSet<>();
|
||||
for (String key : params.keySet()) {
|
||||
Matcher matcher = ENTITY_METRIC_DATA_MEMBER.matcher(key);
|
||||
if (matcher.lookingAt()) {
|
||||
entityIndexes.add(Integer.parseInt(matcher.group(1)));
|
||||
}
|
||||
}
|
||||
for (int index : entityIndexes) {
|
||||
datums.addAll(parseMetricData(params, "EntityMetricData.member." + index + ".MetricData"));
|
||||
}
|
||||
LOG.debugv("Query PutMetricData parsed {0} datums", datums.size());
|
||||
return datums;
|
||||
}
|
||||
|
||||
private List<MetricDatum> parseMetricData(MultivaluedMap<String, String> params, String listPrefix) {
|
||||
List<MetricDatum> datums = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String metricName = params.getFirst("MetricData.member." + i + ".MetricName");
|
||||
if (metricName == null) {
|
||||
break;
|
||||
String memberPrefix = listPrefix + ".member." + i + ".";
|
||||
String metricName = params.getFirst(memberPrefix + "MetricName");
|
||||
if (metricName == null || metricName.isEmpty()) {
|
||||
if (metricName == null && params.keySet().stream().noneMatch(key -> key.startsWith(memberPrefix))) {
|
||||
break;
|
||||
}
|
||||
throw CloudWatchMetricsException.missingParameter(memberPrefix + "MetricName");
|
||||
}
|
||||
MetricDatum datum = new MetricDatum();
|
||||
datum.setMetricName(metricName);
|
||||
datum.setUnit(params.getFirst("MetricData.member." + i + ".Unit"));
|
||||
datum.setUnit(params.getFirst(listPrefix + ".member." + i + ".Unit"));
|
||||
|
||||
String valueStr = params.getFirst("MetricData.member." + i + ".Value");
|
||||
String valueStr = params.getFirst(listPrefix + ".member." + i + ".Value");
|
||||
if (valueStr != null) {
|
||||
datum.setValue(parseDouble(valueStr, 0));
|
||||
}
|
||||
|
||||
String tsStr = params.getFirst("MetricData.member." + i + ".Timestamp");
|
||||
String tsStr = params.getFirst(listPrefix + ".member." + i + ".Timestamp");
|
||||
if (tsStr != null) {
|
||||
Instant ts = parseInstant(tsStr);
|
||||
datum.setTimestamp(ts != null ? ts.getEpochSecond() : 0);
|
||||
}
|
||||
|
||||
// StatisticValues
|
||||
String sc = params.getFirst("MetricData.member." + i + ".StatisticValues.SampleCount");
|
||||
String sc = params.getFirst(listPrefix + ".member." + i + ".StatisticValues.SampleCount");
|
||||
if (sc != null) {
|
||||
datum.setSampleCount(parseDouble(sc, 0));
|
||||
datum.setSum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Sum"), 0));
|
||||
datum.setMinimum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Minimum"), 0));
|
||||
datum.setMaximum(parseDouble(params.getFirst("MetricData.member." + i + ".StatisticValues.Maximum"), 0));
|
||||
datum.setSum(parseDouble(params.getFirst(listPrefix + ".member." + i + ".StatisticValues.Sum"), 0));
|
||||
datum.setMinimum(parseDouble(params.getFirst(listPrefix + ".member." + i + ".StatisticValues.Minimum"), 0));
|
||||
datum.setMaximum(parseDouble(params.getFirst(listPrefix + ".member." + i + ".StatisticValues.Maximum"), 0));
|
||||
}
|
||||
|
||||
// Dimensions
|
||||
List<Dimension> dims = new ArrayList<>();
|
||||
for (int j = 1; ; j++) {
|
||||
String dimName = params.getFirst("MetricData.member." + i + ".Dimensions.member." + j + ".Name");
|
||||
String dimValue = params.getFirst("MetricData.member." + i + ".Dimensions.member." + j + ".Value");
|
||||
String dimName = params.getFirst(listPrefix + ".member." + i + ".Dimensions.member." + j + ".Name");
|
||||
String dimValue = params.getFirst(listPrefix + ".member." + i + ".Dimensions.member." + j + ".Value");
|
||||
if (dimName == null) {
|
||||
break;
|
||||
}
|
||||
@@ -653,14 +720,12 @@ public class CloudWatchMetricsQueryHandler {
|
||||
|
||||
private MetricAlarm parseAlarm(MultivaluedMap<String, String> params) {
|
||||
MetricAlarm a = new MetricAlarm();
|
||||
a.setAlarmName(params.getFirst("AlarmName"));
|
||||
a.setAlarmDescription(params.getFirst("AlarmDescription"));
|
||||
String actionsEnabled = params.getFirst("ActionsEnabled");
|
||||
a.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled));
|
||||
parseAlarmFields(params, a);
|
||||
a.setMetricName(params.getFirst("MetricName"));
|
||||
a.setNamespace(params.getFirst("Namespace"));
|
||||
a.setStatistic(params.getFirst("Statistic"));
|
||||
a.setPeriod(parseIntParam(params, "Period", 60));
|
||||
a.setMetrics(parseAlarmMetricQueries(params));
|
||||
a.setPeriod(a.getMetrics().isEmpty() ? parseIntParam(params, "Period", 60) : null);
|
||||
a.setUnit(params.getFirst("Unit"));
|
||||
a.setEvaluationPeriods(parseIntParam(params, "EvaluationPeriods", 1));
|
||||
String datapointsToAlarm = params.getFirst("DatapointsToAlarm");
|
||||
@@ -680,38 +745,100 @@ public class CloudWatchMetricsQueryHandler {
|
||||
}
|
||||
a.setDimensions(dims);
|
||||
|
||||
// Actions
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("OKActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getOkActions().add(act);
|
||||
}
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("AlarmActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getAlarmActions().add(act);
|
||||
}
|
||||
for (int i = 1; ; i++) {
|
||||
String act = params.getFirst("InsufficientDataActions.member." + i);
|
||||
if (act == null) break;
|
||||
a.getInsufficientDataActions().add(act);
|
||||
}
|
||||
|
||||
// Tags
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String key = params.getFirst("Tags.member." + i + ".Key");
|
||||
if (key == null) break;
|
||||
tags.put(key, params.getFirst("Tags.member." + i + ".Value"));
|
||||
}
|
||||
a.setTags(tags);
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
private void parseAlarmFields(MultivaluedMap<String, String> params, Alarm alarm) {
|
||||
alarm.setAlarmName(params.getFirst("AlarmName"));
|
||||
alarm.setAlarmDescription(params.getFirst("AlarmDescription"));
|
||||
String actionsEnabled = params.getFirst("ActionsEnabled");
|
||||
alarm.setActionsEnabled(actionsEnabled == null || Boolean.parseBoolean(actionsEnabled));
|
||||
alarm.setAlarmActions(alarmMembers(params, "AlarmActions"));
|
||||
alarm.setOkActions(alarmMembers(params, "OKActions"));
|
||||
alarm.setInsufficientDataActions(alarmMembers(params, "InsufficientDataActions"));
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (int i = 1; params.getFirst("Tags.member." + i + ".Key") != null; i++) {
|
||||
tags.put(params.getFirst("Tags.member." + i + ".Key"), params.getFirst("Tags.member." + i + ".Value"));
|
||||
}
|
||||
alarm.setTags(tags);
|
||||
}
|
||||
|
||||
private List<AlarmMetricDataQuery> parseAlarmMetricQueries(MultivaluedMap<String, String> params) {
|
||||
List<AlarmMetricDataQuery> queries = new ArrayList<>();
|
||||
for (int index = 1; ; index++) {
|
||||
String prefix = "Metrics.member." + index;
|
||||
String id = params.getFirst(prefix + ".Id");
|
||||
if (id == null) {
|
||||
break;
|
||||
}
|
||||
AlarmMetricDataQuery.MetricStat metricStat = null;
|
||||
String metricPrefix = prefix + ".MetricStat.Metric";
|
||||
if (params.getFirst(metricPrefix + ".Namespace") != null) {
|
||||
List<AlarmMetricDataQuery.MetricDimension> dimensions = null;
|
||||
for (int dimensionIndex = 1; ; dimensionIndex++) {
|
||||
String dimensionPrefix = metricPrefix + ".Dimensions.member." + dimensionIndex;
|
||||
String name = params.getFirst(dimensionPrefix + ".Name");
|
||||
if (name == null) {
|
||||
break;
|
||||
}
|
||||
if (dimensions == null) {
|
||||
dimensions = new ArrayList<>();
|
||||
}
|
||||
dimensions.add(new AlarmMetricDataQuery.MetricDimension(
|
||||
name, params.getFirst(dimensionPrefix + ".Value")));
|
||||
}
|
||||
AlarmMetricDataQuery.Metric metric = new AlarmMetricDataQuery.Metric(
|
||||
params.getFirst(metricPrefix + ".Namespace"),
|
||||
params.getFirst(metricPrefix + ".MetricName"), dimensions);
|
||||
metricStat = new AlarmMetricDataQuery.MetricStat(metric,
|
||||
optionalInteger(params.getFirst(prefix + ".MetricStat.Period")),
|
||||
params.getFirst(prefix + ".MetricStat.Stat"), params.getFirst(prefix + ".MetricStat.Unit"));
|
||||
}
|
||||
String returnData = params.getFirst(prefix + ".ReturnData");
|
||||
queries.add(new AlarmMetricDataQuery(id, params.getFirst(prefix + ".Expression"),
|
||||
params.getFirst(prefix + ".Label"), returnData == null ? null : Boolean.valueOf(returnData),
|
||||
optionalInteger(params.getFirst(prefix + ".Period")),
|
||||
params.getFirst(prefix + ".AccountId"), metricStat));
|
||||
}
|
||||
return queries;
|
||||
}
|
||||
|
||||
private static Integer optionalInteger(String value) {
|
||||
return value == null ? null : Integer.valueOf(value);
|
||||
}
|
||||
|
||||
private void toAlarmXml(XmlBuilder xml, MetricAlarm a) {
|
||||
xml.start("member")
|
||||
.elem("AlarmName", a.getAlarmName())
|
||||
xml.start("member");
|
||||
describeAlarmFields(xml, a);
|
||||
if (!a.getMetrics().isEmpty()) {
|
||||
toAlarmMetricsXml(xml, a.getMetrics());
|
||||
} else {
|
||||
xml.start("Dimensions");
|
||||
for (Dimension d : a.getDimensions()) {
|
||||
xml.start("member").elem("Name", d.name()).elem("Value", d.value()).end("member");
|
||||
}
|
||||
xml.end("Dimensions")
|
||||
.elem("MetricName", a.getMetricName())
|
||||
.elem("Namespace", a.getNamespace())
|
||||
.elem("Statistic", a.getStatistic())
|
||||
.elem("Period", a.getPeriod() == null ? null : a.getPeriod().toString())
|
||||
.elem("Unit", a.getUnit());
|
||||
}
|
||||
|
||||
xml.elem("EvaluationPeriods", String.valueOf(a.getEvaluationPeriods()))
|
||||
.elem("Threshold", String.valueOf(a.getThreshold()))
|
||||
.elem("ComparisonOperator", a.getComparisonOperator())
|
||||
.elem("TreatMissingData", a.getTreatMissingData());
|
||||
// Only an alarm the caller gave an M for carries the member, matching what AWS returns.
|
||||
if (a.getDatapointsToAlarm() != null) {
|
||||
xml.elem("DatapointsToAlarm", String.valueOf(a.getDatapointsToAlarm()));
|
||||
}
|
||||
|
||||
xml.end("member");
|
||||
}
|
||||
|
||||
private void describeAlarmFields(XmlBuilder xml, Alarm a) {
|
||||
xml.elem("AlarmName", a.getAlarmName())
|
||||
.elem("AlarmArn", a.getAlarmArn())
|
||||
.elem("AlarmDescription", a.getAlarmDescription());
|
||||
xml.start("AlarmActions");
|
||||
@@ -726,31 +853,41 @@ public class CloudWatchMetricsQueryHandler {
|
||||
xml.start("InsufficientDataActions");
|
||||
a.getInsufficientDataActions().forEach(act -> xml.elem("member", act));
|
||||
xml.end("InsufficientDataActions");
|
||||
xml.start("Dimensions");
|
||||
for (Dimension d : a.getDimensions()) {
|
||||
xml.start("member").elem("Name", d.name()).elem("Value", d.value()).end("member");
|
||||
}
|
||||
xml.end("Dimensions");
|
||||
|
||||
xml.elem("StateValue", a.getStateValue())
|
||||
.elem("StateReason", a.getStateReason())
|
||||
.elem("StateReasonData", a.getStateReasonData())
|
||||
.elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString())
|
||||
.elem("MetricName", a.getMetricName())
|
||||
.elem("Namespace", a.getNamespace())
|
||||
.elem("Statistic", a.getStatistic())
|
||||
.elem("Period", String.valueOf(a.getPeriod()))
|
||||
.elem("Unit", a.getUnit())
|
||||
.elem("EvaluationPeriods", String.valueOf(a.getEvaluationPeriods()))
|
||||
.elem("Threshold", String.valueOf(a.getThreshold()))
|
||||
.elem("ComparisonOperator", a.getComparisonOperator())
|
||||
.elem("TreatMissingData", a.getTreatMissingData());
|
||||
// Only an alarm the caller gave an M for carries the member, matching what AWS returns.
|
||||
if (a.getDatapointsToAlarm() != null) {
|
||||
xml.elem("DatapointsToAlarm", String.valueOf(a.getDatapointsToAlarm()));
|
||||
}
|
||||
.elem("StateUpdatedTimestamp", Instant.ofEpochSecond(a.getStateUpdatedTimestamp()).toString());
|
||||
}
|
||||
|
||||
xml.end("member");
|
||||
private void toAlarmMetricsXml(XmlBuilder xml, List<AlarmMetricDataQuery> metrics) {
|
||||
xml.start("Metrics");
|
||||
for (AlarmMetricDataQuery query : metrics) {
|
||||
xml.start("member").elem("Id", query.id()).elem("Expression", query.expression())
|
||||
.elem("Label", query.label()).elem("AccountId", query.accountId())
|
||||
.elem("Period", query.period() == null ? null : query.period().toString())
|
||||
.elem("ReturnData", query.returnData() == null ? null : query.returnData().toString());
|
||||
AlarmMetricDataQuery.MetricStat stat = query.metricStat();
|
||||
if (stat != null) {
|
||||
xml.start("MetricStat");
|
||||
AlarmMetricDataQuery.Metric metric = stat.metric();
|
||||
if (metric != null) {
|
||||
xml.start("Metric").elem("Namespace", metric.namespace()).elem("MetricName", metric.metricName());
|
||||
if (metric.dimensions() != null) {
|
||||
xml.start("Dimensions");
|
||||
for (AlarmMetricDataQuery.MetricDimension dimension : metric.dimensions()) {
|
||||
xml.start("member").elem("Name", dimension.name()).elem("Value", dimension.value())
|
||||
.end("member");
|
||||
}
|
||||
xml.end("Dimensions");
|
||||
}
|
||||
xml.end("Metric");
|
||||
}
|
||||
xml.elem("Period", stat.period() == null ? null : stat.period().toString())
|
||||
.elem("Stat", stat.stat()).elem("Unit", stat.unit()).end("MetricStat");
|
||||
}
|
||||
xml.end("member");
|
||||
}
|
||||
xml.end("Metrics");
|
||||
}
|
||||
|
||||
private Instant parseInstant(String value) {
|
||||
|
||||
+291
-57
@@ -1,10 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
@@ -14,11 +19,16 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -27,25 +37,41 @@ public class CloudWatchMetricsService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchMetricsService.class);
|
||||
|
||||
private static final List<String> ALARM_TYPES = List.of("CompositeAlarm", "MetricAlarm", "LogAlarm");
|
||||
|
||||
private final StorageBackend<String, MetricDatum> metricStore;
|
||||
private final StorageBackend<String, MetricAlarm> alarmStore;
|
||||
private final StorageBackend<String, Alarm> alarmStore;
|
||||
private final RegionResolver regionResolver;
|
||||
private final AlarmSnsNotifier alarmSnsNotifier;
|
||||
|
||||
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
this(storageFactory, regionResolver, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
public CloudWatchMetricsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
AlarmSnsNotifier alarmSnsNotifier) {
|
||||
this.metricStore = storageFactory.create("cloudwatchmetrics", "cwmetrics.json",
|
||||
new TypeReference<Map<String, MetricDatum>>() {});
|
||||
this.alarmStore = storageFactory.create("cloudwatchmetrics", "cwalarms.json",
|
||||
new TypeReference<Map<String, MetricAlarm>>() {});
|
||||
new TypeReference<Map<String, Alarm>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
this.alarmSnsNotifier = alarmSnsNotifier;
|
||||
}
|
||||
|
||||
CloudWatchMetricsService(StorageBackend<String, MetricDatum> metricStore,
|
||||
StorageBackend<String, MetricAlarm> alarmStore,
|
||||
StorageBackend<String, Alarm> alarmStore,
|
||||
RegionResolver regionResolver) {
|
||||
this(metricStore, alarmStore, regionResolver, null);
|
||||
}
|
||||
|
||||
CloudWatchMetricsService(StorageBackend<String, MetricDatum> metricStore,
|
||||
StorageBackend<String, Alarm> alarmStore,
|
||||
RegionResolver regionResolver, AlarmSnsNotifier alarmSnsNotifier) {
|
||||
this.metricStore = metricStore;
|
||||
this.alarmStore = alarmStore;
|
||||
this.regionResolver = regionResolver;
|
||||
this.alarmSnsNotifier = alarmSnsNotifier;
|
||||
}
|
||||
|
||||
public void putMetricData(String namespace, List<MetricDatum> datums, String region) {
|
||||
@@ -282,85 +308,293 @@ public class CloudWatchMetricsService {
|
||||
};
|
||||
}
|
||||
|
||||
public void putMetricAlarm(MetricAlarm alarm, String region) {
|
||||
public synchronized void putMetricAlarm(MetricAlarm alarm, String region) {
|
||||
putAlarm(alarm, region);
|
||||
evaluateComposites(region, Set.of(alarm.getAlarmName()), null);
|
||||
}
|
||||
|
||||
public void putCompositeAlarm(CompositeAlarm alarm, String region) {
|
||||
putCompositeAlarm(alarm, region, true);
|
||||
}
|
||||
|
||||
public synchronized void putCompositeAlarm(CompositeAlarm alarm, String region, boolean replaceExisting) {
|
||||
if (!replaceExisting && alarmStore.get(region + "::" + alarm.getAlarmName()).isPresent()) {
|
||||
throw new AwsException("AlreadyExists", "Alarm already exists: " + alarm.getAlarmName(), 400);
|
||||
}
|
||||
Set<String> references = alarmReferences(alarm, region);
|
||||
if (references.size() > 100) {
|
||||
throw new AwsException("LimitExceeded", "AlarmRule references more than 100 child alarms", 400);
|
||||
}
|
||||
List<CompositeAlarm> existing = describeCompositeAlarms(null, null, region);
|
||||
for (String reference : references) {
|
||||
long parents = existing.stream().filter(parent -> !parent.getAlarmName().equals(alarm.getAlarmName()))
|
||||
.filter(parent -> alarmReferences(parent, region).contains(reference))
|
||||
.count();
|
||||
if (parents >= 150) {
|
||||
throw new AwsException("LimitExceeded", "An alarm can be referenced by at most 150 composite alarms", 400);
|
||||
}
|
||||
}
|
||||
boolean created = alarmStore.get(region + "::" + alarm.getAlarmName()).isEmpty();
|
||||
putAlarm(alarm, region);
|
||||
if (created) {
|
||||
evaluateComposites(region, Set.of(), alarm.getAlarmName());
|
||||
}
|
||||
}
|
||||
|
||||
private Set<String> alarmReferences(CompositeAlarm alarm, String region) {
|
||||
return CompositeAlarmRule.parse(alarm.getAlarmRule()).references().stream()
|
||||
.map(reference -> AwsArnUtils.isArn(reference) ? reference
|
||||
: regionResolver.buildArn("cloudwatch", region, "alarm:" + reference))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private void putAlarm(Alarm alarm, String region) {
|
||||
String name = alarm.getAlarmName();
|
||||
if (name == null || name.isBlank() || name.length() > 255) {
|
||||
throw SmithyValidationErrors.validationError(name == null ? SmithyValidationErrors.notNull("alarmName")
|
||||
: "Value '" + name + "' at 'alarmName' failed to satisfy constraint: Member must have length "
|
||||
+ (name.length() > 255 ? "less than or equal to 255" : "greater than or equal to 1"));
|
||||
}
|
||||
Alarm previous = alarmStore.get(region + "::" + name).orElse(null);
|
||||
if (previous != null) {
|
||||
if (!previous.getClass().equals(alarm.getClass())) {
|
||||
throw new AwsException("ValidationError", "An alarm of another type already has this name", 400);
|
||||
}
|
||||
if (alarm instanceof CompositeAlarm) {
|
||||
alarm.setStateValue(previous.getStateValue());
|
||||
alarm.setStateReason(previous.getStateReason());
|
||||
alarm.setStateReasonData(previous.getStateReasonData());
|
||||
alarm.setStateUpdatedTimestamp(previous.getStateUpdatedTimestamp());
|
||||
alarm.setTags(new HashMap<>(previous.getTags()));
|
||||
}
|
||||
}
|
||||
if (alarm.getAlarmArn() == null) {
|
||||
alarm.setAlarmArn(regionResolver.buildArn("cloudwatch", region, "alarm:" + alarm.getAlarmName()));
|
||||
alarm.setAlarmArn(regionResolver.buildArn("cloudwatch", region, "alarm:" + name));
|
||||
}
|
||||
alarm.setRegion(region);
|
||||
alarm.setAlarmConfigurationUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
LOG.infov("PutMetricAlarm: {0} in {1}", alarm.getAlarmName(), region);
|
||||
alarmStore.put(region + "::" + name, alarm);
|
||||
LOG.infov("Put {0}: {1} in {2}", alarm.getClass().getSimpleName(), name, region);
|
||||
}
|
||||
|
||||
/** Every stored alarm, across all regions. Used by the background {@link AlarmEvaluator}
|
||||
* tick, which has no per-request region to scope a lookup to. */
|
||||
/** Metric alarms evaluated by the existing metric evaluator. */
|
||||
public List<MetricAlarm> allAlarms() {
|
||||
return alarmStore.scan(k -> true);
|
||||
return alarmStore.scan(k -> true).stream().filter(MetricAlarm.class::isInstance)
|
||||
.map(MetricAlarm.class::cast).toList();
|
||||
}
|
||||
|
||||
public List<MetricAlarm> describeAlarms(List<String> alarmNames, String alarmNamePrefix, String region) {
|
||||
String prefix = region + "::";
|
||||
List<MetricAlarm> all = alarmStore.scan(k -> k.startsWith(prefix));
|
||||
|
||||
if (alarmNames != null && !alarmNames.isEmpty()) {
|
||||
return all.stream().filter(a -> alarmNames.contains(a.getAlarmName())).toList();
|
||||
}
|
||||
if (alarmNamePrefix != null && !alarmNamePrefix.isBlank()) {
|
||||
return all.stream().filter(a -> a.getAlarmName().startsWith(alarmNamePrefix)).toList();
|
||||
}
|
||||
return all;
|
||||
public List<MetricAlarm> describeAlarms(List<String> names, String prefix, String region) {
|
||||
return matchingAlarms(names, prefix, region).stream().filter(MetricAlarm.class::isInstance)
|
||||
.map(MetricAlarm.class::cast).toList();
|
||||
}
|
||||
|
||||
public void deleteAlarms(List<String> alarmNames, String region) {
|
||||
public void validateAlarmTypes(List<String> types) {
|
||||
if (!ALARM_TYPES.containsAll(types)) {
|
||||
throw SmithyValidationErrors.validationError(
|
||||
SmithyValidationErrors.notAllInEnum(types, "alarmTypes", ALARM_TYPES));
|
||||
}
|
||||
}
|
||||
|
||||
public List<CompositeAlarm> describeCompositeAlarms(List<String> names, String prefix, String region) {
|
||||
return matchingAlarms(names, prefix, region).stream().filter(CompositeAlarm.class::isInstance)
|
||||
.map(CompositeAlarm.class::cast).toList();
|
||||
}
|
||||
|
||||
private List<Alarm> matchingAlarms(List<String> names, String prefix, String region) {
|
||||
return alarmStore.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(a -> names == null || names.isEmpty() || names.contains(a.getAlarmName()))
|
||||
.filter(a -> prefix == null || a.getAlarmName().startsWith(prefix)).toList();
|
||||
}
|
||||
|
||||
private Map<String, Alarm> alarmIndex(String region) {
|
||||
Map<String, Alarm> alarms = new HashMap<>();
|
||||
for (Alarm alarm : alarmStore.scan(k -> k.startsWith(region + "::"))) {
|
||||
alarms.put(alarm.getAlarmName(), alarm);
|
||||
alarms.put(alarm.getAlarmArn(), alarm);
|
||||
}
|
||||
return alarms;
|
||||
}
|
||||
|
||||
private void evaluateComposites(String region, Set<String> changedAlarmNames, String newAlarm) {
|
||||
if (changedAlarmNames.isEmpty() && newAlarm == null) {
|
||||
return;
|
||||
}
|
||||
Map<String, Alarm> alarms = alarmIndex(region);
|
||||
Set<String> changed = new HashSet<>(changedAlarmNames);
|
||||
for (String name : changedAlarmNames) {
|
||||
changed.add(regionResolver.buildArn("cloudwatch", region, "alarm:" + name));
|
||||
}
|
||||
Map<String, CompositeAlarmRule.Rule> candidates = new HashMap<>();
|
||||
for (Alarm alarm : new HashSet<>(alarms.values())) {
|
||||
if (alarm instanceof CompositeAlarm composite && !changedAlarmNames.contains(alarm.getAlarmName())) {
|
||||
candidates.put(alarm.getAlarmName(), CompositeAlarmRule.parse(composite.getAlarmRule()));
|
||||
}
|
||||
}
|
||||
Set<String> affected = new HashSet<>(changed);
|
||||
Map<String, CompositeAlarmRule.Rule> pending = new HashMap<>();
|
||||
boolean discovered;
|
||||
do {
|
||||
discovered = false;
|
||||
Iterator<Map.Entry<String, CompositeAlarmRule.Rule>> iterator = candidates.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, CompositeAlarmRule.Rule> next = iterator.next();
|
||||
if (next.getKey().equals(newAlarm) || next.getValue().references().stream().anyMatch(affected::contains)) {
|
||||
pending.put(next.getKey(), next.getValue());
|
||||
affected.add(next.getKey());
|
||||
affected.add(alarms.get(next.getKey()).getAlarmArn());
|
||||
iterator.remove();
|
||||
discovered = true;
|
||||
}
|
||||
}
|
||||
} while (discovered);
|
||||
Set<String> cycles = pending.keySet().stream()
|
||||
.filter(name -> isCyclic(name, alarms)).collect(Collectors.toSet());
|
||||
boolean progress;
|
||||
do {
|
||||
progress = false;
|
||||
Iterator<Map.Entry<String, CompositeAlarmRule.Rule>> iterator = pending.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry<String, CompositeAlarmRule.Rule> next = iterator.next();
|
||||
boolean blocked = next.getValue().references().stream().map(alarms::get)
|
||||
.anyMatch(child -> child != null && pending.containsKey(child.getAlarmName()));
|
||||
if (blocked || cycles.contains(next.getKey())) {
|
||||
continue;
|
||||
}
|
||||
if (!next.getKey().equals(newAlarm)
|
||||
&& next.getValue().references().stream().noneMatch(changed::contains)) {
|
||||
iterator.remove();
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
Alarm alarm = alarms.get(next.getKey());
|
||||
boolean triggered = next.getValue().evaluate(reference -> {
|
||||
Alarm child = alarms.get(reference);
|
||||
return child == null ? null : child.getStateValue();
|
||||
});
|
||||
String state = triggered ? "ALARM" : "OK";
|
||||
if (!state.equals(alarm.getStateValue())) {
|
||||
alarm.setStateValue(state);
|
||||
alarm.setStateReason("AlarmRule evaluated to " + state);
|
||||
alarm.setStateReasonData(null);
|
||||
alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
changed.add(alarm.getAlarmName());
|
||||
changed.add(alarm.getAlarmArn());
|
||||
}
|
||||
iterator.remove();
|
||||
progress = true;
|
||||
}
|
||||
} while (progress && !pending.isEmpty());
|
||||
if (!pending.isEmpty()) {
|
||||
LOG.debugv("Composite alarm evaluation stopped at cyclic dependencies: {0}", pending.keySet());
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void deleteAlarms(List<String> alarmNames, String region) {
|
||||
Map<String, Alarm> alarms = alarmIndex(region);
|
||||
long composites = alarmNames.stream().map(alarms::get).filter(CompositeAlarm.class::isInstance).count();
|
||||
if (composites > 1) {
|
||||
throw new AwsException("ValidationError", "DeleteAlarms accepts at most one composite alarm", 400);
|
||||
}
|
||||
for (String name : alarmNames) {
|
||||
if (isCyclic(name, alarms)) {
|
||||
throw new AwsException("ValidationError", "Break the composite alarm cycle before deleting " + name, 400);
|
||||
}
|
||||
}
|
||||
Set<String> deletedNames = new HashSet<>();
|
||||
for (String name : alarmNames) {
|
||||
if (alarmStore.get(region + "::" + name).isPresent()) {
|
||||
deletedNames.add(name);
|
||||
}
|
||||
alarmStore.delete(region + "::" + name);
|
||||
}
|
||||
evaluateComposites(region, deletedNames, null);
|
||||
LOG.infov("Deleted alarms: {0} in {1}", alarmNames, region);
|
||||
}
|
||||
|
||||
public void setAlarmState(String alarmName, String stateValue, String stateReason, String stateReasonData, String region) {
|
||||
String key = region + "::" + alarmName;
|
||||
MetricAlarm alarm = alarmStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFound", "Alarm not found: " + alarmName, 404));
|
||||
|
||||
alarm.setStateValue(stateValue);
|
||||
alarm.setStateReason(stateReason);
|
||||
alarm.setStateReasonData(stateReasonData);
|
||||
alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
|
||||
alarmStore.put(key, alarm);
|
||||
LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue);
|
||||
private boolean isCyclic(String name, Map<String, Alarm> alarms) {
|
||||
Set<String> visited = new HashSet<>();
|
||||
ArrayDeque<String> pending = new ArrayDeque<>();
|
||||
pending.add(name);
|
||||
while (!pending.isEmpty()) {
|
||||
Alarm next = alarms.get(pending.remove());
|
||||
if (next instanceof CompositeAlarm composite && visited.add(next.getAlarmName())) {
|
||||
for (String reference : CompositeAlarmRule.parse(composite.getAlarmRule()).references()) {
|
||||
Alarm child = alarms.get(reference);
|
||||
if (child != null && child.getAlarmName().equals(name)) {
|
||||
return true;
|
||||
}
|
||||
if (child != null) {
|
||||
pending.add(child.getAlarmName());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
public void setAlarmState(String alarmName, String stateValue, String stateReason, String stateReasonData, String region) {
|
||||
List<AlarmSnsNotifier.Notification> notifications = List.of();
|
||||
synchronized (this) {
|
||||
String key = region + "::" + alarmName;
|
||||
Alarm alarm = alarmStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFound", "Alarm not found: " + alarmName, 404));
|
||||
|
||||
String oldState = alarm.getStateValue();
|
||||
alarm.setStateValue(stateValue);
|
||||
alarm.setStateReason(stateReason);
|
||||
alarm.setStateReasonData(stateReasonData);
|
||||
alarm.setStateUpdatedTimestamp(Instant.now().getEpochSecond());
|
||||
|
||||
alarmStore.put(key, alarm);
|
||||
evaluateComposites(region, Set.of(alarmName), null);
|
||||
LOG.infov("SetAlarmState: {0} -> {1}", alarmName, stateValue);
|
||||
if (alarmSnsNotifier != null && alarm instanceof MetricAlarm metricAlarm) {
|
||||
notifications = alarmSnsNotifier.prepareTransition(metricAlarm, oldState);
|
||||
}
|
||||
}
|
||||
if (alarmSnsNotifier != null) {
|
||||
alarmSnsNotifier.publish(notifications);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the alarm an ARN names, or reports that nothing does.
|
||||
*
|
||||
* <p>CloudWatch's three tag operations each declare {@code ResourceNotFoundException},
|
||||
* which is a different shape from the {@code ResourceNotFound} that {@code SetAlarmState}
|
||||
* and {@code GetDashboard} declare; the SDK maps the two codes to two exception classes,
|
||||
* so the tag path uses the longer one rather than the code used elsewhere in this service.
|
||||
*
|
||||
* <p>The message names the ARN rather than asserting it was an alarm, because both tag
|
||||
* handlers route every ARN that is not a dashboard and not a metric stream here. That
|
||||
* includes kinds AWS considers taggable and Floci does not serve, a Contributor Insights
|
||||
* {@code insight-rule/} ARN being the one AWS documents; reporting that no resource
|
||||
* matches the ARN is true of those, where "alarm not found" would not be.
|
||||
*/
|
||||
private Alarm requireAlarm(String resourceArn, String region) {
|
||||
return alarmStore.scan(k -> k.startsWith(region + "::"))
|
||||
.stream()
|
||||
.filter(a -> resourceArn.equals(a.getAlarmArn()))
|
||||
.filter(a -> a.getAlarmArn() != null && a.getAlarmArn().equals(resourceArn))
|
||||
.findFirst()
|
||||
.map(MetricAlarm::getTags)
|
||||
.orElse(Map.of());
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"No CloudWatch resource matches the ARN " + resourceArn + ".", 404));
|
||||
}
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
alarmStore.scan(k -> k.startsWith(region + "::"))
|
||||
.stream()
|
||||
.filter(a -> resourceArn.equals(a.getAlarmArn()))
|
||||
.findFirst()
|
||||
.ifPresent(alarm -> {
|
||||
alarm.getTags().putAll(tags);
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
});
|
||||
public synchronized Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
return new HashMap<>(requireAlarm(resourceArn, region).getTags());
|
||||
}
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
alarmStore.scan(k -> k.startsWith(region + "::"))
|
||||
.stream()
|
||||
.filter(a -> resourceArn.equals(a.getAlarmArn()))
|
||||
.findFirst()
|
||||
.ifPresent(alarm -> {
|
||||
tagKeys.forEach(alarm.getTags()::remove);
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
});
|
||||
public synchronized void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
Alarm alarm = requireAlarm(resourceArn, region);
|
||||
alarm.getTags().putAll(tags);
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
}
|
||||
|
||||
public synchronized void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
Alarm alarm = requireAlarm(resourceArn, region);
|
||||
tagKeys.forEach(alarm.getTags()::remove);
|
||||
alarmStore.put(region + "::" + alarm.getAlarmName(), alarm);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** CloudWatch's boolean alarm language, parsed completely before any alarm is stored. */
|
||||
final class CompositeAlarmRule {
|
||||
private final String input;
|
||||
private final Set<String> references = new HashSet<>();
|
||||
private int offset;
|
||||
private int elements;
|
||||
|
||||
private CompositeAlarmRule(String input) {
|
||||
this.input = input;
|
||||
}
|
||||
|
||||
static Rule parse(String input) {
|
||||
if (input == null || input.isBlank() || input.length() > 10240) {
|
||||
throw SmithyValidationErrors.validationError(input == null ? SmithyValidationErrors.notNull("alarmRule")
|
||||
: "Value '" + input + "' at 'alarmRule' failed to satisfy constraint: Member must have length "
|
||||
+ (input.length() > 10240 ? "less than or equal to 10240" : "greater than or equal to 1"));
|
||||
}
|
||||
CompositeAlarmRule parser = new CompositeAlarmRule(input);
|
||||
Expression expression = parser.or();
|
||||
parser.whitespace();
|
||||
if (parser.offset != input.length()) {
|
||||
throw invalid("Invalid AlarmRule");
|
||||
}
|
||||
return new Rule(expression, Set.copyOf(parser.references));
|
||||
}
|
||||
|
||||
private Expression or() {
|
||||
Expression left = and();
|
||||
while (word("OR")) {
|
||||
Expression prior = left;
|
||||
Expression right = and();
|
||||
left = states -> prior.evaluate(states) || right.evaluate(states);
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
private Expression and() {
|
||||
Expression left = atom();
|
||||
while (word("AND")) {
|
||||
Expression prior = left;
|
||||
Expression right = atom();
|
||||
left = states -> prior.evaluate(states) && right.evaluate(states);
|
||||
}
|
||||
return left;
|
||||
}
|
||||
|
||||
private Expression atom() {
|
||||
boolean negate = false;
|
||||
while (word("NOT")) {
|
||||
negate = !negate;
|
||||
}
|
||||
Expression operand = primary();
|
||||
return negate ? states -> !operand.evaluate(states) : operand;
|
||||
}
|
||||
|
||||
private Expression primary() {
|
||||
element();
|
||||
if (character('(')) {
|
||||
Expression nested = or();
|
||||
require(')');
|
||||
element();
|
||||
return nested;
|
||||
}
|
||||
if (word("TRUE")) {
|
||||
return states -> true;
|
||||
}
|
||||
if (word("FALSE")) {
|
||||
return states -> false;
|
||||
}
|
||||
String state;
|
||||
if (word("ALARM")) {
|
||||
state = "ALARM";
|
||||
} else if (word("OK")) {
|
||||
state = "OK";
|
||||
} else if (word("INSUFFICIENT_DATA")) {
|
||||
state = "INSUFFICIENT_DATA";
|
||||
} else {
|
||||
throw invalid("Expected an alarm state, boolean, NOT, or parenthesis");
|
||||
}
|
||||
require('(');
|
||||
whitespace();
|
||||
String name;
|
||||
if (character('"')) {
|
||||
StringBuilder quoted = new StringBuilder();
|
||||
boolean closed = false;
|
||||
while (offset < input.length()) {
|
||||
char next = input.charAt(offset++);
|
||||
if (next == '"') {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
if (next == '\\') {
|
||||
if (offset == input.length()) {
|
||||
throw invalid("Unterminated quoted alarm name");
|
||||
}
|
||||
next = input.charAt(offset++);
|
||||
if (next != '\\' && next != '"') {
|
||||
throw invalid("Invalid quoted alarm name escape");
|
||||
}
|
||||
}
|
||||
quoted.append(next);
|
||||
}
|
||||
if (!closed) {
|
||||
throw invalid("Unterminated quoted alarm name");
|
||||
}
|
||||
name = quoted.toString();
|
||||
} else {
|
||||
int start = offset;
|
||||
while (offset < input.length() && input.charAt(offset) != ')') {
|
||||
offset++;
|
||||
}
|
||||
name = input.substring(start, offset).trim();
|
||||
}
|
||||
if (name.isEmpty()) {
|
||||
throw invalid("An alarm name or ARN is required");
|
||||
}
|
||||
require(')');
|
||||
references.add(name);
|
||||
return states -> state.equals(states.apply(name));
|
||||
}
|
||||
|
||||
private void element() {
|
||||
if (++elements > 500) {
|
||||
throw invalid("AlarmRule exceeds 500 child alarms, booleans, and parentheses");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean word(String word) {
|
||||
whitespace();
|
||||
if (!input.startsWith(word, offset)) {
|
||||
return false;
|
||||
}
|
||||
int end = offset + word.length();
|
||||
if (end < input.length() && (Character.isLetterOrDigit(input.charAt(end)) || input.charAt(end) == '_')) {
|
||||
return false;
|
||||
}
|
||||
offset = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean character(char expected) {
|
||||
whitespace();
|
||||
if (offset < input.length() && input.charAt(offset) == expected) {
|
||||
offset++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void require(char expected) {
|
||||
if (!character(expected)) {
|
||||
throw invalid("Expected '" + expected + "' in AlarmRule");
|
||||
}
|
||||
}
|
||||
|
||||
private void whitespace() {
|
||||
while (offset < input.length() && Character.isWhitespace(input.charAt(offset))) {
|
||||
offset++;
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("ValidationError", message, 400);
|
||||
}
|
||||
|
||||
record Rule(Expression expression, Set<String> references) {
|
||||
boolean evaluate(Function<String, String> states) {
|
||||
return expression.evaluate(states);
|
||||
}
|
||||
}
|
||||
|
||||
interface Expression {
|
||||
boolean evaluate(Function<String, String> states);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY,
|
||||
property = "alarmType", defaultImpl = MetricAlarm.class)
|
||||
@JsonSubTypes({@JsonSubTypes.Type(value = MetricAlarm.class, name = "MetricAlarm"),
|
||||
@JsonSubTypes.Type(value = CompositeAlarm.class, name = "CompositeAlarm")})
|
||||
public abstract class Alarm {
|
||||
private String alarmName;
|
||||
private String alarmArn;
|
||||
private String alarmDescription;
|
||||
private long alarmConfigurationUpdatedTimestamp;
|
||||
private boolean actionsEnabled;
|
||||
private List<String> okActions = new ArrayList<>();
|
||||
private List<String> alarmActions = new ArrayList<>();
|
||||
private List<String> insufficientDataActions = new ArrayList<>();
|
||||
private String stateValue = "INSUFFICIENT_DATA";
|
||||
private String stateReason = "Unchecked";
|
||||
private String stateReasonData;
|
||||
private long stateUpdatedTimestamp;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private String region;
|
||||
|
||||
|
||||
protected Alarm() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
this.alarmConfigurationUpdatedTimestamp = now;
|
||||
this.stateUpdatedTimestamp = now;
|
||||
}
|
||||
|
||||
public abstract String getAlarmType();
|
||||
|
||||
public String getAlarmName() { return alarmName; }
|
||||
public void setAlarmName(String alarmName) { this.alarmName = alarmName; }
|
||||
|
||||
public String getAlarmArn() { return alarmArn; }
|
||||
public void setAlarmArn(String alarmArn) { this.alarmArn = alarmArn; }
|
||||
|
||||
public String getAlarmDescription() { return alarmDescription; }
|
||||
public void setAlarmDescription(String alarmDescription) { this.alarmDescription = alarmDescription; }
|
||||
|
||||
public long getAlarmConfigurationUpdatedTimestamp() { return alarmConfigurationUpdatedTimestamp; }
|
||||
public void setAlarmConfigurationUpdatedTimestamp(long timestamp) { this.alarmConfigurationUpdatedTimestamp = timestamp; }
|
||||
|
||||
public boolean isActionsEnabled() { return actionsEnabled; }
|
||||
public void setActionsEnabled(boolean actionsEnabled) { this.actionsEnabled = actionsEnabled; }
|
||||
|
||||
public List<String> getOkActions() { return okActions; }
|
||||
public void setOkActions(List<String> okActions) { this.okActions = okActions; }
|
||||
|
||||
public List<String> getAlarmActions() { return alarmActions; }
|
||||
public void setAlarmActions(List<String> alarmActions) { this.alarmActions = alarmActions; }
|
||||
|
||||
public List<String> getInsufficientDataActions() { return insufficientDataActions; }
|
||||
public void setInsufficientDataActions(List<String> insufficientDataActions) { this.insufficientDataActions = insufficientDataActions; }
|
||||
|
||||
public String getStateValue() { return stateValue; }
|
||||
public void setStateValue(String stateValue) { this.stateValue = stateValue; }
|
||||
|
||||
public String getStateReason() { return stateReason; }
|
||||
public void setStateReason(String stateReason) { this.stateReason = stateReason; }
|
||||
|
||||
public String getStateReasonData() { return stateReasonData; }
|
||||
public void setStateReasonData(String stateReasonData) { this.stateReasonData = stateReasonData; }
|
||||
|
||||
public long getStateUpdatedTimestamp() { return stateUpdatedTimestamp; }
|
||||
public void setStateUpdatedTimestamp(long stateUpdatedTimestamp) { this.stateUpdatedTimestamp = stateUpdatedTimestamp; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** The persisted AWS wire shape of a metric-math alarm query, including optional members. */
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record AlarmMetricDataQuery(
|
||||
@JsonProperty("Id") String id,
|
||||
@JsonProperty("Expression") String expression,
|
||||
@JsonProperty("Label") String label,
|
||||
@JsonProperty("ReturnData") Boolean returnData,
|
||||
@JsonProperty("Period") Integer period,
|
||||
@JsonProperty("AccountId") String accountId,
|
||||
@JsonProperty("MetricStat") MetricStat metricStat) {
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record MetricStat(
|
||||
@JsonProperty("Metric") Metric metric,
|
||||
@JsonProperty("Period") Integer period,
|
||||
@JsonProperty("Stat") String stat,
|
||||
@JsonProperty("Unit") String unit) { }
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record Metric(
|
||||
@JsonProperty("Namespace") String namespace,
|
||||
@JsonProperty("MetricName") String metricName,
|
||||
@JsonProperty("Dimensions") List<MetricDimension> dimensions) { }
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public record MetricDimension(
|
||||
@JsonProperty("Name") String name,
|
||||
@JsonProperty("Value") String value) { }
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public class CompositeAlarm extends Alarm {
|
||||
private String alarmRule;
|
||||
|
||||
@Override
|
||||
public String getAlarmType() { return "CompositeAlarm"; }
|
||||
|
||||
public String getAlarmRule() { return alarmRule; }
|
||||
public void setAlarmRule(String alarmRule) { this.alarmRule = alarmRule; }
|
||||
}
|
||||
+14
-70
@@ -3,32 +3,22 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics.model;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MetricAlarm {
|
||||
private String alarmName;
|
||||
private String alarmArn;
|
||||
private String alarmDescription;
|
||||
private long alarmConfigurationUpdatedTimestamp;
|
||||
private boolean actionsEnabled;
|
||||
private List<String> okActions = new ArrayList<>();
|
||||
private List<String> alarmActions = new ArrayList<>();
|
||||
private List<String> insufficientDataActions = new ArrayList<>();
|
||||
private String stateValue = "INSUFFICIENT_DATA";
|
||||
private String stateReason = "Unchecked";
|
||||
private String stateReasonData;
|
||||
private long stateUpdatedTimestamp;
|
||||
public class MetricAlarm extends Alarm {
|
||||
@Override
|
||||
public String getAlarmType() { return "MetricAlarm"; }
|
||||
|
||||
private String metricName;
|
||||
private String namespace;
|
||||
private String statistic;
|
||||
private List<Dimension> dimensions = new ArrayList<>();
|
||||
private int period;
|
||||
/** Single-metric period; absent for alarms whose periods are defined in Metrics. */
|
||||
private Integer period;
|
||||
private List<AlarmMetricDataQuery> metrics = new ArrayList<>();
|
||||
private String unit;
|
||||
private int evaluationPeriods;
|
||||
/**
|
||||
@@ -43,50 +33,6 @@ public class MetricAlarm {
|
||||
private String comparisonOperator;
|
||||
private String treatMissingData = "missing";
|
||||
private String evaluateLowSampleCountPercentile;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
private String region;
|
||||
|
||||
public MetricAlarm() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
this.alarmConfigurationUpdatedTimestamp = now;
|
||||
this.stateUpdatedTimestamp = now;
|
||||
}
|
||||
|
||||
public String getAlarmName() { return alarmName; }
|
||||
public void setAlarmName(String alarmName) { this.alarmName = alarmName; }
|
||||
|
||||
public String getAlarmArn() { return alarmArn; }
|
||||
public void setAlarmArn(String alarmArn) { this.alarmArn = alarmArn; }
|
||||
|
||||
public String getAlarmDescription() { return alarmDescription; }
|
||||
public void setAlarmDescription(String alarmDescription) { this.alarmDescription = alarmDescription; }
|
||||
|
||||
public long getAlarmConfigurationUpdatedTimestamp() { return alarmConfigurationUpdatedTimestamp; }
|
||||
public void setAlarmConfigurationUpdatedTimestamp(long timestamp) { this.alarmConfigurationUpdatedTimestamp = timestamp; }
|
||||
|
||||
public boolean isActionsEnabled() { return actionsEnabled; }
|
||||
public void setActionsEnabled(boolean actionsEnabled) { this.actionsEnabled = actionsEnabled; }
|
||||
|
||||
public List<String> getOkActions() { return okActions; }
|
||||
public void setOkActions(List<String> okActions) { this.okActions = okActions; }
|
||||
|
||||
public List<String> getAlarmActions() { return alarmActions; }
|
||||
public void setAlarmActions(List<String> alarmActions) { this.alarmActions = alarmActions; }
|
||||
|
||||
public List<String> getInsufficientDataActions() { return insufficientDataActions; }
|
||||
public void setInsufficientDataActions(List<String> insufficientDataActions) { this.insufficientDataActions = insufficientDataActions; }
|
||||
|
||||
public String getStateValue() { return stateValue; }
|
||||
public void setStateValue(String stateValue) { this.stateValue = stateValue; }
|
||||
|
||||
public String getStateReason() { return stateReason; }
|
||||
public void setStateReason(String stateReason) { this.stateReason = stateReason; }
|
||||
|
||||
public String getStateReasonData() { return stateReasonData; }
|
||||
public void setStateReasonData(String stateReasonData) { this.stateReasonData = stateReasonData; }
|
||||
|
||||
public long getStateUpdatedTimestamp() { return stateUpdatedTimestamp; }
|
||||
public void setStateUpdatedTimestamp(long stateUpdatedTimestamp) { this.stateUpdatedTimestamp = stateUpdatedTimestamp; }
|
||||
|
||||
public String getMetricName() { return metricName; }
|
||||
public void setMetricName(String metricName) { this.metricName = metricName; }
|
||||
@@ -100,8 +46,13 @@ public class MetricAlarm {
|
||||
public List<Dimension> getDimensions() { return dimensions; }
|
||||
public void setDimensions(List<Dimension> dimensions) { this.dimensions = dimensions; }
|
||||
|
||||
public int getPeriod() { return period; }
|
||||
public void setPeriod(int period) { this.period = period; }
|
||||
public Integer getPeriod() { return period; }
|
||||
public void setPeriod(Integer period) { this.period = period; }
|
||||
|
||||
public List<AlarmMetricDataQuery> getMetrics() { return metrics; }
|
||||
public void setMetrics(List<AlarmMetricDataQuery> metrics) {
|
||||
this.metrics = metrics == null ? new ArrayList<>() : new ArrayList<>(metrics);
|
||||
}
|
||||
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
@@ -124,11 +75,4 @@ public class MetricAlarm {
|
||||
public String getEvaluateLowSampleCountPercentile() { return evaluateLowSampleCountPercentile; }
|
||||
public void setEvaluateLowSampleCountPercentile(String percentile) { this.evaluateLowSampleCountPercentile = percentile; }
|
||||
|
||||
public Map<String, String> getTags() { return tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags; }
|
||||
|
||||
/** Not part of the AWS shape; set by {@code putMetricAlarm} so a background evaluator
|
||||
* that only holds the alarm object still knows which region's metric data to query. */
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
}
|
||||
|
||||
+18
-9
@@ -196,21 +196,30 @@ public class CloudWatchMetricStreamsService {
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
return findByArn(resourceArn, region).map(MetricStream::getTags).orElse(Map.of());
|
||||
return requireStream(resourceArn, region).getTags();
|
||||
}
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(stream -> {
|
||||
stream.getTags().putAll(tags);
|
||||
streamStore.put(key(region, stream.getName()), stream);
|
||||
});
|
||||
MetricStream stream = requireStream(resourceArn, region);
|
||||
stream.getTags().putAll(tags);
|
||||
streamStore.put(key(region, stream.getName()), stream);
|
||||
}
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
findByArn(resourceArn, region).ifPresent(stream -> {
|
||||
tagKeys.forEach(stream.getTags()::remove);
|
||||
streamStore.put(key(region, stream.getName()), stream);
|
||||
});
|
||||
MetricStream stream = requireStream(resourceArn, region);
|
||||
tagKeys.forEach(stream.getTags()::remove);
|
||||
streamStore.put(key(region, stream.getName()), stream);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the stream an ARN names, or reports that nothing does. The tag operations declare
|
||||
* {@code ResourceNotFoundException}, the same code {@code GetMetricStream} already answers
|
||||
* with, so an unknown ARN here reads the same way an unknown name does.
|
||||
*/
|
||||
private MetricStream requireStream(String resourceArn, String region) {
|
||||
return findByArn(resourceArn, region).orElseThrow(() ->
|
||||
new AwsException("ResourceNotFoundException",
|
||||
"Metric stream " + resourceArn + " does not exist.", 404));
|
||||
}
|
||||
|
||||
private Optional<MetricStream> findByArn(String resourceArn, String region) {
|
||||
|
||||
+4
-1
@@ -291,7 +291,10 @@ final class CognitoAuthFlowHandler {
|
||||
if (!"UserNotFoundException".equals(ae.getErrorCode())) throw ae;
|
||||
user = tryUserMigration(pool, client, username, password, null, clientMetadata,
|
||||
"UserMigration_Authentication");
|
||||
if (user == null) throw ae;
|
||||
if (user == null) {
|
||||
if (!CognitoService.hidesUserExistence(client)) throw ae;
|
||||
throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);
|
||||
}
|
||||
}
|
||||
|
||||
firePreAuthentication(pool, client, user, null, clientMetadata, false);
|
||||
|
||||
@@ -2592,7 +2592,8 @@ public class CognitoService implements ResourceProvider {
|
||||
String confirmationCode) {
|
||||
UserPool pool = poolStore.get(userPoolId)
|
||||
.orElseThrow(() -> userPoolNotFound(userPoolId));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
CognitoUser user = userForClientOrNull(client, username);
|
||||
if (user == null) throw codeMismatch();
|
||||
if (verificationCodeService != null && isSignUpConfirmationEnabled(pool)) {
|
||||
try {
|
||||
verificationCodeService.consume(client.getUserPoolId(), user.getUsername(),
|
||||
@@ -2636,7 +2637,8 @@ public class CognitoService implements ResourceProvider {
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found",
|
||||
400));
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
CognitoUser user = userForClientOrNull(client, username);
|
||||
if (user == null) return simulatedCodeDelivery(username);
|
||||
if (!"UNCONFIRMED".equals(user.getUserStatus())) {
|
||||
throw new AwsException("NotAuthorizedException",
|
||||
"User cannot be confirmed. Current status is " + user.getUserStatus(), 400);
|
||||
@@ -2774,7 +2776,8 @@ public class CognitoService implements ResourceProvider {
|
||||
public Map<String, Object> forgotPassword(String clientId, String username) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
CognitoUser user = userForClientOrNull(client, username);
|
||||
if (user == null) return new LinkedHashMap<>(simulatedCodeDelivery(username));
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
ensureVerificationWiring();
|
||||
DeliveryTarget deliveryTarget = resolveForgotPasswordDeliveryTarget(pool, user);
|
||||
@@ -2800,7 +2803,8 @@ public class CognitoService implements ResourceProvider {
|
||||
public void confirmForgotPassword(String clientId, String username, String confirmationCode, String newPassword) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
CognitoUser user = userForClientOrNull(client, username);
|
||||
if (user == null) throw codeMismatch();
|
||||
ensureVerificationWiring();
|
||||
try {
|
||||
verificationCodeService.consume(client.getUserPoolId(), user.getUsername(),
|
||||
@@ -3075,6 +3079,18 @@ public class CognitoService implements ResourceProvider {
|
||||
return overrideId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The signing keys, by kid, of this emulator's own pool that {@code issuer} names exactly, so a
|
||||
* JWT authorizer can verify the pool's tokens in-process; empty for every other issuer.
|
||||
*/
|
||||
public Optional<Map<String, RSAPublicKey>> localIssuerKeys(String issuer) {
|
||||
if (issuer == null) return Optional.empty();
|
||||
String trimmed = issuer.replaceAll("/+$", "");
|
||||
String poolId = trimmed.substring(trimmed.lastIndexOf('/') + 1);
|
||||
if (poolId.isEmpty() || !getIssuer(poolId).equals(trimmed)) return Optional.empty();
|
||||
return poolStore.get(poolId).map(pool -> Map.of(getSigningKeyId(pool), getSigningPublicKey(pool)));
|
||||
}
|
||||
|
||||
public String getJwksUri(String poolId) {
|
||||
return getIssuer(poolId) + "/.well-known/jwks.json";
|
||||
}
|
||||
@@ -4446,10 +4462,38 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the app client hides which usernames exist (PreventUserExistenceErrors=ENABLED). Real Cognito then
|
||||
* answers for an unknown user exactly as for a real one: a failed sign-in is "Incorrect username or password",
|
||||
* a code request reports a simulated delivery and a code check reports a wrong code. Unset means LEGACY.
|
||||
*/
|
||||
static boolean hidesUserExistence(UserPoolClient client) {
|
||||
return "ENABLED".equals(client.getPreventUserExistenceErrors());
|
||||
}
|
||||
|
||||
/** The user, or null when it does not exist and the client hides that; otherwise UserNotFoundException. */
|
||||
private CognitoUser userForClientOrNull(UserPoolClient client, String username) {
|
||||
try {
|
||||
return adminGetUser(client.getUserPoolId(), username);
|
||||
} catch (AwsException e) {
|
||||
if ("UserNotFoundException".equals(e.getErrorCode()) && hidesUserExistence(client)) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> simulatedCodeDelivery(String username) {
|
||||
return username != null && username.contains("@")
|
||||
? Map.of("AttributeName", "email", "DeliveryMedium", "EMAIL", "Destination", maskEmail(username))
|
||||
: Map.of("AttributeName", "phone_number", "DeliveryMedium", "SMS", "Destination", "+*******0000");
|
||||
}
|
||||
|
||||
private static AwsException codeMismatch() {
|
||||
return new AwsException("CodeMismatchException", "Invalid verification code provided, please try again.", 400);
|
||||
}
|
||||
|
||||
private AwsException mapVerificationCodeException(VerificationCodeException e) {
|
||||
return switch (e.getKind()) {
|
||||
case MISMATCH, NOT_FOUND -> new AwsException("CodeMismatchException",
|
||||
"Invalid verification code provided, please try again.", 400);
|
||||
case MISMATCH, NOT_FOUND -> codeMismatch();
|
||||
case EXPIRED -> new AwsException("ExpiredCodeException",
|
||||
"Invalid code provided, please request a code again.", 400);
|
||||
case RATE_LIMIT -> new AwsException("LimitExceededException",
|
||||
|
||||
@@ -8554,6 +8554,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
"Network interface '" + networkInterfaceId + "' is currently in use", 400);
|
||||
}
|
||||
networkInterfaces.delete(key(region, networkInterfaceId));
|
||||
// Its addresses go back to the subnet, or every task or mount target that ever held one
|
||||
// would leave it leased until the emulator restarts.
|
||||
if (vpcNetworkManager != null && ni.getPrivateIpAddresses() != null) {
|
||||
ni.getPrivateIpAddresses().forEach(address ->
|
||||
vpcNetworkManager.releasePrivateIp(region, ni.getSubnetId(), address.getPrivateIpAddress()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -285,7 +285,10 @@ public class VpcNetworkManager {
|
||||
}
|
||||
|
||||
int desiredPrefix = declared.map(Cidr4::prefix).orElse(24);
|
||||
Cidr4 slice = allocateSubBlock(vpc.effective, desiredPrefix, siblings);
|
||||
Cidr4 slice = translatedIntoSubstitute(vpc, declared, siblings);
|
||||
if (slice == null) {
|
||||
slice = allocateSubBlock(vpc.effective, desiredPrefix, siblings);
|
||||
}
|
||||
if (slice == null) {
|
||||
LOG.warnv("Subnet {0} in VPC {1}: no free /{2} slice remains inside {3}; instances in this "
|
||||
+ "subnet fall back to synthesised private addresses.",
|
||||
@@ -301,6 +304,26 @@ public class VpcNetworkManager {
|
||||
return bindSubnet(vpc, subnetId, declared.orElse(null), slice, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The declared subnet moved to the same place inside its VPC's substitute range, or null when
|
||||
* that does not apply. Keeping each subnet's offset, rather than handing out the next free
|
||||
* slice, is what makes the plan come out the same in every run whatever order the subnets are
|
||||
* declared in, so the addresses persisted instances and mount targets hold stay valid.
|
||||
*/
|
||||
private static Cidr4 translatedIntoSubstitute(VpcBinding vpc, Optional<Cidr4> declared, List<Cidr4> siblings) {
|
||||
if (!vpc.substituted || vpc.declared == null || declared.isEmpty()
|
||||
|| vpc.declared.prefix() != vpc.effective.prefix() || !vpc.declared.contains(declared.get())) {
|
||||
return null;
|
||||
}
|
||||
long offset = declared.get().network() - vpc.declared.network();
|
||||
Cidr4 translated = Cidr4.parse(Cidr4.format(vpc.effective.network() + offset) + "/" + declared.get().prefix())
|
||||
.orElse(null);
|
||||
if (translated == null || siblings.stream().anyMatch(sibling -> sibling.overlaps(translated))) {
|
||||
return null;
|
||||
}
|
||||
return translated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds a subnet to a range it can actually allocate out of.
|
||||
*
|
||||
|
||||
+15
-63
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.efs.EfsMounts;
|
||||
import io.github.hectorvent.floci.services.ec2.SecurityGroupFirewallManager;
|
||||
import io.github.hectorvent.floci.services.ec2.SecurityGroupNftCompiler;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
|
||||
@@ -63,14 +64,11 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -124,6 +122,7 @@ public class EcsContainerManager {
|
||||
private final HostVolumePolicy hostVolumePolicy;
|
||||
private Ec2Service ec2Service;
|
||||
private SecurityGroupFirewallManager firewallManager;
|
||||
private EfsMounts efsMounts;
|
||||
|
||||
@Inject
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -139,11 +138,13 @@ public class EcsContainerManager {
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
HostVolumePolicy hostVolumePolicy,
|
||||
Ec2Service ec2Service,
|
||||
SecurityGroupFirewallManager firewallManager) {
|
||||
SecurityGroupFirewallManager firewallManager,
|
||||
EfsMounts efsMounts) {
|
||||
this(containerBuilder, lifecycleManager, logStreamer, containerDetector, config, regionResolver,
|
||||
awsEnv, ssmService, secretsManagerService, s3Service, ecrRegistryManager, hostVolumePolicy);
|
||||
this.ec2Service = ec2Service;
|
||||
this.firewallManager = firewallManager;
|
||||
this.efsMounts = efsMounts;
|
||||
}
|
||||
|
||||
public EcsContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -170,6 +171,8 @@ public class EcsContainerManager {
|
||||
this.s3Service = s3Service;
|
||||
this.hostVolumePolicy = hostVolumePolicy;
|
||||
this.ecrRegistryManager = ecrRegistryManager;
|
||||
// Without the EFS service only mounts that name no access point can be resolved.
|
||||
this.efsMounts = new EfsMounts(null, lifecycleManager, config);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -391,7 +394,7 @@ public class EcsContainerManager {
|
||||
specBuilder.withBind(sourcePath, mp.containerPath());
|
||||
}
|
||||
} else if (efs != null) {
|
||||
mountEfsVolume(specBuilder, efs, mp);
|
||||
mountEfsVolume(specBuilder, efs, mp, region);
|
||||
} else {
|
||||
LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}",
|
||||
mp.sourceVolume(), def.getName());
|
||||
@@ -1769,20 +1772,15 @@ public class EcsContainerManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialises an EFS-configured task volume as a shared local Docker named volume scoped to
|
||||
* both the file system and the mount's effective root (see {@link #efsVolumeName}), then
|
||||
* initialises the volume root's POSIX ownership to emulate the EFS access point's
|
||||
* RootDirectory.CreationInfo (no-op unless {@code floci.storage.efs} configures owner/permissions)
|
||||
* and applies the configured PosixUser emulation (uid[:gid] and/or supplementary group) so a
|
||||
* non-root task image can read/write the shared volume.
|
||||
* Mounts an EFS-configured task volume: the file system's shared Docker volume, or the
|
||||
* access point's or {@code rootDirectory}'s directory inside it (see {@link EfsMounts}). The
|
||||
* container keeps its own user, as on AWS, unless {@code floci.storage.efs.mount-user} sets one.
|
||||
*/
|
||||
private void mountEfsVolume(ContainerBuilder.Builder specBuilder, EfsVolumeConfiguration efs, MountPoint mp) {
|
||||
String efsVolumeName = efsVolumeName(efs.fileSystemId(), efs.accessPointId(), efs.rootDirectory());
|
||||
private void mountEfsVolume(ContainerBuilder.Builder specBuilder, EfsVolumeConfiguration efs, MountPoint mp,
|
||||
String region) {
|
||||
efsMounts.prepare(region, efs.fileSystemId(), efs.accessPointId(), efs.rootDirectory())
|
||||
.applyTo(specBuilder, mp.containerPath(), mp.readOnly());
|
||||
var efsCfg = config.storage().efs();
|
||||
lifecycleManager.ensureSharedVolume(efsVolumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(),
|
||||
efsCfg.initImage());
|
||||
specBuilder.withNamedVolume(efsVolumeName, mp.containerPath(), mp.readOnly());
|
||||
efsCfg.mountUser().ifPresent(u -> {
|
||||
if (!u.matches("^\\d+(:\\d+)?$")) {
|
||||
throw new IllegalArgumentException(
|
||||
@@ -1793,52 +1791,6 @@ public class EcsContainerManager {
|
||||
efsCfg.mountGroupAdd().ifPresent(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Name of the local Docker named volume backing an EFS-configured task volume, scoped to
|
||||
* both the file system and the mount's effective root so two mounts of the same file system
|
||||
* with a different {@code rootDirectory}/{@code accessPointId} land on isolated volumes
|
||||
* while identical configurations keep sharing one, matching how AWS scopes an EFS mount to
|
||||
* a subpath. When {@code accessPointId} is set, it determines the effective root: on real
|
||||
* AWS an access point's own root directory takes precedence over any {@code rootDirectory}
|
||||
* on the volume.
|
||||
*/
|
||||
static String efsVolumeName(String fileSystemId, String accessPointId, String rootDirectory) {
|
||||
if (accessPointId != null && !accessPointId.isBlank()) {
|
||||
return "floci-efs-" + fileSystemId + "-" + sha256Hex("accessPoint:" + accessPointId);
|
||||
}
|
||||
String normalizedRoot = normalizeRootDirectory(rootDirectory);
|
||||
if ("/".equals(normalizedRoot)) {
|
||||
return "floci-efs-" + fileSystemId;
|
||||
}
|
||||
return "floci-efs-" + fileSystemId + "-" + sha256Hex(normalizedRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalises a {@code rootDirectory} path so syntactically different but equivalent
|
||||
* paths (missing/blank, a missing leading slash, repeated slashes, a trailing slash) resolve
|
||||
* to the same effective root instead of silently splitting shared storage across local
|
||||
* volumes that AWS would treat as identical.
|
||||
*/
|
||||
private static String normalizeRootDirectory(String rootDirectory) {
|
||||
if (rootDirectory == null || rootDirectory.isBlank()) {
|
||||
return "/";
|
||||
}
|
||||
String collapsed = rootDirectory.trim().replaceAll("/+", "/");
|
||||
if (collapsed.length() > 1 && collapsed.endsWith("/")) {
|
||||
collapsed = collapsed.substring(0, collapsed.length() - 1);
|
||||
}
|
||||
return collapsed.startsWith("/") ? collapsed : "/" + collapsed;
|
||||
}
|
||||
|
||||
private static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is required but not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Inner enum to avoid import cycle — mirrors model.TaskStatus for readability
|
||||
private enum TaskStatus {RUNNING}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,14 @@ public class EfsException extends AwsException {
|
||||
return new EfsException(Status.NOT_FOUND, "MountTargetNotFound", "Mount target " + mountTargetId + " does not exist.");
|
||||
}
|
||||
|
||||
public static EfsException subnetNotFound(String subnetId) {
|
||||
return new EfsException(Status.BAD_REQUEST, "SubnetNotFound", "The subnet ID '" + subnetId + "' does not exist");
|
||||
}
|
||||
|
||||
public static EfsException securityGroupNotFound(String message) {
|
||||
return new EfsException(Status.BAD_REQUEST, "SecurityGroupNotFound", message);
|
||||
}
|
||||
|
||||
public static EfsException mountTargetConflict(String message) {
|
||||
return new EfsException(Status.CONFLICT, "MountTargetConflict", message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.DirectoryCreation;
|
||||
import io.github.hectorvent.floci.services.efs.model.AccessPointDescription;
|
||||
import io.github.hectorvent.floci.services.efs.model.CreationInfo;
|
||||
import io.github.hectorvent.floci.services.efs.model.PosixUser;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Turns an EFS mount (a file system, optionally through an access point) into a Docker volume
|
||||
* mount. Each file system is one named volume, so every mount of it, from Lambda or ECS, through
|
||||
* any access point, shares the same data. An access point mounts its root directory, a subfolder
|
||||
* of that volume, which is created on first use from the access point's {@code CreationInfo}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EfsMounts {
|
||||
|
||||
/** A file system directory ready to mount, and the identity its access point enforces, if any. */
|
||||
public record Mount(String volumeName, String subpath, Optional<PosixUser> accessPointUser) {
|
||||
|
||||
public void applyTo(ContainerBuilder.Builder spec, String containerPath, boolean readOnly) {
|
||||
if (subpath.isEmpty()) {
|
||||
spec.withNamedVolume(volumeName, containerPath, readOnly);
|
||||
} else {
|
||||
spec.withNamedVolumeSubpath(volumeName, subpath, containerPath, readOnly);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A plain rootDirectory (an ECS volume without an access point) has no CreationInfo; create it
|
||||
// the way a Docker named volume's own root is created.
|
||||
private static final DirectoryCreation PLAIN_ROOT_DIRECTORY = new DirectoryCreation(0, 0, "755");
|
||||
|
||||
private final EfsService efsService;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
public EfsMounts(EfsService efsService, ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
|
||||
this.efsService = efsService;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public static String volumeName(String fileSystemId) {
|
||||
return "floci-efs-" + fileSystemId;
|
||||
}
|
||||
|
||||
/** Prepares a Lambda {@code FileSystemConfig}, which names an access point by ARN. */
|
||||
public Mount prepareAccessPoint(String accessPointArn) {
|
||||
String[] parts = accessPointArn == null ? new String[0] : accessPointArn.split(":", 6);
|
||||
if (parts.length != 6 || !parts[5].startsWith("access-point/")) {
|
||||
throw new IllegalArgumentException("Not an EFS access point ARN: " + accessPointArn);
|
||||
}
|
||||
return prepare(parts[3], null, parts[5].substring("access-point/".length()), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a mount of {@code fileSystemId}. With an access point its own root directory and
|
||||
* owner apply and {@code rootDirectory} is ignored, as on AWS; {@code fileSystemId} may then
|
||||
* be null, and otherwise must be the access point's file system.
|
||||
*/
|
||||
public Mount prepare(String region, String fileSystemId, String accessPointId, String rootDirectory) {
|
||||
String root;
|
||||
Optional<DirectoryCreation> creation;
|
||||
Optional<PosixUser> user = Optional.empty();
|
||||
if (accessPointId != null && !accessPointId.isBlank()) {
|
||||
if (efsService == null) {
|
||||
throw new IllegalStateException("EFS access points are unavailable: the EFS service is not running");
|
||||
}
|
||||
AccessPointDescription accessPoint = efsService.describeAccessPoints(region, null, accessPointId)
|
||||
.stream().findFirst()
|
||||
.orElseThrow(() -> EfsException.accessPointNotFound(accessPointId));
|
||||
if (fileSystemId != null && !fileSystemId.equals(accessPoint.getFileSystemId())) {
|
||||
throw new IllegalArgumentException("Access point " + accessPointId + " belongs to file system "
|
||||
+ accessPoint.getFileSystemId() + ", not " + fileSystemId);
|
||||
}
|
||||
fileSystemId = accessPoint.getFileSystemId();
|
||||
var directory = accessPoint.getRootDirectory();
|
||||
root = normalizeRootDirectory(directory == null ? null : directory.getPath());
|
||||
creation = Optional.ofNullable(directory == null ? null : directory.getCreationInfo())
|
||||
.flatMap(EfsMounts::directoryCreation);
|
||||
user = Optional.ofNullable(accessPoint.getPosixUser());
|
||||
} else {
|
||||
root = normalizeRootDirectory(rootDirectory);
|
||||
creation = Optional.of(PLAIN_ROOT_DIRECTORY);
|
||||
}
|
||||
|
||||
String volumeName = volumeName(fileSystemId);
|
||||
var efsCfg = config.storage().efs();
|
||||
lifecycleManager.ensureSharedVolume(volumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(), efsCfg.initImage());
|
||||
String subpath = root.substring(1);
|
||||
if (!subpath.isEmpty()
|
||||
&& !lifecycleManager.ensureSharedVolumeDirectory(volumeName, subpath, creation, efsCfg.initImage())) {
|
||||
throw new IllegalStateException("The root directory " + root + " of access point " + accessPointId
|
||||
+ " does not exist on file system " + fileSystemId
|
||||
+ ", and the access point has no CreationInfo to create it");
|
||||
}
|
||||
return new Mount(volumeName, subpath, user);
|
||||
}
|
||||
|
||||
/** {@code "uid:gid"} for a container that runs as the access point's POSIX user. */
|
||||
public static String containerUser(PosixUser user) {
|
||||
return user.getUid() + ":" + user.getGid();
|
||||
}
|
||||
|
||||
public static List<Long> secondaryGids(PosixUser user) {
|
||||
return user.getSecondaryGids() == null ? List.of() : user.getSecondaryGids();
|
||||
}
|
||||
|
||||
private static Optional<DirectoryCreation> directoryCreation(CreationInfo info) {
|
||||
if (info.getOwnerUid() == null || info.getOwnerGid() == null || info.getPermissions() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new DirectoryCreation(info.getOwnerUid(), info.getOwnerGid(), info.getPermissions()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalises a root directory so equivalent spellings (missing or blank, no leading slash,
|
||||
* repeated or trailing slashes) name the same directory. A {@code ..} component is refused.
|
||||
*/
|
||||
static String normalizeRootDirectory(String rootDirectory) {
|
||||
if (rootDirectory == null || rootDirectory.isBlank()) {
|
||||
return "/";
|
||||
}
|
||||
String collapsed = rootDirectory.trim().replaceAll("/+", "/");
|
||||
if (collapsed.length() > 1 && collapsed.endsWith("/")) {
|
||||
collapsed = collapsed.substring(0, collapsed.length() - 1);
|
||||
}
|
||||
String normalized = collapsed.startsWith("/") ? collapsed : "/" + collapsed;
|
||||
if (List.of(normalized.split("/")).contains("..")) {
|
||||
throw new IllegalArgumentException("A root directory cannot contain '..': " + rootDirectory);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.BuildImageResultCallback;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
|
||||
import io.github.hectorvent.floci.services.efs.model.MountTarget;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Serves each EFS mount target over NFSv4.1, as on AWS: a privileged helper container running the
|
||||
* kernel NFS server holds the mount target's address on its VPC's Docker network and exports the
|
||||
* file system's volume, the same one Lambda and ECS mount directly. An EC2 instance in the VPC can
|
||||
* then mount the file system with the commands AWS documents, by address or by its DNS name.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class EfsNfsServers {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EfsNfsServers.class);
|
||||
|
||||
static final String LABEL_COMPONENT = "floci_component";
|
||||
static final String COMPONENT_VALUE = "efs-nfs-server";
|
||||
static final String LABEL_OWNER = "floci_efs_owner";
|
||||
static final String DEFAULT_IMAGE = "floci/efs-nfs-server:local";
|
||||
private static final int READY_ATTEMPTS = 60;
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final DockerClient dockerClient;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final VpcNetworkManager vpcNetworkManager;
|
||||
private final ExecutorService starter = Executors.newSingleThreadExecutor(r -> {
|
||||
Thread thread = new Thread(r, "efs-nfs-servers");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
|
||||
@Inject
|
||||
public EfsNfsServers(EmulatorConfig config, DockerClient dockerClient, ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager, VpcNetworkManager vpcNetworkManager) {
|
||||
this.config = config;
|
||||
this.dockerClient = dockerClient;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.vpcNetworkManager = vpcNetworkManager;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
starter.shutdownNow();
|
||||
}
|
||||
|
||||
/** Whether mount targets get an NFS server: configured on, and VPCs have Docker networks to hold their address. */
|
||||
public boolean enabled() {
|
||||
return config.services().efs().nfsServers() && vpcNetworkManager.enabled();
|
||||
}
|
||||
|
||||
static String containerName(String mountTargetId) {
|
||||
return "floci-efs-nfs-" + mountTargetId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the mount target's NFS server in the background and then runs {@code onSettled}
|
||||
* with whether it is serving. A server left from an earlier run is replaced.
|
||||
*/
|
||||
public void serve(String region, String accountId, MountTarget mountTarget, Consumer<Boolean> onSettled) {
|
||||
starter.execute(() -> {
|
||||
boolean serving = false;
|
||||
try {
|
||||
serving = start(region, accountId, mountTarget);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Mount target {0} of {1} has no NFS server: {2}",
|
||||
mountTarget.getMountTargetId(), mountTarget.getFileSystemId(), e.getMessage());
|
||||
}
|
||||
onSettled.accept(serving);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-claims a persisted mount target's address after a restart. The VPC address leases live
|
||||
* only in memory, so without this the next instance launched in the subnet could be handed it.
|
||||
*/
|
||||
public void reserveAddress(String region, MountTarget mountTarget) {
|
||||
vpcNetworkManager.reservePrivateIp(region, mountTarget.getSubnetId(), mountTarget.getIpAddress());
|
||||
}
|
||||
|
||||
/** Stops and removes the mount target's NFS server, if it has one. */
|
||||
public void stop(String mountTargetId) {
|
||||
lifecycleManager.removeIfExists(containerName(mountTargetId));
|
||||
}
|
||||
|
||||
/** Removes every NFS server this emulator started, such as those a previous run left behind. */
|
||||
public void removeAll() {
|
||||
if (!enabled()) {
|
||||
return;
|
||||
}
|
||||
dockerClient.listContainersCmd().withShowAll(true)
|
||||
.withLabelFilter(Map.of(LABEL_COMPONENT, COMPONENT_VALUE, LABEL_OWNER, owner()))
|
||||
.exec()
|
||||
.forEach(container -> lifecycleManager.removeIfExists(container.getId()));
|
||||
}
|
||||
|
||||
private boolean start(String region, String accountId, MountTarget mountTarget) {
|
||||
String name = containerName(mountTarget.getMountTargetId());
|
||||
String image = ensureImage();
|
||||
String volumeName = EfsMounts.volumeName(mountTarget.getFileSystemId());
|
||||
var efsCfg = config.storage().efs();
|
||||
lifecycleManager.ensureSharedVolume(volumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(), efsCfg.initImage());
|
||||
lifecycleManager.removeIfExists(name);
|
||||
|
||||
var spec = containerBuilder.newContainer(image)
|
||||
.withName(name)
|
||||
.withPrivileged(true)
|
||||
.withNamedVolume(volumeName, "/export", false)
|
||||
.withLogRotation()
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"efs", mountTarget.getMountTargetId(), accountId, region))
|
||||
.withLabels(Map.of(LABEL_COMPONENT, COMPONENT_VALUE, LABEL_OWNER, owner()))
|
||||
.build();
|
||||
String containerId = lifecycleManager.createAndStart(spec).containerId();
|
||||
if (vpcNetworkManager.attach(region, mountTarget.getVpcId(), mountTarget.getSubnetId(),
|
||||
containerId, mountTarget.getIpAddress()).isEmpty()) {
|
||||
lifecycleManager.removeIfExists(name);
|
||||
LOG.warnv("Mount target {0} could not take its address {1} on the VPC network; it has no NFS server",
|
||||
mountTarget.getMountTargetId(), mountTarget.getIpAddress());
|
||||
return false;
|
||||
}
|
||||
if (!awaitReady(containerId)) {
|
||||
lifecycleManager.removeIfExists(name);
|
||||
LOG.warnv("The NFS server of mount target {0} did not start", mountTarget.getMountTargetId());
|
||||
return false;
|
||||
}
|
||||
LOG.infov("Mount target {0} serves file system {1} over NFS at {2}",
|
||||
mountTarget.getMountTargetId(), mountTarget.getFileSystemId(), mountTarget.getIpAddress());
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ready once the kernel NFS server has threads and mountd answers export lookups. */
|
||||
private boolean awaitReady(String containerId) {
|
||||
for (int attempt = 0; attempt < READY_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
String execId = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd("sh", "-c", "[ \"$(cat /proc/fs/nfsd/threads)\" -gt 0 ] && pgrep rpc.mountd")
|
||||
.withAttachStdout(true).withAttachStderr(true)
|
||||
.exec().getId();
|
||||
dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>()).awaitCompletion(10, TimeUnit.SECONDS);
|
||||
Long exitCode = dockerClient.inspectExecCmd(execId).exec().getExitCodeLong();
|
||||
if (exitCode != null && exitCode == 0) {
|
||||
return true;
|
||||
}
|
||||
TimeUnit.MILLISECONDS.sleep(500);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
} catch (RuntimeException e) {
|
||||
LOG.debugv("NFS server {0} not ready yet: {1}", containerId, e.getMessage());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private synchronized String ensureImage() {
|
||||
String configured = config.services().efs().nfsServerImage();
|
||||
String image = containerBuilder.resolveImage(configured);
|
||||
if (!DEFAULT_IMAGE.equals(configured)) {
|
||||
return image;
|
||||
}
|
||||
try {
|
||||
dockerClient.inspectImageCmd(image).exec();
|
||||
return image;
|
||||
} catch (NotFoundException missing) {
|
||||
// Build Floci's own recipe in the daemon that runs the workloads.
|
||||
}
|
||||
try (InputStream dockerfile = getClass().getResourceAsStream("/docker/efs-nfs-server.Dockerfile")) {
|
||||
if (dockerfile == null) {
|
||||
throw new IllegalStateException("The EFS NFS server Dockerfile is missing");
|
||||
}
|
||||
byte[] content = dockerfile.readAllBytes();
|
||||
ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024);
|
||||
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) {
|
||||
TarArchiveEntry entry = new TarArchiveEntry("Dockerfile");
|
||||
entry.setSize(content.length);
|
||||
tar.putArchiveEntry(entry);
|
||||
tar.write(content);
|
||||
tar.closeArchiveEntry();
|
||||
}
|
||||
try (BuildImageResultCallback callback = new BuildImageResultCallback()) {
|
||||
String built = dockerClient.buildImageCmd(new ByteArrayInputStream(archive.toByteArray()))
|
||||
.withTags(Set.of(image)).exec(callback).awaitImageId();
|
||||
if (built == null || built.isBlank()) {
|
||||
throw new IllegalStateException("Docker did not build the EFS NFS server image");
|
||||
}
|
||||
}
|
||||
return image;
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("Cannot build the EFS NFS server image", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** The emulator that owns a server, so one emulator never removes another's on a shared daemon. */
|
||||
private String owner() {
|
||||
String namespace = config.docker() == null || config.docker().resourceNamespace() == null
|
||||
? "" : config.docker().resourceNamespace().orElse("");
|
||||
return namespace.isBlank() ? String.valueOf(config.port()) : namespace + "/" + config.port();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,15 @@ package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Subnet;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import io.github.hectorvent.floci.services.efs.model.*;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -14,6 +22,9 @@ import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@@ -32,14 +43,29 @@ public class EfsService implements Resettable {
|
||||
private final StorageBackend<String, List<LifecyclePolicy>> lifecycleConfigurationStore;
|
||||
private final ConcurrentHashMap<String, Object> syncLocks = new ConcurrentHashMap<>();
|
||||
private final RegionResolver regionResolver;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private EfsNfsServers nfsServers;
|
||||
private EmbeddedDnsServer dnsServer;
|
||||
|
||||
// A file system's DNS name, optionally for one Availability Zone's mount target:
|
||||
// [az.]fs-id.efs.region.amazonaws.com
|
||||
private static final Pattern FILE_SYSTEM_DNS_NAME = Pattern.compile(
|
||||
"^(?:([a-z0-9-]+)\\.)?(fs-[0-9a-f]+)\\.efs\\.([a-z0-9-]+)\\.amazonaws\\.com\\.?$");
|
||||
|
||||
// RootDirectory.Path as the EFS API documents it: "/" or up to 100 "/name" segments, where a
|
||||
// name does not start with "." and holds none of $#<>;`|&?{}^* or a newline.
|
||||
private static final Pattern ROOT_DIRECTORY_PATH = Pattern.compile("^(/|(/(?!\\.)[^$#<>;`|&?{}^*/\\n]+){1,100})$");
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
private Object lockFor(String key) {
|
||||
return syncLocks.computeIfAbsent(key, k -> new Object());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public EfsService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
public EfsService(StorageFactory storageFactory, RegionResolver regionResolver, Ec2Service ec2Service) {
|
||||
this.regionResolver = regionResolver;
|
||||
this.ec2Service = ec2Service;
|
||||
this.fileSystemStore = storageFactory.create("efs", "efs-filesystems.json",
|
||||
new com.fasterxml.jackson.core.type.TypeReference<java.util.Map<String, FileSystem>>() {});
|
||||
this.mountTargetStore = storageFactory.create("efs", "efs-mounttargets.json",
|
||||
@@ -54,6 +80,82 @@ public class EfsService implements Resettable {
|
||||
new com.fasterxml.jackson.core.type.TypeReference<java.util.Map<String, List<LifecyclePolicy>>>() {});
|
||||
}
|
||||
|
||||
/** Lets a deleted file system take its stored data with it; absent in tests without Docker. */
|
||||
@Inject
|
||||
void setLifecycleManager(ContainerLifecycleManager lifecycleManager) {
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
}
|
||||
|
||||
/** Serves mount targets over NFS; absent in tests that build the service by hand. */
|
||||
@Inject
|
||||
void setNfsServers(EfsNfsServers nfsServers, EmbeddedDnsServer dnsServer) {
|
||||
this.nfsServers = nfsServers;
|
||||
this.dnsServer = dnsServer;
|
||||
}
|
||||
|
||||
/**
|
||||
* The address a file system's DNS name resolves to: the mount target in the named Availability
|
||||
* Zone, or, for the plain name, the first mount target that is serving. AWS answers the plain
|
||||
* name with the mount target in the client's own zone; every mount target here is reachable
|
||||
* from the whole VPC, so any serving one will do.
|
||||
*/
|
||||
Optional<String> resolveDnsName(String name) {
|
||||
Matcher matcher = FILE_SYSTEM_DNS_NAME.matcher(name.toLowerCase());
|
||||
if (!matcher.matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String zone = matcher.group(1);
|
||||
String fileSystemId = matcher.group(2);
|
||||
String region = matcher.group(3);
|
||||
return mountTargetStore.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(mt -> fileSystemId.equals(mt.getFileSystemId()))
|
||||
.filter(mt -> mt.getLifeCycleState() == LifeCycleState.available)
|
||||
.filter(mt -> zone == null || zone.equals(mt.getAvailabilityZoneName()))
|
||||
.sorted(Comparator.comparing(MountTarget::getAvailabilityZoneName))
|
||||
.map(MountTarget::getIpAddress)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings back the NFS servers of persisted mount targets after a restart: each one re-claims
|
||||
* its address on the VPC network, so no instance is handed it, and serves again.
|
||||
*/
|
||||
void onStart(@Observes StartupEvent ignored) {
|
||||
if (nfsServers == null || !nfsServers.enabled()) {
|
||||
return;
|
||||
}
|
||||
dnsServer.addResolver(this::resolveDnsName);
|
||||
nfsServers.removeAll();
|
||||
for (String key : mountTargetStore.keys()) {
|
||||
String region = key.substring(0, key.indexOf("::"));
|
||||
mountTargetStore.get(key).ifPresent(mt -> {
|
||||
// Looking the subnet up first also brings up EC2, which is what rebuilds the VPC
|
||||
// networks the address reservation and the server's attachment both need.
|
||||
try {
|
||||
requireSubnet(region, mt.getSubnetId());
|
||||
} catch (EfsException e) {
|
||||
LOG.warnv("Mount target {0} is in subnet {1}, which no longer exists; it has no NFS server",
|
||||
mt.getMountTargetId(), mt.getSubnetId());
|
||||
return;
|
||||
}
|
||||
nfsServers.reserveAddress(region, mt);
|
||||
serveOverNfs(region, mt);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void serveOverNfs(String region, MountTarget mt) {
|
||||
nfsServers.serve(region, regionResolver.getAccountId(), mt, serving -> {
|
||||
String key = regionKey(region, mt.getMountTargetId());
|
||||
synchronized (lockFor(key)) {
|
||||
mountTargetStore.get(key).ifPresent(current -> {
|
||||
current.setLifeCycleState(LifeCycleState.available);
|
||||
mountTargetStore.put(key, current);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
fileSystemStore.clear();
|
||||
@@ -267,6 +369,10 @@ public class EfsService implements Resettable {
|
||||
|
||||
fileSystemStore.delete(key);
|
||||
}
|
||||
if (lifecycleManager != null && !lifecycleManager.removeVolume(EfsMounts.volumeName(fileSystemId))) {
|
||||
LOG.warnv("The data of deleted file system {0} is still in Docker volume {1}, which is in use",
|
||||
fileSystemId, EfsMounts.volumeName(fileSystemId));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Tags ---
|
||||
@@ -361,37 +467,60 @@ public class EfsService implements Resettable {
|
||||
public MountTarget createMountTarget(CreateMountTargetRequest request, String region) {
|
||||
synchronized (lockFor(regionKey(region, request.getFileSystemId()))) {
|
||||
FileSystem fs = getFileSystem(region, request.getFileSystemId());
|
||||
|
||||
for (MountTarget existing : mountTargetStore.scan(k -> k.startsWith(region + "::"))) {
|
||||
Subnet subnet = requireSubnet(region, request.getSubnetId());
|
||||
|
||||
List<MountTarget> regionMountTargets = mountTargetStore.scan(k -> k.startsWith(region + "::"));
|
||||
for (MountTarget existing : regionMountTargets) {
|
||||
if (existing.getFileSystemId().equals(request.getFileSystemId())) {
|
||||
if (existing.getSubnetId().equals(request.getSubnetId())) {
|
||||
throw EfsException.mountTargetConflict("Mount target already exists in this subnet");
|
||||
}
|
||||
// AWS allows one mount target per Availability Zone, all in one VPC.
|
||||
if (subnet.getAvailabilityZone().equals(existing.getAvailabilityZoneName())) {
|
||||
throw EfsException.mountTargetConflict("Mount target already exists in this AZ");
|
||||
}
|
||||
if (!subnet.getVpcId().equals(existing.getVpcId())) {
|
||||
throw EfsException.mountTargetConflict("Mount targets of a file system must be in the same VPC");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String mtId = "fsmt-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17);
|
||||
|
||||
// As on AWS, the mount target is a network interface in the subnet, which is what
|
||||
// gives it an address no instance can be handed as well.
|
||||
NetworkInterface eni;
|
||||
try {
|
||||
eni = ec2Service.createNetworkInterface(region, request.getSubnetId(),
|
||||
"EFS mount target for " + fs.getFileSystemId() + " (" + mtId + ")",
|
||||
request.getIpAddress(), null, request.getSecurityGroups(), null);
|
||||
} catch (AwsException e) {
|
||||
if ("InvalidGroup.NotFound".equals(e.getErrorCode())) {
|
||||
throw EfsException.securityGroupNotFound(e.getMessage());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
ec2Service.holdNetworkInterfaceForService(region, eni.getNetworkInterfaceId());
|
||||
|
||||
MountTarget mt = new MountTarget();
|
||||
mt.setMountTargetId(mtId);
|
||||
mt.setFileSystemId(request.getFileSystemId());
|
||||
mt.setSubnetId(request.getSubnetId());
|
||||
mt.setIpAddress(request.getIpAddress() != null ? request.getIpAddress() : "10.0.0.10");
|
||||
mt.setLifeCycleState(LifeCycleState.available);
|
||||
mt.setVpcId("vpc-12345678");
|
||||
mt.setAvailabilityZoneName(region + "a");
|
||||
mt.setAvailabilityZoneId(generateAzId(region + "a"));
|
||||
mt.setNetworkInterfaceId("eni-" + UUID.randomUUID().toString().replace("-", "").substring(0, 17));
|
||||
if (request.getSecurityGroups() != null) {
|
||||
mt.setSecurityGroups(new ArrayList<>(request.getSecurityGroups()));
|
||||
} else {
|
||||
mt.setSecurityGroups(new ArrayList<>());
|
||||
}
|
||||
mt.setIpAddress(eni.getPrivateIpAddress());
|
||||
mt.setVpcId(subnet.getVpcId());
|
||||
mt.setAvailabilityZoneName(subnet.getAvailabilityZone());
|
||||
mt.setAvailabilityZoneId(generateAzId(subnet.getAvailabilityZone()));
|
||||
mt.setNetworkInterfaceId(eni.getNetworkInterfaceId());
|
||||
mt.setSecurityGroups(eni.getGroups().stream().map(group -> group.getGroupId())
|
||||
.collect(Collectors.toCollection(ArrayList::new)));
|
||||
boolean servedOverNfs = nfsServers != null && nfsServers.enabled();
|
||||
mt.setLifeCycleState(servedOverNfs ? LifeCycleState.creating : LifeCycleState.available);
|
||||
|
||||
fs.setNumberOfMountTargets(fs.getNumberOfMountTargets() + 1);
|
||||
fileSystemStore.put(regionKey(region, fs.getFileSystemId()), fs);
|
||||
|
||||
mountTargetStore.put(regionKey(region, mtId), mt);
|
||||
if (servedOverNfs) {
|
||||
serveOverNfs(region, mt);
|
||||
}
|
||||
return mt;
|
||||
}
|
||||
}
|
||||
@@ -453,7 +582,11 @@ public class EfsService implements Resettable {
|
||||
if (mt == null) {
|
||||
throw EfsException.mountTargetNotFound(mountTargetId);
|
||||
}
|
||||
|
||||
if (nfsServers != null) {
|
||||
nfsServers.stop(mountTargetId);
|
||||
}
|
||||
releaseNetworkInterface(region, mt);
|
||||
|
||||
try {
|
||||
synchronized (lockFor(regionKey(region, mt.getFileSystemId()))) {
|
||||
FileSystem fs = getFileSystem(region, mt.getFileSystemId());
|
||||
@@ -499,6 +632,7 @@ public class EfsService implements Resettable {
|
||||
synchronized (lockFor(regionKey(region, request.getFileSystemId()))) {
|
||||
// Validate file system exists
|
||||
getFileSystem(region, request.getFileSystemId());
|
||||
validateAccessPoint(request);
|
||||
|
||||
for (AccessPointDescription existing : accessPointStore.scan(k -> k.startsWith(region + "::"))) {
|
||||
if (token.equals(existing.getClientToken())) {
|
||||
@@ -530,6 +664,31 @@ public class EfsService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateAccessPoint(CreateAccessPointRequest request) {
|
||||
PosixUser user = request.getPosixUser();
|
||||
if (user != null && (user.getUid() == null || user.getGid() == null)) {
|
||||
throw EfsException.badRequest("PosixUser requires both Uid and Gid");
|
||||
}
|
||||
RootDirectory root = request.getRootDirectory();
|
||||
if (root == null) {
|
||||
return;
|
||||
}
|
||||
if (root.getPath() != null && (root.getPath().length() > 100
|
||||
|| !ROOT_DIRECTORY_PATH.matcher(root.getPath()).matches())) {
|
||||
throw EfsException.badRequest("RootDirectory.Path is not a valid directory path: " + root.getPath());
|
||||
}
|
||||
CreationInfo info = root.getCreationInfo();
|
||||
if (info != null) {
|
||||
if (info.getOwnerUid() == null || info.getOwnerGid() == null || info.getPermissions() == null) {
|
||||
throw EfsException.badRequest("CreationInfo requires OwnerUid, OwnerGid and Permissions");
|
||||
}
|
||||
if (!info.getPermissions().matches("^[0-7]{3,4}$")) {
|
||||
throw EfsException.badRequest("CreationInfo.Permissions must be 3 or 4 octal digits: "
|
||||
+ info.getPermissions());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public List<AccessPointDescription> describeAccessPoints(String region, String fileSystemId, String accessPointId) {
|
||||
return accessPointStore.scan(k -> k.startsWith(region + "::")).stream()
|
||||
.filter(ap -> fileSystemId == null || ap.getFileSystemId().equals(fileSystemId))
|
||||
@@ -613,6 +772,30 @@ public class EfsService implements Resettable {
|
||||
return region + "::" + id;
|
||||
}
|
||||
|
||||
private Subnet requireSubnet(String region, String subnetId) {
|
||||
if (subnetId == null || subnetId.isBlank()) {
|
||||
throw EfsException.badRequest("SubnetId is required.");
|
||||
}
|
||||
try {
|
||||
return ec2Service.requireSubnet(region, subnetId);
|
||||
} catch (AwsException e) {
|
||||
throw EfsException.subnetNotFound(subnetId);
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseNetworkInterface(String region, MountTarget mt) {
|
||||
if (mt.getNetworkInterfaceId() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ec2Service.releaseNetworkInterfaceFromService(region, mt.getNetworkInterfaceId());
|
||||
ec2Service.deleteNetworkInterface(region, mt.getNetworkInterfaceId());
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("Network interface {0} of mount target {1} is already gone: {2}",
|
||||
mt.getNetworkInterfaceId(), mt.getMountTargetId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String generateAzId(String azName) {
|
||||
if (azName == null || azName.length() < 2) return azName + "-id";
|
||||
String region = azName.substring(0, azName.length() - 1);
|
||||
|
||||
@@ -243,6 +243,9 @@ public class GlueService {
|
||||
}
|
||||
database.setName(databaseName);
|
||||
database.setCatalogId(regionResolver.getAccountId());
|
||||
if (database.getCreateTime() == null) {
|
||||
database.setCreateTime(Instant.now());
|
||||
}
|
||||
databaseStore.put(databaseName, database);
|
||||
if (tags != null && !tags.isEmpty()) {
|
||||
resourceGroupsTaggingService.tagResources(List.of(databaseArn(region, databaseName)), tags, region);
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.glue.model;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -47,10 +48,12 @@ public class Connection {
|
||||
|
||||
@JsonProperty("CreationTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant creationTime;
|
||||
|
||||
@JsonProperty("LastUpdatedTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastUpdatedTime;
|
||||
|
||||
@JsonProperty("LastUpdatedBy")
|
||||
@@ -64,6 +67,7 @@ public class Connection {
|
||||
|
||||
@JsonProperty("LastConnectionValidationTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastConnectionValidationTime;
|
||||
|
||||
@JsonProperty("AuthenticationConfiguration")
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Crawler {
|
||||
@JsonProperty("Classifiers")
|
||||
private List<String> classifiers;
|
||||
@@ -22,6 +25,7 @@ public class Crawler {
|
||||
|
||||
@JsonProperty("CreationTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant creationTime;
|
||||
|
||||
@JsonProperty("DatabaseName")
|
||||
@@ -38,6 +42,7 @@ public class Crawler {
|
||||
|
||||
@JsonProperty("LastUpdated")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastUpdated;
|
||||
|
||||
@JsonProperty("LineageConfiguration")
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Database {
|
||||
@JsonProperty("Name")
|
||||
private String name;
|
||||
@@ -18,6 +21,7 @@ public class Database {
|
||||
private Map<String, String> parameters;
|
||||
@JsonProperty("CreateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant createTime;
|
||||
@JsonProperty("CatalogId")
|
||||
private String catalogId;
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.glue.model;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -22,10 +23,12 @@ public class GluePolicy {
|
||||
|
||||
@JsonProperty("CreateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant createTime;
|
||||
|
||||
@JsonProperty("UpdateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant updateTime;
|
||||
|
||||
public String getPolicyInJson() { return policyInJson; }
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Writes a Glue timestamp as AWS does: epoch seconds to the millisecond, in the shortest
|
||||
* form ({@code 1792964720.27}, not {@code 1792964720.270000000}). The AWS SDK for
|
||||
* JavaScript v3 keeps any number whose text differs from its shortest form as a
|
||||
* BigDecimal, and then refuses it as a timestamp.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public class GlueTimestampSerializer extends JsonSerializer<Instant> {
|
||||
|
||||
@Override
|
||||
public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
gen.writeNumber(epochSeconds(value));
|
||||
}
|
||||
|
||||
static String epochSeconds(Instant value) {
|
||||
return BigDecimal.valueOf(value.toEpochMilli(), 3).stripTrailingZeros().toPlainString();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@@ -9,6 +11,7 @@ import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Job {
|
||||
@JsonProperty("AllocatedCapacity")
|
||||
private Integer allocatedCapacity;
|
||||
@@ -24,6 +27,7 @@ public class Job {
|
||||
|
||||
@JsonProperty("CreatedOn")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant createdOn;
|
||||
|
||||
@JsonProperty("DefaultArguments")
|
||||
@@ -49,6 +53,7 @@ public class Job {
|
||||
|
||||
@JsonProperty("LastModifiedOn")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastModifiedOn;
|
||||
|
||||
@JsonProperty("LogUri")
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class LastCrawlInfo {
|
||||
@JsonProperty("ErrorMessage")
|
||||
private String errorMessage;
|
||||
@@ -21,6 +24,7 @@ public class LastCrawlInfo {
|
||||
|
||||
@JsonProperty("StartTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant startTime;
|
||||
|
||||
@JsonProperty("Status")
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Partition {
|
||||
@JsonProperty("Values")
|
||||
private List<String> values;
|
||||
@@ -17,9 +20,11 @@ public class Partition {
|
||||
private String tableName;
|
||||
@JsonProperty("CreationTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant creationTime;
|
||||
@JsonProperty("LastAccessTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastAccessTime;
|
||||
@JsonProperty("StorageDescriptor")
|
||||
private StorageDescriptor storageDescriptor;
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class Table {
|
||||
@JsonProperty("Name")
|
||||
private String name;
|
||||
@@ -19,12 +22,15 @@ public class Table {
|
||||
private String owner;
|
||||
@JsonProperty("CreateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant createTime;
|
||||
@JsonProperty("UpdateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant updateTime;
|
||||
@JsonProperty("LastAccessTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant lastAccessTime;
|
||||
@JsonProperty("PartitionKeys")
|
||||
private List<Column> partitionKeys;
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class UserDefinedFunction {
|
||||
@JsonProperty("FunctionName")
|
||||
private String functionName;
|
||||
@@ -23,6 +26,7 @@ public class UserDefinedFunction {
|
||||
private String ownerType;
|
||||
@JsonProperty("CreateTime")
|
||||
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
|
||||
@JsonSerialize(using = GlueTimestampSerializer.class)
|
||||
private Instant createTime;
|
||||
@JsonProperty("ResourceUris")
|
||||
private List<ResourceUri> resourceUris;
|
||||
|
||||
+28
-39
@@ -10,6 +10,8 @@ import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.efs.EfsMounts;
|
||||
import io.github.hectorvent.floci.services.efs.model.PosixUser;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.ContainerState;
|
||||
@@ -36,17 +38,13 @@ import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CancellationException;
|
||||
@@ -110,6 +108,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
private final LambdaLayerService layerService;
|
||||
private final LaunchedContainerAwsEnv awsEnv;
|
||||
private final LambdaExecutionRoleCredentials executionRoleCredentials;
|
||||
private final EfsMounts efsMounts;
|
||||
|
||||
@Inject
|
||||
public ContainerLauncher(ContainerBuilder containerBuilder,
|
||||
@@ -122,7 +121,8 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
EcrRegistryManager ecrRegistryManager,
|
||||
LambdaLayerService layerService,
|
||||
LaunchedContainerAwsEnv awsEnv,
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials) {
|
||||
LambdaExecutionRoleCredentials executionRoleCredentials,
|
||||
EfsMounts efsMounts) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -134,6 +134,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
this.layerService = layerService;
|
||||
this.awsEnv = awsEnv;
|
||||
this.executionRoleCredentials = executionRoleCredentials;
|
||||
this.efsMounts = efsMounts;
|
||||
this.populateSemaphore = new java.util.concurrent.Semaphore(resolvePopulateConcurrency(config));
|
||||
}
|
||||
|
||||
@@ -310,21 +311,28 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
|
||||
if (fn.getFileSystemConfigs() != null && !fn.getFileSystemConfigs().isEmpty()) {
|
||||
var efsCfg = config.storage().efs();
|
||||
fn.getFileSystemConfigs().forEach(fileSystem -> {
|
||||
String volumeName = efsVolumeName(fileSystem.getArn());
|
||||
lifecycleManager.ensureSharedVolume(volumeName,
|
||||
efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(),
|
||||
efsCfg.initImage());
|
||||
specBuilder.withNamedVolume(volumeName, fileSystem.getLocalMountPath(), false);
|
||||
});
|
||||
efsCfg.mountUser().ifPresent(user -> {
|
||||
if (!user.matches("^\\d+(:\\d+)?$")) {
|
||||
throw new IllegalArgumentException(
|
||||
"floci.storage.efs.mount-user must be \"uid\" or \"uid:gid\": " + user);
|
||||
}
|
||||
specBuilder.withUser(user);
|
||||
});
|
||||
efsCfg.mountGroupAdd().ifPresent(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
|
||||
// Lambda allows one file system per function. Running as the access point's POSIX user
|
||||
// is how its identity reaches every file the function creates, as EFS enforces it.
|
||||
Optional<PosixUser> accessPointUser = Optional.empty();
|
||||
for (var fileSystem : fn.getFileSystemConfigs()) {
|
||||
EfsMounts.Mount mount = efsMounts.prepareAccessPoint(fileSystem.getArn());
|
||||
mount.applyTo(specBuilder, fileSystem.getLocalMountPath(), false);
|
||||
accessPointUser = accessPointUser.or(mount::accessPointUser);
|
||||
}
|
||||
if (accessPointUser.isPresent()) {
|
||||
specBuilder.withUser(EfsMounts.containerUser(accessPointUser.get()));
|
||||
EfsMounts.secondaryGids(accessPointUser.get())
|
||||
.forEach(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
|
||||
} else {
|
||||
efsCfg.mountUser().ifPresent(user -> {
|
||||
if (!user.matches("^\\d+(:\\d+)?$")) {
|
||||
throw new IllegalArgumentException(
|
||||
"floci.storage.efs.mount-user must be \"uid\" or \"uid:gid\": " + user);
|
||||
}
|
||||
specBuilder.withUser(user);
|
||||
});
|
||||
efsCfg.mountGroupAdd().ifPresent(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
|
||||
}
|
||||
}
|
||||
|
||||
// For Image package type use ImageConfig.Command/EntryPoint/WorkingDirectory if set, otherwise fall back to Handler (Zip-style)
|
||||
@@ -1133,25 +1141,6 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
|
||||
return namePrefix + "-code-" + fname + "-" + h;
|
||||
}
|
||||
|
||||
static String efsVolumeName(String accessPointArn) {
|
||||
int separator = Math.max(accessPointArn.lastIndexOf('/'), accessPointArn.lastIndexOf(':'));
|
||||
String resourceId = separator >= 0 ? accessPointArn.substring(separator + 1) : accessPointArn;
|
||||
if (resourceId.isBlank()) {
|
||||
throw new IllegalArgumentException("File system access point ARN must include a resource id");
|
||||
}
|
||||
return "floci-efs-" + resourceId + "-" + sha256Hex(accessPointArn);
|
||||
}
|
||||
|
||||
private static String sha256Hex(String value) {
|
||||
try {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 is required but not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Buffer for the tar-streaming pipe. The default {@link java.io.PipedInputStream} buffer is
|
||||
* only 1KB, which forces a writer/reader thread hand-off (wait/notify) every 1KB. Streaming a
|
||||
|
||||
@@ -57,6 +57,8 @@ public class SmtpRelay {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SmtpRelay.class);
|
||||
private static final long RELAY_TIMEOUT_SECONDS = 30;
|
||||
/** Every SASL method the mail client supports except XOAUTH2, which expects a token. */
|
||||
static final String PASSWORD_AUTH_METHODS = "CRAM-SHA256 CRAM-SHA1 CRAM-MD5 DIGEST-MD5 LOGIN PLAIN";
|
||||
|
||||
/** SES control header naming the configuration set to apply to a raw send. */
|
||||
public static final String HEADER_CONFIGURATION_SET = "X-SES-CONFIGURATION-SET";
|
||||
@@ -118,6 +120,9 @@ public class SmtpRelay {
|
||||
.filter(u -> !u.isBlank())
|
||||
.ifPresent(u -> {
|
||||
mailConfig.setUsername(u);
|
||||
// smtp-pass is a password, never an OAuth token: without this the client prefers
|
||||
// XOAUTH2 whenever the server offers it (Gmail does) and the login is refused.
|
||||
mailConfig.setAuthMethods(PASSWORD_AUTH_METHODS);
|
||||
config.services().ses().smtpPass()
|
||||
.filter(p -> !p.isBlank())
|
||||
.ifPresent(mailConfig::setPassword);
|
||||
|
||||
@@ -747,6 +747,8 @@ floci:
|
||||
enabled: true
|
||||
efs:
|
||||
enabled: true
|
||||
nfs-servers: true # serve each mount target over NFSv4.1 for EC2 instances
|
||||
nfs-server-image: floci/efs-nfs-server:local # built locally on first use
|
||||
organizations:
|
||||
enabled: true
|
||||
# management-account-email: "" # When set, overrides the management-account email reported by DescribeOrganization and account listings.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
FROM alpine:3.21
|
||||
RUN apk add --no-cache nfs-utils
|
||||
# Serves /export, the EFS file system's volume, over NFSv4.1 from the kernel NFS server, as an EFS
|
||||
# mount target does. fsid=0 makes it the NFSv4 root, so clients mount "<address>:/" like on AWS.
|
||||
CMD ["sh", "-c", "set -e; mount -t nfsd nfsd /proc/fs/nfsd; echo '/export *(rw,fsid=0,no_subtree_check,no_root_squash,insecure,sync)' > /etc/exports; exportfs -ra; rpc.nfsd -N 3 -V 4 -V 4.1 -V 4.2 8; trap 'rpc.nfsd 0; exportfs -ua; exit 0' TERM INT; rpc.mountd -N 2 -N 3 -F & wait"]
|
||||
+25
@@ -6,11 +6,13 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -82,6 +84,29 @@ class AwsJsonCborCloudWatchTimestampIntegrationTest {
|
||||
+ driftSeconds + "s): " + datapoint);
|
||||
}
|
||||
|
||||
// CloudWatch is awsQueryCompatible: the header keeps the Query code while the body names
|
||||
// the model shape, which is what the AWS SDK v2 uses to pick the typed exception.
|
||||
@Test
|
||||
void putMetricDataWithoutMetricNameReturnsTheModelledExceptionShape() throws Exception {
|
||||
ObjectNode putRequest = JSON.createObjectNode();
|
||||
putRequest.put("Namespace", "CborRpcV2MissingName-" + System.nanoTime());
|
||||
putRequest.putArray("MetricData").addObject().put("Value", 1.0);
|
||||
|
||||
Response response = given()
|
||||
.contentType("application/cbor")
|
||||
.accept("application/cbor")
|
||||
.header("smithy-protocol", "rpc-v2-cbor")
|
||||
.body(AwsJsonCborController.nodeToSmithyCbor(putRequest))
|
||||
.when().post("/service/GraniteServiceVersion20100801/operation/PutMetricData");
|
||||
|
||||
assertEquals(400, response.statusCode());
|
||||
assertEquals("MissingParameter;Sender", response.header("x-amzn-query-error"));
|
||||
JsonNode body = CBOR.readTree(response.asByteArray());
|
||||
assertEquals("MissingRequiredParameterException", body.path("__type").asText(), body.toString());
|
||||
assertEquals("The parameter MetricData.member.1.MetricName is required.",
|
||||
body.path("message").asText(), body.toString());
|
||||
}
|
||||
|
||||
private static JsonNode rpcV2Call(String action, ObjectNode body) throws Exception {
|
||||
byte[] responseCbor = given()
|
||||
.contentType("application/cbor")
|
||||
|
||||
@@ -103,6 +103,18 @@ class EmbeddedDnsServerTest {
|
||||
dns.resolveARecord("ip-172-16-128-9.ec2.internal", "172.16.128.5").orElseThrow());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveARecord_asksAddedResolversForOtherNames() {
|
||||
dns.addResolver(name -> name.equals("fs-1.efs.us-east-1.amazonaws.com")
|
||||
? java.util.Optional.of("172.31.0.10") : java.util.Optional.empty());
|
||||
dns.addResolver(name -> { throw new IllegalStateException("broken resolver"); });
|
||||
|
||||
assertEquals("172.31.0.10",
|
||||
dns.resolveARecord("fs-1.efs.us-east-1.amazonaws.com", "172.16.128.5").orElseThrow());
|
||||
assertTrue(dns.resolveARecord("example.com", "172.16.128.5").isEmpty(),
|
||||
"a name no resolver knows is forwarded upstream, even when a resolver fails");
|
||||
}
|
||||
|
||||
// ── matchesSuffix — built-in emulator domains ─────────────────────────────
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package io.github.hectorvent.floci.services.acm;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
|
||||
@QuarkusTest
|
||||
class AcmExportableRequestTest {
|
||||
|
||||
private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCertificateKeepsTheExportOption() {
|
||||
String exportable = request("{\"DomainName\":\"exportable.example.com\",\"Options\":{\"Export\":\"ENABLED\"}}");
|
||||
|
||||
call("DescribeCertificate", "{\"CertificateArn\":\"" + exportable + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Certificate.Options.Export", equalTo("ENABLED"))
|
||||
.body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("ENABLED"));
|
||||
|
||||
call("ExportCertificate", "{\"CertificateArn\":\"" + exportable + "\",\"Passphrase\":\"c2VjcmV0\"}")
|
||||
.statusCode(200)
|
||||
.body("PrivateKey", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCertificateWithoutExportIsNotExportable() {
|
||||
String plain = request("{\"DomainName\":\"plain.example.com\",\"Options\":{\"CertificateTransparencyLoggingPreference\":\"DISABLED\"}}");
|
||||
|
||||
call("DescribeCertificate", "{\"CertificateArn\":\"" + plain + "\"}")
|
||||
.statusCode(200)
|
||||
.body("Certificate.Options.Export", equalTo("DISABLED"))
|
||||
.body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("DISABLED"));
|
||||
|
||||
call("ExportCertificate", "{\"CertificateArn\":\"" + plain + "\",\"Passphrase\":\"c2VjcmV0\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestCertificateRejectsAnUnknownExportValue() {
|
||||
call("RequestCertificate", "{\"DomainName\":\"bad.example.com\",\"Options\":{\"Export\":\"MAYBE\"}}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
private String request(String body) {
|
||||
return call("RequestCertificate", body).statusCode(200).extract().jsonPath().getString("CertificateArn");
|
||||
}
|
||||
|
||||
private io.restassured.response.ValidatableResponse call(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "CertificateManager." + action)
|
||||
.contentType(ACM_CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+20
@@ -98,6 +98,26 @@ class JwtSignatureVerifierTest {
|
||||
verifier.verify(token, issuer); // does not throw
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifiesAnInProcessIssuerWithoutFetchingIt() throws Exception {
|
||||
// Floci's own Cognito issuer: plain HTTP on a hostname, which the strict fetch rules refuse.
|
||||
String localIssuer = "http://floci:4566/us-east-1_local";
|
||||
strictVerifier.withLocalIssuerKeys(candidate -> candidate.equals(localIssuer)
|
||||
? java.util.Optional.of(Map.of("test-key-1", publicKey)) : java.util.Optional.empty());
|
||||
|
||||
assertDoesNotThrow(() -> strictVerifier.verify(signToken("test-key-1", privateKey), localIssuer));
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(signToken("other-key", privateKey), localIssuer));
|
||||
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
|
||||
gen.initialize(2048);
|
||||
String forged = signToken("test-key-1", (RSAPrivateKey) gen.generateKeyPair().getPrivate());
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(forged, localIssuer));
|
||||
// Any other plain-HTTP issuer still goes through the strict fetch, and is refused.
|
||||
assertThrows(JwtSignatureVerifier.JwtVerificationException.class,
|
||||
() -> strictVerifier.verify(signToken("test-key-1", privateKey), "http://floci:4566/us-east-1_other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsATokenSignedWithADifferentKey() throws Exception {
|
||||
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package io.github.hectorvent.floci.services.athena;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class AthenaQueryTextTest {
|
||||
|
||||
@Test
|
||||
void dropsTheClosingSemicolonsAthenaAccepts() {
|
||||
assertEquals("SELECT * FROM orders LIMIT 10", AthenaService.withoutTrailingSemicolons("SELECT * FROM orders LIMIT 10;"));
|
||||
assertEquals("SELECT 1", AthenaService.withoutTrailingSemicolons("SELECT 1 ; ;\n"));
|
||||
assertEquals("SELECT ';' AS s", AthenaService.withoutTrailingSemicolons("SELECT ';' AS s"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsTheEngineErrorWithoutItsEnvelopeOrTheWrappedStatement() {
|
||||
String engine = "floci-duck execute returned HTTP 500: {\"status\":\"error\",\"message\":\"Catalog Error: Table with name nope does not exist!\\nDid you mean \\\"orders\\\"?\\n\\nLINE 1: COPY (SELECT * FROM nope) TO 's3://results/q.csv'\"}";
|
||||
assertEquals("Catalog Error: Table with name nope does not exist!\nDid you mean \"orders\"?", AthenaService.failureReason(engine));
|
||||
assertEquals("Failed to call floci-duck execute: timeout", AthenaService.failureReason("Failed to call floci-duck execute: timeout"));
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package io.github.hectorvent.floci.services.athena;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** Queries belong to their workgroup: they use its result location and are listed under it. */
|
||||
@QuarkusTest
|
||||
class AthenaWorkGroupQueriesIntegrationTest {
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse athena(String action, String body) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AmazonAthena." + action)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
private static String workGroup(String location, boolean enforce) {
|
||||
String name = "wg-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
athena("CreateWorkGroup", """
|
||||
{"Name": "%s", "Configuration": {"ResultConfiguration": {"OutputLocation": "%s"}, "EnforceWorkGroupConfiguration": %s}}
|
||||
""".formatted(name, location, enforce)).statusCode(200);
|
||||
return name;
|
||||
}
|
||||
|
||||
private static String start(String workGroup, String outputLocation) {
|
||||
String result = outputLocation == null ? "" : ", \"ResultConfiguration\": {\"OutputLocation\": \"" + outputLocation + "\"}";
|
||||
return athena("StartQueryExecution", "{\"QueryString\": \"SELECT 1\", \"WorkGroup\": \"" + workGroup + "\"" + result + "}")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("QueryExecutionId");
|
||||
}
|
||||
|
||||
private static String outputLocation(String queryId) {
|
||||
return athena("GetQueryExecution", "{\"QueryExecutionId\": \"" + queryId + "\"}")
|
||||
.statusCode(200)
|
||||
.body("QueryExecution.WorkGroup", not(equalTo(null)))
|
||||
.extract().jsonPath().getString("QueryExecution.ResultConfiguration.OutputLocation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesTheWorkGroupResultLocationWhenTheQueryNamesNone() {
|
||||
String name = workGroup("s3://team-results/athena/", false);
|
||||
String queryId = start(name, null);
|
||||
|
||||
assertEquals("s3://team-results/athena/" + queryId + ".csv", outputLocation(queryId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestedLocationWinsUnlessTheWorkGroupEnforcesItsOwn() {
|
||||
String open = workGroup("s3://team-results/open/", false);
|
||||
String openQuery = start(open, "s3://mine/results/");
|
||||
assertEquals("s3://mine/results/" + openQuery + ".csv", outputLocation(openQuery));
|
||||
|
||||
String enforced = workGroup("s3://team-results/enforced/", true);
|
||||
String enforcedQuery = start(enforced, "s3://mine/results/");
|
||||
assertEquals("s3://team-results/enforced/" + enforcedQuery + ".csv", outputLocation(enforcedQuery));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAWorkGroupThatDoesNotExist() {
|
||||
athena("StartQueryExecution", "{\"QueryString\": \"SELECT 1\", \"WorkGroup\": \"no-such-group\"}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsOnlyTheWorkGroupQueriesNewestFirst() {
|
||||
String name = workGroup("s3://team-results/listed/", false);
|
||||
String first = start(name, null);
|
||||
String second = start(name, null);
|
||||
String elsewhere = start("primary", null);
|
||||
|
||||
List<String> listed = athena("ListQueryExecutions", "{\"WorkGroup\": \"" + name + "\"}")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getList("QueryExecutionIds", String.class);
|
||||
assertEquals(List.of(second, first), listed);
|
||||
|
||||
athena("ListQueryExecutions", "{}")
|
||||
.statusCode(200)
|
||||
.body("QueryExecutionIds", hasItem(elsewhere))
|
||||
.body("QueryExecutionIds", not(hasItem(first)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePrimaryWorkGroupKeepsItsDefaultLocation() {
|
||||
String queryId = start("primary", null);
|
||||
org.hamcrest.MatcherAssert.assertThat(outputLocation(queryId), startsWith("s3://floci-athena-results/results/"));
|
||||
}
|
||||
}
|
||||
+2
@@ -45,6 +45,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCf
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCompositeAlarmCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoUserPoolGroupCfnProvisioner;
|
||||
@@ -300,6 +301,7 @@ final class CfnProvisionerFixture {
|
||||
}
|
||||
if (cloudWatchMetricsService != null) {
|
||||
discovered.add(new CloudWatchCfnProvisioner(cloudWatchMetricsService));
|
||||
discovered.add(new CloudWatchCompositeAlarmCfnProvisioner(cloudWatchMetricsService));
|
||||
}
|
||||
if (cloudWatchDashboardsService != null) {
|
||||
discovered.add(new CloudWatchDashboardCfnProvisioner(cloudWatchDashboardsService));
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.CfnStackWaits;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationCompositeAlarmIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void failedUpdateRestoresRuleTagsAndIdentity(boolean rename) throws Exception {
|
||||
String stack = unique("composite-rollback");
|
||||
String name = stack + "-alarm";
|
||||
String next = rename ? name + "-new" : name;
|
||||
deploy("CreateStack", stack, template(name, "TRUE", Map.of("team", "old", "drop", "restore"), false, false));
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
String arn = alarm(name).get("AlarmArn").toString();
|
||||
Response described = given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks").formParam("StackName", stack).post("/");
|
||||
assertEquals(name, described.xmlPath().getString(
|
||||
"DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member.find { it.OutputKey == 'Name' }.OutputValue"));
|
||||
assertEquals(arn, described.xmlPath().getString(
|
||||
"DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member.find { it.OutputKey == 'Arn' }.OutputValue"));
|
||||
cw("TagResource", Map.of("ResourceARN", arn, "Tags", List.of(Map.of("Key", "external", "Value", "keep"))))
|
||||
.then().statusCode(200);
|
||||
deploy("UpdateStack", stack, template(next, "FALSE", Map.of("team", "new", "added", "remove"), true, false));
|
||||
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
assertEquals("TRUE", alarm(name).get("AlarmRule"));
|
||||
List<Map<String, String>> tags = cw("ListTagsForResource", Map.of("ResourceARN", arn))
|
||||
.then().statusCode(200).extract().jsonPath().getList("Tags");
|
||||
assertEquals(Map.of("team", "old", "drop", "restore", "external", "keep"),
|
||||
tags.stream().collect(Collectors.toMap(t -> t.get("Key"), t -> t.get("Value"))));
|
||||
if (rename) {
|
||||
assertMissing(next);
|
||||
}
|
||||
deleteStack(stack);
|
||||
assertMissing(name);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void replacementHonorsRetentionAndDeletesItsCurrentBackingAlarm(boolean retain) throws Exception {
|
||||
String stack = unique("composite-replace");
|
||||
String original = stack + "-old";
|
||||
String next = stack + "-new";
|
||||
deploy("CreateStack", stack, template(original, "TRUE", Map.of(), false, retain));
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
deploy("UpdateStack", stack, template(next, "FALSE", Map.of(), false, retain));
|
||||
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
assertEquals("FALSE", alarm(next).get("AlarmRule"));
|
||||
if (retain) {
|
||||
assertEquals("TRUE", alarm(original).get("AlarmRule"));
|
||||
} else {
|
||||
assertMissing(original);
|
||||
}
|
||||
deleteStack(stack);
|
||||
assertMissing(next);
|
||||
if (retain) {
|
||||
assertEquals("TRUE", alarm(original).get("AlarmRule"));
|
||||
cw("DeleteAlarms", Map.of("AlarmNames", List.of(original))).then().statusCode(200);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void committedInPlaceUpdatesAllowAnotherUpdateAndReplacement() throws Exception {
|
||||
String stack = unique("composite-sequence");
|
||||
String name = stack + "-alarm";
|
||||
String replacement = name + "-new";
|
||||
deploy("CreateStack", stack, template(name, "TRUE", Map.of("team", "initial"), false, false));
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
for (String rule : List.of("FALSE", "TRUE")) {
|
||||
deploy("UpdateStack", stack, template(name, rule, Map.of("team", rule), false, false));
|
||||
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
assertEquals(rule, alarm(name).get("AlarmRule"));
|
||||
}
|
||||
deploy("UpdateStack", stack, template(replacement, "FALSE", Map.of(), false, false));
|
||||
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
assertMissing(name);
|
||||
assertEquals("FALSE", alarm(replacement).get("AlarmRule"));
|
||||
deleteStack(stack);
|
||||
assertMissing(replacement);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCollisionCannotOverwriteOrDeleteAnUnmanagedAlarm() throws Exception {
|
||||
String stack = unique("composite-foreign");
|
||||
String name = stack + "-alarm";
|
||||
cw("PutCompositeAlarm", Map.of("AlarmName", name, "AlarmRule", "TRUE")).then().statusCode(200);
|
||||
deploy("CreateStack", stack, template(name, "FALSE", Map.of(), false, false));
|
||||
assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
assertEquals("TRUE", alarm(name).get("AlarmRule"));
|
||||
deleteStack(stack);
|
||||
assertEquals("TRUE", alarm(name).get("AlarmRule"));
|
||||
cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200);
|
||||
}
|
||||
|
||||
private String template(String name, String rule, Map<String, String> tags, boolean fail, boolean retain)
|
||||
throws JsonProcessingException {
|
||||
cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200));
|
||||
Map<String, Object> resources = new LinkedHashMap<>();
|
||||
resources.put("Alarm", Map.of("Type", "AWS::CloudWatch::CompositeAlarm",
|
||||
"UpdateReplacePolicy", retain ? "Retain" : "Delete",
|
||||
"Properties", Map.of("AlarmName", name, "AlarmRule", rule,
|
||||
"Tags", tags.entrySet().stream().map(e -> Map.of("Key", e.getKey(), "Value", e.getValue())).toList())));
|
||||
if (fail) {
|
||||
resources.put("Failure", Map.of("Type", "AWS::SecretsManager::Secret", "DependsOn", "Alarm",
|
||||
"Properties", Map.of("SecretString", "explicit", "GenerateSecretString", Map.of("PasswordLength", 32))));
|
||||
}
|
||||
return MAPPER.writeValueAsString(Map.of("Resources", resources, "Outputs", Map.of(
|
||||
"Name", Map.of("Value", Map.of("Ref", "Alarm")),
|
||||
"Arn", Map.of("Value", Map.of("Fn::GetAtt", List.of("Alarm", "Arn"))))));
|
||||
}
|
||||
|
||||
private void deploy(String action, String stack, String template) {
|
||||
if ("CreateStack".equals(action)) {
|
||||
cleanup.register(() -> given().port(baseUri.getPort())
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DeleteStack").formParam("StackName", stack)
|
||||
.post("/").then().statusCode(200));
|
||||
}
|
||||
given().contentType("application/x-www-form-urlencoded").formParam("Action", action)
|
||||
.formParam("StackName", stack).formParam("TemplateBody", template).post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private Response cw(String operation, Map<String, ?> body) {
|
||||
if ("PutCompositeAlarm".equals(operation)) {
|
||||
String name = body.get("AlarmName").toString();
|
||||
cleanup.register(() -> cw("DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200));
|
||||
}
|
||||
return given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
|
||||
.body(MAPPER.valueToTree(body).toString()).post("/");
|
||||
}
|
||||
|
||||
private Map<String, Object> alarm(String name) throws JsonProcessingException {
|
||||
List<Map<String, Object>> alarms = cw("DescribeAlarms", Map.of("AlarmNames", List.of(name),
|
||||
"AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200)
|
||||
.extract().jsonPath().getList("CompositeAlarms");
|
||||
assertEquals(1, alarms.size(), name);
|
||||
return alarms.getFirst();
|
||||
}
|
||||
|
||||
private void assertMissing(String name) throws JsonProcessingException {
|
||||
assertEquals(List.of(), cw("DescribeAlarms", Map.of("AlarmNames", List.of(name),
|
||||
"AlarmTypes", List.of("CompositeAlarm"))).then().statusCode(200)
|
||||
.extract().jsonPath().getList("CompositeAlarms"));
|
||||
}
|
||||
|
||||
private void deleteStack(String stack) {
|
||||
given().contentType("application/x-www-form-urlencoded").formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stack).post("/").then().statusCode(200);
|
||||
CfnStackWaits.awaitStackDeleted(stack);
|
||||
}
|
||||
|
||||
private static String unique(String prefix) {
|
||||
return prefix + "-" + Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class CloudWatchCompositeAlarmCfnProvisionerTest {
|
||||
@Test
|
||||
void rejectedBackingUpdateDoesNotArmRollbackToDeleteAnUnmanagedReplacement() throws Exception {
|
||||
CloudWatchMetricsService service = mock(CloudWatchMetricsService.class);
|
||||
CloudWatchCompositeAlarmCfnProvisioner provisioner = new CloudWatchCompositeAlarmCfnProvisioner(service);
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(call -> {
|
||||
JsonNode node = call.getArgument(0);
|
||||
return node == null || node.isMissingNode() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Alarm");
|
||||
resource.setResourceType("AWS::CloudWatch::CompositeAlarm");
|
||||
resource.setPhysicalId("kept");
|
||||
resource.getAttributes().put("Arn", "prior-arn");
|
||||
AwsException collision = new AwsException("ValidationError", "A metric alarm now has this name", 400);
|
||||
doThrow(collision).when(service).putCompositeAlarm(any(), eq("us-east-1"), eq(true));
|
||||
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "kept");
|
||||
JsonNode props = new ObjectMapper().readTree("{\"AlarmName\":\"kept\",\"AlarmRule\":\"TRUE\"}");
|
||||
assertSame(collision, assertThrows(AwsException.class, () -> provisioner.provision(resource, props, context)));
|
||||
assertFalse(provisioner.retainsFailedUpdateState(resource));
|
||||
assertFalse(provisioner.rollbackUpdate(resource));
|
||||
assertEquals("kept", resource.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", "prior-arn"), resource.getAttributes());
|
||||
verify(service, never()).deleteAlarms(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inPlaceUpdateRetriesPreviouslyDisplacedAlarmCleanup() throws Exception {
|
||||
CloudWatchMetricsService service = mock(CloudWatchMetricsService.class);
|
||||
CloudWatchCompositeAlarmCfnProvisioner provisioner = new CloudWatchCompositeAlarmCfnProvisioner(service);
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(call -> {
|
||||
JsonNode node = call.getArgument(0);
|
||||
return node == null || node.isMissingNode() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
|
||||
StackResource resource = new StackResource();
|
||||
resource.setLogicalId("Alarm");
|
||||
resource.setResourceType("AWS::CloudWatch::CompositeAlarm");
|
||||
resource.setPhysicalId("current");
|
||||
ReplacementCleanup.record(resource,
|
||||
new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "displaced"), Map.of());
|
||||
doThrow(new IllegalStateException("delete unavailable"))
|
||||
.doThrow(new IllegalStateException("delete still unavailable")).doNothing()
|
||||
.when(service).deleteAlarms(List.of("displaced"), "us-east-1");
|
||||
assertFalse(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
assertEquals(Set.of("displaced"), ReplacementCleanup.owedPhysicalIds(resource));
|
||||
|
||||
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "current");
|
||||
JsonNode props = new ObjectMapper().readTree("{\"AlarmName\":\"current\",\"AlarmRule\":\"TRUE\"}");
|
||||
provisioner.provision(resource, props, context);
|
||||
assertTrue(provisioner.retainsFailedUpdateState(resource));
|
||||
UpdateCleanupResult retry = provisioner.completeUpdate(resource);
|
||||
assertFalse(retry.complete());
|
||||
assertEquals(2, retry.attempts());
|
||||
assertEquals("displaced", retry.previousPhysicalId());
|
||||
assertEquals("delete still unavailable", retry.failureReason());
|
||||
assertEquals(Set.of("displaced"), ReplacementCleanup.owedPhysicalIds(resource));
|
||||
assertTrue(provisioner.completeUpdate(resource).complete());
|
||||
provisioner.clearUpdate(resource);
|
||||
assertFalse(provisioner.retainsFailedUpdateState(resource));
|
||||
assertTrue(ReplacementCleanup.owedPhysicalIds(resource).isEmpty());
|
||||
assertEquals("current", resource.getPhysicalId());
|
||||
verify(service, times(3)).deleteAlarms(List.of("displaced"), "us-east-1");
|
||||
verify(service, never()).deleteAlarms(List.of("current"), "us-east-1");
|
||||
}
|
||||
|
||||
}
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Tagging a CloudWatch resource whose ARN names nothing has to fail, on every one of the three
|
||||
* tag operations and for every taggable kind CloudWatch owns.
|
||||
*
|
||||
* <p>Each kind is checked twice: once on an ARN that resolves, so the operation is known to work
|
||||
* at all, and once on the same ARN with the resource name swapped for one that was never created.
|
||||
* The two ARNs are byte-identical in shape, so "the ARN was malformed" cannot explain the second
|
||||
* answer. Without that pairing a test asserting only the failure would also pass against a build
|
||||
* whose tag operations were broken outright.
|
||||
*
|
||||
* <p>The failure to look for is {@code ResourceNotFoundException}. CloudWatch's model declares
|
||||
* that code, not the shorter {@code ResourceNotFound} that {@code GetDashboard} and
|
||||
* {@code SetAlarmState} answer with, for {@code TagResource}, {@code UntagResource} and
|
||||
* {@code ListTagsForResource}; the SDK maps the two to different exception classes, so a caller
|
||||
* catching the documented one would not see the other.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchTagUnknownResourceIntegrationTest {
|
||||
|
||||
private static final String CW_SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/monitoring/aws4_request";
|
||||
private static final String LOGS_SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/logs/aws4_request";
|
||||
|
||||
private static final String JSON_1_0 = "application/x-amz-json-1.0";
|
||||
private static final String JSON_1_1 = "application/x-amz-json-1.1";
|
||||
|
||||
private static final String PREFIX = "arn:aws:cloudwatch:us-east-1:000000000000:";
|
||||
private static final String FIREHOSE_ARN =
|
||||
"arn:aws:firehose:us-east-1:000000000000:deliverystream/metrics";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/metric-stream-role";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static RequestSpecification query(String action) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CW_SCOPE)
|
||||
.formParam("Action", action);
|
||||
}
|
||||
|
||||
private static RequestSpecification json(String contentType, String scope, String target, String body) {
|
||||
return given()
|
||||
.contentType(contentType)
|
||||
.header("Authorization", scope)
|
||||
.header("X-Amz-Target", target)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
private static RequestSpecification metricsJson(String target, String body) {
|
||||
return json(JSON_1_0, CW_SCOPE, "GraniteServiceVersion20100801." + target, body);
|
||||
}
|
||||
|
||||
private static RequestSpecification logsJson(String target, String body) {
|
||||
return json(JSON_1_1, LOGS_SCOPE, "Logs_20140328." + target, body);
|
||||
}
|
||||
|
||||
/** The three Query tag operations against one ARN, asserting the same outcome for each. */
|
||||
private static void assertQueryTagOpsNotFound(String arn) {
|
||||
query("TagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("Tags.member.1.Key", "env")
|
||||
.formParam("Tags.member.1.Value", "prod")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"));
|
||||
|
||||
query("UntagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("TagKeys.member.1", "env")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"));
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/** The same three operations against an ARN that does resolve, read back through a list. */
|
||||
private static void assertQueryTagOpsSucceed(String arn) {
|
||||
query("TagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("Tags.member.1.Key", "env")
|
||||
.formParam("Tags.member.1.Value", "prod")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListTagsForResourceResponse.ListTagsForResourceResult.Tags.member.Key",
|
||||
equalTo("env"))
|
||||
.body("ListTagsForResourceResponse.ListTagsForResourceResult.Tags.member.Value",
|
||||
equalTo("prod"));
|
||||
|
||||
query("UntagResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.formParam("TagKeys.member.1", "env")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
query("ListTagsForResource")
|
||||
.formParam("ResourceARN", arn)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Key>env</Key>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void alarmTagOperationsRejectAnArnThatNamesNoAlarm() {
|
||||
query("PutMetricAlarm")
|
||||
.formParam("AlarmName", "tag-unknown-alarm")
|
||||
.formParam("MetricName", "CPUUtilization")
|
||||
.formParam("Namespace", "AWS/EC2")
|
||||
.formParam("ComparisonOperator", "GreaterThanThreshold")
|
||||
.formParam("EvaluationPeriods", "1")
|
||||
.formParam("Period", "60")
|
||||
.formParam("Statistic", "Average")
|
||||
.formParam("Threshold", "80")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertQueryTagOpsSucceed(PREFIX + "alarm:tag-unknown-alarm");
|
||||
assertQueryTagOpsNotFound(PREFIX + "alarm:tag-unknown-alarm-nosuch");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dashboardTagOperationsRejectAnArnThatNamesNoDashboard() {
|
||||
query("PutDashboard")
|
||||
.formParam("DashboardName", "tag-unknown-dashboard")
|
||||
.formParam("DashboardBody", "{\"widgets\":[]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertQueryTagOpsSucceed(PREFIX + "dashboard/tag-unknown-dashboard");
|
||||
assertQueryTagOpsNotFound(PREFIX + "dashboard/tag-unknown-dashboard-nosuch");
|
||||
}
|
||||
|
||||
@Test
|
||||
void metricStreamTagOperationsRejectAnArnThatNamesNoStream() {
|
||||
query("PutMetricStream")
|
||||
.formParam("Name", "tag-unknown-stream")
|
||||
.formParam("FirehoseArn", FIREHOSE_ARN)
|
||||
.formParam("RoleArn", ROLE_ARN)
|
||||
.formParam("OutputFormat", "json")
|
||||
.formParam("IncludeFilters.member.1.Namespace", "AWS/EC2")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertQueryTagOpsSucceed(PREFIX + "metric-stream/tag-unknown-stream");
|
||||
assertQueryTagOpsNotFound(PREFIX + "metric-stream/tag-unknown-stream-nosuch");
|
||||
}
|
||||
|
||||
/**
|
||||
* The dashboard ARN AWS documents carries no region, and the one Floci mints does. A
|
||||
* caller sending the documented form for a dashboard that exists must not be told the
|
||||
* dashboard does not exist, which is what raising on a miss would otherwise have made of
|
||||
* a shape that used to fall through to an empty tag map.
|
||||
*/
|
||||
@Test
|
||||
void theRegionlessDashboardArnAwsDocumentsAlsoResolves() {
|
||||
query("PutDashboard")
|
||||
.formParam("DashboardName", "tag-regionless-dashboard")
|
||||
.formParam("DashboardBody", "{\"widgets\":[]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
assertQueryTagOpsSucceed("arn:aws:cloudwatch::000000000000:dashboard/tag-regionless-dashboard");
|
||||
|
||||
// Still only an absent region: another region's ARN remains a miss.
|
||||
assertQueryTagOpsNotFound(
|
||||
"arn:aws:cloudwatch:eu-west-1:000000000000:dashboard/tag-regionless-dashboard");
|
||||
}
|
||||
|
||||
/**
|
||||
* Both handlers route every ARN that is not a dashboard and not a metric stream to the
|
||||
* alarm path, so a Contributor Insights ARN, which AWS documents as taggable and Floci
|
||||
* does not serve, lands there. Reporting it as not found is right; calling it an alarm
|
||||
* that was not found is not, so the message names the ARN instead.
|
||||
*/
|
||||
@Test
|
||||
void anArnOfAKindFlociDoesNotServeIsReportedAgainstTheArn() {
|
||||
query("TagResource")
|
||||
.formParam("ResourceARN", PREFIX + "insight-rule/no-such-rule")
|
||||
.formParam("Tags.member.1.Key", "env")
|
||||
.formParam("Tags.member.1.Value", "prod")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ResourceNotFoundException"))
|
||||
.body("ErrorResponse.Error.Message",
|
||||
containsString("insight-rule/no-such-rule"))
|
||||
.body("ErrorResponse.Error.Message",
|
||||
not(containsString("Alarm")));
|
||||
}
|
||||
|
||||
/**
|
||||
* CloudWatch Metrics serves the same three operations over JSON as well as Query, and
|
||||
* AGENTS.md requires the two handlers not to drift. A fix applied to only one of them
|
||||
* would leave the CLI and SDK v3 route still answering 200.
|
||||
*/
|
||||
@Test
|
||||
void theJsonProtocolRejectsTheSameArns() {
|
||||
metricsJson("PutMetricAlarm", """
|
||||
{"AlarmName": "tag-unknown-json-alarm", "MetricName": "CPUUtilization",
|
||||
"Namespace": "AWS/EC2", "ComparisonOperator": "GreaterThanThreshold",
|
||||
"EvaluationPeriods": 1, "Period": 60, "Statistic": "Average", "Threshold": 80}""")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
String real = PREFIX + "alarm:tag-unknown-json-alarm";
|
||||
String ghost = PREFIX + "alarm:tag-unknown-json-alarm-nosuch";
|
||||
|
||||
metricsJson("TagResource",
|
||||
"{\"ResourceARN\": \"" + real + "\", \"Tags\": [{\"Key\": \"env\", \"Value\": \"prod\"}]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
metricsJson("ListTagsForResource", "{\"ResourceARN\": \"" + real + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Tags[0].Key", equalTo("env"))
|
||||
.body("Tags[0].Value", equalTo("prod"));
|
||||
|
||||
metricsJson("TagResource",
|
||||
"{\"ResourceARN\": \"" + ghost + "\", \"Tags\": [{\"Key\": \"env\", \"Value\": \"prod\"}]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
|
||||
metricsJson("UntagResource", "{\"ResourceARN\": \"" + ghost + "\", \"TagKeys\": [\"env\"]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
|
||||
metricsJson("ListTagsForResource", "{\"ResourceARN\": \"" + ghost + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* CloudWatch Logs serves its own TagResource, UntagResource and ListTagsForResource over
|
||||
* a separate handler, and already rejects an ARN that names no log group. Pinning it keeps
|
||||
* the two halves of CloudWatch's tagging from diverging again in the other direction.
|
||||
*/
|
||||
@Test
|
||||
void logGroupTagOperationsRejectAnArnThatNamesNoGroup() {
|
||||
String real = "arn:aws:logs:us-east-1:000000000000:log-group:tag-unknown-group:*";
|
||||
String ghost = "arn:aws:logs:us-east-1:000000000000:log-group:tag-unknown-group-nosuch:*";
|
||||
|
||||
logsJson("CreateLogGroup", "{\"logGroupName\": \"tag-unknown-group\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
logsJson("TagResource",
|
||||
"{\"resourceArn\": \"" + real + "\", \"tags\": {\"env\": \"prod\"}}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
logsJson("ListTagsForResource", "{\"resourceArn\": \"" + real + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.env", equalTo("prod"));
|
||||
|
||||
logsJson("TagResource",
|
||||
"{\"resourceArn\": \"" + ghost + "\", \"tags\": {\"env\": \"prod\"}}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
|
||||
logsJson("UntagResource", "{\"resourceArn\": \"" + ghost + "\", \"tagKeys\": [\"env\"]}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
|
||||
logsJson("ListTagsForResource", "{\"resourceArn\": \"" + ghost + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+73
-8
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -116,10 +117,10 @@ class CloudWatchDashboardsServiceTest {
|
||||
|
||||
@Test
|
||||
void tagsGivenOnCreateAreReadableByArn() {
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
|
||||
service.putDashboard("ops", BODY, Map.of("team", "platform"), REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
assertEquals(Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
assertTrue(CloudWatchDashboardsService.isDashboardArn(arn));
|
||||
}
|
||||
|
||||
@@ -129,12 +130,12 @@ class CloudWatchDashboardsServiceTest {
|
||||
*/
|
||||
@Test
|
||||
void tagsOnAReplacingPutDoNotOverwriteTheExistingOnes() {
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "platform"), REGION);
|
||||
service.putDashboard("ops", BODY, Map.of("team", "platform"), REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
service.putDashboard("ops", BODY, java.util.Map.of("team", "someone-else"), REGION);
|
||||
service.putDashboard("ops", BODY, Map.of("team", "someone-else"), REGION);
|
||||
|
||||
assertEquals(java.util.Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
assertEquals(Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -142,11 +143,75 @@ class CloudWatchDashboardsServiceTest {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
|
||||
service.tagResource(arn, java.util.Map.of("env", "dev"), REGION);
|
||||
assertEquals(java.util.Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
|
||||
service.tagResource(arn, Map.of("env", "dev"), REGION);
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
|
||||
|
||||
service.untagResource(arn, List.of("env"), REGION);
|
||||
assertEquals(java.util.Map.of(), service.listTagsForResource(arn, REGION));
|
||||
assertEquals(Map.of(), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS documents the dashboard ARN without a region and Floci mints one with a region, so
|
||||
* both forms have to resolve. Before the tag operations raised on a miss this divergence
|
||||
* was invisible here: the documented ARN matched nothing and got an empty tag map back.
|
||||
*/
|
||||
@Test
|
||||
void bothTheRegionlessAndTheRegionfulDashboardArnResolve() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
String regionful = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
String regionless = "arn:aws:cloudwatch::000000000000:dashboard/ops";
|
||||
|
||||
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:dashboard/ops", regionful);
|
||||
assertTrue(CloudWatchDashboardsService.isDashboardArn(regionless));
|
||||
|
||||
service.tagResource(regionless, Map.of("env", "dev"), REGION);
|
||||
// Read back through the other form: one dashboard, reachable either way.
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(regionful, REGION));
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(regionless, REGION));
|
||||
|
||||
service.untagResource(regionless, List.of("env"), REGION);
|
||||
assertEquals(Map.of(), service.listTagsForResource(regionful, REGION));
|
||||
}
|
||||
|
||||
/**
|
||||
* Only an absent region stands in for the dashboard's own. An ARN naming a different
|
||||
* region must not resolve to the same-named dashboard in this one.
|
||||
*/
|
||||
@Test
|
||||
void anArnNamingAnotherRegionDoesNotResolve() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
String elsewhere = "arn:aws:cloudwatch:eu-west-1:000000000000:dashboard/ops";
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.listTagsForResource(elsewhere, REGION));
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* An ARN naming no dashboard is an error on all three operations, not a silent no-op. The
|
||||
* ARN used here differs from a working one only in the dashboard name, so the outcome
|
||||
* cannot be explained by the ARN failing to parse as a dashboard ARN.
|
||||
*/
|
||||
@Test
|
||||
void tagOperationsRejectAnArnThatNamesNoDashboard() {
|
||||
service.putDashboard("ops", BODY, REGION);
|
||||
String arn = service.getDashboard("ops", REGION).getDashboardArn();
|
||||
String ghost = arn.replace("dashboard/ops", "dashboard/nosuch");
|
||||
assertTrue(CloudWatchDashboardsService.isDashboardArn(ghost));
|
||||
|
||||
for (Runnable call : List.<Runnable>of(
|
||||
() -> service.tagResource(ghost, Map.of("env", "prod"), REGION),
|
||||
() -> service.untagResource(ghost, List.of("env"), REGION),
|
||||
() -> service.listTagsForResource(ghost, REGION))) {
|
||||
AwsException e = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
|
||||
// The failures wrote nothing: the real dashboard still carries only what it was given.
|
||||
assertEquals(Map.of(), service.listTagsForResource(arn, REGION));
|
||||
service.tagResource(arn, Map.of("env", "dev"), REGION);
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class AlarmSnsNotifierTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:alarms";
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private SnsService sns;
|
||||
private CloudWatchMetricsService service;
|
||||
private MetricAlarm alarm;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
sns = mock(SnsService.class);
|
||||
service = new CloudWatchMetricsService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, "000000000000"), new AlarmSnsNotifier(sns, mapper));
|
||||
alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("test-alarm");
|
||||
alarm.setActionsEnabled(true);
|
||||
alarm.setAlarmActions(List.of(TOPIC));
|
||||
alarm.setOkActions(List.of(TOPIC));
|
||||
alarm.setInsufficientDataActions(List.of(TOPIC));
|
||||
alarm.setEvaluationPeriods(3);
|
||||
alarm.setStatistic("Average");
|
||||
alarm.setMetricName("Errors");
|
||||
alarm.setNamespace("Local/PoC");
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesAwsPayloadForEachTransitionButNotRepeatedState() throws Exception {
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION);
|
||||
service.setAlarmState("test-alarm", "ALARM", "still breached", null, REGION);
|
||||
service.setAlarmState("test-alarm", "OK", "recovered", null, REGION);
|
||||
service.setAlarmState("test-alarm", "INSUFFICIENT_DATA", "missing", null, REGION);
|
||||
ArgumentCaptor<String> messages = ArgumentCaptor.forClass(String.class);
|
||||
verify(sns, times(3)).publish(eq(TOPIC), isNull(), messages.capture(), anyString(), eq(REGION));
|
||||
JsonNode first = mapper.readTree(messages.getAllValues().getFirst());
|
||||
assertEquals("test-alarm", first.path("AlarmName").asText());
|
||||
assertEquals("INSUFFICIENT_DATA", first.path("OldStateValue").asText());
|
||||
assertEquals("ALARM", first.path("NewStateValue").asText());
|
||||
assertEquals("000000000000", first.path("AWSAccountId").asText());
|
||||
assertEquals(alarm.getAlarmArn(), first.path("AlarmArn").asText());
|
||||
assertEquals("Errors", first.path("Trigger").path("MetricName").asText());
|
||||
assertFalse(first.path("Trigger").has("DatapointsToAlarm"));
|
||||
assertEquals("AVERAGE", first.path("Trigger").path("Statistic").asText());
|
||||
assertEquals("", first.path("Trigger").path("EvaluateLowSampleCountPercentile").asText());
|
||||
assertTrue(first.path("Trigger").path("EvaluateLowSampleCountPercentile").isTextual());
|
||||
assertNull(alarm.getDatapointsToAlarm());
|
||||
assertEquals("OK", mapper.readTree(messages.getAllValues().get(2)).path("OldStateValue").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatsBothTimestampsWithMillisAndUtcOffset() throws Exception {
|
||||
alarm.setAlarmConfigurationUpdatedTimestamp(1716280510L);
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION);
|
||||
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
|
||||
verify(sns).publish(eq(TOPIC), isNull(), message.capture(), anyString(), eq(REGION));
|
||||
JsonNode payload = mapper.readTree(message.getValue());
|
||||
assertEquals("2024-05-21T08:35:10.000+0000",
|
||||
payload.path("AlarmConfigurationUpdatedTimestamp").asText());
|
||||
String stateChangeTime = payload.path("StateChangeTime").asText();
|
||||
assertTrue(stateChangeTime
|
||||
.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}\\+0000"));
|
||||
assertEquals(alarm.getStateUpdatedTimestamp(),
|
||||
Instant.parse(stateChangeTime.replace("+0000", "Z")).getEpochSecond());
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesExplicitDatapointsToAlarmInPayload() throws Exception {
|
||||
alarm.setDatapointsToAlarm(2);
|
||||
alarm.setStatistic("Maximum");
|
||||
alarm.setEvaluateLowSampleCountPercentile("ignore");
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION);
|
||||
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
|
||||
verify(sns).publish(eq(TOPIC), isNull(), message.capture(), anyString(), eq(REGION));
|
||||
assertEquals(2, mapper.readTree(message.getValue()).path("Trigger").path("DatapointsToAlarm").intValue());
|
||||
JsonNode trigger = mapper.readTree(message.getValue()).path("Trigger");
|
||||
assertEquals("MAXIMUM", trigger.path("Statistic").asText());
|
||||
assertEquals("ignore", trigger.path("EvaluateLowSampleCountPercentile").asText());
|
||||
assertEquals(2, alarm.getDatapointsToAlarm());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledActionsDoNotPublish() {
|
||||
alarm.setActionsEnabled(false);
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION);
|
||||
verifyNoInteractions(sns);
|
||||
assertEquals("ALARM", alarm.getStateValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedTargetDoesNotPreventOtherTargetsOrStateChange() {
|
||||
String missing = "arn:aws:sns:us-east-1:000000000000:missing";
|
||||
alarm.setAlarmActions(List.of(missing, "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:x", TOPIC));
|
||||
doThrow(new IllegalStateException("missing topic"))
|
||||
.when(sns).publish(eq(missing), isNull(), anyString(), anyString(), eq(REGION));
|
||||
assertDoesNotThrow(() -> service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION));
|
||||
verify(sns).publish(eq(TOPIC), isNull(), anyString(), anyString(), eq(REGION));
|
||||
assertEquals("ALARM", alarm.getStateValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesTopicRegionAndPreservesChinaPartition() {
|
||||
String topic = "arn:aws-cn:sns:cn-north-1:000000000000:alarms";
|
||||
alarm.setAlarmArn("arn:aws-cn:cloudwatch:cn-north-1:000000000000:alarm:test-alarm");
|
||||
alarm.setAlarmActions(List.of(topic));
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION);
|
||||
verify(sns).publish(eq(topic), isNull(), contains("arn:aws-cn:cloudwatch:"), anyString(), eq("cn-north-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockedNotificationDoesNotHoldTheAlarmMutationLock() throws Exception {
|
||||
CountDownLatch publishing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(call -> {
|
||||
if (call.<String>getArgument(3).startsWith("ALARM:")) {
|
||||
publishing.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
}
|
||||
return "message-id";
|
||||
}).when(sns).publish(eq(TOPIC), isNull(), anyString(), anyString(), eq(REGION));
|
||||
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> transition = executor.submit(() ->
|
||||
service.setAlarmState("test-alarm", "ALARM", "breached", null, REGION));
|
||||
try {
|
||||
assertTrue(publishing.await(2, TimeUnit.SECONDS));
|
||||
Future<?> unrelated = executor.submit(() -> {
|
||||
CompositeAlarm composite = new CompositeAlarm();
|
||||
composite.setAlarmName("unrelated");
|
||||
composite.setAlarmRule("FALSE");
|
||||
service.putCompositeAlarm(composite, REGION);
|
||||
service.setAlarmState("test-alarm", "OK", "recovered", null, REGION);
|
||||
});
|
||||
unrelated.get(2, TimeUnit.SECONDS);
|
||||
assertEquals("OK", alarm.getStateValue());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
transition.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
ArgumentCaptor<String> messages = ArgumentCaptor.forClass(String.class);
|
||||
verify(sns, times(2)).publish(eq(TOPIC), isNull(), messages.capture(), anyString(), eq(REGION));
|
||||
assertEquals("ALARM", mapper.readTree(messages.getAllValues().getFirst()).path("NewStateValue").asText());
|
||||
assertEquals("OK", mapper.readTree(messages.getAllValues().getLast()).path("NewStateValue").asText());
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CloudWatchAlarmQueryHandlerTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"PutMetricAlarm", "PutCompositeAlarm"})
|
||||
void sharedFieldsReachBothAlarmTypes(String operation) {
|
||||
String region = "us-east-1";
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new RegionResolver(region, "123456789012"));
|
||||
CloudWatchMetricsQueryHandler handler = new CloudWatchMetricsQueryHandler(service, null, null);
|
||||
MultivaluedMap<String, String> request = new MultivaluedHashMap<>();
|
||||
request.putSingle("AlarmName", "shared");
|
||||
request.putSingle("AlarmRule", "FALSE");
|
||||
request.putSingle("AlarmDescription", "shared fields");
|
||||
request.putSingle("ActionsEnabled", "false");
|
||||
request.putSingle("AlarmActions.member.1", "alarm-action");
|
||||
request.putSingle("OKActions.member.1", "ok-action");
|
||||
request.putSingle("InsufficientDataActions.member.1", "missing-action");
|
||||
request.putSingle("Tags.member.1.Key", "team");
|
||||
request.putSingle("Tags.member.1.Value", "metrics");
|
||||
assertEquals(200, handler.handle(operation, request, region).getStatus());
|
||||
Alarm alarm = "PutMetricAlarm".equals(operation)
|
||||
? service.describeAlarms(List.of("shared"), null, region).getFirst()
|
||||
: service.describeCompositeAlarms(List.of("shared"), null, region).getFirst();
|
||||
assertEquals("shared fields", alarm.getAlarmDescription());
|
||||
assertFalse(alarm.isActionsEnabled());
|
||||
assertEquals(List.of("alarm-action"), alarm.getAlarmActions());
|
||||
assertEquals(List.of("ok-action"), alarm.getOkActions());
|
||||
assertEquals(List.of("missing-action"), alarm.getInsufficientDataActions());
|
||||
assertEquals(Map.of("team", "metrics"), alarm.getTags());
|
||||
}
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.w3c.dom.Document;
|
||||
|
||||
import javax.xml.xpath.XPath;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
class CloudWatchMetricMathAlarmTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ALARM_NAME = "metric-math-round-trip";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String XML_ALARM = "/DescribeAlarmsResponse/DescribeAlarmsResult/MetricAlarms/member";
|
||||
|
||||
private CloudWatchMetricsJsonHandler jsonHandler;
|
||||
private CloudWatchMetricsQueryHandler queryHandler;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
initialize(new InMemoryStorage<>());
|
||||
}
|
||||
|
||||
private void initialize(StorageBackend<String, Alarm> alarmStore) {
|
||||
RegionResolver resolver = new RegionResolver(REGION, "000000000000");
|
||||
CloudWatchMetricsService service = new CloudWatchMetricsService(new InMemoryStorage<>(), alarmStore, resolver);
|
||||
CloudWatchDashboardsService dashboards = new CloudWatchDashboardsService(new InMemoryStorage<>(), resolver);
|
||||
jsonHandler = new CloudWatchMetricsJsonHandler(service, dashboards, null, MAPPER);
|
||||
queryHandler = new CloudWatchMetricsQueryHandler(service, dashboards, null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void metricMathQueriesRoundTripThroughBothProtocols(boolean queryProtocol) throws Exception {
|
||||
ObjectNode request = metricMathRequest();
|
||||
put(request, queryProtocol);
|
||||
assertMetricMathAlarm(request);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void metricMathQueriesSurvivePersistentStorageReload(boolean queryProtocol, @TempDir Path directory)
|
||||
throws Exception {
|
||||
Path storageFile = directory.resolve("alarms.json");
|
||||
TypeReference<Map<String, Alarm>> type = new TypeReference<>() { };
|
||||
initialize(new PersistentStorage<>(storageFile, type));
|
||||
ObjectNode request = metricMathRequest();
|
||||
put(request, queryProtocol);
|
||||
|
||||
PersistentStorage<String, Alarm> reloaded = new PersistentStorage<>(storageFile, type);
|
||||
reloaded.load();
|
||||
assertEquals(1, reloaded.keys().size(), "the stored alarm must deserialize after a restart");
|
||||
initialize(reloaded);
|
||||
assertMetricMathAlarm(request);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void switchingBetweenSingleMetricAndMetricMathReplacesThePreviousDefinition(boolean queryProtocol)
|
||||
throws Exception {
|
||||
ObjectNode singleMetric = singleMetricRequest();
|
||||
put(singleMetric, queryProtocol);
|
||||
assertSingleMetricAlarm(300);
|
||||
|
||||
ObjectNode math = metricMathRequest();
|
||||
put(math, !queryProtocol);
|
||||
assertMetricMathAlarm(math);
|
||||
|
||||
singleMetric.put("Period", 120);
|
||||
put(singleMetric, queryProtocol);
|
||||
assertSingleMetricAlarm(120);
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingSingleMetricDefaultPeriodIsPreserved() throws Exception {
|
||||
ObjectNode singleMetric = singleMetricRequest();
|
||||
singleMetric.remove("Period");
|
||||
put(singleMetric, false);
|
||||
assertSingleMetricAlarm(60);
|
||||
}
|
||||
|
||||
private void put(ObjectNode request, boolean queryProtocol) {
|
||||
if (queryProtocol) {
|
||||
assertEquals(200, queryHandler.handle("PutMetricAlarm", toQuery(request), REGION).getStatus());
|
||||
} else {
|
||||
assertEquals(200, jsonHandler.handle("PutMetricAlarm", request, REGION).getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode describeJson() {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.putArray("AlarmNames").add(ALARM_NAME);
|
||||
JsonNode response = (JsonNode) jsonHandler.handle("DescribeAlarms", request, REGION).getEntity();
|
||||
assertEquals(1, response.path("MetricAlarms").size());
|
||||
return response.path("MetricAlarms").get(0);
|
||||
}
|
||||
|
||||
private Document describeXml() throws Exception {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("AlarmNames.member.1", ALARM_NAME);
|
||||
String xml = (String) queryHandler.handle("DescribeAlarms", params, REGION).getEntity();
|
||||
return XmlParser.parseDocument(xml);
|
||||
}
|
||||
|
||||
private void assertMetricMathAlarm(ObjectNode request) throws Exception {
|
||||
JsonNode alarm = describeJson();
|
||||
assertEquals(request.path("Metrics"), alarm.path("Metrics"));
|
||||
Document document = describeXml();
|
||||
XPath xpath = XPathFactory.newInstance().newXPath();
|
||||
for (String field : new String[]{"Period", "MetricName", "Namespace", "Statistic", "ExtendedStatistic",
|
||||
"Unit", "Dimensions"}) {
|
||||
assertFalse(alarm.has(field), "metric-math JSON must not contain " + field);
|
||||
assertEquals("0", xpath.evaluate("count(" + XML_ALARM + "/" + field + ")", document),
|
||||
"metric-math XML must not contain " + field);
|
||||
}
|
||||
assertEquals("3", xpath.evaluate("count(" + XML_ALARM + "/Metrics/member)", document));
|
||||
assertEquals("5", xpath.evaluate(XML_ALARM + "/Threshold", document).replace(".0", ""));
|
||||
assertEquals("2", xpath.evaluate(XML_ALARM + "/EvaluationPeriods", document));
|
||||
assertEquals(5.0, alarm.path("Threshold").asDouble());
|
||||
assertEquals(2, alarm.path("EvaluationPeriods").asInt());
|
||||
assertXmlMatchesJson(request.path("Metrics"), XML_ALARM + "/Metrics", document, xpath);
|
||||
}
|
||||
|
||||
private void assertSingleMetricAlarm(int period) throws Exception {
|
||||
JsonNode alarm = describeJson();
|
||||
assertEquals(period, alarm.path("Period").asInt());
|
||||
assertEquals("AWS/ApiGateway", alarm.path("Namespace").asText());
|
||||
assertEquals("5xx", alarm.path("MetricName").asText());
|
||||
assertEquals("Sum", alarm.path("Statistic").asText());
|
||||
assertFalse(alarm.has("Metrics"));
|
||||
Document document = describeXml();
|
||||
XPath xpath = XPathFactory.newInstance().newXPath();
|
||||
assertEquals(Integer.toString(period), xpath.evaluate(XML_ALARM + "/Period", document));
|
||||
assertEquals("0", xpath.evaluate("count(" + XML_ALARM + "/Metrics)", document));
|
||||
}
|
||||
|
||||
private static void assertXmlMatchesJson(JsonNode value, String path, Document document, XPath xpath)
|
||||
throws Exception {
|
||||
if (value.isArray()) {
|
||||
assertEquals(Integer.toString(value.size()), xpath.evaluate("count(" + path + "/member)", document));
|
||||
for (int index = 0; index < value.size(); index++) {
|
||||
assertXmlMatchesJson(value.get(index), path + "/member[" + (index + 1) + "]", document, xpath);
|
||||
}
|
||||
} else if (value.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
assertXmlMatchesJson(field.getValue(), path + "/" + field.getKey(), document, xpath);
|
||||
}
|
||||
} else {
|
||||
assertEquals(value.asText(), xpath.evaluate(path, document), path);
|
||||
}
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> toQuery(JsonNode value) {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
flatten(value, "", params);
|
||||
return params;
|
||||
}
|
||||
|
||||
private static void flatten(JsonNode value, String prefix, MultivaluedMap<String, String> params) {
|
||||
if (value.isArray()) {
|
||||
for (int index = 0; index < value.size(); index++) {
|
||||
flatten(value.get(index), prefix + ".member." + (index + 1), params);
|
||||
}
|
||||
} else if (value.isObject()) {
|
||||
for (Map.Entry<String, JsonNode> field : value.properties()) {
|
||||
flatten(field.getValue(), prefix.isEmpty() ? field.getKey() : prefix + "." + field.getKey(), params);
|
||||
}
|
||||
} else {
|
||||
params.putSingle(prefix, value.asText());
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode metricMathRequest() throws Exception {
|
||||
return (ObjectNode) MAPPER.readTree("""
|
||||
{"AlarmName":"metric-math-round-trip","EvaluationPeriods":2,"Threshold":5,
|
||||
"ComparisonOperator":"GreaterThanThreshold","Metrics":[
|
||||
{"Id":"rate","Expression":"100 * errors / requests","ReturnData":true,
|
||||
"Period":300,"Label":"Error <rate> & requests"},
|
||||
{"Id":"errors","ReturnData":false,"AccountId":"123456789012","Label":"Errors",
|
||||
"MetricStat":{"Metric":{"Namespace":"AWS/ApiGateway","MetricName":"5xx",
|
||||
"Dimensions":[{"Name":"ApiName","Value":"api<&>"},{"Name":"Stage","Value":"test"}]},
|
||||
"Period":300,"Stat":"Sum","Unit":"Count"}},
|
||||
{"Id":"requests","ReturnData":false,"MetricStat":{
|
||||
"Metric":{"Namespace":"AWS/ApiGateway","MetricName":"Count"},"Period":300,"Stat":"Sum"}}
|
||||
]}
|
||||
""");
|
||||
}
|
||||
|
||||
private static ObjectNode singleMetricRequest() throws Exception {
|
||||
return (ObjectNode) MAPPER.readTree("""
|
||||
{"AlarmName":"metric-math-round-trip","Namespace":"AWS/ApiGateway","MetricName":"5xx",
|
||||
"Statistic":"Sum","Period":300,"EvaluationPeriods":2,"Threshold":5,
|
||||
"ComparisonOperator":"GreaterThanThreshold"}
|
||||
""");
|
||||
}
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.restassured.config.EncoderConfig;
|
||||
import io.restassured.http.ContentType;
|
||||
import io.restassured.parsing.Parser;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static io.restassured.RestAssured.config;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
|
||||
/**
|
||||
* PutMetricData datums nested under EntityMetricData, as the CloudWatch Agent sends them,
|
||||
* must be stored under the request namespace on every protocol path. floci-io/floci#6066.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudWatchMetricsEntityMetricDataIntegrationTest {
|
||||
|
||||
private static final String CW_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261020/us-east-1/monitoring/aws4_request";
|
||||
private static final String JSON_1_0 = "application/x-amz-json-1.0";
|
||||
|
||||
@BeforeAll
|
||||
static void registerJsonParser() {
|
||||
RestAssured.registerParser(JSON_1_0, Parser.JSON);
|
||||
}
|
||||
|
||||
private static RequestSpecification json(String operation) {
|
||||
return given()
|
||||
.header("Authorization", CW_AUTH)
|
||||
.contentType(JSON_1_0)
|
||||
.config(config().encoderConfig(EncoderConfig.encoderConfig()
|
||||
.encodeContentTypeAs(JSON_1_0, ContentType.TEXT)))
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation);
|
||||
}
|
||||
|
||||
private static RequestSpecification query(String action) {
|
||||
return given()
|
||||
.header("Authorization", CW_AUTH)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-08-01");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonEntityMetricDataOnlyIsListedAndAggregated() {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
json("PutMetricData")
|
||||
.body("""
|
||||
{"Namespace":"CWAgent/Json","MetricData":[],
|
||||
"EntityMetricData":[{
|
||||
"Entity":{"KeyAttributes":{"Type":"AWS::Resource",
|
||||
"ResourceType":"AWS::EC2::Instance","Identifier":"i-0123456789abcdef0"},
|
||||
"Attributes":{}},
|
||||
"MetricData":[
|
||||
{"MetricName":"mem_used_percent","Value":6.5,"Unit":"Percent",
|
||||
"StorageResolution":60,"Timestamp":%d,
|
||||
"Dimensions":[{"Name":"host","Value":"h1"}]},
|
||||
{"MetricName":"disk_used_percent","Value":0.75,"Unit":"Percent",
|
||||
"StorageResolution":60,"Timestamp":%d,
|
||||
"Dimensions":[{"Name":"host","Value":"h1"}]}]}],
|
||||
"StrictEntityValidation":false}
|
||||
""".formatted(now, now))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
json("ListMetrics")
|
||||
.body("{\"Namespace\":\"CWAgent/Json\"}")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Metrics.MetricName", containsInAnyOrder("mem_used_percent", "disk_used_percent"));
|
||||
|
||||
json("GetMetricStatistics")
|
||||
.body("""
|
||||
{"Namespace":"CWAgent/Json","MetricName":"mem_used_percent",
|
||||
"Dimensions":[{"Name":"host","Value":"h1"}],
|
||||
"StartTime":%d,"EndTime":%d,"Period":60,"Statistics":["Sum"]}
|
||||
""".formatted(now - 120, now + 120))
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Datapoints.Sum", hasItem(6.5f));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonTopLevelAndEntityMetricDataAreBothStored() {
|
||||
json("PutMetricData")
|
||||
.body("""
|
||||
{"Namespace":"CWAgent/JsonMixed",
|
||||
"MetricData":[{"MetricName":"TopLevel","Value":1}],
|
||||
"EntityMetricData":[{"Entity":{"KeyAttributes":{"Type":"Service",
|
||||
"Name":"checkout","Environment":"prod"}},
|
||||
"MetricData":[{"MetricName":"FromEntity","Value":2}]}]}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
json("ListMetrics")
|
||||
.body("{\"Namespace\":\"CWAgent/JsonMixed\"}")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Metrics.MetricName", containsInAnyOrder("TopLevel", "FromEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryTopLevelAndEntityMetricDataAreListedAndAggregated() {
|
||||
Instant now = Instant.now();
|
||||
query("PutMetricData")
|
||||
.formParam("Namespace", "CWAgent/Query")
|
||||
.formParam("MetricData.member.1.MetricName", "TopLevel")
|
||||
.formParam("MetricData.member.1.Value", "1")
|
||||
.formParam("EntityMetricData.member.1.Entity.KeyAttributes.entry.1.key", "Type")
|
||||
.formParam("EntityMetricData.member.1.Entity.KeyAttributes.entry.1.value", "AWS::Resource")
|
||||
.formParam("EntityMetricData.member.1.MetricData.member.1.MetricName", "mem_used_percent")
|
||||
.formParam("EntityMetricData.member.1.MetricData.member.1.Value", "6.5")
|
||||
.formParam("EntityMetricData.member.1.MetricData.member.1.Timestamp", now.toString())
|
||||
.formParam("EntityMetricData.member.1.MetricData.member.1.Dimensions.member.1.Name", "host")
|
||||
.formParam("EntityMetricData.member.1.MetricData.member.1.Dimensions.member.1.Value", "h1")
|
||||
.formParam("StrictEntityValidation", "false")
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
query("ListMetrics")
|
||||
.formParam("Namespace", "CWAgent/Query")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListMetricsResponse.ListMetricsResult.Metrics.member.MetricName",
|
||||
containsInAnyOrder("TopLevel", "mem_used_percent"));
|
||||
|
||||
query("GetMetricStatistics")
|
||||
.formParam("Namespace", "CWAgent/Query")
|
||||
.formParam("MetricName", "mem_used_percent")
|
||||
.formParam("Dimensions.member.1.Name", "host")
|
||||
.formParam("Dimensions.member.1.Value", "h1")
|
||||
.formParam("StartTime", now.minusSeconds(120).toString())
|
||||
.formParam("EndTime", now.plusSeconds(120).toString())
|
||||
.formParam("Period", "60")
|
||||
.formParam("Statistics.member.1", "Sum")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("GetMetricStatisticsResponse.GetMetricStatisticsResult.Datapoints.member.Sum",
|
||||
equalTo("6.5"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonNestedDatumWithoutMetricNameIsRejectedAndNothingIsStored() {
|
||||
json("PutMetricData")
|
||||
.body("""
|
||||
{"Namespace":"CWAgent/JsonInvalid",
|
||||
"MetricData":[{"MetricName":"TopLevel","Value":1}],
|
||||
"EntityMetricData":[{"MetricData":[{"Value":2}]}]}
|
||||
""")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.header("x-amzn-query-error", equalTo("MissingParameter;Sender"))
|
||||
.body("__type", equalTo("MissingRequiredParameterException"))
|
||||
.body("message", equalTo(
|
||||
"The parameter EntityMetricData.member.1.MetricData.member.1.MetricName is required."));
|
||||
|
||||
json("ListMetrics")
|
||||
.body("{\"Namespace\":\"CWAgent/JsonInvalid\"}")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Metrics", empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryMemberWithoutMetricNameIsRejectedAndNothingIsStored() {
|
||||
query("PutMetricData")
|
||||
.formParam("Namespace", "CWAgent/QueryInvalid")
|
||||
.formParam("MetricData.member.1.Value", "1")
|
||||
.formParam("MetricData.member.2.MetricName", "Valid")
|
||||
.formParam("MetricData.member.2.Value", "2")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("MissingParameter"))
|
||||
.body("ErrorResponse.Error.Message",
|
||||
equalTo("The parameter MetricData.member.1.MetricName is required."));
|
||||
|
||||
query("ListMetrics")
|
||||
.formParam("Namespace", "CWAgent/QueryInvalid")
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ListMetricsResponse.ListMetricsResult.Metrics.member.size()", equalTo(0));
|
||||
}
|
||||
}
|
||||
+132
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
@@ -17,6 +18,13 @@ import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Handler-level tests for CloudWatchMetricsJsonHandler.
|
||||
@@ -146,6 +154,114 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
"metric stored with 24h-ago timestamp must not appear in a 20-second window around now");
|
||||
}
|
||||
|
||||
// The CloudWatch Agent sends an empty top-level MetricData and nests every datum under
|
||||
// EntityMetricData, floci-io/floci#6066.
|
||||
@Test
|
||||
void putMetricData_entityMetricDataOnly_storesNestedDatumsUnderTheRequestNamespace() {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("Namespace", "CWAgent");
|
||||
req.putArray("MetricData");
|
||||
ObjectNode entityMetricData = req.putArray("EntityMetricData").addObject();
|
||||
ObjectNode entity = entityMetricData.putObject("Entity");
|
||||
entity.putObject("KeyAttributes")
|
||||
.put("Type", "AWS::Resource")
|
||||
.put("ResourceType", "AWS::EC2::Instance")
|
||||
.put("Identifier", "i-0123456789abcdef0");
|
||||
entity.putObject("Attributes");
|
||||
ObjectNode datum = entityMetricData.putArray("MetricData").addObject();
|
||||
datum.put("MetricName", "mem_used_percent");
|
||||
datum.put("Value", 6.43);
|
||||
datum.put("Unit", "Percent");
|
||||
datum.put("StorageResolution", 60);
|
||||
datum.put("Timestamp", sdkTimestamp(EPOCH_NOW));
|
||||
datum.putArray("Dimensions").addObject().put("Name", "host").put("Value", "h1");
|
||||
req.put("StrictEntityValidation", false);
|
||||
|
||||
assertEquals(200, handler.handle("PutMetricData", req, REGION).getStatus());
|
||||
|
||||
ObjectNode stats = getStats("CWAgent", "mem_used_percent", "host", "h1",
|
||||
EPOCH_NOW.minusSeconds(60), EPOCH_NOW.plusSeconds(60), 60);
|
||||
assertEquals(1, stats.get("Datapoints").size());
|
||||
assertEquals(6.43, stats.get("Datapoints").get(0).get("Sum").asDouble());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricData_topLevelAndEntityMetricData_storesBoth() {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("Namespace", "Mixed");
|
||||
req.putArray("MetricData").addObject()
|
||||
.put("MetricName", "TopLevel").put("Value", 1.0);
|
||||
ArrayNode entityMetricData = req.putArray("EntityMetricData");
|
||||
entityMetricData.addObject().putArray("MetricData").addObject()
|
||||
.put("MetricName", "FirstEntity").put("Value", 2.0);
|
||||
entityMetricData.addObject().putArray("MetricData").addObject()
|
||||
.put("MetricName", "SecondEntity").put("Value", 3.0);
|
||||
|
||||
assertEquals(200, handler.handle("PutMetricData", req, REGION).getStatus());
|
||||
|
||||
ObjectNode listReq = MAPPER.createObjectNode();
|
||||
listReq.put("Namespace", "Mixed");
|
||||
ObjectNode listed = (ObjectNode) handler.handle("ListMetrics", listReq, REGION).getEntity();
|
||||
List<String> names = new ArrayList<>();
|
||||
listed.get("Metrics").forEach(m -> names.add(m.get("MetricName").asText()));
|
||||
assertEquals(List.of("FirstEntity", "SecondEntity", "TopLevel"), names.stream().sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricData_entityDatumWithoutMetricName_rejectsTheWholeRequest() {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("Namespace", "Invalid");
|
||||
req.putArray("MetricData").addObject()
|
||||
.put("MetricName", "TopLevel").put("Value", 1.0);
|
||||
ArrayNode nested = req.putArray("EntityMetricData").addObject().putArray("MetricData");
|
||||
nested.addObject().put("MetricName", "Valid").put("Value", 2.0);
|
||||
nested.addObject().put("Value", 3.0);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricData", req, REGION));
|
||||
assertEquals("MissingParameter", e.getErrorCode());
|
||||
assertEquals("MissingRequiredParameterException", e.jsonType());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals("The parameter EntityMetricData.member.1.MetricData.member.2.MetricName is required.",
|
||||
e.getMessage());
|
||||
assertEquals(0, listMetricNames("Invalid").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricData_topLevelDatumWithEmptyMetricName_rejectsTheWholeRequest() {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("Namespace", "InvalidTop");
|
||||
ArrayNode data = req.putArray("MetricData");
|
||||
data.addObject().put("MetricName", "Valid").put("Value", 1.0);
|
||||
data.addObject().put("MetricName", "").put("Value", 2.0);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricData", req, REGION));
|
||||
assertEquals("MissingParameter", e.getErrorCode());
|
||||
assertEquals("The parameter MetricData.member.2.MetricName is required.", e.getMessage());
|
||||
assertEquals(0, listMetricNames("InvalidTop").size());
|
||||
}
|
||||
|
||||
// AWS constrains MetricName to 1 to 255 characters with no pattern, so whitespace is a name.
|
||||
@Test
|
||||
void putMetricData_whitespaceMetricName_isStored() {
|
||||
ObjectNode req = MAPPER.createObjectNode();
|
||||
req.put("Namespace", "WhitespaceName");
|
||||
req.putArray("MetricData").addObject().put("MetricName", " ").put("Value", 1.0);
|
||||
|
||||
assertEquals(200, handler.handle("PutMetricData", req, REGION).getStatus());
|
||||
assertEquals(List.of(" "), listMetricNames("WhitespaceName"));
|
||||
}
|
||||
|
||||
private List<String> listMetricNames(String namespace) {
|
||||
ObjectNode listReq = MAPPER.createObjectNode();
|
||||
listReq.put("Namespace", namespace);
|
||||
ObjectNode listed = (ObjectNode) handler.handle("ListMetrics", listReq, REGION).getEntity();
|
||||
List<String> names = new ArrayList<>();
|
||||
listed.get("Metrics").forEach(m -> names.add(m.get("MetricName").asText()));
|
||||
return names;
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAlarmState_updatesFieldsCorrectly() {
|
||||
putMetric("NS", "M", "type", "current", 100.0, EPOCH_NOW);
|
||||
@@ -234,6 +350,22 @@ class CloudWatchMetricsJsonHandlerTest {
|
||||
assertEquals("Count", alarm.get("Unit").asText());
|
||||
}
|
||||
|
||||
// AWS sends every alarm collection even when it is empty. The CLI's text output writes a
|
||||
// None line for each paginator result key missing from the page (floci-io/floci#6362).
|
||||
@Test
|
||||
void describeAlarms_returnsEmptyCompositeAndLogAlarmCollections() {
|
||||
handler.handle("PutMetricAlarm", alarmRequest("MetricOnly"), REGION);
|
||||
|
||||
ObjectNode response = (ObjectNode) handler.handle("DescribeAlarms", MAPPER.createObjectNode(), REGION)
|
||||
.getEntity();
|
||||
|
||||
assertEquals(1, response.get("MetricAlarms").size());
|
||||
assertTrue(response.get("CompositeAlarms").isArray());
|
||||
assertTrue(response.get("CompositeAlarms").isEmpty());
|
||||
assertTrue(response.get("LogAlarms").isArray());
|
||||
assertTrue(response.get("LogAlarms").isEmpty());
|
||||
}
|
||||
|
||||
// An alarm the caller never gave an M for reports no DatapointsToAlarm at all. AWS omits the
|
||||
// member in that case, and echoing EvaluationPeriods instead reads as a change to any client
|
||||
// that re-plans against its own configuration, which is what floci-io/floci#3660 hit.
|
||||
|
||||
+130
@@ -1,6 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -12,12 +15,15 @@ import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -123,4 +129,128 @@ class CloudWatchMetricsQueryHandlerTest {
|
||||
anyInt(), any(), unitCaptor.capture(), any());
|
||||
assertEquals("Count", unitCaptor.getValue());
|
||||
}
|
||||
|
||||
// The Query serialization of EntityMetricData nests each datum two lists deep;
|
||||
// floci-io/floci#6066 is the JSON-side report of the same dropped datums.
|
||||
@Test
|
||||
void putMetricDataStoresTopLevelAndEntityMetricDataUnderTheRequestNamespace() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Namespace", "CWAgent");
|
||||
params.putSingle("MetricData.member.1.MetricName", "TopLevel");
|
||||
params.putSingle("MetricData.member.1.Value", "1");
|
||||
params.putSingle("EntityMetricData.member.1.Entity.KeyAttributes.entry.1.key", "Type");
|
||||
params.putSingle("EntityMetricData.member.1.Entity.KeyAttributes.entry.1.value", "AWS::Resource");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.MetricName", "mem_used_percent");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.Value", "6.5");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.Unit", "Percent");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.Dimensions.member.1.Name", "host");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.Dimensions.member.1.Value", "h1");
|
||||
params.putSingle("EntityMetricData.member.2.MetricData.member.1.MetricName", "disk_used_percent");
|
||||
params.putSingle("EntityMetricData.member.2.MetricData.member.1.Value", "0.75");
|
||||
params.putSingle("StrictEntityValidation", "false");
|
||||
|
||||
handler.handle("PutMetricData", params, REGION);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<MetricDatum>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(metricsService).putMetricData(eq("CWAgent"), captor.capture(), eq(REGION));
|
||||
List<MetricDatum> datums = captor.getValue();
|
||||
assertEquals(List.of("TopLevel", "mem_used_percent", "disk_used_percent"),
|
||||
datums.stream().map(MetricDatum::getMetricName).toList());
|
||||
MetricDatum entityDatum = datums.get(1);
|
||||
assertEquals(6.5, entityDatum.getValue());
|
||||
assertEquals("Percent", entityDatum.getUnit());
|
||||
assertEquals("host", entityDatum.getDimensions().get(0).name());
|
||||
assertEquals("h1", entityDatum.getDimensions().get(0).value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricDataStoresEntityMetricDataAfterAnEmptyEntityEntry() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Namespace", "CWAgent");
|
||||
params.putSingle("EntityMetricData.member.2.MetricData.member.1.MetricName", "M");
|
||||
params.putSingle("EntityMetricData.member.2.MetricData.member.1.Value", "1");
|
||||
params.putSingle("EntityMetricData.member.10.MetricData.member.1.MetricName", "N");
|
||||
params.putSingle("EntityMetricData.member.10.MetricData.member.1.Value", "2");
|
||||
params.putSingle("StrictEntityValidation", "false");
|
||||
|
||||
handler.handle("PutMetricData", params, REGION);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<MetricDatum>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(metricsService).putMetricData(eq("CWAgent"), captor.capture(), eq(REGION));
|
||||
List<MetricDatum> datums = captor.getValue();
|
||||
assertEquals(List.of("M", "N"), datums.stream().map(MetricDatum::getMetricName).toList());
|
||||
assertEquals(1.0, datums.get(0).getValue());
|
||||
assertEquals(2.0, datums.get(1).getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricDataRejectsAMemberWithoutMetricNameBeforeStoringAnything() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Namespace", "NS");
|
||||
params.putSingle("MetricData.member.1.Value", "1");
|
||||
params.putSingle("MetricData.member.2.MetricName", "Valid");
|
||||
params.putSingle("MetricData.member.2.Value", "2");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricData", params, REGION));
|
||||
assertEquals("MissingParameter", e.getErrorCode());
|
||||
assertEquals("MissingRequiredParameterException", e.jsonType());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
assertEquals("The parameter MetricData.member.1.MetricName is required.", e.getMessage());
|
||||
verify(metricsService, never()).putMetricData(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricDataRejectsANestedMemberWithoutMetricNameBeforeStoringAnything() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Namespace", "NS");
|
||||
params.putSingle("MetricData.member.1.MetricName", "TopLevel");
|
||||
params.putSingle("MetricData.member.1.Value", "1");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.1.Unit", "Percent");
|
||||
params.putSingle("EntityMetricData.member.1.MetricData.member.2.MetricName", "Valid");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricData", params, REGION));
|
||||
assertEquals("The parameter EntityMetricData.member.1.MetricData.member.1.MetricName is required.",
|
||||
e.getMessage());
|
||||
verify(metricsService, never()).putMetricData(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putMetricDataRejectsAnEmptyMetricNameButAcceptsWhitespace() {
|
||||
MultivaluedMap<String, String> empty = new MultivaluedHashMap<>();
|
||||
empty.putSingle("Namespace", "NS");
|
||||
empty.putSingle("MetricData.member.1.MetricName", "");
|
||||
empty.putSingle("MetricData.member.1.Value", "1");
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> handler.handle("PutMetricData", empty, REGION));
|
||||
assertEquals("The parameter MetricData.member.1.MetricName is required.", e.getMessage());
|
||||
verify(metricsService, never()).putMetricData(any(), any(), any());
|
||||
|
||||
MultivaluedMap<String, String> whitespace = new MultivaluedHashMap<>();
|
||||
whitespace.putSingle("Namespace", "NS");
|
||||
whitespace.putSingle("MetricData.member.1.MetricName", " ");
|
||||
whitespace.putSingle("MetricData.member.1.Value", "1");
|
||||
|
||||
handler.handle("PutMetricData", whitespace, REGION);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<List<MetricDatum>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(metricsService).putMetricData(eq("NS"), captor.capture(), eq(REGION));
|
||||
assertEquals(List.of(" "), captor.getValue().stream().map(MetricDatum::getMetricName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeAlarmsReturnsEmptyCompositeAndLogAlarmCollections() {
|
||||
when(metricsService.describeAlarms(any(), any(), eq(REGION))).thenReturn(List.of());
|
||||
|
||||
String xml = (String) handler.handle("DescribeAlarms", new MultivaluedHashMap<>(), REGION).getEntity();
|
||||
|
||||
assertTrue(xml.contains("<MetricAlarms></MetricAlarms>"), xml);
|
||||
assertTrue(xml.contains("<CompositeAlarms></CompositeAlarms>"), xml);
|
||||
assertTrue(xml.contains("<LogAlarms></LogAlarms>"), xml);
|
||||
}
|
||||
}
|
||||
|
||||
+29
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.dashboards.CloudWatchDashboardsService;
|
||||
@@ -83,6 +84,34 @@ class CloudWatchMetricsTagsTest {
|
||||
assertNull(tags.get("team"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An ARN naming no alarm is an error on all three operations, not a silent no-op. The ARN
|
||||
* used here differs from a working one only in the alarm name, so the outcome cannot be
|
||||
* explained by the ARN failing to parse.
|
||||
*/
|
||||
@Test
|
||||
void tagOperationsRejectAnArnThatNamesNoAlarm() {
|
||||
MetricAlarm alarm = new MetricAlarm();
|
||||
alarm.setAlarmName("test-alarm");
|
||||
alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:test-alarm");
|
||||
service.putMetricAlarm(alarm, REGION);
|
||||
String ghost = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:nosuch";
|
||||
|
||||
for (Runnable call : List.<Runnable>of(
|
||||
() -> service.tagResource(ghost, Map.of("env", "prod"), REGION),
|
||||
() -> service.untagResource(ghost, List.of("env"), REGION),
|
||||
() -> service.listTagsForResource(ghost, REGION))) {
|
||||
AwsException e = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
|
||||
// The failures wrote nothing: the real alarm still carries only what it was given.
|
||||
assertEquals(Map.of(), service.listTagsForResource(alarm.getAlarmArn(), REGION));
|
||||
service.tagResource(alarm.getAlarmArn(), Map.of("env", "dev"), REGION);
|
||||
assertEquals(Map.of("env", "dev"), service.listTagsForResource(alarm.getAlarmArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsViaPutMetricAlarmQuery() {
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
class CompositeAlarmIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String SCOPE =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261010/cn-north-1/monitoring/aws4_request";
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void bothProtocolsCreateDescribeEvaluateAndDeleteRealAlarms(boolean json) throws Exception {
|
||||
String prefix = "wire-composite-" + Long.toString(System.nanoTime(), 36);
|
||||
String source = prefix + "-source";
|
||||
String aggregate = prefix + "-aggregate";
|
||||
call(json, "PutCompositeAlarm", Map.of("AlarmName", source, "AlarmRule", "TRUE")).then().statusCode(200);
|
||||
call(json, "PutCompositeAlarm", Map.of("AlarmName", aggregate, "AlarmRule", "ALARM(\"" + source + "\")",
|
||||
"ActionsEnabled", false, "AlarmDescription", "combined")).then().statusCode(200);
|
||||
Response result = call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(aggregate),
|
||||
"AlarmTypes", List.of("CompositeAlarm")));
|
||||
result.then().statusCode(200);
|
||||
if (json) {
|
||||
assertEquals(List.of(), result.jsonPath().getList("LogAlarms"));
|
||||
assertEquals(1, result.jsonPath().getList("CompositeAlarms").size());
|
||||
assertEquals("ALARM", result.jsonPath().getString("CompositeAlarms[0].StateValue"));
|
||||
assertEquals("arn:aws-cn:cloudwatch:cn-north-1:000000000000:alarm:" + aggregate,
|
||||
result.jsonPath().getString("CompositeAlarms[0].AlarmArn"));
|
||||
assertFalse(result.jsonPath().getBoolean("CompositeAlarms[0].ActionsEnabled"));
|
||||
} else {
|
||||
assertTrue(result.asString().contains("<LogAlarms>"));
|
||||
assertEquals("ALARM", result.xmlPath().getString(
|
||||
"DescribeAlarmsResponse.DescribeAlarmsResult.CompositeAlarms.member.StateValue"));
|
||||
assertTrue(result.asString().contains("arn:aws-cn:cloudwatch:cn-north-1:000000000000:alarm:" + aggregate));
|
||||
assertEquals("false", result.xmlPath().getString(
|
||||
"DescribeAlarmsResponse.DescribeAlarmsResult.CompositeAlarms.member.ActionsEnabled"));
|
||||
}
|
||||
assertFalse(call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(aggregate)))
|
||||
.then().statusCode(200).extract().asString().contains(aggregate));
|
||||
call(json, "SetAlarmState", Map.of("AlarmName", source, "StateValue", "OK",
|
||||
"StateReason", "recovery")).then().statusCode(200);
|
||||
Response recovered = call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(aggregate),
|
||||
"AlarmTypes", List.of("CompositeAlarm")));
|
||||
assertEquals("OK", json ? recovered.jsonPath().getString("CompositeAlarms[0].StateValue")
|
||||
: recovered.xmlPath().getString(
|
||||
"DescribeAlarmsResponse.DescribeAlarmsResult.CompositeAlarms.member.StateValue"));
|
||||
for (String name : List.of(aggregate, source)) {
|
||||
call(json, "DeleteAlarms", Map.of("AlarmNames", List.of(name))).then().statusCode(200);
|
||||
}
|
||||
Response empty = call(json, "DescribeAlarms", Map.of("AlarmNamePrefix", prefix,
|
||||
"AlarmTypes", List.of("CompositeAlarm")));
|
||||
assertFalse(empty.asString().contains(aggregate));
|
||||
assertFalse(empty.asString().contains(source));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void invalidRuleAndUnsupportedSuppressionCannotCreateAnAlarm(boolean json) throws Exception {
|
||||
String name = "invalid-composite-" + Long.toString(System.nanoTime(), 36);
|
||||
call(json, "PutCompositeAlarm", Map.of("AlarmName", name, "AlarmRule", "TRUE AND"))
|
||||
.then().statusCode(400);
|
||||
call(json, "PutCompositeAlarm", Map.of("AlarmName", name, "AlarmRule", "TRUE",
|
||||
"ActionsSuppressor", "other")).then().statusCode(400);
|
||||
assertFalse(call(json, "DescribeAlarms", Map.of("AlarmNames", List.of(name),
|
||||
"AlarmTypes", List.of("CompositeAlarm"))).asString().contains(name));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void alarmTypeValidationAcceptsLogAlarmsAndUsesSmithyErrors(boolean json) throws Exception {
|
||||
call(json, "DescribeAlarms", Map.of("AlarmTypes", List.of("LogAlarm"))).then().statusCode(200);
|
||||
Response error = call(json, "DescribeAlarms", Map.of("AlarmTypes", List.of("Unknown")));
|
||||
error.then().statusCode(400);
|
||||
assertEquals("1 validation error detected: Value '[Unknown]' at 'alarmTypes' failed to satisfy constraint: "
|
||||
+ "Member must satisfy constraint: [Member must satisfy enum value set: "
|
||||
+ "[CompositeAlarm, MetricAlarm, LogAlarm]]", errorMessage(json, error));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void lengthErrorsUseSmithyMessages(boolean json) throws Exception {
|
||||
for (String field : List.of("AlarmName", "AlarmRule")) {
|
||||
int maximum = "AlarmName".equals(field) ? 255 : 10240;
|
||||
String path = "AlarmName".equals(field) ? "alarmName" : "alarmRule";
|
||||
for (String value : List.of("", "x".repeat(maximum + 1))) {
|
||||
Map<String, String> request = new LinkedHashMap<>(Map.of("AlarmName", "length-validation", "AlarmRule", "TRUE"));
|
||||
request.put(field, value);
|
||||
Response error = call(json, "PutCompositeAlarm", request);
|
||||
error.then().statusCode(400);
|
||||
assertEquals("1 validation error detected: Value '" + value + "' at '" + path
|
||||
+ "' failed to satisfy constraint: Member must have length "
|
||||
+ (value.isEmpty() ? "greater than or equal to 1" : "less than or equal to " + maximum),
|
||||
errorMessage(json, error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String errorMessage(boolean json, Response response) {
|
||||
return json ? response.jsonPath().getString("message") : response.xmlPath().getString("ErrorResponse.Error.Message");
|
||||
}
|
||||
|
||||
private Response call(boolean json, String operation, Map<String, ?> body)
|
||||
throws JsonProcessingException {
|
||||
if ("PutCompositeAlarm".equals(operation)) {
|
||||
String name = body.get("AlarmName").toString();
|
||||
cleanup.register(() -> given().port(baseUri.getPort()).contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", SCOPE)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801.DeleteAlarms")
|
||||
.body(MAPPER.valueToTree(Map.of("AlarmNames", List.of(name))).toString())
|
||||
.post("/").then().statusCode(200));
|
||||
}
|
||||
if (json) {
|
||||
return given().contentType("application/x-amz-json-1.0").header("Authorization", SCOPE)
|
||||
.header("X-Amz-Target", "GraniteServiceVersion20100801." + operation)
|
||||
.body(MAPPER.writeValueAsString(body)).post("/");
|
||||
}
|
||||
Map<String, Object> form = new LinkedHashMap<>();
|
||||
form.put("Action", operation);
|
||||
body.forEach((key, value) -> {
|
||||
if (value instanceof List<?> values) {
|
||||
for (int index = 0; index < values.size(); index++) {
|
||||
form.put(key + ".member." + (index + 1), values.get(index));
|
||||
}
|
||||
} else {
|
||||
form.put(key, value);
|
||||
}
|
||||
});
|
||||
return given().contentType("application/x-www-form-urlencoded").header("Authorization", SCOPE)
|
||||
.formParams(form).post("/");
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
package io.github.hectorvent.floci.services.cloudwatch.metrics;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Alarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.CompositeAlarm;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
|
||||
import io.github.hectorvent.floci.testing.ThreadStates;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CompositeAlarmServiceTest {
|
||||
private static final String REGION = "cn-north-1";
|
||||
private final CloudWatchMetricsService service = new CloudWatchMetricsService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "123456789012"));
|
||||
|
||||
@Test
|
||||
void metricTransitionsPropagateThroughNamesArnsAndNestedComposites() {
|
||||
MetricAlarm metric = new MetricAlarm();
|
||||
metric.setAlarmName("latency");
|
||||
service.putMetricAlarm(metric, REGION);
|
||||
put("combined", "ALARM(\"" + metric.getAlarmArn() + "\") AND NOT ALARM(\"maintenance\")");
|
||||
put("outer", "ALARM(combined) OR (TRUE AND FALSE)");
|
||||
assertEquals("OK", state("outer"));
|
||||
service.setAlarmState("latency", "ALARM", "high latency", null, REGION);
|
||||
assertEquals("ALARM", state("combined"));
|
||||
assertEquals("ALARM", state("outer"));
|
||||
service.setAlarmState("latency", "OK", "recovered", null, REGION);
|
||||
assertEquals("OK", state("outer"));
|
||||
assertEquals(List.of(metric), service.describeAlarms(null, null, REGION));
|
||||
assertTrue(service.describeCompositeAlarms(null, null, "us-east-1").isEmpty());
|
||||
assertTrue(service.describeCompositeAlarms(List.of("combined"), null, REGION)
|
||||
.getFirst().getAlarmArn().startsWith("arn:aws-cn:cloudwatch:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatesPreserveStateAndTagsUntilTheNextDependencyChange() {
|
||||
put("source", "FALSE");
|
||||
CompositeAlarm alarm = put("aggregate", "ALARM(source)");
|
||||
service.tagResource(alarm.getAlarmArn(), Map.of("owner", "retained"), REGION);
|
||||
service.setAlarmState("aggregate", "ALARM", "manual", null, REGION);
|
||||
CompositeAlarm replacement = put("aggregate", "OK(source)");
|
||||
assertEquals("ALARM", replacement.getStateValue());
|
||||
assertEquals(Map.of("owner", "retained"), replacement.getTags());
|
||||
service.setAlarmState("source", "ALARM", "dependency changed", null, REGION);
|
||||
assertEquals("OK", state("aggregate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedWritesPreserveManualCompositeStatesAndParentStates() {
|
||||
put("source", "FALSE");
|
||||
put("aggregate", "ALARM(source)");
|
||||
put("parent", "ALARM(aggregate)");
|
||||
service.setAlarmState("aggregate", "ALARM", "manual", null, REGION);
|
||||
assertEquals("ALARM", state("parent"));
|
||||
put("unrelated", "TRUE");
|
||||
assertEquals("ALARM", state("aggregate"));
|
||||
assertEquals("ALARM", state("parent"));
|
||||
MetricAlarm metric = new MetricAlarm();
|
||||
metric.setAlarmName("unrelated-metric");
|
||||
service.putMetricAlarm(metric, REGION);
|
||||
assertEquals("ALARM", state("aggregate"));
|
||||
service.setAlarmState("unrelated-metric", "ALARM", "unrelated", null, REGION);
|
||||
assertEquals("ALARM", state("aggregate"));
|
||||
service.deleteAlarms(List.of("unrelated"), REGION);
|
||||
assertEquals("ALARM", state("aggregate"));
|
||||
assertEquals("ALARM", state("parent"));
|
||||
service.setAlarmState("source", "ALARM", "child changed", null, REGION);
|
||||
service.setAlarmState("source", "OK", "child recovered", null, REGION);
|
||||
assertEquals("OK", state("aggregate"));
|
||||
assertEquals("OK", state("parent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unchangedChildStateDoesNotResetManuallySetParent() {
|
||||
put("source", "FALSE");
|
||||
put("child", "ALARM(source) AND FALSE");
|
||||
put("parent", "ALARM(child)");
|
||||
service.setAlarmState("parent", "ALARM", "manual", null, REGION);
|
||||
service.setAlarmState("source", "ALARM", "child condition remains false", null, REGION);
|
||||
assertEquals("OK", state("child"));
|
||||
assertEquals("ALARM", state("parent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void creationAndDeletionReevaluateOnlyReferencingComposites() {
|
||||
MetricAlarm metric = new MetricAlarm();
|
||||
metric.setAlarmName("late");
|
||||
put("watcher", "INSUFFICIENT_DATA(late)");
|
||||
put("outer", "ALARM(watcher)");
|
||||
assertEquals("OK", state("watcher"));
|
||||
service.putMetricAlarm(metric, REGION);
|
||||
assertEquals("ALARM", state("watcher"));
|
||||
assertEquals("ALARM", state("outer"));
|
||||
service.deleteAlarms(List.of("late"), REGION);
|
||||
assertEquals("OK", state("watcher"));
|
||||
assertEquals("OK", state("outer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagReadIsAnIndependentSnapshotOfTheOwnedAlarm() {
|
||||
CompositeAlarm alarm = put("tag-snapshot", "TRUE");
|
||||
service.tagResource(alarm.getAlarmArn(), Map.of("team", "old"), REGION);
|
||||
Map<String, String> read = service.listTagsForResource(alarm.getAlarmArn(), REGION);
|
||||
service.tagResource(alarm.getAlarmArn(), Map.of("team", "new"), REGION);
|
||||
assertEquals(Map.of("team", "old"), read);
|
||||
read.put("injected", "unowned");
|
||||
assertEquals(Map.of("team", "new"), service.listTagsForResource(alarm.getAlarmArn(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cyclesStopEvaluationEvenBehindShortCircuitAndMustBeBrokenBeforeDelete() {
|
||||
put("a", "FALSE AND ALARM(b)");
|
||||
put("b", "ALARM(a)");
|
||||
service.setAlarmState("b", "ALARM", "manual", null, REGION);
|
||||
assertThrows(AwsException.class, () -> service.deleteAlarms(List.of("a"), REGION));
|
||||
assertEquals(2, service.describeCompositeAlarms(null, null, REGION).size());
|
||||
put("a", "FALSE");
|
||||
service.deleteAlarms(List.of("b"), REGION);
|
||||
assertEquals("OK", state("a"));
|
||||
service.deleteAlarms(List.of("a"), REGION);
|
||||
assertTrue(service.describeCompositeAlarms(null, null, REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void manuallyChangingOneMemberDoesNotResumeACyclicDependency() {
|
||||
put("a", "ALARM(b)");
|
||||
put("b", "ALARM(a)");
|
||||
assertEquals("OK", state("a"));
|
||||
service.setAlarmState("b", "ALARM", "manual", null, REGION);
|
||||
assertEquals("OK", state("a"));
|
||||
put("b", "TRUE");
|
||||
service.setAlarmState("b", "ALARM", "cycle broken", null, REGION);
|
||||
assertEquals("ALARM", state("a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentQuotaTreatsAChildNameAndItsArnAsTheSameAlarm() {
|
||||
CompositeAlarm child = put("child", "FALSE");
|
||||
for (int index = 0; index < 150; index++) {
|
||||
put("parent-" + index, "ALARM(child)");
|
||||
}
|
||||
assertThrows(AwsException.class, () -> put("overflow", "ALARM(\"" + child.getAlarmArn() + "\")"));
|
||||
service.deleteAlarms(List.of("parent-0"), REGION);
|
||||
assertEquals("OK", put("replacement", "ALARM(\"" + child.getAlarmArn() + "\")").getStateValue());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "ALARM()", "TRUE junk", "TRUE AND", "ALARM(\"unterminated)",
|
||||
"(TRUE", "ALARM(x) XOR FALSE", "ALARM(\"x\\z\")"})
|
||||
void invalidRulesDoNotReplaceAnExistingAlarm(String invalid) {
|
||||
put("saved", "TRUE");
|
||||
assertThrows(AwsException.class, () -> put("saved", invalid));
|
||||
assertEquals("TRUE", service.describeCompositeAlarms(List.of("saved"), null, REGION).getFirst().getAlarmRule());
|
||||
assertEquals("ALARM", state("saved"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotasAndAtomicCreatePreventExcessReferencesAndForeignNameReplacement() {
|
||||
String many = IntStream.range(0, 101).mapToObj(i -> "ALARM(a" + i + ")")
|
||||
.collect(Collectors.joining(" OR "));
|
||||
assertThrows(AwsException.class, () -> put("too-many", many));
|
||||
put("owned", "TRUE");
|
||||
CompositeAlarm foreign = new CompositeAlarm();
|
||||
foreign.setAlarmName("owned");
|
||||
foreign.setAlarmRule("FALSE");
|
||||
assertThrows(AwsException.class, () -> service.putCompositeAlarm(foreign, REGION, false));
|
||||
assertEquals("ALARM", state("owned"));
|
||||
assertThrows(AwsException.class, () -> put("deep", "(".repeat(250) + "TRUE" + ")".repeat(250)));
|
||||
assertEquals("ALARM", put("many-not", "NOT ".repeat(502) + "TRUE").getStateValue());
|
||||
assertThrows(AwsException.class, () -> put("elements", "FALSE OR ".repeat(500) + "TRUE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixedPersistenceLoadsLegacyMetricsAndRoundTripsComposites() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
TypeReference<Map<String, Alarm>> type = new TypeReference<>() {};
|
||||
Map<String, Alarm> legacy = mapper.readValue(
|
||||
"{\"legacy\":{\"alarmName\":\"old\",\"metricName\":\"CPU\",\"stateValue\":\"OK\"}}", type);
|
||||
assertInstanceOf(MetricAlarm.class, legacy.get("legacy"));
|
||||
CompositeAlarm alarm = put("new", "FALSE");
|
||||
Map<String, Alarm> restored = mapper.readValue(mapper.writeValueAsBytes(Map.of("new", alarm)), type);
|
||||
assertEquals("FALSE", assertInstanceOf(CompositeAlarm.class, restored.get("new")).getAlarmRule());
|
||||
assertEquals("OK", restored.get("new").getStateValue());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void concurrentTagChangesPreserveTheUpdatedDefinition(boolean remove) throws Exception {
|
||||
CountDownLatch updating = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
InMemoryStorage<String, Alarm> storage = new InMemoryStorage<>() {
|
||||
@Override
|
||||
public void put(String key, Alarm value) {
|
||||
if (value instanceof CompositeAlarm composite && "TRUE".equals(composite.getAlarmRule())) {
|
||||
updating.countDown();
|
||||
try {
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(error);
|
||||
}
|
||||
}
|
||||
super.put(key, value);
|
||||
}
|
||||
};
|
||||
CloudWatchMetricsService concurrent = new CloudWatchMetricsService(new InMemoryStorage<>(), storage,
|
||||
new RegionResolver(REGION, "123456789012"));
|
||||
CompositeAlarm original = new CompositeAlarm();
|
||||
original.setAlarmName("concurrent");
|
||||
original.setAlarmRule("FALSE");
|
||||
original.setTags(new HashMap<>(Map.of("team", "old")));
|
||||
concurrent.putCompositeAlarm(original, REGION);
|
||||
CompositeAlarm replacement = new CompositeAlarm();
|
||||
replacement.setAlarmName("concurrent");
|
||||
replacement.setAlarmRule("TRUE");
|
||||
AtomicReference<Thread> tagThread = new AtomicReference<>();
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> update = executor.submit(() -> concurrent.putCompositeAlarm(replacement, REGION));
|
||||
Future<?> tags;
|
||||
try {
|
||||
assertTrue(updating.await(2, TimeUnit.SECONDS));
|
||||
tags = executor.submit(() -> {
|
||||
tagThread.set(Thread.currentThread());
|
||||
if (remove) {
|
||||
concurrent.untagResource(original.getAlarmArn(), List.of("team"), REGION);
|
||||
} else {
|
||||
concurrent.tagResource(original.getAlarmArn(), Map.of("team", "new"), REGION);
|
||||
}
|
||||
});
|
||||
ThreadStates.awaitBlockedOrDone(tagThread, tags);
|
||||
assertFalse(tags.isDone(), "tag mutation must share the definition update lock");
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
update.get(2, TimeUnit.SECONDS);
|
||||
tags.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
CompositeAlarm result = concurrent.describeCompositeAlarms(List.of("concurrent"), null, REGION).getFirst();
|
||||
assertEquals("TRUE", result.getAlarmRule());
|
||||
assertEquals(remove ? Map.of() : Map.of("team", "new"), result.getTags());
|
||||
}
|
||||
|
||||
private CompositeAlarm put(String name, String rule) {
|
||||
CompositeAlarm alarm = new CompositeAlarm();
|
||||
alarm.setAlarmName(name);
|
||||
alarm.setAlarmRule(rule);
|
||||
alarm.setActionsEnabled(true);
|
||||
service.putCompositeAlarm(alarm, REGION);
|
||||
return alarm;
|
||||
}
|
||||
|
||||
private String state(String name) {
|
||||
return service.describeCompositeAlarms(List.of(name), null, REGION).getFirst().getStateValue();
|
||||
}
|
||||
}
|
||||
+25
@@ -232,4 +232,29 @@ class CloudWatchMetricStreamsServiceTest {
|
||||
service.untagResource(arn, List.of("team"), REGION);
|
||||
assertFalse(service.listTagsForResource(arn, REGION).containsKey("team"));
|
||||
}
|
||||
|
||||
/**
|
||||
* An ARN naming no stream is an error on all three operations, not a silent no-op. The ARN
|
||||
* used here differs from a working one only in the stream name, so the outcome cannot be
|
||||
* explained by the ARN failing to parse as a metric stream ARN.
|
||||
*/
|
||||
@Test
|
||||
void tagOperationsRejectAnArnThatNamesNoStream() {
|
||||
String arn = service.putMetricStream(stream("ops"), REGION).getArn();
|
||||
String ghost = arn.replace("metric-stream/ops", "metric-stream/nosuch");
|
||||
assertTrue(CloudWatchMetricStreamsService.isMetricStreamArn(ghost));
|
||||
|
||||
for (Runnable call : List.<Runnable>of(
|
||||
() -> service.tagResource(ghost, Map.of("env", "prod"), REGION),
|
||||
() -> service.untagResource(ghost, List.of("env"), REGION),
|
||||
() -> service.listTagsForResource(ghost, REGION))) {
|
||||
AwsException e = assertThrows(AwsException.class, call::run);
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode());
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
|
||||
// The failures wrote nothing: the real stream still carries only what it was given.
|
||||
service.tagResource(arn, Map.of("team", "platform"), REGION);
|
||||
assertEquals(Map.of("team", "platform"), service.listTagsForResource(arn, REGION));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,6 +373,63 @@ class CognitoServiceTest {
|
||||
null, null, List.of(), null, null);
|
||||
}
|
||||
|
||||
@Nested
|
||||
class PreventUserExistenceErrors {
|
||||
|
||||
private UserPoolClient client(UserPool pool, String preventUserExistenceErrors) {
|
||||
return service.createUserPoolClient(pool.getId(), "existence-client", false, false, List.of(), List.of(),
|
||||
null, List.of(), null, List.of("ALLOW_USER_PASSWORD_AUTH"), null, null, List.of(),
|
||||
preventUserExistenceErrors, List.of(), null, null, null, List.of(), null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledAnswersAnUnknownUserLikeAWrongPassword() {
|
||||
UserPool pool = createPoolAndUser();
|
||||
UserPoolClient client = client(pool, "ENABLED");
|
||||
|
||||
AwsException unknown = assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(),
|
||||
"USER_PASSWORD_AUTH", Map.of("USERNAME", "nobody", "PASSWORD", "Perm1234!")));
|
||||
AwsException wrongPassword = assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(),
|
||||
"USER_PASSWORD_AUTH", Map.of("USERNAME", "alice", "PASSWORD", "Wrong1234!")));
|
||||
|
||||
assertEquals("NotAuthorizedException", unknown.getErrorCode());
|
||||
assertEquals(wrongPassword.getErrorCode(), unknown.getErrorCode());
|
||||
assertEquals(wrongPassword.getMessage(), unknown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledSimulatesCodeDeliveryAndRejectsCodesForAnUnknownUser() {
|
||||
UserPool pool = createPoolAndUser();
|
||||
UserPoolClient client = client(pool, "ENABLED");
|
||||
|
||||
assertEquals(Map.of("AttributeName", "email", "DeliveryMedium", "EMAIL", "Destination", "n***@e***"),
|
||||
service.forgotPassword(client.getClientId(), "nobody@example.com"));
|
||||
assertEquals("EMAIL", service.resendConfirmationCode(client.getClientId(), "nobody@example.com")
|
||||
.get("DeliveryMedium"));
|
||||
assertEquals("CodeMismatchException", assertThrows(AwsException.class, () ->
|
||||
service.confirmForgotPassword(client.getClientId(), "nobody@example.com", "123456", "Perm1234!"))
|
||||
.getErrorCode());
|
||||
assertEquals("CodeMismatchException", assertThrows(AwsException.class, () ->
|
||||
service.confirmSignUp(client.getClientId(), "nobody@example.com", "123456")).getErrorCode());
|
||||
assertThrows(AwsException.class, () -> service.adminGetUser(pool.getId(), "nobody@example.com"),
|
||||
"no user is created along the way");
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyAndUnsetStillReportUserNotFound() {
|
||||
UserPool pool = createPoolAndUser();
|
||||
for (String setting : new String[] {"LEGACY", null}) {
|
||||
UserPoolClient client = client(pool, setting);
|
||||
|
||||
assertEquals("UserNotFoundException", assertThrows(AwsException.class, () -> service.initiateAuth(
|
||||
client.getClientId(), "USER_PASSWORD_AUTH", Map.of("USERNAME", "nobody", "PASSWORD", "x")))
|
||||
.getErrorCode());
|
||||
assertEquals("UserNotFoundException", assertThrows(AwsException.class, () ->
|
||||
service.forgotPassword(client.getClientId(), "nobody")).getErrorCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"Short1!a",
|
||||
@@ -1312,6 +1369,22 @@ class CognitoServiceTest {
|
||||
assertEquals("http://localhost:4566/custompool", service.getIssuer(pool.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void localIssuerKeysServeOnlyThisEmulatorsOwnPoolIssuers() throws Exception {
|
||||
UserPool pool = createPoolAndUser();
|
||||
UserPoolClient client = clientWithFlows(pool, "ALLOW_USER_PASSWORD_AUTH");
|
||||
String token = (String) ((Map<?, ?>) service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")).get("AuthenticationResult")).get("AccessToken");
|
||||
String kid = MAPPER.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[0])).path("kid").asText();
|
||||
|
||||
Map<String, java.security.interfaces.RSAPublicKey> keys = service.localIssuerKeys(service.getIssuer(pool.getId())).orElseThrow();
|
||||
assertTrue(keys.containsKey(kid), "the key that signed the pool's tokens");
|
||||
assertTrue(service.localIssuerKeys(service.getIssuer(pool.getId()) + "/").isPresent());
|
||||
assertTrue(service.localIssuerKeys("https://cognito-idp.us-east-1.amazonaws.com/" + pool.getId()).isEmpty());
|
||||
assertTrue(service.localIssuerKeys(service.getIssuer("us-east-1_missing")).isEmpty());
|
||||
assertTrue(service.localIssuerKeys(null).isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Groups
|
||||
// =========================================================================
|
||||
|
||||
@@ -284,6 +284,23 @@ class VpcNetworkManagerTest {
|
||||
assertTrue(second.containsAddress(Cidr4.parse(b + "/32").orElseThrow().network()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubstitutedVpcKeepsEachSubnetAtItsOffsetWhateverTheDeclarationOrder() {
|
||||
existingNetwork("someone-else", "172.31.0.0/16", Map.of());
|
||||
|
||||
manager.declareVpc(REGION, "vpc-default", "172.31.0.0/16");
|
||||
manager.declareSubnet(REGION, "vpc-default", "subnet-c", "172.31.32.0/20");
|
||||
manager.declareSubnet(REGION, "vpc-default", "subnet-a", "172.31.0.0/20");
|
||||
manager.declareSubnet(REGION, "vpc-default", "subnet-b", "172.31.16.0/20");
|
||||
|
||||
assertTrue(manager.isSubstituted(REGION, "vpc-default"));
|
||||
assertEquals("10.240.0.0/16", manager.effectiveVpcCidr(REGION, "vpc-default").orElseThrow());
|
||||
assertEquals("10.240.0.0/20", manager.effectiveSubnetCidr(REGION, "subnet-a").orElseThrow());
|
||||
assertEquals("10.240.16.0/20", manager.effectiveSubnetCidr(REGION, "subnet-b").orElseThrow());
|
||||
assertEquals("10.240.32.0/20", manager.effectiveSubnetCidr(REGION, "subnet-c").orElseThrow(),
|
||||
"a restart that declares subnets in another order must reach the same plan");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSubnetOutsideItsVpcRangeIsRemappedInsideIt() {
|
||||
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
|
||||
|
||||
-169
@@ -1,169 +0,0 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Volume;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Docker-backed proof that an EFS-configured task volume's local mount is scoped to
|
||||
* {@code (fileSystemId, rootDirectory, accessPointId)}, not just {@code fileSystemId} (#2563).
|
||||
* Each scenario runs a real busybox container against the same {@code fileSystemId}, writing
|
||||
* and checking marker files under {@code /mnt/efs} with a shell one-liner whose exit code
|
||||
* proves whether the previous task's data was visible.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EcsContainerManagerEfsIsolationDockerIntegrationTest {
|
||||
|
||||
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";
|
||||
|
||||
@Inject
|
||||
EcsContainerManager containerManager;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
private final List<String> volumesToCleanUp = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"Docker daemon must be available for ECS EFS isolation integration tests");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUpVolumes() {
|
||||
volumesToCleanUp.forEach(lifecycleManager::removeVolume);
|
||||
volumesToCleanUp.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Task A writes a marker under {@code rootDirectory} {@code /team-a}; task B, on the same
|
||||
* file system but a different root, must not see it (if the bug were still present, one
|
||||
* shared volume keyed only by {@code fileSystemId} would leak team-a's marker into team-b's
|
||||
* task before it ever reaches its own write); a third task back on {@code /team-a} must
|
||||
* likewise not see what team-b wrote.
|
||||
*/
|
||||
@Test
|
||||
void differentRootDirectoriesOnSameFileSystemAreIsolated() {
|
||||
String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null,
|
||||
"echo team-a > /mnt/efs/only-a.txt"),
|
||||
"task A should write its marker cleanly");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-b", null,
|
||||
"test ! -e /mnt/efs/only-a.txt && echo team-b > /mnt/efs/only-b.txt"),
|
||||
"task B must not see task A's rootDirectory-scoped data");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null,
|
||||
"test ! -e /mnt/efs/only-b.txt"),
|
||||
"task on /team-a must not see /team-b's data");
|
||||
}
|
||||
|
||||
/**
|
||||
* A second task using the identical {@code rootDirectory} must see the first task's data:
|
||||
* sharing an identical configuration is existing, desired behaviour.
|
||||
*/
|
||||
@Test
|
||||
void sameRootDirectoryOnSameFileSystemStillShares() {
|
||||
String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/shared", null,
|
||||
"echo hello > /mnt/efs/shared.txt"),
|
||||
"first task should write its marker cleanly");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/shared", null,
|
||||
"grep -qx hello /mnt/efs/shared.txt"),
|
||||
"a second task with the same rootDirectory must share the first task's data");
|
||||
}
|
||||
|
||||
/**
|
||||
* A plain {@code rootDirectory} mount (no {@code accessPointId}) on the same file system
|
||||
* must not see access-point-scoped data and vice versa, while a second task through the
|
||||
* same access point must still share its data.
|
||||
*/
|
||||
@Test
|
||||
void accessPointIdIsolatesFromRootDirectoryOnSameFileSystem() {
|
||||
String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String accessPointId = "fsap-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, null, accessPointId,
|
||||
"echo via-ap > /mnt/efs/via-ap.txt"),
|
||||
"task mounted through the access point should write its marker cleanly");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/", null,
|
||||
"test ! -e /mnt/efs/via-ap.txt"),
|
||||
"a plain rootDirectory mount must not see access-point-scoped data");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, null, accessPointId,
|
||||
"grep -qx via-ap /mnt/efs/via-ap.txt"),
|
||||
"a second task through the same access point must share its data");
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a single-container ECS task that mounts {@code fileSystemId} (scoped by
|
||||
* {@code rootDirectory}/{@code accessPointId}) at {@code /mnt/efs} and executes
|
||||
* {@code shellCommand}, then blocks until the container exits and returns its exit code.
|
||||
*/
|
||||
private int runEfsCommand(String fileSystemId, String rootDirectory, String accessPointId, String shellCommand) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
app.setImage(IMAGE);
|
||||
app.setCommand(List.of("sh", "-c", shellCommand));
|
||||
app.setMountPoints(List.of(new MountPoint("efs-data", "/mnt/efs", false)));
|
||||
|
||||
TaskDefinition taskDef = new TaskDefinition();
|
||||
taskDef.setFamily("efs-isolation-" + suffix);
|
||||
taskDef.setContainerDefinitions(List.of(app));
|
||||
taskDef.setVolumes(List.of(new Volume("efs-data", null,
|
||||
new EfsVolumeConfiguration(fileSystemId, rootDirectory, null, null, accessPointId, null))));
|
||||
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/efs-isolation/" + suffix);
|
||||
|
||||
volumesToCleanUp.add(EcsContainerManager.efsVolumeName(fileSystemId, accessPointId, rootDirectory));
|
||||
|
||||
EcsTaskHandle handle = containerManager.startTask(task, taskDef, List.of(), "us-east-1");
|
||||
String dockerId = handle.getContainerIds().get("app");
|
||||
try {
|
||||
return dockerClient.waitContainerCmd(dockerId)
|
||||
.exec(new WaitContainerResultCallback())
|
||||
.awaitStatusCode(60, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
containerManager.stopTask(handle);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.core.command.WaitContainerResultCallback;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
|
||||
import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration;
|
||||
import io.github.hectorvent.floci.services.ecs.model.MountPoint;
|
||||
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
|
||||
import io.github.hectorvent.floci.services.ecs.model.Volume;
|
||||
import io.github.hectorvent.floci.services.efs.EfsMounts;
|
||||
import io.github.hectorvent.floci.services.efs.EfsService;
|
||||
import io.github.hectorvent.floci.services.efs.model.CreateAccessPointRequest;
|
||||
import io.github.hectorvent.floci.services.efs.model.CreateFileSystemRequest;
|
||||
import io.github.hectorvent.floci.services.efs.model.CreationInfo;
|
||||
import io.github.hectorvent.floci.services.efs.model.PosixUser;
|
||||
import io.github.hectorvent.floci.services.efs.model.RootDirectory;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* Docker-backed proof that an EFS file system is one shared store, as on AWS: every task volume
|
||||
* of it mounts the same Docker volume, a {@code rootDirectory} or access point mounts its own
|
||||
* folder of it, and a mount of the file system root sees every folder. Each scenario runs a real
|
||||
* busybox container whose exit code proves what it could see under {@code /mnt/efs}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EcsContainerManagerEfsSharingDockerIntegrationTest {
|
||||
|
||||
private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
EcsContainerManager containerManager;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
EfsService efsService;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
private final List<String> volumesToCleanUp = new ArrayList<>();
|
||||
|
||||
@BeforeEach
|
||||
void requireDocker() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"Docker daemon must be available for ECS EFS integration tests");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanUpVolumes() {
|
||||
volumesToCleanUp.forEach(lifecycleManager::removeVolume);
|
||||
volumesToCleanUp.clear();
|
||||
}
|
||||
|
||||
/** Two root directories are separate folders, and the file system root sees both. */
|
||||
@Test
|
||||
void rootDirectoriesAreFoldersOfOneFileSystem() {
|
||||
String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null,
|
||||
"echo team-a > /mnt/efs/only-a.txt"));
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-b", null,
|
||||
"test ! -e /mnt/efs/only-a.txt && echo team-b > /mnt/efs/only-b.txt"),
|
||||
"a task on /team-b must not see /team-a's files");
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null,
|
||||
"grep -qx team-a /mnt/efs/only-a.txt && test ! -e /mnt/efs/only-b.txt"),
|
||||
"a second task on /team-a shares its files and still does not see /team-b's");
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/", null,
|
||||
"grep -qx team-a /mnt/efs/team-a/only-a.txt && grep -qx team-b /mnt/efs/team-b/only-b.txt"),
|
||||
"a task on the file system root sees every root directory's files");
|
||||
}
|
||||
|
||||
/**
|
||||
* An access point mounts its root directory, created on first use with its CreationInfo, and
|
||||
* shares it with every other mount of the file system.
|
||||
*/
|
||||
@Test
|
||||
void anAccessPointMountsItsFolderOfTheFileSystem() {
|
||||
String fileSystemId = createFileSystem();
|
||||
String accessPointId = createAccessPoint(fileSystemId, "/apps/orders", 1001L, 1002L, "750");
|
||||
|
||||
assertEquals(0, runEfsCommand(fileSystemId, null, accessPointId,
|
||||
"echo order-1 > /mnt/efs/orders.txt"));
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/", null,
|
||||
"grep -qx order-1 /mnt/efs/apps/orders/orders.txt"
|
||||
+ " && test \"$(stat -c '%u:%g %a' /mnt/efs/apps/orders)\" = '1001:1002 750'"
|
||||
+ " && test \"$(stat -c '%u:%g %a' /mnt/efs/apps)\" = '1001:1002 750'"),
|
||||
"the root mount sees the access point's files, in folders created from its CreationInfo");
|
||||
assertEquals(0, runEfsCommand(fileSystemId, "/apps", null,
|
||||
"grep -qx order-1 /mnt/efs/orders/orders.txt"),
|
||||
"a rootDirectory above the access point's folder sees it too");
|
||||
}
|
||||
|
||||
/** Without CreationInfo, an access point whose root directory does not exist cannot be mounted. */
|
||||
@Test
|
||||
void anAccessPointWithAMissingRootDirectoryAndNoCreationInfoIsRefused() {
|
||||
String fileSystemId = createFileSystem();
|
||||
String accessPointId = createAccessPoint(fileSystemId, "/absent", null, null, null);
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> runEfsCommand(fileSystemId, null, accessPointId, "true"));
|
||||
}
|
||||
|
||||
private String createFileSystem() {
|
||||
CreateFileSystemRequest request = new CreateFileSystemRequest();
|
||||
request.setCreationToken("efs-sharing-" + UUID.randomUUID());
|
||||
return efsService.createFileSystem(request, REGION).getFileSystemId();
|
||||
}
|
||||
|
||||
private String createAccessPoint(String fileSystemId, String path, Long ownerUid, Long ownerGid,
|
||||
String permissions) {
|
||||
RootDirectory root = new RootDirectory();
|
||||
root.setPath(path);
|
||||
if (permissions != null) {
|
||||
CreationInfo info = new CreationInfo();
|
||||
info.setOwnerUid(ownerUid);
|
||||
info.setOwnerGid(ownerGid);
|
||||
info.setPermissions(permissions);
|
||||
root.setCreationInfo(info);
|
||||
}
|
||||
PosixUser user = new PosixUser();
|
||||
user.setUid(1001L);
|
||||
user.setGid(1002L);
|
||||
CreateAccessPointRequest request = new CreateAccessPointRequest();
|
||||
request.setFileSystemId(fileSystemId);
|
||||
request.setRootDirectory(root);
|
||||
request.setPosixUser(user);
|
||||
return efsService.createAccessPoint(REGION, request).getAccessPointId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a single-container ECS task that mounts {@code fileSystemId} (through
|
||||
* {@code rootDirectory} or {@code accessPointId}) at {@code /mnt/efs} and executes
|
||||
* {@code shellCommand}, then blocks until the container exits and returns its exit code.
|
||||
*/
|
||||
private int runEfsCommand(String fileSystemId, String rootDirectory, String accessPointId, String shellCommand) {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
ContainerDefinition app = new ContainerDefinition();
|
||||
app.setName("app");
|
||||
app.setImage(IMAGE);
|
||||
app.setCommand(List.of("sh", "-c", shellCommand));
|
||||
app.setMountPoints(List.of(new MountPoint("efs-data", "/mnt/efs", false)));
|
||||
|
||||
TaskDefinition taskDef = new TaskDefinition();
|
||||
taskDef.setFamily("efs-sharing-" + suffix);
|
||||
taskDef.setContainerDefinitions(List.of(app));
|
||||
taskDef.setVolumes(List.of(new Volume("efs-data", null,
|
||||
new EfsVolumeConfiguration(fileSystemId, rootDirectory, null, null, accessPointId, null))));
|
||||
|
||||
EcsTask task = new EcsTask();
|
||||
task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/efs-sharing/" + suffix);
|
||||
|
||||
if (!volumesToCleanUp.contains(EfsMounts.volumeName(fileSystemId))) {
|
||||
volumesToCleanUp.add(EfsMounts.volumeName(fileSystemId));
|
||||
}
|
||||
|
||||
EcsTaskHandle handle = containerManager.startTask(task, taskDef, List.of(), REGION);
|
||||
String dockerId = handle.getContainerIds().get("app");
|
||||
try {
|
||||
return dockerClient.waitContainerCmd(dockerId)
|
||||
.exec(new WaitContainerResultCallback())
|
||||
.awaitStatusCode(60, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
containerManager.stopTask(handle);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
package io.github.hectorvent.floci.services.ecs.container;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link EcsContainerManager#efsVolumeName}, the naming logic that scopes an
|
||||
* EFS-backed task volume's shared Docker named volume to both {@code fileSystemId} and its
|
||||
* effective root (#2563). The name must be stable for a given (fileSystemId, rootDirectory,
|
||||
* accessPointId) combination (so identical mounts keep sharing one volume), distinct across
|
||||
* different roots on the same file system (so mounts do not collide on the same tree), and
|
||||
* always a legal Docker volume name.
|
||||
*/
|
||||
class EcsContainerManagerEfsVolumeNamingTest {
|
||||
|
||||
private static final Pattern DOCKER_VOLUME_NAME = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$");
|
||||
|
||||
@Test
|
||||
void defaultsToPlainFileSystemNameWhenNoRootOrAccessPointIsSet() {
|
||||
assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, null));
|
||||
assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, ""));
|
||||
assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, "/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentRootDirectoriesOnSameFileSystemYieldDifferentVolumes() {
|
||||
String rootA = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a");
|
||||
String rootB = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-b");
|
||||
String rootNone = EcsContainerManager.efsVolumeName("fs-shared", null, null);
|
||||
|
||||
assertNotEquals(rootA, rootB, "different rootDirectory values must isolate the volume");
|
||||
assertNotEquals(rootA, rootNone, "a non-root rootDirectory must not collapse to the plain name");
|
||||
assertTrue(DOCKER_VOLUME_NAME.matcher(rootA).matches(), "must be docker-safe, was: " + rootA);
|
||||
assertTrue(DOCKER_VOLUME_NAME.matcher(rootB).matches(), "must be docker-safe, was: " + rootB);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameRootDirectoryOnSameFileSystemStillShares() {
|
||||
String first = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a");
|
||||
String second = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a");
|
||||
|
||||
assertEquals(first, second, "identical (fileSystemId, rootDirectory) must keep sharing one volume");
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessPointIdTakesPrecedenceOverRootDirectory() {
|
||||
String viaAccessPoint = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", "/ignored");
|
||||
String viaRootOnly = EcsContainerManager.efsVolumeName("fs-shared", null, "/ignored");
|
||||
|
||||
assertNotEquals(viaAccessPoint, viaRootOnly,
|
||||
"an access point's own root must take precedence over rootDirectory, not merge with it");
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentAccessPointsOnSameFileSystemYieldDifferentVolumes() {
|
||||
String apOne = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", null);
|
||||
String apTwo = EcsContainerManager.efsVolumeName("fs-shared", "fsap-222", null);
|
||||
|
||||
assertNotEquals(apOne, apTwo, "different accessPointId values must isolate the volume");
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameAccessPointStillShares() {
|
||||
String first = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", null);
|
||||
String second = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", "/whatever-is-ignored");
|
||||
|
||||
assertEquals(first, second,
|
||||
"the same accessPointId must keep sharing one volume regardless of rootDirectory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void equivalentRootDirectorySpellingsShareTheSameVolume() {
|
||||
String canonical = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a");
|
||||
|
||||
assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a/"),
|
||||
"a trailing slash must not create a distinct volume for the same directory");
|
||||
assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "//team-a"),
|
||||
"a repeated leading slash must not create a distinct volume for the same directory");
|
||||
assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "team-a"),
|
||||
"a missing leading slash must not create a distinct volume for the same directory");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -89,7 +89,7 @@ class EcsContainerManagerSecurityGroupTest {
|
||||
containerDetector, config, regionResolver, awsEnv,
|
||||
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
|
||||
ecrRegistryManager, mock(HostVolumePolicy.class),
|
||||
ec2Service, firewallManager);
|
||||
ec2Service, firewallManager, mock(io.github.hectorvent.floci.services.efs.EfsMounts.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+7
-7
@@ -69,6 +69,7 @@ class EcsContainerManagerVolumesTest {
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any()))
|
||||
.thenReturn(new ContainerInfo("docker-id", Map.of()));
|
||||
when(lifecycleManager.ensureSharedVolumeDirectory(anyString(), anyString(), any(), any())).thenReturn(true);
|
||||
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
@@ -132,9 +133,8 @@ class EcsContainerManagerVolumesTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Each EFS volume resolves to a shared local Docker named volume keyed by file system id
|
||||
* AND effective root (here: rootDirectory, since neither volume sets an accessPointId),
|
||||
* read-write or read-only per the mountPoint.
|
||||
* Each EFS volume mounts its file system's one Docker named volume: the whole volume for the
|
||||
* file system root, or the rootDirectory's folder of it, read-write or read-only per the mountPoint.
|
||||
*/
|
||||
@Test
|
||||
void efsVolumeMountPointsResolveToSharedNamedVolumesByAccessMode() {
|
||||
@@ -159,10 +159,10 @@ class EcsContainerManagerVolumesTest {
|
||||
|
||||
manager.startTask(task, taskDef, List.of(), "us-east-1");
|
||||
|
||||
verify(builder, times(1)).withNamedVolumeSubpath(
|
||||
"floci-efs-fs-0123456789abcdef0", "dps", "/mnt/efs", false);
|
||||
verify(builder, times(1)).withNamedVolume(
|
||||
EcsContainerManager.efsVolumeName("fs-0123456789abcdef0", null, "/dps"), "/mnt/efs", false);
|
||||
verify(builder, times(1)).withNamedVolume(
|
||||
EcsContainerManager.efsVolumeName("fs-00000000000000001", null, null), "/mnt/shared", true);
|
||||
"floci-efs-fs-00000000000000001", "/mnt/shared", true);
|
||||
|
||||
// EFS volumes are never bind-mounted as host paths.
|
||||
verify(builder, never()).withBind(any(), any());
|
||||
@@ -202,7 +202,7 @@ class EcsContainerManagerVolumesTest {
|
||||
configured.startTask(task, taskDef, List.of(), "us-east-1");
|
||||
|
||||
verify(lifecycleManager, times(1)).ensureSharedVolume(
|
||||
EcsContainerManager.efsVolumeName("fs-abc", null, "/dps"),
|
||||
"floci-efs-fs-abc",
|
||||
OptionalInt.of(1001), OptionalInt.of(1001), Optional.of("2775"), "busybox:stable");
|
||||
}
|
||||
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/** CreateAccessPoint refuses a root directory or identity that EFS itself would refuse. */
|
||||
@QuarkusTest
|
||||
class EfsAccessPointValidationTest {
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private String createFileSystem(String token) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body("{\"CreationToken\": \"" + token + "\"}")
|
||||
.when()
|
||||
.post("/2015-02-01/file-systems")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().jsonPath().getString("FileSystemId");
|
||||
}
|
||||
|
||||
private io.restassured.response.ValidatableResponse createAccessPoint(String body) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/2015-02-01/access-points")
|
||||
.then();
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsANestedRootDirectoryWithCreationInfo() {
|
||||
String fileSystemId = createFileSystem("ap-valid");
|
||||
|
||||
createAccessPoint("{\"FileSystemId\": \"" + fileSystemId + "\","
|
||||
+ " \"PosixUser\": {\"Uid\": 1001, \"Gid\": 1001},"
|
||||
+ " \"RootDirectory\": {\"Path\": \"/apps/my-function\","
|
||||
+ " \"CreationInfo\": {\"OwnerUid\": 1001, \"OwnerGid\": 1001, \"Permissions\": \"0755\"}}}")
|
||||
.statusCode(200)
|
||||
.body("RootDirectory.Path", equalTo("/apps/my-function"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesARootDirectoryThatClimbsOutOrHidesItself() {
|
||||
String fileSystemId = createFileSystem("ap-bad-path");
|
||||
|
||||
for (String path : new String[] {"/a/../b", "/.hidden", "relative", "/a;rm"}) {
|
||||
createAccessPoint("{\"FileSystemId\": \"" + fileSystemId + "\","
|
||||
+ " \"RootDirectory\": {\"Path\": \"" + path + "\"}}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequest"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesPartialCreationInfoAndPosixUser() {
|
||||
String fileSystemId = createFileSystem("ap-partial");
|
||||
|
||||
createAccessPoint("{\"FileSystemId\": \"" + fileSystemId + "\","
|
||||
+ " \"RootDirectory\": {\"Path\": \"/data\", \"CreationInfo\": {\"OwnerUid\": 1001}}}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequest"));
|
||||
createAccessPoint("{\"FileSystemId\": \"" + fileSystemId + "\","
|
||||
+ " \"RootDirectory\": {\"Path\": \"/data\","
|
||||
+ " \"CreationInfo\": {\"OwnerUid\": 1001, \"OwnerGid\": 1001, \"Permissions\": \"rwx\"}}}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequest"));
|
||||
createAccessPoint("{\"FileSystemId\": \"" + fileSystemId + "\", \"PosixUser\": {\"Uid\": 1001}}")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("BadRequest"));
|
||||
}
|
||||
}
|
||||
@@ -90,8 +90,8 @@ class EfsIntegrationTest {
|
||||
.body("""
|
||||
{
|
||||
"FileSystemId": "%s",
|
||||
"SubnetId": "subnet-12345",
|
||||
"SecurityGroups": ["sg-11111"]
|
||||
"SubnetId": "subnet-default-us-east-1-a",
|
||||
"SecurityGroups": ["sg-default-us-east-1"]
|
||||
}
|
||||
""".formatted(fileSystemId))
|
||||
.when()
|
||||
@@ -100,7 +100,12 @@ class EfsIntegrationTest {
|
||||
.statusCode(200)
|
||||
.body("MountTargetId", startsWith("fsmt-"))
|
||||
.body("FileSystemId", equalTo(fileSystemId))
|
||||
.body("SubnetId", equalTo("subnet-12345"))
|
||||
.body("SubnetId", equalTo("subnet-default-us-east-1-a"))
|
||||
.body("VpcId", equalTo("vpc-default-us-east-1"))
|
||||
.body("AvailabilityZoneName", equalTo("us-east-1a"))
|
||||
.body("IpAddress", startsWith("172.31.0."))
|
||||
.body("NetworkInterfaceId", startsWith("eni-"))
|
||||
.body("LifeCycleState", equalTo("available"))
|
||||
.extract().jsonPath().getString("MountTargetId");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Mount targets take their VPC, zone and address from the EC2 subnet they are created in, hold an
|
||||
* EC2 network interface for that address, and answer the file system's DNS name.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class EfsMountTargetSubnetTest {
|
||||
|
||||
@Inject
|
||||
EfsService efsService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private String createFileSystem(String token) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body("{\"CreationToken\": \"" + token + "\"}")
|
||||
.when()
|
||||
.post("/2015-02-01/file-systems")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().jsonPath().getString("FileSystemId");
|
||||
}
|
||||
|
||||
private io.restassured.response.ValidatableResponse createMountTarget(String fileSystemId, String subnetId) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body("{\"FileSystemId\": \"" + fileSystemId + "\", \"SubnetId\": \"" + subnetId + "\"}")
|
||||
.when()
|
||||
.post("/2015-02-01/mount-targets")
|
||||
.then();
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesTheZoneAndVpcOfEachSubnet() {
|
||||
String fileSystemId = createFileSystem("subnet-zones");
|
||||
|
||||
createMountTarget(fileSystemId, "subnet-default-us-east-1-b")
|
||||
.statusCode(200)
|
||||
.body("VpcId", equalTo("vpc-default-us-east-1"))
|
||||
.body("AvailabilityZoneName", equalTo("us-east-1b"))
|
||||
.body("IpAddress", startsWith("172.31.16."));
|
||||
createMountTarget(fileSystemId, "subnet-default-us-east-1-c")
|
||||
.statusCode(200)
|
||||
.body("AvailabilityZoneName", equalTo("us-east-1c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesASubnetThatDoesNotExist() {
|
||||
String fileSystemId = createFileSystem("subnet-missing");
|
||||
|
||||
createMountTarget(fileSystemId, "subnet-nope")
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SubnetNotFound"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesASecurityGroupThatDoesNotExist() {
|
||||
String fileSystemId = createFileSystem("subnet-missing-sg");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"FileSystemId\": \"" + fileSystemId + "\", \"SubnetId\": \"subnet-default-us-east-1-a\","
|
||||
+ " \"SecurityGroups\": [\"sg-nope\"]}")
|
||||
.when()
|
||||
.post("/2015-02-01/mount-targets")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("SecurityGroupNotFound"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsOneMountTargetPerZone() {
|
||||
String fileSystemId = createFileSystem("subnet-one-per-zone");
|
||||
String vpcId = "vpc-default-us-east-1";
|
||||
String secondSubnet = given()
|
||||
.formParam("Action", "CreateSubnet")
|
||||
.formParam("VpcId", vpcId)
|
||||
.formParam("CidrBlock", "172.31.200.0/24")
|
||||
.formParam("AvailabilityZone", "us-east-1a")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/ec2/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("CreateSubnetResponse.subnet.subnetId");
|
||||
|
||||
createMountTarget(fileSystemId, "subnet-default-us-east-1-a").statusCode(200);
|
||||
createMountTarget(fileSystemId, secondSubnet)
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("MountTargetConflict"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void holdsAnEc2NetworkInterfaceWithItsAddressUntilDeleted() {
|
||||
String fileSystemId = createFileSystem("subnet-eni");
|
||||
var mountTarget = createMountTarget(fileSystemId, "subnet-default-us-east-1-c")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath();
|
||||
String eniId = mountTarget.getString("NetworkInterfaceId");
|
||||
|
||||
describeNetworkInterface(eniId)
|
||||
.statusCode(200)
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddress",
|
||||
equalTo(mountTarget.getString("IpAddress")))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.status", equalTo("in-use"))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.subnetId",
|
||||
equalTo("subnet-default-us-east-1-c"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/2015-02-01/mount-targets/" + mountTarget.getString("MountTargetId"))
|
||||
.then()
|
||||
.statusCode(204);
|
||||
describeNetworkInterface(eniId).statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesTheFileSystemDnsNameToAMountTarget() {
|
||||
String fileSystemId = createFileSystem("subnet-dns");
|
||||
String inZoneB = createMountTarget(fileSystemId, "subnet-default-us-east-1-b")
|
||||
.statusCode(200).extract().jsonPath().getString("IpAddress");
|
||||
String inZoneA = createMountTarget(fileSystemId, "subnet-default-us-east-1-a")
|
||||
.statusCode(200).extract().jsonPath().getString("IpAddress");
|
||||
|
||||
assertEquals(Optional.of(inZoneA),
|
||||
efsService.resolveDnsName(fileSystemId + ".efs.us-east-1.amazonaws.com"));
|
||||
assertEquals(Optional.of(inZoneB),
|
||||
efsService.resolveDnsName("us-east-1b." + fileSystemId + ".efs.us-east-1.amazonaws.com."));
|
||||
assertEquals(Optional.empty(),
|
||||
efsService.resolveDnsName("us-east-1c." + fileSystemId + ".efs.us-east-1.amazonaws.com"));
|
||||
assertEquals(Optional.empty(),
|
||||
efsService.resolveDnsName(fileSystemId + ".efs.eu-west-1.amazonaws.com"));
|
||||
assertEquals(Optional.empty(), efsService.resolveDnsName("example.com"));
|
||||
}
|
||||
|
||||
private io.restassured.response.ValidatableResponse describeNetworkInterface(String eniId) {
|
||||
return given()
|
||||
.formParam("Action", "DescribeNetworkInterfaces")
|
||||
.formParam("NetworkInterfaceId.1", eniId)
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/ec2/aws4_request")
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package io.github.hectorvent.floci.services.efs;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.DirectoryCreation;
|
||||
import io.github.hectorvent.floci.services.efs.model.AccessPointDescription;
|
||||
import io.github.hectorvent.floci.services.efs.model.CreationInfo;
|
||||
import io.github.hectorvent.floci.services.efs.model.PosixUser;
|
||||
import io.github.hectorvent.floci.services.efs.model.RootDirectory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Every mount of a file system shares its one volume; access points mount their root directory in it. */
|
||||
class EfsMountsTest {
|
||||
|
||||
private EfsService efsService;
|
||||
private ContainerLifecycleManager lifecycleManager;
|
||||
private EfsMounts mounts;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
efsService = mock(EfsService.class);
|
||||
lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.ensureSharedVolumeDirectory(anyString(), anyString(), any(), any())).thenReturn(true);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.storage().efs().ownerUid()).thenReturn(OptionalInt.empty());
|
||||
when(config.storage().efs().ownerGid()).thenReturn(OptionalInt.empty());
|
||||
when(config.storage().efs().rootPermissions()).thenReturn(Optional.empty());
|
||||
when(config.storage().efs().initImage()).thenReturn("busybox:stable");
|
||||
mounts = new EfsMounts(efsService, lifecycleManager, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFileSystemRootMountsTheWholeVolume() {
|
||||
EfsMounts.Mount mount = mounts.prepare("us-east-1", "fs-abc", null, null);
|
||||
|
||||
assertEquals("floci-efs-fs-abc", mount.volumeName());
|
||||
assertEquals("", mount.subpath());
|
||||
assertTrue(mount.accessPointUser().isEmpty());
|
||||
verify(lifecycleManager).ensureSharedVolume("floci-efs-fs-abc",
|
||||
OptionalInt.empty(), OptionalInt.empty(), Optional.empty(), "busybox:stable");
|
||||
verify(lifecycleManager, never()).ensureSharedVolumeDirectory(anyString(), anyString(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRootDirectoryMountsItsFolderOfTheSameVolume() {
|
||||
EfsMounts.Mount mount = mounts.prepare("us-east-1", "fs-abc", null, "/team-a/");
|
||||
|
||||
assertEquals("floci-efs-fs-abc", mount.volumeName());
|
||||
assertEquals("team-a", mount.subpath());
|
||||
verify(lifecycleManager).ensureSharedVolumeDirectory("floci-efs-fs-abc", "team-a",
|
||||
Optional.of(new DirectoryCreation(0, 0, "755")), "busybox:stable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccessPointMountsItsRootDirectoryAndCarriesItsUser() {
|
||||
when(efsService.describeAccessPoints("us-east-1", null, "fsap-1"))
|
||||
.thenReturn(List.of(accessPoint("fs-abc", "/my-function", creationInfo(1001L, 1001L, "755"))));
|
||||
|
||||
EfsMounts.Mount mount = mounts.prepare("us-east-1", null, "fsap-1", "/ignored");
|
||||
|
||||
assertEquals("floci-efs-fs-abc", mount.volumeName());
|
||||
assertEquals("my-function", mount.subpath());
|
||||
assertEquals("1001:1001", EfsMounts.containerUser(mount.accessPointUser().orElseThrow()));
|
||||
assertEquals(List.of(2000L), EfsMounts.secondaryGids(mount.accessPointUser().orElseThrow()));
|
||||
verify(lifecycleManager).ensureSharedVolumeDirectory("floci-efs-fs-abc", "my-function",
|
||||
Optional.of(new DirectoryCreation(1001, 1001, "755")), "busybox:stable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLambdaAccessPointArnIsLookedUpInItsRegion() {
|
||||
when(efsService.describeAccessPoints("eu-west-1", null, "fsap-1"))
|
||||
.thenReturn(List.of(accessPoint("fs-abc", "/", null)));
|
||||
|
||||
EfsMounts.Mount mount = mounts.prepareAccessPoint(
|
||||
"arn:aws:elasticfilesystem:eu-west-1:000000000000:access-point/fsap-1");
|
||||
|
||||
assertEquals("floci-efs-fs-abc", mount.volumeName());
|
||||
assertEquals("", mount.subpath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingRootDirectoryWithoutCreationInfoCannotBeMounted() {
|
||||
when(efsService.describeAccessPoints("us-east-1", null, "fsap-1"))
|
||||
.thenReturn(List.of(accessPoint("fs-abc", "/absent", null)));
|
||||
when(lifecycleManager.ensureSharedVolumeDirectory("floci-efs-fs-abc", "absent", Optional.empty(),
|
||||
"busybox:stable")).thenReturn(false);
|
||||
|
||||
IllegalStateException error = assertThrows(IllegalStateException.class,
|
||||
() -> mounts.prepare("us-east-1", "fs-abc", "fsap-1", null));
|
||||
|
||||
assertTrue(error.getMessage().contains("/absent"), error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccessPointOfAnotherFileSystemIsRefused() {
|
||||
when(efsService.describeAccessPoints("us-east-1", null, "fsap-1"))
|
||||
.thenReturn(List.of(accessPoint("fs-other", "/", null)));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> mounts.prepare("us-east-1", "fs-abc", "fsap-1", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownAccessPointIsRefused() {
|
||||
when(efsService.describeAccessPoints("us-east-1", null, "fsap-404")).thenReturn(List.of());
|
||||
|
||||
assertThrows(EfsException.class, () -> mounts.prepare("us-east-1", "fs-abc", "fsap-404", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void equivalentRootDirectorySpellingsNameOneFolder() {
|
||||
assertEquals("/", EfsMounts.normalizeRootDirectory(null));
|
||||
assertEquals("/", EfsMounts.normalizeRootDirectory(" "));
|
||||
assertEquals("/team-a", EfsMounts.normalizeRootDirectory("team-a"));
|
||||
assertEquals("/team-a", EfsMounts.normalizeRootDirectory("//team-a/"));
|
||||
assertThrows(IllegalArgumentException.class, () -> EfsMounts.normalizeRootDirectory("/a/../b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFolderMountUsesTheVolumeSubpath() {
|
||||
ContainerBuilder.Builder spec = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
|
||||
|
||||
new EfsMounts.Mount("floci-efs-fs-abc", "team-a", Optional.empty()).applyTo(spec, "/mnt/efs", true);
|
||||
new EfsMounts.Mount("floci-efs-fs-abc", "", Optional.empty()).applyTo(spec, "/mnt/all", false);
|
||||
|
||||
verify(spec).withNamedVolumeSubpath("floci-efs-fs-abc", "team-a", "/mnt/efs", true);
|
||||
verify(spec).withNamedVolume("floci-efs-fs-abc", "/mnt/all", false);
|
||||
}
|
||||
|
||||
private static AccessPointDescription accessPoint(String fileSystemId, String path, CreationInfo creationInfo) {
|
||||
RootDirectory root = new RootDirectory();
|
||||
root.setPath(path);
|
||||
root.setCreationInfo(creationInfo);
|
||||
PosixUser user = new PosixUser();
|
||||
user.setUid(1001L);
|
||||
user.setGid(1001L);
|
||||
user.setSecondaryGids(List.of(2000L));
|
||||
AccessPointDescription accessPoint = new AccessPointDescription();
|
||||
accessPoint.setAccessPointId("fsap-1");
|
||||
accessPoint.setFileSystemId(fileSystemId);
|
||||
accessPoint.setRootDirectory(root);
|
||||
accessPoint.setPosixUser(user);
|
||||
return accessPoint;
|
||||
}
|
||||
|
||||
private static CreationInfo creationInfo(Long uid, Long gid, String permissions) {
|
||||
CreationInfo info = new CreationInfo();
|
||||
info.setOwnerUid(uid);
|
||||
info.setOwnerGid(gid);
|
||||
info.setPermissions(permissions);
|
||||
return info;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.glue;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* AWS leaves unset fields out of Glue responses and reports times in milliseconds.
|
||||
* A null or nanosecond timestamp instead breaks the AWS SDK for JavaScript v3,
|
||||
* which refuses to read either.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class GlueOmitsNullFieldsIntegrationTest {
|
||||
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String DATABASE = "nulls_" + UUID.randomUUID().toString().substring(0, 8);
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static io.restassured.response.ValidatableResponse glue(String action, String body) {
|
||||
return given().contentType(CONTENT_TYPE)
|
||||
.header("X-Amz-Target", "AWSGlue." + action)
|
||||
.body(body)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewTableHasOnlyAMillisecondCreateTime() {
|
||||
glue("CreateDatabase", "{\"DatabaseInput\": {\"Name\": \"" + DATABASE + "\"}}");
|
||||
glue("CreateTable", """
|
||||
{
|
||||
"DatabaseName": "%s",
|
||||
"TableInput": {
|
||||
"Name": "orders",
|
||||
"StorageDescriptor": {"Columns": [{"Name": "id", "Type": "int"}], "Location": "s3://data/orders/"}
|
||||
}
|
||||
}
|
||||
""".formatted(DATABASE));
|
||||
|
||||
String tables = glue("GetTables", "{\"DatabaseName\": \"" + DATABASE + "\"}")
|
||||
.body("TableList[0].Name", equalTo("orders"))
|
||||
.body("TableList[0].CreateTime", notNullValue())
|
||||
.body("TableList[0]", not(hasKey("UpdateTime")))
|
||||
.body("TableList[0]", not(hasKey("LastAccessTime")))
|
||||
.extract().asString();
|
||||
// Milliseconds in their shortest form, as AWS sends them: no trailing zeros.
|
||||
assertTrue(tables.matches("(?s).*\"CreateTime\":\\d+(\\.\\d{0,2}[1-9])?[,}].*"), tables);
|
||||
|
||||
glue("GetDatabase", "{\"Name\": \"" + DATABASE + "\"}")
|
||||
.body("Database", not(hasKey("Description")))
|
||||
.body("Database.CreateTime", notNullValue());
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.glue.model;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class GlueTimestampSerializerTest {
|
||||
|
||||
@Test
|
||||
void writesMillisecondsInTheirShortestForm() {
|
||||
assertEquals("1792964720.273", GlueTimestampSerializer.epochSeconds(Instant.ofEpochSecond(1792964720, 273_456_789)));
|
||||
assertEquals("1792964720.27", GlueTimestampSerializer.epochSeconds(Instant.ofEpochSecond(1792964720, 270_000_000)));
|
||||
assertEquals("1792964720", GlueTimestampSerializer.epochSeconds(Instant.ofEpochSecond(1792964720)));
|
||||
}
|
||||
}
|
||||
@@ -250,7 +250,8 @@ class LambdaImageConfigTest {
|
||||
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
|
||||
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
|
||||
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,
|
||||
mock(io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials.class));
|
||||
mock(io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials.class),
|
||||
mock(io.github.hectorvent.floci.services.efs.EfsMounts.class));
|
||||
|
||||
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
when(runtimeApiServer.getPort()).thenReturn(9000);
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ class ContainerLauncherCodeVolumeReuseTest {
|
||||
mock(ImageResolver.class), mock(RuntimeApiServerFactory.class),
|
||||
mock(DockerHostResolver.class), config, mock(EcrRegistryManager.class),
|
||||
mock(LambdaLayerService.class), mock(LaunchedContainerAwsEnv.class),
|
||||
mock(LambdaExecutionRoleCredentials.class));
|
||||
mock(LambdaExecutionRoleCredentials.class), mock(io.github.hectorvent.floci.services.efs.EfsMounts.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+48
-12
@@ -12,6 +12,9 @@ import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
|
||||
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
|
||||
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFileSystemConfig;
|
||||
import io.github.hectorvent.floci.services.efs.EfsMounts;
|
||||
import io.github.hectorvent.floci.services.efs.model.PosixUser;
|
||||
import io.github.hectorvent.floci.core.common.docker.SubpathVolumeOptions;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer;
|
||||
import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory;
|
||||
@@ -87,6 +90,7 @@ class ContainerLauncherTest {
|
||||
Path tempDir;
|
||||
|
||||
ContainerLauncher launcher;
|
||||
EfsMounts efsMounts = mock(EfsMounts.class);
|
||||
/** Collects remote paths passed to withRemotePath across all copy mocks. */
|
||||
final java.util.List<String> capturedRemotePaths = new java.util.ArrayList<>();
|
||||
|
||||
@@ -134,7 +138,7 @@ class ContainerLauncherTest {
|
||||
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver,
|
||||
runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager,
|
||||
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class), awsEnv,
|
||||
executionRoleCredentials);
|
||||
executionRoleCredentials, efsMounts);
|
||||
|
||||
when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer);
|
||||
when(runtimeApiServer.getPort()).thenReturn(9000);
|
||||
@@ -469,8 +473,15 @@ class ContainerLauncherTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFunction_mountsConfiguredFileSystemVolume() throws Exception {
|
||||
void launchFunction_mountsTheAccessPointFolderAsItsUser() throws Exception {
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("efs-code"));
|
||||
String accessPointArn = "arn:aws:elasticfilesystem:us-east-1:000000000000:access-point/fsap-0123456789abcdef0";
|
||||
PosixUser user = new PosixUser();
|
||||
user.setUid(1001L);
|
||||
user.setGid(1002L);
|
||||
user.setSecondaryGids(List.of(2000L));
|
||||
when(efsMounts.prepareAccessPoint(accessPointArn))
|
||||
.thenReturn(new EfsMounts.Mount("floci-efs-fs-abc", "my-function", Optional.of(user)));
|
||||
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("efs-fn");
|
||||
@@ -478,23 +489,48 @@ class ContainerLauncherTest {
|
||||
fn.setRuntime("nodejs20.x");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setCodeLocalPath(codePath.toString());
|
||||
fn.setFileSystemConfigs(List.of(new LambdaFileSystemConfig(
|
||||
"arn:aws:elasticfilesystem:us-east-1:000000000000:access-point/fsap-0123456789abcdef0",
|
||||
"/mnt/shared")));
|
||||
fn.setFileSystemConfigs(List.of(new LambdaFileSystemConfig(accessPointArn, "/mnt/shared")));
|
||||
|
||||
launcher.launch(fn);
|
||||
|
||||
String expectedVolumeName = "floci-efs-fsap-0123456789abcdef0-"
|
||||
+ "9d6eafd2aec94d4518a004f005725b4b3c673c1506436bb7368cfd5450fc0810";
|
||||
verify(lifecycleManager).ensureSharedVolume(expectedVolumeName,
|
||||
OptionalInt.empty(), OptionalInt.empty(), Optional.empty(), "busybox:stable");
|
||||
Mount mount = captureRealContainerSpec().mounts().stream()
|
||||
ContainerSpec spec = captureRealContainerSpec();
|
||||
Mount mount = spec.mounts().stream()
|
||||
.filter(candidate -> "/mnt/shared".equals(candidate.getTarget()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertEquals(MountType.VOLUME, mount.getType());
|
||||
assertEquals(expectedVolumeName, mount.getSource());
|
||||
assertEquals("floci-efs-fs-abc", mount.getSource());
|
||||
assertEquals("my-function", ((SubpathVolumeOptions) mount.getVolumeOptions()).getSubpath());
|
||||
assertTrue(!Boolean.TRUE.equals(mount.getReadOnly()));
|
||||
assertEquals("1001:1002", spec.user());
|
||||
assertEquals(List.of("2000"), spec.groupAdd());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchFunction_withoutAnAccessPointUserKeepsTheImageUser() throws Exception {
|
||||
Path codePath = Files.createDirectory(tempDir.resolve("efs-root-code"));
|
||||
String accessPointArn = "arn:aws:elasticfilesystem:us-east-1:000000000000:access-point/fsap-1";
|
||||
when(efsMounts.prepareAccessPoint(accessPointArn))
|
||||
.thenReturn(new EfsMounts.Mount("floci-efs-fs-abc", "", Optional.empty()));
|
||||
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName("efs-root-fn");
|
||||
fn.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:efs-root-fn");
|
||||
fn.setRuntime("nodejs20.x");
|
||||
fn.setHandler("index.handler");
|
||||
fn.setCodeLocalPath(codePath.toString());
|
||||
fn.setFileSystemConfigs(List.of(new LambdaFileSystemConfig(accessPointArn, "/mnt/efs")));
|
||||
|
||||
launcher.launch(fn);
|
||||
|
||||
ContainerSpec spec = captureRealContainerSpec();
|
||||
Mount mount = spec.mounts().stream()
|
||||
.filter(candidate -> "/mnt/efs".equals(candidate.getTarget()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
assertEquals("floci-efs-fs-abc", mount.getSource());
|
||||
assertEquals(null, mount.getVolumeOptions());
|
||||
assertEquals(null, spec.user());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1631,7 +1667,7 @@ class ContainerLauncherTest {
|
||||
ecrRegistryManager,
|
||||
mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class),
|
||||
new LaunchedContainerAwsEnv(reachableEndpoint),
|
||||
executionRoleCredentials);
|
||||
executionRoleCredentials, efsMounts);
|
||||
|
||||
stubExtensionDiscovery("otel-collector");
|
||||
// Feed a real stdout frame through whatever callback the launcher hands to execStartCmd.
|
||||
|
||||
-27
@@ -100,33 +100,6 @@ class ContainerLauncherVolumeNamingTest {
|
||||
"a later lastModified must produce a different volume name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void efsVolumeNameIncludesStableHashOfCompleteArn() {
|
||||
String arn = "arn:aws:elasticfilesystem:us-east-1:000000000000:"
|
||||
+ "access-point/fsap-0123456789abcdef0";
|
||||
|
||||
String volumeName = ContainerLauncher.efsVolumeName(arn);
|
||||
|
||||
assertEquals("floci-efs-fsap-0123456789abcdef0-"
|
||||
+ "9d6eafd2aec94d4518a004f005725b4b3c673c1506436bb7368cfd5450fc0810",
|
||||
volumeName);
|
||||
assertEquals(volumeName, ContainerLauncher.efsVolumeName(arn));
|
||||
assertTrue(DOCKER_VOLUME_NAME.matcher(volumeName).matches(),
|
||||
"EFS volume name must be Docker-safe, was: " + volumeName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void efsVolumeNameDistinguishesSameResourceIdAcrossArns() {
|
||||
String eastArn = "arn:aws:elasticfilesystem:us-east-1:000000000000:"
|
||||
+ "access-point/fsap-0123456789abcdef0";
|
||||
String westArn = "arn:aws:elasticfilesystem:us-west-2:111111111111:"
|
||||
+ "access-point/fsap-0123456789abcdef0";
|
||||
|
||||
assertNotEquals(ContainerLauncher.efsVolumeName(eastArn),
|
||||
ContainerLauncher.efsVolumeName(westArn),
|
||||
"the complete ARN must participate in volume identity");
|
||||
}
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
|
||||
@@ -287,7 +287,8 @@ class SmtpRelayServerTest {
|
||||
String command = line.toUpperCase(Locale.ROOT);
|
||||
if (command.startsWith("EHLO")) {
|
||||
reply(out, "250-floci-stub");
|
||||
reply(out, "250 AUTH PLAIN");
|
||||
// Gmail also offers OAuth sign-in, which a password must never be sent as.
|
||||
reply(out, "250 AUTH PLAIN XOAUTH2 OAUTHBEARER");
|
||||
} else if (command.startsWith("HELO")) {
|
||||
reply(out, "250 floci-stub");
|
||||
} else if (command.startsWith("AUTH")) {
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.path.xml.element.Node;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* DeleteStack answers before the stack is gone. The deletion runs on an executor, so a test
|
||||
* that looks at the stack's resources right after the answer races it.
|
||||
*/
|
||||
public final class CfnStackWaits {
|
||||
|
||||
private CfnStackWaits() {
|
||||
}
|
||||
|
||||
/** What DescribeStacks reported: the status and, when present, the StackStatusReason. */
|
||||
public record StackState(String status, String reason) {
|
||||
}
|
||||
|
||||
private static final Set<String> TERMINAL = Set.of(
|
||||
"CREATE_COMPLETE", "CREATE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED",
|
||||
"UPDATE_COMPLETE", "UPDATE_FAILED", "UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED",
|
||||
"DELETE_COMPLETE", "DELETE_FAILED");
|
||||
|
||||
private static final Set<String> OPERATION_STARTS = Set.of("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS");
|
||||
|
||||
/**
|
||||
* Waits until DescribeStacks reports a terminal status for a create or update and returns
|
||||
* it, so the caller decides what counts as success. A DescribeStacks that is not 200 (the
|
||||
* stack does not exist) fails at once with the error body rather than polling the clock out;
|
||||
* ten seconds without a terminal status fails too.
|
||||
*/
|
||||
public static StackState awaitTerminal(String stackName) {
|
||||
return awaitTerminal(stackName, null);
|
||||
}
|
||||
|
||||
public static StackState awaitTerminal(String stackName, String authorization) {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
StackState last = new StackState(null, "");
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName);
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
if (response.statusCode() != 200) {
|
||||
fail("DescribeStacks " + stackName + " answered " + response.statusCode() + ": " + response.asString());
|
||||
}
|
||||
XmlPath xml = response.xmlPath();
|
||||
String status = xml.getString("**.find { it.name() == 'StackStatus' }");
|
||||
String reason = xml.getString("**.find { it.name() == 'StackStatusReason' }");
|
||||
last = new StackState(status == null || status.isEmpty() ? null : status, reason == null ? "" : reason);
|
||||
if (last.status() != null && TERMINAL.contains(last.status())) {
|
||||
return last;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("Interrupted while waiting for stack " + stackName, e);
|
||||
}
|
||||
}
|
||||
fail("Stack " + stackName + " reached no terminal status within ten seconds, last: " + last);
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until DescribeStacks reports {@code expectedStatus} and returns that state. Any other
|
||||
* terminal status fails at once with its reason, as do a DescribeStacks that is not 200 and ten
|
||||
* seconds without the expected status.
|
||||
*/
|
||||
public static StackState awaitStatus(String stackName, String expectedStatus) {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
StackState last = new StackState(null, "");
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response response = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/");
|
||||
if (response.statusCode() != 200) {
|
||||
fail("DescribeStacks " + stackName + " answered " + response.statusCode() + ": " + response.asString());
|
||||
}
|
||||
XmlPath xml = response.xmlPath();
|
||||
String status = xml.getString("**.find { it.name() == 'StackStatus' }");
|
||||
String reason = xml.getString("**.find { it.name() == 'StackStatusReason' }");
|
||||
last = new StackState(status == null || status.isEmpty() ? null : status, reason == null ? "" : reason);
|
||||
if (expectedStatus.equals(last.status())) {
|
||||
return last;
|
||||
}
|
||||
if (last.status() != null && TERMINAL.contains(last.status())) {
|
||||
fail("Stack " + stackName + " reached " + last.status() + " instead of " + expectedStatus
|
||||
+ ": " + last.reason());
|
||||
}
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("Interrupted while waiting for stack " + stackName, e);
|
||||
}
|
||||
}
|
||||
fail("Stack " + stackName + " did not reach " + expectedStatus + " within ten seconds, last: " + last);
|
||||
return last;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason on the first resource event that failed a create or update in the stack's latest
|
||||
* operation, the one its last stack-level CREATE_IN_PROGRESS or UPDATE_IN_PROGRESS began. The
|
||||
* stack's own reason only names the failed resource, as on AWS, so the failure's message is read
|
||||
* here. Fails when DescribeStackEvents is not 200 or no resource failed in that operation.
|
||||
*/
|
||||
public static String failedResourceReason(String stackName) {
|
||||
return failedResourceReason(stackName, null);
|
||||
}
|
||||
|
||||
public static String failedResourceReason(String stackName, String authorization) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stackName);
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
if (response.statusCode() != 200) {
|
||||
fail("DescribeStackEvents " + stackName + " answered " + response.statusCode() + ": " + response.asString());
|
||||
}
|
||||
List<Node> newestFirst = response.xmlPath().getList("**.findAll { it.name() == 'member' }", Node.class);
|
||||
String reason = null;
|
||||
for (Node event : newestFirst) {
|
||||
String status = text(event, "ResourceStatus");
|
||||
if (text(event, "StackName").equals(text(event, "LogicalResourceId"))
|
||||
&& text(event, "StackId").equals(text(event, "PhysicalResourceId"))) {
|
||||
if (OPERATION_STARTS.contains(status)) {
|
||||
break;
|
||||
}
|
||||
} else if ("CREATE_FAILED".equals(status) || "UPDATE_FAILED".equals(status)) {
|
||||
reason = text(event, "ResourceStatusReason");
|
||||
}
|
||||
}
|
||||
if (reason == null) {
|
||||
fail("Stack " + stackName + " has no failed resource event in its latest operation: " + response.asString());
|
||||
}
|
||||
return reason;
|
||||
}
|
||||
|
||||
private static String text(Node event, String name) {
|
||||
Node child = event.getNode(name);
|
||||
return child == null ? "" : child.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until DescribeStacks answers 400, which is how a missing stack is reported. Fails on
|
||||
* DELETE_FAILED or after ten seconds.
|
||||
*/
|
||||
public static void awaitStackDeleted(String stackName) {
|
||||
awaitStackDeleted(stackName, null);
|
||||
}
|
||||
|
||||
public static void awaitStackDeleted(String stackName, String authorization) {
|
||||
long deadline = System.currentTimeMillis() + 10_000;
|
||||
String body = "";
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName);
|
||||
if (authorization != null) {
|
||||
request.header("Authorization", authorization);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
body = response.asString();
|
||||
assertThat(body, not(containsString("<StackStatus>DELETE_FAILED</StackStatus>")));
|
||||
if (response.statusCode() == 400) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError("Interrupted while waiting for stack " + stackName + " to be deleted", e);
|
||||
}
|
||||
}
|
||||
fail("Stack " + stackName + " was not deleted within ten seconds: " + body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import org.junit.jupiter.api.extension.AfterEachCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
|
||||
/**
|
||||
* Deletes what a test created, in reverse order, after each test. The {@code @QuarkusTest}
|
||||
* emulator is shared by every test class, so a resource left behind outlives the class that made
|
||||
* it: one under {@code cn-north-1} shows up in every later cross-region listing (ResourceExplorer
|
||||
* scans all resources), and an IAM user or an S3 bucket shows up in the next class to list either
|
||||
* one unscoped. A test that leaves such a resource registers each create here.
|
||||
*
|
||||
* <pre>{@code
|
||||
* @RegisterExtension
|
||||
* final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
* ...
|
||||
* createTable(region, name);
|
||||
* cleanup.register(() -> deleteTable(region, name));
|
||||
* }</pre>
|
||||
*
|
||||
* A failing cleanup never fails the test: it is reported on stderr so the leak is visible and
|
||||
* the assertion that actually failed stays the headline.
|
||||
*/
|
||||
public final class PartitionCleanup implements AfterEachCallback {
|
||||
|
||||
private final Deque<Runnable> actions = new ArrayDeque<>();
|
||||
|
||||
public void register(Runnable action) {
|
||||
actions.push(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterEach(ExtensionContext context) {
|
||||
while (!actions.isEmpty()) {
|
||||
Runnable action = actions.pop();
|
||||
try {
|
||||
action.run();
|
||||
} catch (RuntimeException | AssertionError e) {
|
||||
System.err.println("PartitionCleanup: cleanup step failed after "
|
||||
+ context.getDisplayName() + ": " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.locks.LockSupport;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/** Waiting for a thread to reach a lock, for tests that force two requests to overlap. */
|
||||
public final class ThreadStates {
|
||||
|
||||
/** Every state a thread is in once it has stopped running: parked in any way, or ended. */
|
||||
public static final Set<Thread.State> PARKED_OR_DONE = Collections.unmodifiableSet(EnumSet.of(
|
||||
Thread.State.BLOCKED, Thread.State.WAITING, Thread.State.TIMED_WAITING, Thread.State.TERMINATED));
|
||||
|
||||
private ThreadStates() {}
|
||||
|
||||
/**
|
||||
* Returns once {@code thread} is blocked entering a monitor or parked on a lock, or {@code task} has
|
||||
* finished, whichever comes first. Code that serializes correctly leaves the second request blocked
|
||||
* behind the first; code that does not lets it run to the end, which the caller's assertions
|
||||
* then catch. Polls every 5 ms and gives up after five seconds rather than hang a broken test.
|
||||
*/
|
||||
public static void awaitBlockedOrDone(AtomicReference<Thread> thread, Future<?> task)
|
||||
throws InterruptedException {
|
||||
awaitBlockedOrDone(thread::get, task::isDone, 5);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns once {@code thread} is blocked entering a monitor, parked on a lock, or is no longer alive.
|
||||
* Same wait as the {@link Future} overload, for a test that owns the {@link Thread} directly; gives up
|
||||
* after ten seconds and fails, since a thread still running unblocked by then is not overlapping the
|
||||
* way the test needs.
|
||||
*/
|
||||
public static void awaitBlockedOrDone(Thread thread) throws InterruptedException {
|
||||
assertTrue(awaitBlockedOrDone(() -> thread, () -> !thread.isAlive(), 10),
|
||||
"worker blocked or finished before timeout");
|
||||
}
|
||||
|
||||
private static boolean awaitBlockedOrDone(Supplier<Thread> thread, BooleanSupplier done, long timeoutSeconds)
|
||||
throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
|
||||
while (System.nanoTime() < deadline && !done.getAsBoolean()) {
|
||||
if (isBlocked(thread.get())) {
|
||||
return true;
|
||||
}
|
||||
Thread.sleep(5);
|
||||
}
|
||||
return done.getAsBoolean() || isBlocked(thread.get());
|
||||
}
|
||||
|
||||
private static boolean isBlocked(Thread thread) {
|
||||
if (thread == null) {
|
||||
return false;
|
||||
}
|
||||
Thread.State state = thread.getState();
|
||||
return state == Thread.State.BLOCKED || state == Thread.State.WAITING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until {@code thread} is parked in any way (blocked on a monitor, waiting or timed
|
||||
* waiting) or has ended, and returns the state it reached. Fails after ten seconds.
|
||||
*/
|
||||
public static Thread.State awaitParkedOrDone(Thread thread) {
|
||||
return awaitState(thread, PARKED_OR_DONE, Duration.ofSeconds(10), "the thread");
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until {@code thread} is in one of {@code states} and returns the one it reached, checking
|
||||
* every millisecond. Fails naming {@code what} and the state it was left in once {@code timeout}
|
||||
* passes, so a thread that never gets there fails the test instead of hanging it.
|
||||
*/
|
||||
public static Thread.State awaitState(Thread thread, Set<Thread.State> states, Duration timeout, String what) {
|
||||
long deadline = System.nanoTime() + timeout.toNanos();
|
||||
Thread.State state = thread.getState();
|
||||
while (!states.contains(state)) {
|
||||
if (System.nanoTime() - deadline > 0) {
|
||||
fail(what + " never reached " + states + ", it was " + state);
|
||||
}
|
||||
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
|
||||
state = thread.getState();
|
||||
}
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,7 @@ floci:
|
||||
enabled: true
|
||||
efs:
|
||||
enabled: true
|
||||
nfs-servers: false
|
||||
organizations:
|
||||
enabled: true
|
||||
rum:
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user