Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(kinesisanalyticsv2): run Managed Flink jobs in Docker (#2135)

Luke Duttonbdd4261b111b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4328441..b2366bee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys.
+- **Managed Service for Apache Flink — job execution** — with Docker available, starting a `FLINK-1_19` or `FLINK-1_20` application runs its jar from MiniStack S3 in the official Apache Flink image (1.19.1 or 1.20.5, Java 11) with a JobManager and a TaskManager, its runtime properties at `/etc/flink/application_properties.json`, its configured parallelism and checkpointing, and its AWS calls pointed at MiniStack in the application's account. Snapshots are Flink savepoints, restores resume the job's state, and a job that fails to start returns the application to `READY`. Jars in `/opt/ministack/flink-lib` (for example a mounted `aws-kinesisanalytics-runtime`) are added to every cluster. Without Docker the control plane behaves as before.
- **Managed Service for Apache Flink — control plane** — `kinesisanalyticsv2` applications for the `FLINK-*` runtimes: create, describe, update and delete, start and stop with the model's status transitions, snapshots, CloudWatch logging options and tags, per account and region. Updates bump `ApplicationVersionId` and the `ConditionalToken`, and a stale one returns `ConcurrentModificationException`. CloudFormation creates, updates and deletes `AWS::KinesisAnalyticsV2::Application`, `AWS::KinesisAnalyticsV2::ApplicationCloudWatchLoggingOption` and `AWS::Logs::LogStream`, so a CDK Flink stack deploys. The Flink job itself does not run (control plane only).
## [1.5.28] — 2026-10-16
diff --git a/README.md b/README.md
index e5a93d07..ab07016c 100644
--- a/README.md
+++ b/README.md
@@ -450,7 +450,7 @@ subnet = ec2.create_subnet(
| **Cloud Control API** | CreateResource, GetResource, UpdateResource, DeleteResource, ListResources, ListResourceRequests, GetResourceRequestStatus, CancelResourceRequest | Generic resource control plane behind Terraform's `awscc` provider and CDK L1 constructs; AWS `ProgressEvent` and `ResourceDescription` shapes (`Properties` as a JSON string); resource-request status + cancel |
| **Cost & Usage Reports** | DeleteReportDefinition, DescribeReportDefinitions, ListTagsForResource, ModifyReportDefinition, PutReportDefinition, TagResource, UntagResource | 7 of 7 spec ops |
| **AWS Budgets** | CreateBudget, DescribeBudget, DescribeBudgets, UpdateBudget, DeleteBudget, CreateNotification, UpdateNotification, DeleteNotification, DescribeNotificationsForBudget, CreateSubscriber, UpdateSubscriber, DeleteSubscriber, DescribeSubscribersForNotification, TagResource, UntagResource, ListTagsForResource | Global (account-scoped) service; `CreateBudget` accepts inline `NotificationsWithSubscribers` and `ResourceTags`; enforces the 10-notification/budget and 11-subscriber/notification quotas (`CreationLimitExceededException`); deleting a notification's last subscriber deletes the notification; a budget's `CalculatedSpend` always reports zero (no billing engine); verified against Terraform's `aws_budgets_budget` resource |
-| **Managed Service for Apache Flink** | CreateApplication, DescribeApplication, UpdateApplication, DeleteApplication, StartApplication, StopApplication, CreateApplicationSnapshot, ListApplicationSnapshots, DescribeApplicationSnapshot, DeleteApplicationSnapshot, AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption, TagResource, UntagResource, ListTagsForResource | `kinesisanalyticsv2` control plane for Apache Flink applications (`FLINK-*` runtimes; SQL and Studio applications are not implemented): application versions and `ConditionalToken` with `ConcurrentModificationException` on a stale one, the model's status transitions on start, stop and update (without a running job, a transitional status settles on the next read), snapshots (a graceful stop takes one when snapshots are enabled, `Force` does not), CloudWatch logging options and tags. The Flink job itself does not run (control plane only), and an application restored after a restart comes back `READY` |
+| **Managed Service for Apache Flink** | CreateApplication, DescribeApplication, UpdateApplication, DeleteApplication, StartApplication, StopApplication, CreateApplicationSnapshot, ListApplicationSnapshots, DescribeApplicationSnapshot, DeleteApplicationSnapshot, AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption, TagResource, UntagResource, ListTagsForResource | `kinesisanalyticsv2` control plane for Apache Flink applications (`FLINK-*` runtimes; SQL and Studio applications are not implemented): application versions and `ConditionalToken` with `ConcurrentModificationException` on a stale one, the model's status transitions on start, stop and update (without a running job, a transitional status settles on the next read), snapshots (a graceful stop takes one when snapshots are enabled, `Force` does not), CloudWatch logging options and tags. With Docker, `FLINK-1_19` and `FLINK-1_20` jobs run in the official Flink image (see [Managed Flink with Real Jobs](#managed-flink-with-real-jobs)); other runtimes and Docker-less setups stay control plane only. An application restored after a restart comes back `READY` |
| **Inspector2** | Enable, Disable, ListFindings, BatchGetFindingDetails, ListCoverage, ListCoverageStatistics, ListFindingAggregations, SearchVulnerabilities, TagResource, UntagResource, ListTagsForResource, CreateFilter, ListFilters, DeleteFilter | 14 operations; deterministic stub vulnerability findings for ECR images, Lambda functions, and EC2 instances; filtering, sorting, pagination |
| **AmazonMQ** | CreateBroker, ListBrokers, DescribeBrokers, DeleteBrokers, UpdateBroker, RebootBroker, DescribeBrokerEngineTypes, DescribeBrokerInstanceOptions, CreateTags, ListTags, DeleteTags, CreateUser, DeleteUser, ListUsers, UpdateUser, DescribeUser | 16 of 24 spec ops; No real container support |
| **Amazon Location (trackers)** | CreateTracker, DescribeTracker, UpdateTracker, ListTrackers, DeleteTracker, BatchUpdateDevicePosition, GetDevicePosition, BatchGetDevicePosition, GetDevicePositionHistory | Tracker control plane + in-memory device-position store; signs with credential scope `geo` (the client is named `location`); ISO 8601 `SampleTime`/`ReceivedTime`, `Position` as the modeled `[lon, lat]` double pair, out-of-range coordinates as per-entry `Errors`; `GetDevicePositionHistory` ascending, defaulting to the last 24 h; `ListTrackers` and the history page at `MaxResults` 1..100 with `NextToken`; every sample is stored (no position filtering, no 30-day expiry), newest 100 per device; `KmsKeyId`/`PositionFiltering`/`EventBridgeEnabled`/`Tags` stored without effect; no consumers, geofences, maps, places or routes; CFN `AWS::Location::Tracker` supported |
@@ -877,6 +877,12 @@ come from `repositoryCredentials.credentialsParameter` (a Secrets Manager secret
---
+## Managed Flink with Real Jobs
+
+When Docker is available, `StartApplication` for a `FLINK-1_19` or `FLINK-1_20` application starts a JobManager and a TaskManager from the official Apache Flink image (1.19.1 or 1.20.5, Java 11, as Managed Flink runs them) and submits the application's jar from MiniStack S3, with the runtime properties at `/etc/flink/application_properties.json` and the job's AWS calls pointed at MiniStack. Snapshots are Flink savepoints, and a restore resumes the job's state. Managed Flink puts `com.amazonaws:aws-kinesisanalytics-runtime` on the cluster classpath, and AWS documents building jobs with it in `provided` scope, so MiniStack copies every jar in `/opt/ministack/flink-lib` into the Flink lib directory of each cluster. Mount a directory holding `aws-kinesisanalytics-runtime` (1.2.0, from Maven Central) there, for example `-v ./flink-lib:/opt/ministack/flink-lib`; without it, jobs must bundle the library themselves. Any other jar placed there, such as a connector, is provided to every job the same way.
+
+---
+
## Configuration
| Variable | Default | Description |
diff --git a/ministack/services/kinesisanalyticsv2.py b/ministack/services/kinesisanalyticsv2.py
index 7302b0b2..d27387f8 100644
--- a/ministack/services/kinesisanalyticsv2.py
+++ b/ministack/services/kinesisanalyticsv2.py
@@ -17,18 +17,22 @@ Supports the operations a CDK deploy and a lifecycle script use:
AddApplicationCloudWatchLoggingOption, DeleteApplicationCloudWatchLoggingOption,
TagResource, UntagResource, ListTagsForResource.
-This is the control plane: applications move through the model's statuses
-and keep snapshot records, but no Flink job runs.
+Running the job is the job of the optional data plane module
+(``kinesisanalyticsv2_flink``), which starts Flink containers when Docker is
+available. Without it, applications move through the same statuses and keep
+snapshot records, but no job runs.
Records keep the request shape of ApplicationConfiguration; DescribeApplication
renders the Description shape from it. Stores are per account and region.
"""
import base64
+import contextvars
import copy
import hashlib
import json
import logging
+import threading
import time
from ministack.core.responses import (
@@ -42,6 +46,11 @@ from ministack.core.responses import (
logger = logging.getLogger("kinesisanalyticsv2")
+try: # The Docker-backed data plane is optional.
+ from ministack.services import kinesisanalyticsv2_flink as _dataplane
+except ImportError: # pragma: no cover - present once the data plane lands
+ _dataplane = None
+
_applications = AccountRegionScopedDict() # ApplicationName -> record
_snapshots = AccountRegionScopedDict() # ApplicationName -> {SnapshotName -> snapshot}
_tags = AccountRegionScopedDict() # ApplicationARN -> {Key: Value}
@@ -49,7 +58,7 @@ _tags = AccountRegionScopedDict() # ApplicationARN -> {Key: Value}
_SUPPORTED_RUNTIME_PREFIX = "FLINK-"
# Statuses in which the application is busy with an operation.
_TRANSITIONAL = ("STARTING", "STOPPING", "FORCE_STOPPING", "UPDATING", "DELETING")
-# What a transitional status settles into on the next read.
+# What a transitional status settles into when no data plane drives it.
_SETTLES_TO = {
"STARTING": "RUNNING",
"UPDATING": "RUNNING",
@@ -83,13 +92,19 @@ def load_persisted_state(data):
for store, key in ((_applications, "applications"), (_snapshots, "snapshots"), (_tags, "tags")):
store.clear()
store.update(data.get(key) or {})
- # No Flink job survives a restart, so a running or busy application
+ # No Flink cluster survives a restart, so a running or busy application
# comes back READY and can be started again.
for record in _applications.all_values():
record["ApplicationStatus"] = "READY"
+ record["_driven"] = False
def reset():
+ if _dataplane is not None:
+ try:
+ _dataplane.reset()
+ except Exception: # never let cleanup break a reset
+ logger.exception("kinesisanalyticsv2 data plane reset failed")
_applications.clear()
_snapshots.clear()
_tags.clear()
@@ -137,8 +152,10 @@ def _check_concurrency(record, data):
def _settle(record):
- """No Flink job runs, so a transitional status settles on the next read
- and a script polling DescribeApplication sees each status once."""
+ """Without a data plane a transitional status settles on the next read,
+ so a script polling DescribeApplication sees each status once."""
+ if record.get("_driven"):
+ return
target = _SETTLES_TO.get(record["ApplicationStatus"])
if target:
record["ApplicationStatus"] = target
@@ -255,7 +272,7 @@ def _refresh_code_stats(record):
def application_detail(record):
- """The ApplicationDetail shape for a stored record."""
+ """The ApplicationDetail shape for a stored record (also the data plane's view)."""
detail = {k: copy.deepcopy(v) for k, v in record.items() if not k.startswith("_")}
detail["ApplicationConfigurationDescription"] = _configuration_description(record)
detail["CloudWatchLoggingOptionDescriptions"] = copy.deepcopy(record.get("_LoggingOptions", []))
@@ -263,6 +280,13 @@ def application_detail(record):
return detail
+def _dataplane_view(record):
+ view = application_detail(record)
+ view["AccountId"] = get_account_id()
+ view["Region"] = get_region()
+ return view
+
+
# ---------------------------------------------------------------------------
# Applications
# ---------------------------------------------------------------------------
@@ -420,6 +444,8 @@ def delete_application(data, check_timestamp=True):
if record["ApplicationStatus"] in _TRANSITIONAL:
return _error("ResourceInUseException",
f"Application {name} is in {record['ApplicationStatus']} status and cannot be deleted.")
+ if _dataplane is not None and record.get("_driven"):
+ _in_background(_dataplane_call, "delete", _dataplane_view(record))
del _applications[name]
_snapshots.pop(name, None)
_tags.pop(record["ApplicationARN"], None)
@@ -431,6 +457,61 @@ def delete_application(data, check_timestamp=True):
# Start / stop
# ---------------------------------------------------------------------------
+def _dataplane_call(method, *args):
+ try:
+ return getattr(_dataplane, method)(*args)
+ except Exception:
+ logger.exception("kinesisanalyticsv2 data plane %s failed", method)
+ return None
+
+
+def _in_background(fn, *args):
+ """Run slow data plane work (savepoints, container removal) off the
+ request path, in the caller's account and region context, so other
+ requests (including the job's own writes to MiniStack) are not blocked."""
+ ctx = contextvars.copy_context()
+ threading.Thread(target=ctx.run, args=(fn, *args), daemon=True).start()
+
+
+def _status_callback(record):
+ """on_status for the data plane: RUNNING once the job runs, or READY with
+ a message when the cluster or job fails (ApplicationStatus has no failed
+ value). Called from a background thread, so it writes to the record object
+ and never looks the application up by tenant."""
+ def on_status(status, message=None):
+ if status == "RUNNING":
+ record["ApplicationStatus"] = "RUNNING"
+ else:
+ record["ApplicationStatus"] = "READY"
+ record["_driven"] = False
+ logger.warning("Flink application %s failed to start: %s", record["ApplicationName"], message)
+ return on_status
+
+
+def _restore_path(record, restore):
+ """Savepoint path for the restore the run configuration asks for."""
+ restore_type = restore.get("ApplicationRestoreType", "RESTORE_FROM_LATEST_SNAPSHOT")
+ snapshots = _snapshots.get(record["ApplicationName"]) or {}
+ if restore_type == "SKIP_RESTORE_FROM_SNAPSHOT":
+ return None
+ if restore_type == "RESTORE_FROM_CUSTOM_SNAPSHOT":
+ snap = snapshots.get(restore.get("SnapshotName", ""))
+ return snap.get("_SavepointPath") if snap else None
+ ready = [s for s in snapshots.values() if s["SnapshotStatus"] == "READY"]
+ return max(ready, key=lambda s: s["SnapshotCreationTimestamp"]).get("_SavepointPath") if ready else None
+
+
+def _runs_jobs(record):
+ """Docker is available and the data plane has an image for the runtime."""
+ return (_dataplane is not None and _dataplane.available()
+ and _dataplane.supports(record["RuntimeEnvironment"]))
+
+
+def _launch(record, savepoint):
+ record["_driven"] = True
+ _dataplane_call("start", _dataplane_view(record), savepoint, _status_callback(record))
+
+
def _snapshots_enabled(record):
return bool((record["_Configuration"].get("ApplicationSnapshotConfiguration") or {}).get("SnapshotsEnabled"))
@@ -443,8 +524,26 @@ def _restart_for_update(record, previous_version):
snapshot_name = None
if _snapshots_enabled(record):
snapshot_name = f"UPDATEAPPLICATION-{record['ApplicationName']}-{int(time.time() * 1000)}"
+ driven = record.get("_driven") and _runs_jobs(record)
if snapshot_name:
- _add_snapshot(record, snapshot_name)["ApplicationVersionId"] = previous_version
+ snap = _add_snapshot(record, snapshot_name, None, status="CREATING" if driven else "READY")
+ snap["ApplicationVersionId"] = previous_version
+ if driven:
+ _restart_in_place(record, snapshot_name)
+
+
+def _restart_in_place(record, snapshot_name=None):
+ """A running application restarts on its new configuration from a savepoint."""
+ record["_driven"] = True
+ view = _dataplane_view(record)
+
+ def restart():
+ savepoint = _dataplane_call("stop", view, False, True)
+ if snapshot_name:
+ _finish_snapshot(record["ApplicationName"], snapshot_name, savepoint)
+ _launch(record, savepoint)
+
+ _in_background(restart)
def _start_application(data):
@@ -463,9 +562,17 @@ def _start_application(data):
return _error("InvalidArgumentException",
f"The snapshot name {restore.get('SnapshotName')} provided for restore configuration "
"does not exist.")
+ if snap["SnapshotStatus"] != "READY":
+ return _error("InvalidArgumentException",
+ f"Snapshot {restore.get('SnapshotName')} is {snap['SnapshotStatus']} and cannot be restored.")
record["_RunConfiguration"] = run
record["ApplicationStatus"] = "STARTING"
- logger.info("StartApplication %s: control plane only, so the Flink job does not run", name)
+ if _runs_jobs(record):
+ _launch(record, _restore_path(record, restore))
+ else:
+ record["_driven"] = False
+ logger.info("StartApplication %s: no Docker or no Flink image for %s, so the Flink job "
+ "does not run (control plane only)", name, record["RuntimeEnvironment"])
return json_response({"OperationId": _new_token()})
@@ -482,8 +589,21 @@ def _stop_application(data):
record["ApplicationStatus"] = "FORCE_STOPPING" if force else "STOPPING"
# Managed Flink takes a snapshot on a graceful stop when snapshots are enabled.
snapshot_name = f"STOP-{name}-{int(time.time() * 1000)}" if take_snapshot else None
- if snapshot_name:
- _add_snapshot(record, snapshot_name)
+ if record.get("_driven"):
+ view = _dataplane_view(record)
+ if snapshot_name:
+ _add_snapshot(record, snapshot_name, None, status="CREATING")
+
+ def stop():
+ savepoint = _dataplane_call("stop", view, force, take_snapshot)
+ if snapshot_name:
+ _finish_snapshot(record["ApplicationName"], snapshot_name, savepoint)
+ record["ApplicationStatus"] = "READY"
+ record["_driven"] = False
+
+ _in_background(stop)
+ elif snapshot_name:
+ _add_snapshot(record, snapshot_name, None)
return json_response({"OperationId": _new_token()})
@@ -491,19 +611,35 @@ def _stop_application(data):
# Snapshots
# ---------------------------------------------------------------------------
-def _add_snapshot(record, snapshot_name):
+def _add_snapshot(record, snapshot_name, savepoint_path, status="READY"):
snap = {
"SnapshotName": snapshot_name,
- "SnapshotStatus": "READY",
+ "SnapshotStatus": status,
"ApplicationVersionId": record["ApplicationVersionId"],
"SnapshotCreationTimestamp": time.time(),
"RuntimeEnvironment": record["RuntimeEnvironment"],
"ApplicationEncryptionConfigurationDescription": _encryption_description(record),
}
+ if savepoint_path:
+ snap["_SavepointPath"] = savepoint_path
_snapshots.setdefault(record["ApplicationName"], {})[snapshot_name] = snap
return snap
+def _finish_snapshot(app_name, snapshot_name, savepoint_path):
+ """A savepoint the data plane took makes the snapshot READY; none means it
+ failed, so a later restore cannot silently start from an empty state."""
+ snap = (_snapshots.get(app_name) or {}).get(snapshot_name)
+ if snap is None:
+ return
+ if savepoint_path:
+ snap["_SavepointPath"] = savepoint_path
+ snap["SnapshotStatus"] = "READY"
+ else:
+ snap["SnapshotStatus"] = "FAILED"
+ logger.warning("Flink application %s: snapshot %s failed", app_name, snapshot_name)
+
+
def _snapshot_view(snap):
return {k: v for k, v in snap.items() if not k.startswith("_")}
@@ -522,8 +658,14 @@ def _create_application_snapshot(data):
if snapshot_name in (_snapshots.get(name) or {}):
return _error("ResourceInUseException",
f"Provided Snapshot name {snapshot_name} already exists for application {name}")
- # No job runs, so the snapshot is a record without saved state.
- _add_snapshot(record, snapshot_name)
+ if record.get("_driven"):
+ view = _dataplane_view(record)
+ _add_snapshot(record, snapshot_name, None, status="CREATING")
+ _in_background(lambda: _finish_snapshot(
+ name, snapshot_name, _dataplane_call("snapshot", view, snapshot_name)))
+ else:
+ # No job runs, so the snapshot is a record without saved state.
+ _add_snapshot(record, snapshot_name, None)
return json_response({})
diff --git a/ministack/services/kinesisanalyticsv2_flink.py b/ministack/services/kinesisanalyticsv2_flink.py
new file mode 100644
index 00000000..d90b8d27
--- /dev/null
+++ b/ministack/services/kinesisanalyticsv2_flink.py
@@ -0,0 +1,747 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
+"""
+Managed Service for Apache Flink data plane: Docker-backed job execution.
+
+The control plane (``kinesisanalyticsv2``) owns application records and status;
+this module owns the containers. When Docker is available, starting an
+application launches a JobManager and a TaskManager from the official Apache
+Flink image for the application's runtime, fetches the application jar from
+MiniStack S3 and submits it through the Flink REST API. Stop, snapshot and
+restore map to Flink savepoints.
+
+Interface used by the control plane (all synchronous; none raise):
+
+- ``available()``: Docker is reachable.
+- ``supports(runtime)``: this data plane can run jobs for the runtime
+ (``FLINK-1_19`` and ``FLINK-1_20``); other runtimes stay control plane only.
+- ``start(app, savepoint_path, on_status)``: launch the cluster and submit the
+ job in a background thread; ``on_status("RUNNING")`` or
+ ``on_status("FAILED", message)`` reports the outcome.
+- ``snapshot(app, snapshot_name)``: take a savepoint; returns its path, or
+ ``None`` if it failed.
+- ``stop(app, force, take_snapshot)``: stop the job and remove the containers;
+ returns the savepoint path when one was taken.
+- ``delete(app)``: remove containers, network and savepoint volume.
+- ``reset()``: remove everything this MiniStack instance created.
+
+``app`` is the stored record in the DescribeApplication shape plus
+``AccountId`` and ``Region``.
+
+Savepoints live in a per-application Docker volume mounted at the same path in
+both containers, so they survive a stop (which removes the containers) and a
+MiniStack restart, and need no S3 filesystem configuration.
+
+Runtime images match the Flink patch version and Java version AWS documents for
+each runtime (Managed Flink developer guide, "Amazon Managed Service for Apache
+Flink 1.19" and "1.20" pages: Flink 1.19.1 and 1.20.5, Java 11).
+"""
+
+import hashlib
+import io
+import json
+import logging
+import os
+import re
+import tarfile
+import threading
+import time
+import urllib.error
+import urllib.request
+import uuid
+from pathlib import Path
+
+from ministack.core import container_reaper
+from ministack.core.responses import apply_image_prefix, request_scope
+
+logger = logging.getLogger("kinesisanalyticsv2")
+
+# Cap any single Docker daemon call, as the other container-backed services do.
+_DOCKER_TIMEOUT = float(os.environ.get("MINISTACK_DOCKER_TIMEOUT", "10"))
+DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "")
+
+_RUNTIME_IMAGES = {
+ "FLINK-1_20": "flink:1.20.5-java11",
+ "FLINK-1_19": "flink:1.19.1-java11",
+}
+
+_LABEL = "kinesisanalyticsv2"
+_REST_PORT = 8081
+_SAVEPOINT_DIR = "/flink-savepoints"
+# Path the aws-kinesisanalytics-runtime library reads runtime properties from
+# (com.amazonaws:aws-kinesisanalytics-runtime 1.2.0, config.properties).
+_PROPERTIES_PATH = "/etc/flink/application_properties.json"
+# Jars added to every cluster's /opt/flink/lib, like the libraries Managed Flink
+# provides on its classpath. Managed Flink provides
+# com.amazonaws:aws-kinesisanalytics-runtime ("Provided dependencies",
+# Managed Flink developer guide, best practices), and AWS documents building
+# jobs with it in provided scope, so it must come from here: mount a
+# directory holding it. Same pattern as the RDS IAM plugin's artifact root.
+_FLINK_LIB_DIR = "/opt/ministack/flink-lib"
+# UID of the ``flink`` user in the official image; the savepoint volume must be
+# writable by it.
+_FLINK_UID = 9999
+
+_CLUSTER_TIMEOUT = 120.0
+_JOB_TIMEOUT = 120.0
+_SAVEPOINT_TIMEOUT = 120.0
+_POLL_INTERVAL = 1.0
+
+_docker = None
+_ministack_network = None
+
+# (account, region, application name) -> cluster record
+_clusters: dict = {}
+# (account, region, application name) -> thread of the latest start, so a new
+# start waits until an earlier one (possibly stopped mid-launch) has finished.
+_starts: dict = {}
+_lock = threading.Lock()
+
+
+def _get_docker():
+ global _docker
+ if _docker is None:
+ try:
+ import docker
+
+ _docker = docker.from_env(timeout=_DOCKER_TIMEOUT)
+ except Exception:
+ pass
+ return _docker
+
+
+def _get_ministack_network(docker_client):
+ """Detect the Docker network MiniStack is running on (if containerised)."""
+ global _ministack_network
+ if _ministack_network is not None:
+ return _ministack_network or None
+ if DOCKER_NETWORK:
+ _ministack_network = DOCKER_NETWORK
+ return DOCKER_NETWORK
+ try:
+ self_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))
+ nets = list(self_container.attrs["NetworkSettings"]["Networks"].keys())
+ if nets:
+ _ministack_network = nets[0]
+ return nets[0]
+ except Exception:
+ pass
+ _ministack_network = ""
+ return None
+
+
+def _self_ip(docker_client, ms_network):
+ """MiniStack's own address on ``ms_network`` when it runs in a container."""
+ if not ms_network:
+ return None
+ try:
+ self_container = docker_client.containers.get(os.environ.get("HOSTNAME", ""))
+ nets = self_container.attrs["NetworkSettings"]["Networks"]
+ return (nets.get(ms_network) or {}).get("IPAddress") or None
+ except Exception:
+ return None
+
+
+def _gateway_endpoint(docker_client, ms_network):
+ """MiniStack's endpoint as seen from inside a Flink container.
+
+ Same resolution as EKS: MiniStack's address on the shared network when it
+ is containerised, otherwise ``host.docker.internal``, which the containers
+ map to ``host-gateway``.
+ """
+ host = _self_ip(docker_client, ms_network) or "host.docker.internal"
+ port = os.environ.get("GATEWAY_PORT") or os.environ.get("EDGE_PORT") or "4566"
+ return f"http://{host}:{port}"
+
+
+def supports(runtime) -> bool:
+ """Whether this data plane can run jobs for ``runtime``."""
+ return runtime in _RUNTIME_IMAGES
+
+
+def available() -> bool:
+ client = _get_docker()
+ if client is None:
+ return False
+ try:
+ client.ping()
+ return True
+ except Exception:
+ return False
+
+
+# ── Application record helpers ────────────────────────────────────────────────
+
+
+def _key(app):
+ return (app.get("AccountId", ""), app.get("Region", ""), app.get("ApplicationName", ""))
+
+
+def _base_name(app):
+ """Docker name prefix for the application's containers, network and volume.
+
+ The JobManager's name is its address on the Docker network, so it must be
+ a valid DNS label: at most 63 characters, letters, digits and hyphens.
+ Application names allow up to 128 characters including '.' and '_', so the
+ readable part is cleaned and shortened, and a hash of the account, region
+ and full name keeps it unique. Labels carry the full identity.
+ """
+ account_id, region, name = _key(app)
+ readable = re.sub(r"[^a-z0-9-]+", "-", name.lower()).strip("-")[:20].strip("-") or "app"
+ digest = hashlib.sha256(f"{account_id}/{region}/{name}".encode()).hexdigest()[:10]
+ return f"ministack-flink-{readable}-{digest}"
+
+
+def _access_key(app):
+ """Access key the job signs with. MiniStack treats a 12-digit key as the
+ account id, so the job's calls land in the application's own account."""
+ account_id = app.get("AccountId", "")
+ return account_id if len(account_id) == 12 and account_id.isdigit() else "test"
+
+
+def _image_for(app):
+ image = _RUNTIME_IMAGES.get(app.get("RuntimeEnvironment", ""))
+ return apply_image_prefix(image) if image else None
+
+
+def _app_config(app):
+ return app.get("ApplicationConfigurationDescription") or {}
+
+
+def _code_location(app):
+ """(bucket, key, object version) of the application code in S3."""
+ loc = (
+ (_app_config(app).get("ApplicationCodeConfigurationDescription") or {})
+ .get("CodeContentDescription", {})
+ .get("S3ApplicationCodeLocationDescription")
+ ) or {}
+ bucket = loc.get("BucketARN", "").split(":::", 1)[-1]
+ return bucket, loc.get("FileKey", ""), loc.get("ObjectVersion") or None
+
+
+def _parallelism(app):
+ cfg = (
+ (_app_config(app).get("FlinkApplicationConfigurationDescription") or {})
+ .get("ParallelismConfigurationDescription")
+ ) or {}
+ value = cfg.get("CurrentParallelism") or cfg.get("Parallelism") or 1
+ try:
+ return max(1, int(value))
+ except (TypeError, ValueError):
+ return 1
+
+
+def _checkpointing(app):
+ """(interval ms, min pause ms) when checkpointing is enabled, else None.
+
+ Managed Flink applies the application's CheckpointConfiguration to the
+ cluster; the control plane fills in the DEFAULT values (enabled, 60000,
+ 5000) from the developer guide.
+ """
+ cfg = (
+ (_app_config(app).get("FlinkApplicationConfigurationDescription") or {})
+ .get("CheckpointConfigurationDescription")
+ ) or {}
+ if not cfg.get("CheckpointingEnabled", True):
+ return None
+ return int(cfg.get("CheckpointInterval") or 60000), int(cfg.get("MinPauseBetweenCheckpoints") or 5000)
+
+
+def _allow_non_restored_state(app):
+ run_cfg = _app_config(app).get("RunConfigurationDescription") or {}
+ flink_run = run_cfg.get("FlinkRunConfigurationDescription") or {}
+ return bool(flink_run.get("AllowNonRestoredState", False))
+
+
+def _properties_json(app):
+ groups = (
+ (_app_config(app).get("EnvironmentPropertyDescriptions") or {})
+ .get("PropertyGroupDescriptions")
+ ) or []
+ return json.dumps(
+ [{"PropertyGroupId": g.get("PropertyGroupId", ""), "PropertyMap": g.get("PropertyMap") or {}} for g in groups]
+ ).encode()
+
+
+def _fetch_jar(app):
+ bucket, key, version = _code_location(app)
+ if not bucket or not key:
+ return None, "Application code location is not an S3 object"
+ from ministack.services import s3 as _s3
+
+ with request_scope(app.get("AccountId", ""), app.get("Region", "")):
+ data = _s3._get_object_data(bucket, key, version)
+ if data is None:
+ return None, f"Application code s3://{bucket}/{key} was not found"
+ return data, None
+
+
+# ── Flink REST client ─────────────────────────────────────────────────────────
+
+
+def _rest(cluster, method, path, body=None, content_type="application/json", timeout=10.0):
+ url = f"{cluster['rest_url']}{path}"
+ data = None
+ if body is not None:
+ data = body if isinstance(body, bytes) else json.dumps(body).encode()
+ req = urllib.request.Request(url, data=data, method=method)
+ if data is not None:
+ req.add_header("Content-Type", content_type)
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ raw = resp.read()
+ except urllib.error.HTTPError as e:
+ raise RuntimeError(f"Flink REST {method} {path} returned {e.code}: {_root_cause(e.read())}") from e
+ return json.loads(raw) if raw else {}
+
+
+def _root_cause(body):
+ """The innermost ``Caused by`` line of a Flink REST error, which names the
+ real failure (a missing class, an exception from the job's main)."""
+ text = body.decode(errors="replace")
+ try:
+ text = "\n".join(json.loads(text).get("errors") or []) or text
+ except ValueError:
+ pass
+ causes = [line.strip() for line in text.splitlines() if line.strip().startswith("Caused by:")]
+ return (causes[-1] if causes else text.strip().splitlines()[0] if text.strip() else "")[:500]
+
+
+def _upload_jar(cluster, jar_bytes):
+ boundary = uuid.uuid4().hex
+ body = (
+ f"--{boundary}\r\n"
+ 'Content-Disposition: form-data; name="jarfile"; filename="application.jar"\r\n'
+ "Content-Type: application/x-java-archive\r\n\r\n"
+ ).encode() + jar_bytes + f"\r\n--{boundary}--\r\n".encode()
+ resp = _rest(cluster, "POST", "/jars/upload", body, f"multipart/form-data; boundary={boundary}", timeout=60.0)
+ return resp["filename"].rsplit("/", 1)[-1]
+
+
+def _wait_for_slots(cluster, slots, deadline):
+ while time.monotonic() < deadline:
+ if cluster.get("cancelled"):
+ raise RuntimeError("Application was stopped before it started")
+ try:
+ overview = _rest(cluster, "GET", "/overview", timeout=3.0)
+ if overview.get("taskmanagers", 0) >= 1 and overview.get("slots-total", 0) >= slots:
+ return
+ except Exception:
+ pass
+ time.sleep(_POLL_INTERVAL)
+ raise RuntimeError(f"Flink cluster did not become ready within {int(_CLUSTER_TIMEOUT)}s")
+
+
+def _root_exception(cluster, job_id):
+ try:
+ exc = _rest(cluster, "GET", f"/jobs/{job_id}/exceptions", timeout=5.0)
+ text = (exc.get("rootException") or "").strip()
+ return text.splitlines()[0] if text else ""
+ except Exception:
+ return ""
+
+
+def _wait_for_job_running(cluster, job_id, deadline):
+ while time.monotonic() < deadline:
+ if cluster.get("cancelled"):
+ raise RuntimeError("Application was stopped before it started")
+ state = _rest(cluster, "GET", f"/jobs/{job_id}", timeout=5.0).get("state")
+ if state == "RUNNING":
+ return
+ if state in ("FAILED", "CANCELED", "FINISHED"):
+ cause = _root_exception(cluster, job_id)
+ raise RuntimeError(f"Flink job {state}" + (f": {cause}" if cause else ""))
+ time.sleep(_POLL_INTERVAL)
+ raise RuntimeError(f"Flink job did not reach RUNNING within {int(_JOB_TIMEOUT)}s")
+
+
+def _wait_for_savepoint(cluster, job_id, trigger_id):
+ deadline = time.monotonic() + _SAVEPOINT_TIMEOUT
+ while time.monotonic() < deadline:
+ resp = _rest(cluster, "GET", f"/jobs/{job_id}/savepoints/{trigger_id}", timeout=5.0)
+ if (resp.get("status") or {}).get("id") == "COMPLETED":
+ op = resp.get("operation") or {}
+ if op.get("location"):
+ return op["location"]
+ cause = (op.get("failure-cause") or {}).get("stack-trace", "")
+ raise RuntimeError("Savepoint failed: " + (cause.strip().splitlines() or ["unknown cause"])[0])
+ time.sleep(_POLL_INTERVAL)
+ raise RuntimeError(f"Savepoint did not complete within {int(_SAVEPOINT_TIMEOUT)}s")
+
+
+# ── Containers ────────────────────────────────────────────────────────────────
+
+
+def _flink_properties(jm_name, slots, parallelism, endpoint, access_key, checkpointing):
+ lines = [
+ f"jobmanager.rpc.address: {jm_name}",
+ f"taskmanager.numberOfTaskSlots: {slots}",
+ f"parallelism.default: {parallelism}",
+ f"state.savepoints.dir: file://{_SAVEPOINT_DIR}",
+ f"state.checkpoints.dir: file://{_SAVEPOINT_DIR}/checkpoints",
+ # Flink's S3 filesystem shades AWS SDK v1 and ignores
+ # AWS_ENDPOINT_URL, so point it at MiniStack explicitly.
+ f"s3.endpoint: {endpoint}",
+ "s3.path.style.access: true",
+ f"s3.access-key: {access_key}",
+ "s3.secret-key: test",
+ ]
+ if checkpointing:
+ interval, min_pause = checkpointing
+ lines += [
+ f"execution.checkpointing.interval: {interval}ms",
+ f"execution.checkpointing.min-pause: {min_pause}ms",
+ ]
+ return "\n".join(lines)
+
+
+def _flink_lib_jars():
+ """(name, bytes) for each jar in _FLINK_LIB_DIR; empty when there are none."""
+ root = Path(_FLINK_LIB_DIR)
+ jars = sorted(root.glob("*.jar")) if root.is_dir() else []
+ if not jars:
+ logger.info(
+ "Flink: no jars in %s; jobs must bundle aws-kinesisanalytics-runtime themselves", _FLINK_LIB_DIR
+ )
+ return [(jar.name, jar.read_bytes()) for jar in jars]
+
+
+def _container_archive(properties, jars):
+ """The runtime properties file, plus the jars for the Flink lib directory."""
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w") as tar:
+ info = tarfile.TarInfo("etc/flink")
+ info.type = tarfile.DIRTYPE
+ info.mode = 0o755
+ tar.addfile(info)
+ files = [(_PROPERTIES_PATH.lstrip("/"), properties)]
+ files += [(f"opt/flink/lib/{name}", payload) for name, payload in jars]
+ for path, payload in files:
+ info = tarfile.TarInfo(path)
+ info.size = len(payload)
+ info.mode = 0o644
+ tar.addfile(info, io.BytesIO(payload))
+ return buf.getvalue()
+
+
+def _remove_container(client, name_or_id):
+ try:
+ client.containers.get(name_or_id).remove(force=True, v=True)
+ except Exception:
+ pass
+
+
+def _ensure_image(client, image):
+ """Pull the runtime image when it is not local. ``containers.create`` does
+ not pull the way ``containers.run`` does."""
+ try:
+ client.images.get(image)
+ return
+ except Exception:
+ pass
+ logger.info("Flink: pulling %s", image)
+ try:
+ client.images.pull(image)
+ except Exception as e:
+ raise RuntimeError(f"Could not pull Flink image {image}: {e}") from e
+
+
+def _ensure_volume(client, app, image):
+ """Create the application's savepoint volume, writable by the flink user."""
+ name = f"{_base_name(app)}-savepoints"
+ try:
+ client.volumes.get(name)
+ return name
+ except Exception:
+ pass
+ account_id, region, app_name = _key(app)
+ client.volumes.create(
+ name=name,
+ labels=container_reaper.own_labels(_LABEL, account_id=account_id, region=region, application=app_name),
+ )
+ # A fresh named volume is owned by root; hand it to the flink user once.
+ client.containers.run(
+ image,
+ entrypoint=["chown", f"{_FLINK_UID}:{_FLINK_UID}", _SAVEPOINT_DIR],
+ volumes={name: {"bind": _SAVEPOINT_DIR, "mode": "rw"}},
+ user="root",
+ remove=True,
+ labels=container_reaper.own_labels(_LABEL),
+ )
+ return name
+
+
+def _ensure_network(client, app, ms_network):
+ """The network JobManager and TaskManager share: MiniStack's own network
+ when it has one, otherwise a per-application bridge network."""
+ if ms_network:
+ return ms_network, False
+ name = f"{_base_name(app)}-net"
+ try:
+ client.networks.get(name)
+ except Exception:
+ account_id, region, app_name = _key(app)
+ client.networks.create(
+ name,
+ driver="bridge",
+ labels=container_reaper.own_labels(_LABEL, account_id=account_id, region=region, application=app_name),
+ )
+ return name, True
+
+
+def _launch(client, app, cluster):
+ image = cluster["image"]
+ base = _base_name(app)
+ jm_name, tm_name = f"{base}-jm", f"{base}-tm"
+ for stale in (jm_name, tm_name):
+ _remove_container(client, stale)
+
+ _ensure_image(client, image)
+ ms_network = _get_ministack_network(client)
+ network, own_network = _ensure_network(client, app, ms_network)
+ cluster["network"] = network if own_network else None
+ volume = _ensure_volume(client, app, image)
+ endpoint = _gateway_endpoint(client, ms_network)
+
+ parallelism = _parallelism(app)
+ env = {
+ "FLINK_PROPERTIES": _flink_properties(
+ jm_name, parallelism, parallelism, endpoint, _access_key(app), _checkpointing(app)
+ ),
+ "ENABLE_BUILT_IN_PLUGINS": f"flink-s3-fs-hadoop-{image.rsplit(':', 1)[-1].split('-')[0]}.jar",
+ # Fixed credentials so the job always authenticates against MiniStack,
+ # whatever the host environment carries, in the application's account.
+ "AWS_ACCESS_KEY_ID": _access_key(app),
+ "AWS_SECRET_ACCESS_KEY": "test",
+ "AWS_REGION": app.get("Region", ""),
+ "AWS_DEFAULT_REGION": app.get("Region", ""),
+ "AWS_ENDPOINT_URL": endpoint,
+ }
+ account_id, region, app_name = _key(app)
+ common = dict(
+ image=image,
+ environment=env,
+ network=network,
+ volumes={volume: {"bind": _SAVEPOINT_DIR, "mode": "rw"}},
+ extra_hosts={"host.docker.internal": "host-gateway"},
+ detach=True,
+ )
+ properties = _container_archive(_properties_json(app), _flink_lib_jars())
+
+ jm = client.containers.create(
+ command="jobmanager",
+ name=jm_name,
+ hostname=jm_name,
+ ports={f"{_REST_PORT}/tcp": ("127.0.0.1", None)},
+ labels=container_reaper.own_labels(
+ _LABEL, account_id=account_id, region=region, application=app_name, role="jobmanager"
+ ),
+ **common,
+ )
+ cluster["jm_id"] = jm.id
+ jm.put_archive("/", properties)
+ jm.start()
+
+ tm = client.containers.create(
+ command="taskmanager",
+ name=tm_name,
+ hostname=tm_name,
+ labels=container_reaper.own_labels(
+ _LABEL, account_id=account_id, region=region, application=app_name, role="taskmanager"
+ ),
+ **common,
+ )
+ cluster["tm_id"] = tm.id
+ tm.put_archive("/", properties)
+ tm.start()
+
+ # Reach the REST API on the JobManager's network address when MiniStack
+ # shares its network, otherwise through the loopback-published port.
+ if _self_ip(client, ms_network):
+ jm.reload()
+ ip = jm.attrs["NetworkSettings"]["Networks"][network]["IPAddress"]
+ cluster["rest_url"] = f"http://{ip}:{_REST_PORT}"
+ else:
+ jm.reload()
+ binding = jm.attrs["NetworkSettings"]["Ports"][f"{_REST_PORT}/tcp"][0]
+ cluster["rest_url"] = f"http://127.0.0.1:{binding['HostPort']}"
+ return parallelism
+
+
+def _teardown(client, cluster, remove_volume=False, app=None):
+ for cid in (cluster.get("tm_id"), cluster.get("jm_id")):
+ if cid:
+ _remove_container(client, cid)
+ if cluster.get("network"):
+ try:
+ client.networks.get(cluster["network"]).remove()
+ except Exception:
+ pass
+ if remove_volume and app is not None:
+ try:
+ client.volumes.get(f"{_base_name(app)}-savepoints").remove(force=True)
+ except Exception:
+ pass
+
+
+def _run(app, cluster, savepoint_path, on_status, prior=None, previous=None):
+ client = _get_docker()
+ # An earlier start of this application may still be launching containers
+ # under the same names; let it finish (it removes them once it sees it was
+ # cancelled), then make sure nothing of the replaced cluster is left.
+ if prior is not None:
+ prior.join(timeout=_CLUSTER_TIMEOUT + _JOB_TIMEOUT)
+ if previous is not None:
+ _teardown(client, previous)
+ try:
+ jar, error = _fetch_jar(app)
+ if error:
+ raise RuntimeError(error)
+ parallelism = _launch(client, app, cluster)
+ _wait_for_slots(cluster, parallelism, time.monotonic() + _CLUSTER_TIMEOUT)
+ jar_id = _upload_jar(cluster, jar)
+ run_body = {"parallelism": parallelism, "allowNonRestoredState": _allow_non_restored_state(app)}
+ if savepoint_path:
+ run_body["savepointPath"] = savepoint_path
+ job_id = _rest(cluster, "POST", f"/jars/{jar_id}/run", run_body, timeout=60.0)["jobid"]
+ cluster["job_id"] = job_id
+ _wait_for_job_running(cluster, job_id, time.monotonic() + _JOB_TIMEOUT)
+ except Exception as e:
+ if cluster.get("cancelled"):
+ # Stopped or replaced mid-launch: containers created after the
+ # stop's own cleanup would otherwise be left behind.
+ _teardown(client, cluster)
+ return
+ with _lock:
+ if _clusters.get(_key(app)) is cluster:
+ _clusters.pop(_key(app), None)
+ _teardown(client, cluster)
+ _notify(on_status, "FAILED", str(e)[:1000])
+ return
+ logger.info("Flink: application %s running as job %s", app.get("ApplicationName"), cluster["job_id"])
+ _notify(on_status, "RUNNING")
+
+
+def _notify(on_status, status, message=None):
+ try:
+ if message is None:
+ on_status(status)
+ else:
+ on_status(status, message)
+ except Exception:
+ logger.exception("Flink: status callback failed")
+
+
+# ── Interface ─────────────────────────────────────────────────────────────────
+
+
+def start(app, savepoint_path, on_status):
+ image = _image_for(app)
+ if image is None:
+ logger.info(
+ "Flink: runtime %s has no image mapping; application %s runs control plane only",
+ app.get("RuntimeEnvironment"), app.get("ApplicationName"),
+ )
+ _notify(on_status, "RUNNING")
+ return
+ cluster = {"image": image}
+ with _lock:
+ previous = _clusters.get(_key(app))
+ _clusters[_key(app)] = cluster
+ if previous is not None:
+ previous["cancelled"] = True
+ thread = threading.Thread(
+ target=_run, args=(app, cluster, savepoint_path, on_status, _starts.get(_key(app)), previous), daemon=True
+ )
+ _starts[_key(app)] = thread
+ thread.start()
+
+
+def snapshot(app, snapshot_name):
+ with _lock:
+ cluster = _clusters.get(_key(app))
+ if not cluster or not cluster.get("job_id"):
+ return None
+ try:
+ resp = _rest(
+ cluster, "POST", f"/jobs/{cluster['job_id']}/savepoints",
+ {"target-directory": f"file://{_SAVEPOINT_DIR}/{snapshot_name}", "cancel-job": False},
+ )
+ return _wait_for_savepoint(cluster, cluster["job_id"], resp["request-id"])
+ except Exception as e:
+ logger.warning("Flink: snapshot %s of %s failed: %s", snapshot_name, app.get("ApplicationName"), e)
+ return None
+
+
+def stop(app, force, take_snapshot):
+ with _lock:
+ cluster = _clusters.pop(_key(app), None)
+ if not cluster:
+ return None
+ cluster["cancelled"] = True
+ client = _get_docker()
+ location = None
+ job_id = cluster.get("job_id")
+ if job_id:
+ try:
+ if take_snapshot and not force:
+ target = f"file://{_SAVEPOINT_DIR}/stop-{int(time.time() * 1000)}"
+ resp = _rest(cluster, "POST", f"/jobs/{job_id}/stop", {"targetDirectory": target, "drain": False})
+ location = _wait_for_savepoint(cluster, job_id, resp["request-id"])
+ else:
+ _rest(cluster, "PATCH", f"/jobs/{job_id}?mode=cancel")
+ except Exception as e:
+ logger.warning("Flink: stopping %s: %s", app.get("ApplicationName"), e)
+ if client is not None:
+ _teardown(client, cluster)
+ return location
+
+
+def delete(app):
+ with _lock:
+ cluster = _clusters.pop(_key(app), None) or {}
+ cluster["cancelled"] = True
+ client = _get_docker()
+ if client is None:
+ return
+ base = _base_name(app)
+ cluster.setdefault("jm_id", f"{base}-jm")
+ cluster.setdefault("tm_id", f"{base}-tm")
+ cluster.setdefault("network", f"{base}-net")
+ _teardown(client, cluster, remove_volume=True, app=app)
+
+
+def reset():
+ with _lock:
+ clusters = list(_clusters.values())
+ _clusters.clear()
+ _starts.clear()
+ for cluster in clusters:
+ cluster["cancelled"] = True
+ client = _get_docker()
+ if client is None:
+ return
+ filters = {"label": [f"ministack={_LABEL}", f"{container_reaper.INSTANCE_LABEL}={container_reaper.instance_id()}"]}
+ try:
+ for c in client.containers.list(all=True, filters=filters):
+ _remove_container(client, c.id)
+ for n in client.networks.list(filters=filters):
+ try:
+ n.remove()
+ except Exception:
+ pass
+ for v in client.volumes.list(filters=filters):
+ try:
+ v.remove(force=True)
+ except Exception:
+ pass
+ except Exception as e:
+ logger.warning("Flink: reset could not list containers: %s", e)
+
+
+def _live_container_ids():
+ with _lock:
+ return [cid for c in _clusters.values() for cid in (c.get("jm_id"), c.get("tm_id")) if cid]
+
+
+container_reaper.register_live_ids(_LABEL, _live_container_ids)
diff --git a/tests/fixtures/flink/runtime-library-src/ministack/flinktest/RuntimeLibraryJob.java b/tests/fixtures/flink/runtime-library-src/ministack/flinktest/RuntimeLibraryJob.java
new file mode 100644
index 00000000..517f2b83
--- /dev/null
+++ b/tests/fixtures/flink/runtime-library-src/ministack/flinktest/RuntimeLibraryJob.java
@@ -0,0 +1,21 @@
+// Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+package ministack.flinktest;
+
+import java.util.Properties;
+
+import com.amazonaws.services.kinesisanalytics.runtime.KinesisAnalyticsRuntime;
+
+/**
+ * CounterJob, with its properties read through KinesisAnalyticsRuntime. Built
+ * the way AWS documents: the library is provided by the runtime, not bundled,
+ * so this runs only when MiniStack provides it from /opt/ministack/flink-lib.
+ */
+public class RuntimeLibraryJob {
+ public static void main(String[] args) throws Exception {
+ Properties group = KinesisAnalyticsRuntime.getApplicationProperties().get("Test");
+ if (group == null) {
+ throw new IllegalStateException("runtime property group Test is missing");
+ }
+ CounterJob.run(group.getProperty("StreamName"), group.getProperty("Message"));
+ }
+}
diff --git a/tests/fixtures/flink/src/ministack/flinktest/CounterJob.java b/tests/fixtures/flink/src/ministack/flinktest/CounterJob.java
new file mode 100644
index 00000000..f4e6da79
--- /dev/null
+++ b/tests/fixtures/flink/src/ministack/flinktest/CounterJob.java
@@ -0,0 +1,138 @@
+// Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+package ministack.flinktest;
+
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Base64;
+
+import org.apache.flink.api.common.state.ListState;
+import org.apache.flink.api.common.state.ListStateDescriptor;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.runtime.state.FunctionInitializationContext;
+import org.apache.flink.runtime.state.FunctionSnapshotContext;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
+import org.apache.flink.streaming.api.functions.source.SourceFunction;
+
+/**
+ * Test job for MiniStack's Managed Flink data plane.
+ *
+ * Reads the "Test" property group from the runtime properties file, counts
+ * upwards in checkpointed state, and writes {"message", "n"} records to the
+ * Kinesis stream named by the "StreamName" property through the endpoint in
+ * AWS_ENDPOINT_URL. A restore from a savepoint continues the count.
+ *
+ * Uses only Flink and the JDK, so the jar stays a few kilobytes and needs no
+ * connector, AWS SDK or aws-kinesisanalytics-runtime. RuntimeLibraryJob runs
+ * the same pipeline with properties read through KinesisAnalyticsRuntime.
+ */
+public class CounterJob {
+ static final String PROPERTIES = "/etc/flink/application_properties.json";
+
+ public static void main(String[] args) throws Exception {
+ JsonNode group = null;
+ for (JsonNode g : new ObjectMapper().readTree(Files.readString(Path.of(PROPERTIES)))) {
+ if ("Test".equals(g.path("PropertyGroupId").asText())) {
+ group = g.path("PropertyMap");
+ }
+ }
+ if (group == null) {
+ throw new IllegalStateException("property group Test is missing from " + PROPERTIES);
+ }
+ run(group.path("StreamName").asText(), group.path("Message").asText());
+ }
+
+ static void run(String stream, String message) throws Exception {
+ StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.addSource(new Counter()).setParallelism(1)
+ .addSink(new KinesisSink(stream, message)).setParallelism(1);
+ env.execute("ministack-counter");
+ }
+
+ public static class Counter implements SourceFunction<Long>, CheckpointedFunction {
+ private volatile boolean running = true;
+ private long next;
+ private transient ListState<Long> state;
+
+ @Override
+ public void run(SourceContext<Long> ctx) throws Exception {
+ while (running) {
+ synchronized (ctx.getCheckpointLock()) {
+ ctx.collect(next);
+ next++;
+ }
+ Thread.sleep(250);
+ }
+ }
+
+ @Override
+ public void cancel() {
+ running = false;
+ }
+
+ @Override
+ public void snapshotState(FunctionSnapshotContext context) throws Exception {
+ state.update(java.util.List.of(next));
+ }
+
+ @Override
+ public void initializeState(FunctionInitializationContext context) throws Exception {
+ state = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("next", Long.class));
+ for (Long value : state.get()) {
+ next = value;
+ }
+ }
+ }
+
+ public static class KinesisSink extends RichSinkFunction<Long> {
+ private final String stream;
+ private final String message;
+ private transient HttpClient http;
+ private transient String endpoint;
+ private transient String region;
+ private transient String accessKey;
+
+ KinesisSink(String stream, String message) {
+ this.stream = stream;
+ this.message = message;
+ }
+
+ @Override
+ public void open(Configuration parameters) {
+ http = HttpClient.newHttpClient();
+ endpoint = System.getenv("AWS_ENDPOINT_URL");
+ region = System.getenv("AWS_REGION");
+ accessKey = System.getenv("AWS_ACCESS_KEY_ID");
+ }
+
+ @Override
+ public void invoke(Long n, Context context) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String record = mapper.createObjectNode().put("message", message).put("n", n).toString();
+ String body = mapper.createObjectNode()
+ .put("StreamName", stream)
+ .put("PartitionKey", "counter")
+ .put("Data", Base64.getEncoder().encodeToString(record.getBytes(StandardCharsets.UTF_8)))
+ .toString();
+ HttpRequest request = HttpRequest.newBuilder(URI.create(endpoint))
+ .header("Content-Type", "application/x-amz-json-1.1")
+ .header("X-Amz-Target", "Kinesis_20131202.PutRecord")
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKey + "/20260101/" + region
+ + "/kinesis/aws4_request, SignedHeaders=host, Signature=0")
+ .POST(HttpRequest.BodyPublishers.ofString(body))
+ .build();
+ HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
+ if (response.statusCode() != 200) {
+ throw new IllegalStateException("PutRecord returned " + response.statusCode() + ": " + response.body());
+ }
+ }
+ }
+}
diff --git a/tests/test_kinesisanalyticsv2.py b/tests/test_kinesisanalyticsv2.py
index 6a50690f..06fe0837 100644
--- a/tests/test_kinesisanalyticsv2.py
+++ b/tests/test_kinesisanalyticsv2.py
@@ -486,3 +486,151 @@ def test_cloudformation_flink_stack(cfn, logs, kinesisanalyticsv2):
with pytest.raises(ClientError) as exc:
_detail(kinesisanalyticsv2, app)
assert _code(exc) == "ResourceNotFoundException"
+
+
+# ---------------------------------------------------------------------------
+# Data plane hooks (a fake data plane, in process)
+# ---------------------------------------------------------------------------
+
+class _FakeDataPlane:
+ """Stands in for kinesisanalyticsv2_flink: slow savepoints, optional failure."""
+
+ def __init__(self, savepoint="file:///savepoints/sp-1", delay=0.5):
+ import threading
+
+ self.savepoint = savepoint
+ self.delay = delay
+ self.started = []
+ self.release = threading.Event()
+
+ def available(self):
+ return True
+
+ def supports(self, runtime):
+ return runtime in ("FLINK-1_19", "FLINK-1_20")
+
+ def start(self, app, savepoint_path, on_status):
+ self.started.append(savepoint_path)
+ on_status("RUNNING")
+
+ def _slow(self):
+ self.release.wait(self.delay)
+ return self.savepoint
+
+ def stop(self, app, force, take_snapshot):
+ return self._slow() if take_snapshot else None
+
+ def snapshot(self, app, snapshot_name):
+ return self._slow()
+
+ def delete(self, app):
+ pass
+
+ def reset(self):
+ pass
+
+
+def _wait_until(predicate, timeout=5):
+ import time
+
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if predicate():
+ return True
+ time.sleep(0.02)
+ return False
+
+
+def _call(action, payload):
+ import asyncio
+ import json
+
+ status, _, body = asyncio.run(kda.handle_request(
+ "POST", "/", {"x-amz-target": f"KinesisAnalytics_20180523.{action}"}, json.dumps(payload).encode(), {}))
+ return status, json.loads(body) if body else {}
+
+
+def fake_dataplane(local_state, monkeypatch):
+ fake = _FakeDataPlane()
+ monkeypatch.setattr(kda, "_dataplane", fake)
+ kda.create_application({"ApplicationName": "dp", "RuntimeEnvironment": RUNTIME, "ServiceExecutionRole": ROLE,
+ "ApplicationConfiguration": {"ApplicationSnapshotConfiguration": {"SnapshotsEnabled": True}}})
+ assert _call("StartApplication", {"ApplicationName": "dp"})[0] == 200
+ assert kda._applications["dp"]["ApplicationStatus"] == "RUNNING"
+ return fake
+
+
+def _status(name="dp"):
+ return kda._applications[name]["ApplicationStatus"]
+
+
+def _snapshot_status(snapshot_name):
+ return kda._snapshots["dp"][snapshot_name]["SnapshotStatus"]
+
+
+def test_snapshot_runs_in_background(fake_dataplane):
+ import time
+
+ started = time.time()
+ assert _call("CreateApplicationSnapshot", {"ApplicationName": "dp", "SnapshotName": "s1"})[0] == 200
+ assert time.time() - started < 0.3 # the request does not wait for the savepoint
+ assert _snapshot_status("s1") == "CREATING"
+ assert _wait_until(lambda: _snapshot_status("s1") == "READY")
+ assert kda._snapshots["dp"]["s1"]["_SavepointPath"] == "file:///savepoints/sp-1"
+
+
+def test_failed_snapshot_is_marked_failed_and_not_restored(fake_dataplane):
+ fake_dataplane.savepoint = None
+ _call("CreateApplicationSnapshot", {"ApplicationName": "dp", "SnapshotName": "bad"})
+ assert _wait_until(lambda: _snapshot_status("bad") == "FAILED")
+ _call("StopApplication", {"ApplicationName": "dp", "Force": True})
+ assert _wait_until(lambda: _status() == "READY")
+ status, body = _call("StartApplication", {"ApplicationName": "dp", "RunConfiguration": {
+ "ApplicationRestoreConfiguration": {"ApplicationRestoreType": "RESTORE_FROM_CUSTOM_SNAPSHOT",
+ "SnapshotName": "bad"}}})
+ assert status == 400
+ assert body["__type"] == "InvalidArgumentException"
+
+
+def test_graceful_stop_runs_in_background_and_restores_latest(fake_dataplane):
+ import time
+
+ started = time.time()
+ _call("StopApplication", {"ApplicationName": "dp"})
+ assert time.time() - started < 0.3
+ assert _status() == "STOPPING"
+ assert _wait_until(lambda: _status() == "READY")
+ [snap] = kda._snapshots["dp"].values()
+ assert snap["SnapshotStatus"] == "READY"
+
+ _call("StartApplication", {"ApplicationName": "dp", "RunConfiguration": {
+ "ApplicationRestoreConfiguration": {"ApplicationRestoreType": "RESTORE_FROM_LATEST_SNAPSHOT"}}})
+ assert fake_dataplane.started[-1] == "file:///savepoints/sp-1"
+
+
+def test_data_plane_start_failure_returns_to_ready(local_state, monkeypatch):
+ fake = _FakeDataPlane()
+ fake.start = lambda app, savepoint, on_status: on_status("FAILED", "jar not found")
+ monkeypatch.setattr(kda, "_dataplane", fake)
+ kda.create_application({"ApplicationName": "dp", "RuntimeEnvironment": RUNTIME, "ServiceExecutionRole": ROLE})
+ _call("StartApplication", {"ApplicationName": "dp"})
+ assert _status() == "READY"
+
+
+def test_runtime_without_an_image_stays_control_plane_only(local_state, monkeypatch):
+ fake = _FakeDataPlane()
+ monkeypatch.setattr(kda, "_dataplane", fake)
+ kda.create_application({"ApplicationName": "dp", "RuntimeEnvironment": "FLINK-1_18", "ServiceExecutionRole": ROLE,
+ "ApplicationConfiguration": {"ApplicationSnapshotConfiguration": {"SnapshotsEnabled": True}}})
+ _call("StartApplication", {"ApplicationName": "dp"})
+ assert fake.started == []
+
+ def described():
+ return _call("DescribeApplication", {"ApplicationName": "dp"})[1]["ApplicationDetail"]["ApplicationStatus"]
+
+ assert described() == "RUNNING" # settles on read, as without Docker
+ _call("StopApplication", {"ApplicationName": "dp"})
+ assert described() == "READY"
+ [snap] = kda._snapshots["dp"].values()
+ assert snap["SnapshotStatus"] == "READY"
diff --git a/tests/test_kinesisanalyticsv2_dataplane.py b/tests/test_kinesisanalyticsv2_dataplane.py
new file mode 100644
index 00000000..e050885a
--- /dev/null
+++ b/tests/test_kinesisanalyticsv2_dataplane.py
@@ -0,0 +1,408 @@
+"""
+Managed Service for Apache Flink data plane: real jobs in the official Flink
+image, driven through the kinesisanalyticsv2 API.
+
+The test job (tests/fixtures/flink/src) is compiled at setup against the
+Flink classes in the runtime image, so no binary is committed. It reads the
+"Test" runtime property group from the properties file and writes a
+checkpointed counter to a MiniStack Kinesis stream, which covers the property
+file, the endpoint injection, and restore from a savepoint.
+
+RuntimeLibraryJob (tests/fixtures/flink/runtime-library-src) reads the same
+group through KinesisAnalyticsRuntime with the library not bundled, as AWS
+documents; its test runs only when aws-kinesisanalytics-runtime is in
+/opt/ministack/flink-lib.
+"""
+
+import io
+import json
+import os
+import shutil
+import subprocess
+import tarfile
+import tempfile
+import time
+import urllib.request
+import uuid
+from pathlib import Path
+
+import boto3
+import pytest
+from botocore.config import Config
+from conftest import ENDPOINT, REGION
+
+from ministack.services import kinesisanalyticsv2_flink as dataplane
+
+RUNTIME = "FLINK-1_20"
+ROLE = "arn:aws:iam::000000000000:role/flink-app"
+FIXTURES = Path(__file__).parent / "fixtures" / "flink"
+
+requires_docker = pytest.mark.skipif(
+ not os.environ.get("DOCKER_NETWORK"), reason="DOCKER_NETWORK not set -- skipping Flink data-plane tests"
+)
+
+
+def _wait_status(client, name, wanted, timeout=240):
+ deadline = time.monotonic() + timeout
+ status = None
+ while time.monotonic() < deadline:
+ status = client.describe_application(ApplicationName=name)["ApplicationDetail"]["ApplicationStatus"]
+ if status == wanted:
+ return
+ time.sleep(1)
+ raise AssertionError(f"{name} is {status}, expected {wanted} within {timeout}s")
+
+
+def _wait_snapshot(client, name, snapshot, wanted="READY", timeout=180):
+ deadline = time.monotonic() + timeout
+ status = None
+ while time.monotonic() < deadline:
+ status = client.describe_application_snapshot(ApplicationName=name, SnapshotName=snapshot)[
+ "SnapshotDetails"]["SnapshotStatus"]
+ if status == wanted:
+ return
+ time.sleep(1)
+ raise AssertionError(f"snapshot {snapshot} of {name} is {status}, expected {wanted} within {timeout}s")
+
+
+def _containers(name):
+ import docker
+
+ client = docker.from_env()
+ filters = {"label": ["ministack=kinesisanalyticsv2", f"application={name}"]}
+ return client.containers.list(all=True, filters=filters)
+
+
+class _Stream:
+ """Reads the counter records the job writes, in order."""
+
+ def __init__(self, kin, name):
+ self.kin = kin
+ self.name = name
+ self.iterator = kin.get_shard_iterator(
+ StreamName=name, ShardId="shardId-000000000000", ShardIteratorType="TRIM_HORIZON"
+ )["ShardIterator"]
+
+ def read(self):
+ records = []
+ while True:
+ resp = self.kin.get_records(ShardIterator=self.iterator)
+ self.iterator = resp["NextShardIterator"]
+ records += [json.loads(r["Data"]) for r in resp["Records"]]
+ if not resp["Records"]:
+ return records
+
+ def wait_for(self, count, timeout=60):
+ records = []
+ deadline = time.monotonic() + timeout
+ while len(records) < count and time.monotonic() < deadline:
+ records += self.read()
+ time.sleep(0.5)
+ assert len(records) >= count, f"expected {count} records from the job, got {len(records)}"
+ return records
+
+
+def _runtime_library():
+ return sorted(Path(dataplane._FLINK_LIB_DIR).glob("aws-kinesisanalytics-runtime-*.jar"))
+
+
[email protected](scope="module")
+def flink_classes():
+ """The Flink classes of the runtime image, to compile test jobs against."""
+ if shutil.which("javac") is None or shutil.which("jar") is None:
+ pytest.skip("a JDK (javac and jar) is needed to build the Flink test job")
+ import docker
+
+ client = docker.from_env()
+ image = dataplane._image_for({"RuntimeEnvironment": RUNTIME})
+ try:
+ client.images.pull(image)
+ except Exception as e:
+ try:
+ client.images.get(image)
+ except Exception:
+ pytest.skip(f"could not pull {image}: {e}")
+ work = Path(tempfile.mkdtemp(prefix="flink-test-job-"))
+ container = client.containers.create(image)
+ try:
+ stream, _ = container.get_archive("/opt/flink/lib")
+ with tarfile.open(fileobj=io.BytesIO(b"".join(stream))) as tar:
+ tar.extractall(work, filter="data")
+ yield work
+ finally:
+ container.remove(force=True)
+ shutil.rmtree(work, ignore_errors=True)
+
+
+def _build_jar(work, name, main_class, source_dirs, classpath=()):
+ classes = work / f"{name}-classes"
+ sources = [str(p) for d in source_dirs for p in d.rglob("*.java")]
+ subprocess.run(
+ ["javac", "--release", "11", "-nowarn",
+ "-cp", os.pathsep.join([f"{work / 'lib'}{os.sep}*", *map(str, classpath)]), "-d", str(classes), *sources],
+ check=True, capture_output=True,
+ )
+ jar_path = work / f"{name}.jar"
+ subprocess.run(
+ ["jar", "--create", "--file", str(jar_path), "--main-class", main_class, "-C", str(classes), "."],
+ check=True, capture_output=True,
+ )
+ return jar_path.read_bytes()
+
+
[email protected](scope="module")
+def counter_jar(flink_classes):
+ return _build_jar(flink_classes, "counter-job", "ministack.flinktest.CounterJob", [FIXTURES / "src"])
+
+
[email protected](scope="module")
+def runtime_library_jar(flink_classes):
+ """RuntimeLibraryJob, compiled against aws-kinesisanalytics-runtime but not bundling it."""
+ libraries = _runtime_library()
+ if not libraries:
+ pytest.skip(f"aws-kinesisanalytics-runtime is not in {dataplane._FLINK_LIB_DIR}")
+ return _build_jar(flink_classes, "runtime-library-job", "ministack.flinktest.RuntimeLibraryJob",
+ [FIXTURES / "src", FIXTURES / "runtime-library-src"], classpath=libraries)
+
+
+def _create_app(kinesisanalyticsv2, s3, kin, jar, checkpoint=None, name=None):
+ """An application for the counter job, writing to a fresh Kinesis stream."""
+ suffix = uuid.uuid4().hex[:8]
+ bucket, stream = f"flink-jars-{suffix}", f"flink-out-{suffix}"
+ name = name or f"flink-dp-{suffix}"
+ s3.create_bucket(Bucket=bucket)
+ s3.put_object(Bucket=bucket, Key="counter-job.jar", Body=jar)
+ kin.create_stream(StreamName=stream, ShardCount=1)
+ kinesisanalyticsv2.create_application(
+ ApplicationName=name,
+ RuntimeEnvironment=RUNTIME,
+ ServiceExecutionRole=ROLE,
+ ApplicationConfiguration={
+ "ApplicationCodeConfiguration": {
+ "CodeContentType": "ZIPFILE",
+ "CodeContent": {
+ "S3ContentLocation": {"BucketARN": f"arn:aws:s3:::{bucket}", "FileKey": "counter-job.jar"}
+ },
+ },
+ "EnvironmentProperties": {
+ "PropertyGroups": [
+ {"PropertyGroupId": "Test", "PropertyMap": {"StreamName": stream, "Message": f"hello-{suffix}"}}
+ ]
+ },
+ "FlinkApplicationConfiguration": {
+ "ParallelismConfiguration": {"ConfigurationType": "CUSTOM", "Parallelism": 2,
+ "ParallelismPerKPU": 1, "AutoScalingEnabled": False},
+ **({"CheckpointConfiguration": checkpoint} if checkpoint else {}),
+ },
+ "ApplicationSnapshotConfiguration": {"SnapshotsEnabled": True},
+ },
+ )
+ return {"name": name, "stream": stream, "message": f"hello-{suffix}"}
+
+
+def _cleanup(kinesisanalyticsv2, name):
+ try:
+ status = kinesisanalyticsv2.describe_application(ApplicationName=name)["ApplicationDetail"]["ApplicationStatus"]
+ if status in ("RUNNING", "STARTING"):
+ kinesisanalyticsv2.stop_application(ApplicationName=name, Force=True)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=60)
+ created = kinesisanalyticsv2.describe_application(ApplicationName=name)["ApplicationDetail"]["CreateTimestamp"]
+ kinesisanalyticsv2.delete_application(ApplicationName=name, CreateTimestamp=created)
+ except Exception:
+ pass
+
+
+def flink_app(kinesisanalyticsv2, s3, kin, counter_jar):
+ app = _create_app(kinesisanalyticsv2, s3, kin, counter_jar)
+ yield app
+ _cleanup(kinesisanalyticsv2, app["name"])
+
+
+def _start_and_wait(kinesisanalyticsv2, name):
+ kinesisanalyticsv2.start_application(
+ ApplicationName=name,
+ RunConfiguration={"ApplicationRestoreConfiguration": {"ApplicationRestoreType": "SKIP_RESTORE_FROM_SNAPSHOT"}},
+ )
+ _wait_status(kinesisanalyticsv2, name, "RUNNING")
+
+
+def _jobmanager_rest(name):
+ """The Flink REST API of the application's JobManager, from the host."""
+ [jm] = [c for c in _containers(name) if c.labels.get("role") == "jobmanager"]
+ jm.reload()
+ port = jm.attrs["NetworkSettings"]["Ports"]["8081/tcp"][0]["HostPort"]
+ base = f"http://127.0.0.1:{port}"
+
+ def get(path):
+ with urllib.request.urlopen(base + path, timeout=5) as resp:
+ return json.loads(resp.read())
+
+ return get
+
+
+@requires_docker
+def test_job_runs_with_runtime_properties_and_writes_to_kinesis(kinesisanalyticsv2, kin, flink_app):
+ name = flink_app["name"]
+ stream = _Stream(kin, flink_app["stream"])
+ kinesisanalyticsv2.start_application(
+ ApplicationName=name,
+ RunConfiguration={"ApplicationRestoreConfiguration": {"ApplicationRestoreType": "SKIP_RESTORE_FROM_SNAPSHOT"}},
+ )
+ _wait_status(kinesisanalyticsv2, name, "RUNNING")
+ assert {c.labels.get("role") for c in _containers(name)} == {"jobmanager", "taskmanager"}
+
+ records = stream.wait_for(3)
+ assert records[0] == {"message": flink_app["message"], "n": 0}
+
+ kinesisanalyticsv2.stop_application(ApplicationName=name, Force=True)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=60)
+ assert _containers(name) == []
+
+
+@requires_docker
+def test_restore_from_latest_snapshot_resumes_the_job(kinesisanalyticsv2, kin, flink_app):
+ name = flink_app["name"]
+ stream = _Stream(kin, flink_app["stream"])
+ kinesisanalyticsv2.start_application(
+ ApplicationName=name,
+ RunConfiguration={"ApplicationRestoreConfiguration": {"ApplicationRestoreType": "SKIP_RESTORE_FROM_SNAPSHOT"}},
+ )
+ _wait_status(kinesisanalyticsv2, name, "RUNNING")
+ before = stream.wait_for(4)
+
+ kinesisanalyticsv2.create_application_snapshot(ApplicationName=name, SnapshotName="mid-run")
+ _wait_snapshot(kinesisanalyticsv2, name, "mid-run")
+
+ # A graceful stop with snapshots enabled takes the latest snapshot.
+ kinesisanalyticsv2.stop_application(ApplicationName=name)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=180)
+ last_before = max(r["n"] for r in before + stream.read())
+
+ kinesisanalyticsv2.start_application(
+ ApplicationName=name,
+ RunConfiguration={"ApplicationRestoreConfiguration": {"ApplicationRestoreType": "RESTORE_FROM_LATEST_SNAPSHOT"}},
+ )
+ _wait_status(kinesisanalyticsv2, name, "RUNNING")
+ resumed = stream.wait_for(1)
+ assert resumed[0]["n"] > 0, "the job started from scratch instead of the snapshot"
+ assert resumed[0]["n"] >= last_before
+
+
+@requires_docker
+def test_start_with_missing_code_returns_to_ready(kinesisanalyticsv2, s3, flink_app):
+ name = flink_app["name"]
+ detail = kinesisanalyticsv2.describe_application(ApplicationName=name)["ApplicationDetail"]
+ loc = detail["ApplicationConfigurationDescription"]["ApplicationCodeConfigurationDescription"][
+ "CodeContentDescription"]["S3ApplicationCodeLocationDescription"]
+ s3.delete_object(Bucket=loc["BucketARN"].split(":::")[-1], Key=loc["FileKey"])
+
+ kinesisanalyticsv2.start_application(ApplicationName=name)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=60)
+ assert _containers(name) == []
+
+
+@requires_docker
+def test_job_writes_into_the_applications_own_account(counter_jar):
+ """A job runs with the application's account, so its writes land there."""
+ kwargs = dict(endpoint_url=ENDPOINT, aws_access_key_id="111111111111", aws_secret_access_key="test",
+ region_name=REGION, config=Config(retries={"mode": "standard"}))
+ other_kda, other_s3, other_kin = (boto3.client(svc, **kwargs) for svc in ("kinesisanalyticsv2", "s3", "kinesis"))
+ app = _create_app(other_kda, other_s3, other_kin, counter_jar)
+ try:
+ assert other_kda.describe_application(ApplicationName=app["name"])["ApplicationDetail"][
+ "ApplicationARN"].split(":")[4] == "111111111111"
+ stream = _Stream(other_kin, app["stream"])
+ _start_and_wait(other_kda, app["name"])
+ assert stream.wait_for(2)[0]["message"] == app["message"]
+ finally:
+ _cleanup(other_kda, app["name"])
+
+
+@requires_docker
+def test_checkpoint_configuration_reaches_the_cluster(kinesisanalyticsv2, s3, kin, counter_jar):
+ app = _create_app(kinesisanalyticsv2, s3, kin, counter_jar, checkpoint={
+ "ConfigurationType": "CUSTOM", "CheckpointingEnabled": True,
+ "CheckpointInterval": 2000, "MinPauseBetweenCheckpoints": 500})
+ try:
+ _start_and_wait(kinesisanalyticsv2, app["name"])
+ rest = _jobmanager_rest(app["name"])
+ [job] = rest("/jobs")["jobs"]
+ assert rest(f"/jobs/{job['id']}/checkpoints/config")["interval"] == 2000
+ deadline = time.monotonic() + 30
+ while rest(f"/jobs/{job['id']}/checkpoints")["counts"]["completed"] < 1:
+ assert time.monotonic() < deadline, "no checkpoint completed within 30s"
+ time.sleep(1)
+ finally:
+ _cleanup(kinesisanalyticsv2, app["name"])
+
+
+@requires_docker
+def test_runtime_without_an_image_runs_no_containers(kinesisanalyticsv2, s3, kin, counter_jar):
+ app = _create_app(kinesisanalyticsv2, s3, kin, counter_jar)
+ name = app["name"]
+ try:
+ created = kinesisanalyticsv2.describe_application(ApplicationName=name)["ApplicationDetail"]
+ kinesisanalyticsv2.update_application(
+ ApplicationName=name, CurrentApplicationVersionId=created["ApplicationVersionId"],
+ RuntimeEnvironmentUpdate="FLINK-1_18")
+ kinesisanalyticsv2.start_application(ApplicationName=name)
+ _wait_status(kinesisanalyticsv2, name, "RUNNING", timeout=10)
+ assert _containers(name) == []
+ kinesisanalyticsv2.stop_application(ApplicationName=name)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=10)
+ [snap] = kinesisanalyticsv2.list_application_snapshots(ApplicationName=name)["SnapshotSummaries"]
+ assert snap["SnapshotStatus"] == "READY"
+ finally:
+ _cleanup(kinesisanalyticsv2, name)
+
+
+@requires_docker
+def test_long_application_name_with_dots_and_underscores_runs(kinesisanalyticsv2, s3, kin, counter_jar):
+ """Application names allow 128 characters including '.' and '_'; the
+ JobManager's Docker name must still be a valid DNS label."""
+ name = f"Long.App_Name-{uuid.uuid4().hex[:8]}-" + "x" * 105
+ assert len(name) == 128
+ app = _create_app(kinesisanalyticsv2, s3, kin, counter_jar, name=name)
+ try:
+ stream = _Stream(kin, app["stream"])
+ _start_and_wait(kinesisanalyticsv2, name)
+ assert stream.wait_for(1)[0]["message"] == app["message"]
+ finally:
+ _cleanup(kinesisanalyticsv2, name)
+
+
+@requires_docker
+def test_force_stop_while_starting_then_start_again(kinesisanalyticsv2, kin, flink_app):
+ """A start cancelled mid-launch must not leave containers that block the next start."""
+ name = flink_app["name"]
+ stream = _Stream(kin, flink_app["stream"])
+ kinesisanalyticsv2.start_application(ApplicationName=name)
+ kinesisanalyticsv2.stop_application(ApplicationName=name, Force=True)
+ _wait_status(kinesisanalyticsv2, name, "READY", timeout=60)
+
+ _start_and_wait(kinesisanalyticsv2, name)
+ assert stream.wait_for(1)
+ assert {c.labels.get("role") for c in _containers(name)} == {"jobmanager", "taskmanager"}
+
+
+@requires_docker
+def test_runtime_library_is_provided_from_flink_lib(kinesisanalyticsv2, s3, kin, runtime_library_jar):
+ """A job built with aws-kinesisanalytics-runtime in provided scope runs, as on
+ AWS, when the library is in /opt/ministack/flink-lib."""
+ app = _create_app(kinesisanalyticsv2, s3, kin, runtime_library_jar)
+ try:
+ stream = _Stream(kin, app["stream"])
+ _start_and_wait(kinesisanalyticsv2, app["name"])
+ assert stream.wait_for(1)[0]["message"] == app["message"]
+ finally:
+ _cleanup(kinesisanalyticsv2, app["name"])