From 5d844e6bed5751e0d2c992d6dd8b4ca9573a272e Mon Sep 17 00:00:00 2001 From: Brady Svedin Date: Mon, 2 Nov 2026 16:38:48 -0700 Subject: [PATCH 1/2] Add distro option for ec2 deployments Supported distros are Ubuntu24, Ubuntu26, and AL2023. AMIs are now pinned or ignored so aws ami updates don't trigger rebuilds on unrelated terraform applies. --- deploy-aws-ec2/README.md | 53 ++- .../aws/ec2/TerraformAwsEc2BuilderBase.kt | 326 ++++++++++++++---- .../aws/ec2/TerraformAwsScalingEc2Builder.kt | 64 ++-- .../aws/ec2/TerraformAwsSingleEc2Builder.kt | 172 +++++---- .../terraform/aws/ec2/otel-collector-ec2.kt | 22 +- .../awsec2/Ec2BuilderGenerationTest.kt | 208 ++++++++++- docs-guide/drafts/deploy-ec2.md | 6 +- docs-guide/drafts/deploy-vm.md | 6 +- 8 files changed, 683 insertions(+), 174 deletions(-) diff --git a/deploy-aws-ec2/README.md b/deploy-aws-ec2/README.md index 8e29d2bc7..4aa6ea4a1 100644 --- a/deploy-aws-ec2/README.md +++ b/deploy-aws-ec2/README.md @@ -7,18 +7,45 @@ Two deployment styles are provided: | Builder | Shape | Use it when | |---------|-------|-------------| -| `TerraformAwsSingleEc2Builder` | One EC2 instance with an Elastic IP; on-box Angie terminates TLS via Let's Encrypt and reverse-proxies to the app. | Cheapest option; low/predictable traffic; no horizontal scaling needed. | +| `TerraformAwsSingleEc2Builder` | One EC2 instance with an Elastic IP; on-box nginx terminates TLS via Let's Encrypt and reverse-proxies to the app. | Cheapest option; low/predictable traffic; no horizontal scaling needed. | | `TerraformAwsScalingEc2Builder` | Application Load Balancer (ACM TLS) in front of an Auto Scaling Group of instances in private subnets, booting from a golden AMI. | You need horizontal scaling, zero-downtime rolling deploys, and load balancing. | Both share a common base (`TerraformAwsEc2BuilderBase`) for the artifact bucket, IAM, encrypted settings pipeline, the on-instance deploy script, and the user-data fragments. +## Operating system + +Instances run Ubuntu 24.04 by default. Set `distro` to choose another OS: + +| `distro` | OS | +|----------|----| +| `Distro.Ubuntu2404` (default) | Ubuntu 24.04 LTS | +| `Distro.Ubuntu2604` | Ubuntu 26.04 LTS | +| `Distro.AmazonLinux2023` | Amazon Linux 2023 | + +```kotlin +override val distro = Distro.AmazonLinux2023 +``` + +The install scripts, `os-update`, and the scaling builder's reboot check all follow the distro. +`additionalPackages` and custom install scripts are passed through unchanged, so they must use the +distro's own package names and tools. + +Amazon Linux 2023's package repositories are locked to the release of the AMI an instance started +from. Every system upgrade here, at install time and in `os-update`, passes `--releasever=latest` so +it picks up fixes published since. On Amazon Linux, `os-update` takes package names only, not +versions. + +Changing `distro` on an existing deployment, including between Ubuntu releases, replaces the single +instance. On the scaling builder it re-bakes the image from the new distro's latest AMI and rolls the +fleet onto it. + ## Module structure ``` deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/ ├── TerraformAwsEc2BuilderBase.kt # Shared config, deployment resources, user-data fragments -├── TerraformAwsSingleEc2Builder.kt # Single instance + Angie/Let's Encrypt + Elastic IP +├── TerraformAwsSingleEc2Builder.kt # Single instance + nginx/Let's Encrypt + Elastic IP ├── TerraformAwsScalingEc2Builder.kt # ALB + ACM + Auto Scaling Group + golden AMI ├── ImageComponent.kt # Image Builder components, including STIG hardening ├── VpcInfoTerraformManaged.kt # VPC created by this Terraform @@ -29,8 +56,9 @@ deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/e ## Single-instance builder -One instance behind on-box Angie (nginx fork) which terminates TLS with the built-in Let's -Encrypt ACME client and proxies to the app on `:8080`. Route53 A/AAAA records point straight at +One instance behind on-box nginx, installed from nginx.org's repository with the +`nginx-module-acme` dynamic module. nginx obtains and renews its own Let's Encrypt certificate, +terminates TLS, and proxies to the app on `:8080`. Route53 A/AAAA records point straight at the instance's Elastic IP. Code/settings updates are pushed in-place to that one instance via SSM Run Command (`redeploy.sh` → on-instance `lightning-server-redeploy`). @@ -55,6 +83,13 @@ object MyDeployment : TerraformAwsSingleEc2Builder(Server) { } ``` +### Base AMI updates + +The instance ignores changes to its base AMI, so a new release never replaces it on its own. Any +replacement moves to the latest release, including one caused by an install script change. To move +on purpose, run `terraform apply -replace=aws_instance.main`. `os-update` patches the running +instance in place. + ## Scaling (ALB + Auto Scaling Group) builder ### Architecture @@ -93,7 +128,8 @@ object MyDeployment : TerraformAwsSingleEc2Builder(Server) { minute. The application JAR and encrypted settings are **not** baked — they are fetched from S3 at boot — so ordinary app deploys never re-bake the AMI. The AMI re-bakes only when the install script changes (its content hash drives the Image Builder component version) or when - `baseImageSalt` is bumped. + `baseImageSalt` is bumped. The base AMI is pinned, so a new release never forces a re-bake on its + own; only a `baseImageSalt` bump (or a `distro` change) moves the base to the latest release. - **Health check = liveness, autodetected:** the ALB target health check defaults to the server's `/meta/online` liveness endpoint, not the deep `/meta/health`, so a slow downstream service can't make the ALB drain the whole fleet. Override `healthCheckPath` if needed. @@ -114,9 +150,10 @@ object MyDeployment : TerraformAwsSingleEc2Builder(Server) { (the ASG scales out on the max of the two, in only when both agree), which catches I/O-bound concurrency saturation that CPU misses. Memory is intentionally an alarm, not a scaling signal (the JVM heap is fixed via `-Xmx`, so RAM is near-constant under load). -- **OS patching:** the bake runs `apt-get upgrade` from the latest Ubuntu base, so re-baking ships - a fully patched image. Drive `baseImageSalt` from a date (e.g. `get() = "2026-06"`) to rebuild on - a schedule, and set `maxInstanceLifetimeSeconds` to force the fleet to rotate onto new AMIs. +- **OS patching:** the bake runs a full system upgrade, so re-baking ships a fully patched image, and a + `baseImageSalt` bump also moves it onto the latest base AMI. Drive `baseImageSalt` from a date + (e.g. `get() = "2026-06"`) to rebuild on a schedule, and set `maxInstanceLifetimeSeconds` to force + the fleet to rotate onto new AMIs. - **Scheduled tasks need no extra infrastructure:** Lightning Server's long-running engines coordinate scheduled tasks across the fleet through the **shared cache** (a distributed lock per schedule). Therefore the scaling builder **requires a distributed cache** (Redis / Memcached / diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt index 9e925058d..955633372 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt @@ -1,6 +1,5 @@ package com.lightningkite.lightningserver.terraform.aws.ec2 -import com.lightningkite.lightningserver.HttpMethod import com.lightningkite.lightningserver.definition.* import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.engine.local.engineCache @@ -148,6 +147,96 @@ public abstract class TerraformAwsEc2BuilderBase( * */ public abstract val instanceArchitecture: CPUArchitecture + public enum class Distro { + /** Ubuntu 24.04 LTS (Noble). */ + Ubuntu2404, + + /** Ubuntu 26.04 LTS (Resolute). */ + Ubuntu2604, + + /** + * Amazon Linux 2023. Its package repositories are versioned and locked to the AMI's release, so + * every system update here passes `--releasever=latest` to pick up fixes published since. + */ + AmazonLinux2023, + } + + /** + * The OS the instances run, [Distro.Ubuntu2404] by default. Changing it on an existing deployment, + * including between Ubuntu releases, replaces the single instance, or re-bakes the scaling + * builder's image and rolls the fleet onto it. + * [additionalPackages] and custom install scripts are distro-specific and must match. + */ + public open val distro: Distro get() = Distro.Ubuntu2404 + + /** + * Root volume device name of [distro]'s AMIs. A block device mapping must name it exactly to + * resize the root volume; any other name attaches a second, empty volume instead. + */ + protected val rootDeviceName: String + get() = when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> "/dev/sda1" + Distro.AmazonLinux2023 -> "/dev/xvda" + } + + /** The `data.aws_ami.base` lookup for the latest [distro] AMI on [instanceArchitecture]. */ + protected fun TerraformJsonObject.baseAmiData() { + "data.aws_ami.base" { + "most_recent" - true + when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> { + val release = if (distro == Distro.Ubuntu2604) "resolute-26.04" else "noble-24.04" + "owners" - listOf("099720109477") + "filter" - listOf( + terraformJsonObject { + "name" - "name" + "values" - listOf("ubuntu/images/hvm-ssd-gp3/ubuntu-$release-${if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "amd64"}-server-*") + }, + terraformJsonObject { + "name" - "architecture" + "values" - listOf(if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "x86_64") + }, + terraformJsonObject { + "name" - "virtualization-type" + "values" - listOf("hvm") + }, + ) + } + + Distro.AmazonLinux2023 -> { + "owners" - listOf("amazon") + "filter" - listOf( + // The standard AMI; `al2023-ami-minimal-*` lacks the SSM agent and CLI tooling. + terraformJsonObject { + "name" - "name" + "values" - listOf("al2023-ami-2023.*-kernel-*-${if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "x86_64"}") + }, + terraformJsonObject { + "name" - "architecture" + "values" - listOf(if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "x86_64") + }, + terraformJsonObject { + "name" - "virtualization-type" + "values" - listOf("hvm") + }, + ) + } + } + } + } + + /** + * An SSM-safe shell command (no double quotes or backslashes) that prints `REBOOT_REQUIRED=yes` or + * `REBOOT_REQUIRED=no` depending on whether a reboot is needed to activate installed updates. + */ + protected val rebootCheckCommand: String + get() = when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> "test -f /var/run/reboot-required && echo REBOOT_REQUIRED=yes || echo REBOOT_REQUIRED=no" + // Exits 1 when a reboot is needed. Any other failure also reads as "yes", which costs at + // most one unnecessary reboot rather than leaving a patched kernel inactive. + Distro.AmazonLinux2023 -> "dnf needs-restarting -r >/dev/null 2>&1 && echo REBOOT_REQUIRED=no || echo REBOOT_REQUIRED=yes" + } + /** EBS volume size in GiB. */ public open val volumeSizeGiB: Int get() = 20 @@ -185,7 +274,7 @@ public abstract class TerraformAwsEc2BuilderBase( // === Customization Hooks === - /** Additional packages to install on EC2 instances. */ + /** Additional packages to install on EC2 instances, named as [distro]'s package manager knows them. */ public open val additionalPackages: List = emptyList() public enum class JavaVersion(public val outputString: String) { @@ -198,7 +287,10 @@ public abstract class TerraformAwsEc2BuilderBase( public open val javaVersion: JavaVersion get() = JavaVersion.V_17 - /** Seconds apt waits for the dpkg lock (held briefly at boot by Ubuntu's apt-daily) before failing. */ + /** + * Seconds apt waits for the dpkg lock (held briefly at boot by Ubuntu's apt-daily) before failing. + * Ubuntu only; dnf waits for its own lock. + */ public open val aptLockTimeoutSeconds: Int get() = 600 /** @@ -697,8 +789,9 @@ public abstract class TerraformAwsEc2BuilderBase( */ // language="Shell Script" protected fun StringBuilder.disableUnattendedUpgrades() { - appendLine( - """ + when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> appendLine( + """ # === Disable unattended upgrades === echo "[INFO] Disabling unattended-upgrades and apt daily timers at $(date)" cat > /etc/apt/apt.conf.d/20auto-upgrades << 'AUTO_UPGRADES_EOF' @@ -712,29 +805,69 @@ systemctl mask unattended-upgrades.service || true systemctl disable --now apt-daily.timer apt-daily-upgrade.timer || true systemctl mask apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service || true """ - ) + ) + + Distro.AmazonLinux2023 -> + // AL2023 installs no automatic updater. Keep dnf-automatic off should a custom step add it, + // and stop the metadata refresh timer racing the provisioning script for the dnf lock. + appendLine( + """ +# === Disable unattended upgrades === +echo "[INFO] Disabling dnf automatic update and metadata timers at $(date)" +systemctl disable --now dnf-automatic.timer dnf-automatic-install.timer || true +systemctl disable --now dnf-makecache.timer || true +systemctl mask dnf-makecache.timer || true +""" + ) + } } /** Brings the OS fully up to date and installs the JRE, base tooling, and [additionalPackages]. */ // language="Shell Script" protected fun StringBuilder.systemPackages() { - // A freshly-booted Ubuntu holds the dpkg lock for the first few minutes (apt-daily/ - // unattended-upgrades); wait for it instead of failing or appearing to hang. - val apt = "apt-get -o DPkg::Lock::Timeout=$aptLockTimeoutSeconds" - appendLine("# === System update + base packages ===") - appendLine("""echo "[INFO] Updating system packages at $(date)"""") - appendLine("$apt update -y") - // --with-new-pkgs because a plain `upgrade` never installs new packages, and kernel - // security updates arrive as a new package name (linux-image-X-generic) pulled in by a - // dependency change on the metapackage. Without it they are silently held back. - appendLine("$apt -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold upgrade --with-new-pkgs") - appendLine("$apt install -y openjdk-${javaVersion.outputString}-jre-headless openssl curl gnupg ca-certificates unzip") - if (additionalPackages.isNotEmpty()) { - appendLine("echo \"[INFO] Installing additional packages at \$(date)\"") - appendLine("$apt install -y ${additionalPackages.joinToString(" ") { it.shellEscape() }}") + when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> { + // A freshly-booted Ubuntu holds the dpkg lock for the first few minutes (apt-daily/ + // unattended-upgrades); wait for it instead of failing or appearing to hang. + val apt = "apt-get -o DPkg::Lock::Timeout=$aptLockTimeoutSeconds" + appendLine("# === System update + base packages ===") + appendLine("""echo "[INFO] Updating system packages at $(date)"""") + appendLine("$apt update -y") + // --with-new-pkgs because a plain `upgrade` never installs new packages, and kernel + // security updates arrive as a new package name (linux-image-X-generic) pulled in by a + // dependency change on the metapackage. Without it they are silently held back. + appendLine("$apt -y -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold upgrade --with-new-pkgs") + appendLine("$apt install -y openjdk-${javaVersion.outputString}-jre-headless openssl curl gnupg ca-certificates unzip") + if (additionalPackages.isNotEmpty()) { + appendLine("echo \"[INFO] Installing additional packages at \$(date)\"") + appendLine("$apt install -y ${additionalPackages.joinToString(" ") { it.shellEscape() }}") + } + appendLine("$apt -y autoremove") + appendLine() + } + + Distro.AmazonLinux2023 -> { + appendLine("# === System update + base packages ===") + appendLine("""echo "[INFO] Updating system packages at $(date)"""") + // The repositories are locked to the AMI's release, so a plain upgrade would miss every + // update published since. --releasever=latest moves the system to the newest release. + appendLine("dnf -y --releasever=latest upgrade") + // curl, gnupg, and ca-certificates ship in the AMI (curl and gnupg as their -minimal + // variants, which installing the full packages would conflict with). Corretto 8 has no + // separate headless package. + val jre = when (javaVersion) { + JavaVersion.V_8 -> "java-1.8.0-amazon-corretto" + else -> "java-${javaVersion.outputString}-amazon-corretto-headless" + } + appendLine("dnf install -y $jre openssl unzip") + if (additionalPackages.isNotEmpty()) { + appendLine("echo \"[INFO] Installing additional packages at \$(date)\"") + appendLine("dnf install -y ${additionalPackages.joinToString(" ") { it.shellEscape() }}") + } + appendLine("dnf -y autoremove") + appendLine() + } } - appendLine("$apt -y autoremove") - appendLine() } /** Render [customInstallScripts] and [customInstallScriptsRaw] into the provisioning script. */ @@ -818,12 +951,15 @@ systemctl mask apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-dai // language="Shell Script" protected fun StringBuilder.ssm() { - appendLine( - $$""" + + when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> { + appendLine( + $$""" # === SSM Agent === echo "[INFO] Ensuring SSM agent is installed and running at $(date)" # Required so terraform can drive in-place jar/settings redeploys via -# `aws ssm send-command`. Ubuntu 24.04 ships amazon-ssm-agent as a snap; install if missing, +# `aws ssm send-command`. Ubuntu ships amazon-ssm-agent as a snap; install if missing, # then enable + start so newly-created instances register with SSM. if ! snap list amazon-ssm-agent >/dev/null 2>&1; then snap install amazon-ssm-agent --classic @@ -831,7 +967,24 @@ if ! snap list amazon-ssm-agent >/dev/null 2>&1; then systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service fi """ - ) + ) + } + + Distro.AmazonLinux2023 -> { + appendLine( + """ +# === SSM Agent === +echo "[INFO] Ensuring SSM agent is installed and running at $(date)" +# Required so terraform can drive in-place jar/settings redeploys via +# `aws ssm send-command`. The AL2023 AMI ships amazon-ssm-agent as an RPM; install if missing, +# then enable + start so newly-created instances register with SSM. +rpm -q amazon-ssm-agent >/dev/null 2>&1 || dnf install -y amazon-ssm-agent +systemctl enable amazon-ssm-agent +systemctl start amazon-ssm-agent +""" + ) + } + } } /** Write the CloudWatch agent config (log groups + metrics) and enable the service. */ @@ -902,7 +1055,7 @@ systemctl restart amazon-cloudwatch-agent * it enabled for the next boot instead. * * That immediate activation is deliberately non-fatal. The caller's script runs under `set -e`, and - * losing the entire bootstrap — Angie, the systemd unit, the first deploy — because an overflow + * losing the entire bootstrap — nginx, the systemd unit, the first deploy — because an overflow * safety net could not be allocated is a far worse outcome than running without swap. It also matches * the scaling path, where the baked unit is only ordered before the app, never required by it. */ @@ -1360,7 +1513,7 @@ chmod 0700 /usr/local/bin/$$projectPrefix-settings-key # update-fleet.sh drives it one drained instance at a time; routine patching there still # comes from rebuilding the image and rolling the ASG. # -# It restarts the app unconditionally (the JRE is an apt package and may be replaced +# It restarts the app unconditionally (the JRE is a system package and may be replaced # underneath a running JVM), so it is only interruption-free on an instance already # drained from the load balancer. # @@ -1384,6 +1537,43 @@ chown lightning-server:lightning-server "$LOG_FILE" exec > >(tee -a "$LOG_FILE" | logger -t os-update -s) 2>&1 log "OS update started" +$${osUpdatePackageSteps()} + +log "Restarting $$deploymentTag" +systemctl restart $$projectPrefix +sleep 5 +if ! systemctl is-active --quiet $$projectPrefix; then + err "Service failed to start after OS update" + tail -n 100 /var/log/$$projectPrefix/server.log >&2 || true + exit 1 +fi + +log "Waiting for liveness at $$localHealthUrl" +healthy=0 +for i in $(seq 1 20); do + if curl -fsS -o /dev/null --max-time 5 "$$localHealthUrl"; then healthy=1; break; fi + sleep 3 +done +if [ "$healthy" -ne 1 ]; then + err "Liveness endpoint $$localHealthUrl never returned success" + tail -n 100 /var/log/$$projectPrefix/server.log >&2 || true + exit 1 +fi + +$${osUpdateRebootBreadcrumb()} +log "Done" +UPDATE_EOF + +chmod +x /usr/local/bin/os-update +echo "[INFO] Creating OS Emergency Update Script - DONE" +""" + ) + } + + /** The package refresh and upgrade at the heart of [instanceUpdateScript], for [distro]. */ + // language="Shell Script" + private fun osUpdatePackageSteps(): String = when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> $$""" apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds update -y # Keep existing config files on conflict; an interactive dpkg prompt would hang the SSM command. @@ -1413,41 +1603,55 @@ else # happily purge old kernels and anything else currently marked auto-and-no-longer-needed, # which is not a blast radius to take on while chasing a single CVE. apt-get $APT_OPTS autoremove -fi - -log "Restarting $$deploymentTag" -systemctl restart $$projectPrefix -sleep 5 -if ! systemctl is-active --quiet $$projectPrefix; then - err "Service failed to start after OS update" - tail -n 100 /var/log/$$projectPrefix/server.log >&2 || true - exit 1 -fi - -log "Waiting for liveness at $$localHealthUrl" -healthy=0 -for i in $(seq 1 20); do - if curl -fsS -o /dev/null --max-time 5 "$$localHealthUrl"; then healthy=1; break; fi - sleep 3 -done -if [ "$healthy" -ne 1 ]; then - err "Liveness endpoint $$localHealthUrl never returned success" - tail -n 100 /var/log/$$projectPrefix/server.log >&2 || true - exit 1 -fi +fi""".removePrefix("\n") + + Distro.AmazonLinux2023 -> """ +# The repositories are locked to the release this host is on, so a plain upgrade only sees fixes +# already in that release; every fix published since would be silently missed while the update +# reported success. --releasever=latest moves to the newest release first. +DNF_OPTS="-y --releasever=latest" +if [ -n "${'$'}PACKAGES" ]; then + # `dnf upgrade` exits 0 for a package that is not installed, so a typo'd or wrong-architecture + # name would report a clean patch while changing nothing at all. Check each name up front and + # fail loudly instead. + for p in ${'$'}PACKAGES; do + if ! rpm -q "${'$'}p" >/dev/null 2>&1; then + err "not installed on this host, refusing to report a successful update: ${'$'}p" + exit 1 + fi + done + log "Upgrading only: ${'$'}PACKAGES" + dnf ${'$'}DNF_OPTS upgrade ${'$'}PACKAGES +else + log "Applying full upgrade" + dnf ${'$'}DNF_OPTS upgrade + # Deliberately only on the full-upgrade path. Naming packages means the operator asked for a minimal, + # auditable change to one or two packages; autoremove is a whole-system operation, which is not a + # blast radius to take on while chasing a single CVE. + dnf -y autoremove +fi""".removePrefix("\n") + } -# Breadcrumb for the CloudWatch log; a reboot is needed to activate a patched kernel. Callers that -# act on it (update-fleet.sh) probe /var/run/reboot-required with their own SSM command rather than -# reading this back, because SSM truncates command output at 24,000 characters per stream and a -# full apt upgrade can push a trailing marker past that cap. -if [ -f /var/run/reboot-required ]; then log "REBOOT_REQUIRED=yes"; else log "REBOOT_REQUIRED=no"; fi -log "Done" -UPDATE_EOF + /** The `REBOOT_REQUIRED=` log line [instanceUpdateScript] ends with, for [distro]. */ + // language="Shell Script" + private fun osUpdateRebootBreadcrumb(): String = when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> { + """ + # Breadcrumb for the CloudWatch log; a reboot is needed to activate a patched kernel. Callers that + # act on it (update-fleet.sh) probe /var/run/reboot-required with their own SSM command rather than + # reading this back, because SSM truncates command output at 24,000 characters per stream and a + # full apt upgrade can push a trailing marker past that cap. + if [ -f /var/run/reboot-required ]; then log "REBOOT_REQUIRED=yes"; else log "REBOOT_REQUIRED=no"; fi""".trimIndent() + } -chmod +x /usr/local/bin/os-update -echo "[INFO] Creating OS Emergency Update Script - DONE" -""" - ) + Distro.AmazonLinux2023 -> { + """ + # Breadcrumb for the CloudWatch log; a reboot is needed to activate a patched kernel. Callers that + # act on it (update-fleet.sh) run their own reboot check over SSM rather than reading this back, + # because SSM truncates command output at 24,000 characters per stream and a full upgrade can push + # a trailing marker past that cap. needs-restarting exits 1 when a reboot is needed. + if dnf needs-restarting -r >/dev/null 2>&1; then log "REBOOT_REQUIRED=no"; else log "REBOOT_REQUIRED=yes"; fi""".trimIndent() + } } /** diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsScalingEc2Builder.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsScalingEc2Builder.kt index 40cbcb161..79d6403c5 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsScalingEc2Builder.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsScalingEc2Builder.kt @@ -161,7 +161,9 @@ public abstract class TerraformAwsScalingEc2Builder( /** * Salt folded into the golden-AMI version. Bump this to force a re-bake even when the install * script itself has not changed — which is how you pick up OS security patches: a re-bake - * starts from the latest Ubuntu base and re-runs `apt-get upgrade`. To rebuild on a schedule + * re-runs the full system upgrade. This is also the only thing that moves the base AMI: a bump + * re-resolves it to the latest release, whereas a newly published release on its own, or a + * re-bake from an install script change, stays on the current base. To rebuild on a schedule * (e.g. monthly), drive this from a date, for example `get() = "2026-06"`; changing it on * each apply produces a fresh, fully-patched AMI and a rolling instance refresh onto it. */ @@ -339,28 +341,30 @@ public abstract class TerraformAwsScalingEc2Builder( * while leaving its version alone, which is the same rejection one resource over. */ private val imageVersion: String - get() = "1.${expression("regex(\"[0-9]{8}\", data.aws_ami.ubuntu.name)")}.${expression("local.image_data_version")}" + get() = "1.${expression("regex(\"[0-9]{8}\", terraform_data.base_ami.output.name)")}.${expression("local.image_data_version")}" private fun emitImageBuilder() { emit("image") { - // Base Ubuntu 24.04 AMI used as the Image Builder parent image. - "data.aws_ami.ubuntu" { - "most_recent" - true - "owners" - listOf("099720109477") - "filter" - listOf( - terraformJsonObject { - "name" - "name" - "values" - listOf("ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-${if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "amd64"}-server-*") - }, - terraformJsonObject { - "name" - "architecture" - "values" - listOf(if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "x86_64") - }, - terraformJsonObject { - "name" - "virtualization-type" - "values" - listOf("hvm") - }, - ) + // Latest base AMI for the distro. Only read through terraform_data.base_ami below. + baseAmiData() + + // The Image Builder parent image, pinned so a new base AMI release can't force a re-bake and + // instance refresh during an unrelated apply. Bumping [baseImageSalt] or changing [distro] + // replaces this resource, which re-resolves it to the latest AMI: ignore_changes does not + // apply on replacement. The distro must be a trigger too, or a distro change would bake the + // new install script on top of the old distro's pinned image. + "resource.terraform_data.base_ami" { + "input" { + "id" - expression("data.aws_ami.base.id") + "name" - expression("data.aws_ami.base.name") + } + "triggers_replace" { + "salt" - expression("local.image_salt") + "distro" - distro.name + } + "lifecycle" { + "ignore_changes" - listOf("input") + } } // IAM role/instance-profile for the transient Image Builder build instance. @@ -418,7 +422,7 @@ public abstract class TerraformAwsScalingEc2Builder( "resource.aws_imagebuilder_image_recipe.this" { "name" - "$projectPrefix-recipe" "version" - imageVersion - "parent_image" - expression("data.aws_ami.ubuntu.id") + "parent_image" - expression("terraform_data.base_ami.output.id") // Ordered: required + additional installs first, then our custom component, then hardening // last so it locks down the fully-built image. "component" - buildList { @@ -427,7 +431,7 @@ public abstract class TerraformAwsScalingEc2Builder( hardeningComponents.forEach { add(it.toRecipeComponent()) } } "block_device_mapping" { - "device_name" - "/dev/sda1" + "device_name" - rootDeviceName "ebs" { "volume_size" - volumeSizeGiB "volume_type" - "gp3" @@ -444,7 +448,7 @@ public abstract class TerraformAwsScalingEc2Builder( "name" - "$projectPrefix-infra" "instance_profile_name" - expression("aws_iam_instance_profile.imagebuilder.name") "instance_types" - listOf(instanceType) - // Build in a private subnet (no public IP); egress for apt/curl/SSM goes through + // Build in a private subnet (no public IP); egress for packages/curl/SSM goes through // NAT, and S3 through the gateway endpoint. No reason to expose the build host. "subnet_id" - expression("${applicationVpc.privateSubnets.trimExpression()}[0]") "security_group_ids" - listOf(expression("aws_security_group.instance.id")) @@ -492,10 +496,14 @@ public abstract class TerraformAwsScalingEc2Builder( // The recipe's own inputs, which are versioned by [imageVersion] just like the // component document is. `parent_image` is not covered by the date in the minor // node: two AMIs published on one day (a same-day republish, or the arm64 and - // amd64 builds of the same release) share that date, so only the id separates - // them -- and the id moving is exactly what a re-bake exists for. + // amd64 builds of the same release) share that date, so only the id separates them. + // + // Named base_ami rather than parent_image so the hash differs from deployments made + // before the pin existed. A brand-new terraform_data's output is unknown at plan time, + // which plans a replacement of the component and recipe; if they came back at their + // old version, AWS would reject them. "image_recipe_inputs" { - "parent_image" - expression("data.aws_ami.ubuntu.id") + "base_ami" - expression("terraform_data.base_ami.output.id") "volume_size" - volumeSizeGiB } "image_data_version" - expression( @@ -801,7 +809,7 @@ $indentedScript "http_put_response_hop_limit" - 1 } "block_device_mappings" { - "device_name" - "/dev/sda1" + "device_name" - rootDeviceName "ebs" { "volume_size" - volumeSizeGiB "volume_type" - "gp3" @@ -1292,7 +1300,7 @@ run_update() { needs_reboot() { local id="$1" out out=$(ssm_run "$id" 60 24 "reboot check" \ - "test -f /var/run/reboot-required && echo REBOOT_REQUIRED=yes || echo REBOOT_REQUIRED=no") || return 2 + "$$rebootCheckCommand") || return 2 case "$out" in *REBOOT_REQUIRED=yes*) return 0 ;; *REBOOT_REQUIRED=no*) return 1 ;; diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt index 7d1566e09..21588cb06 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt @@ -9,8 +9,9 @@ import com.lightningkite.services.terraform.* * Terraform builder for deploying Lightning Server to a single AWS EC2 instance. * * This is the simplest, cheapest deployment: one instance with an Elastic IP, running the - * application behind an on-box Angie (nginx fork) reverse proxy that terminates TLS via the - * Let's Encrypt ACME client. Route53 A/AAAA records point straight at the instance, and + * application behind an on-box nginx reverse proxy that terminates TLS with a Let's Encrypt + * certificate it obtains and renews itself through `nginx-module-acme`. Route53 A/AAAA records + * point straight at the instance, and * code/settings updates are pushed in-place to that one instance via SSM Run Command. * * For a horizontally-scaled, load-balanced deployment see [TerraformAwsScalingEc2Builder]. @@ -97,7 +98,7 @@ public abstract class TerraformAwsSingleEc2Builder( emptyList() // Example: ::/0, would allow everyone in the world to attempt to ssh in - /** Direct application only accessible internally; we force using Angie. */ + /** Direct application only accessible internally; we force using nginx. */ override val appBindsAllNetworkInterfaces: Boolean get() = false override fun registerProviders() { @@ -153,7 +154,7 @@ public abstract class TerraformAwsSingleEc2Builder( "depends_on" - listOfNotNull( "null_resource.upload_jar", "null_resource.upload_settings", - "aws_instance.ubuntu", + "aws_instance.main", "aws_iam_role_policy_attachment.ssm", "aws_iam_role_policy_attachment.servicesAccess", if (enableIPv4) "aws_eip_association.main" else null, @@ -161,37 +162,19 @@ public abstract class TerraformAwsSingleEc2Builder( ) "provisioner" { "local-exec" { - "command" - $$"bash ${path.module}/redeploy.sh ${aws_instance.ubuntu.id} $$applicationRegion" + "command" - $$"bash ${path.module}/redeploy.sh ${aws_instance.main.id} $$applicationRegion" } } } } emit("ec2") { - // Get latest Ubuntu 24.04 AMI - "data.aws_ami.ubuntu" { - "most_recent" - true - "owners" - listOf("099720109477") - - "filter" - listOf( - terraformJsonObject { - "name" - "name" - "values" - listOf("ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-${if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "amd64"}-server-*") - }, - terraformJsonObject { - "name" - "architecture" - "values" - listOf(if (instanceArchitecture == CPUArchitecture.Arm) "arm64" else "x86_64") - }, - terraformJsonObject { - "name" - "virtualization-type" - "values" - listOf("hvm") - } - ) - } + // Get latest base AMI for the distro + baseAmiData() // EC2 Instance - "resource.aws_instance.ubuntu" { - "ami" - expression("data.aws_ami.ubuntu.id") + "resource.aws_instance.main" { + "ami" - expression("data.aws_ami.base.id") "instance_type" - instanceType "iam_instance_profile" - expression("aws_iam_instance_profile.ec2.name") @@ -243,6 +226,13 @@ public abstract class TerraformAwsSingleEc2Builder( "Name" - deploymentTag } + // A new base AMI release must not replace the only instance during an unrelated apply. + // ignore_changes does not apply on replacement, so any replacement (an init script + // change, or `terraform apply -replace`) still moves to the latest AMI. + "lifecycle" { + "ignore_changes" - listOf("ami") + } + "depends_on" - (listOf( "null_resource.upload_jar", "null_resource.upload_settings", @@ -311,7 +301,7 @@ public abstract class TerraformAwsSingleEc2Builder( "name" - domain "type" - "AAAA" "ttl" - 300 - "records" - listOf(expression("aws_instance.ubuntu.ipv6_addresses[0]")) + "records" - listOf(expression("aws_instance.main.ipv6_addresses[0]")) } @@ -331,7 +321,7 @@ public abstract class TerraformAwsSingleEc2Builder( "name" - wsDomain "type" - "AAAA" "ttl" - 300 - "records" - listOf(expression("aws_instance.ubuntu.ipv6_addresses[0]")) + "records" - listOf(expression("aws_instance.main.ipv6_addresses[0]")) } } } @@ -369,7 +359,7 @@ public abstract class TerraformAwsSingleEc2Builder( "treat_missing_data" - "breaching" "dimensions" { - "InstanceId" - expression("aws_instance.ubuntu.id") + "InstanceId" - expression("aws_instance.main.id") } "alarm_actions" - listOf(expression("aws_sns_topic.emergency.arn")) @@ -388,7 +378,7 @@ public abstract class TerraformAwsSingleEc2Builder( "alarm_description" - "High CPU utilization" "dimensions" { - "InstanceId" - expression("aws_instance.ubuntu.id") + "InstanceId" - expression("aws_instance.main.id") } "alarm_actions" - listOf(expression("aws_sns_topic.emergency.arn")) @@ -406,7 +396,7 @@ public abstract class TerraformAwsSingleEc2Builder( "comparison_operator" - "GreaterThanThreshold" "dimensions" { - "InstanceId" - expression("aws_instance.ubuntu.id") + "InstanceId" - expression("aws_instance.main.id") } "alarm_actions" - listOf(expression("aws_sns_topic.emergency.arn")) @@ -424,7 +414,7 @@ public abstract class TerraformAwsSingleEc2Builder( "comparison_operator" - "GreaterThanThreshold" "dimensions" { - "InstanceId" - expression("aws_instance.ubuntu.id") + "InstanceId" - expression("aws_instance.main.id") } "alarm_actions" - listOf(expression("aws_sns_topic.emergency.arn")) @@ -450,7 +440,7 @@ public abstract class TerraformAwsSingleEc2Builder( } "resource.aws_eip_association.main" { - "instance_id" - expression("aws_instance.ubuntu.id") + "instance_id" - expression("aws_instance.main.id") "allocation_id" - expression("aws_eip.main.id") } } @@ -586,8 +576,16 @@ exec > >(tee /var/log/$$projectPrefix/ec2_init.log | logger -t ec2_init -s) 2>&1 # === Bootstrap packages === # Just enough to fetch ec2_init.sh; the full system update and package install happen there. echo "[INFO] Installing bootstrap packages..." -apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds update -y -apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds install -y curl ca-certificates unzip +$${ + when (distro) { + Distro.Ubuntu2404, Distro.Ubuntu2604 -> """ +apt-get -o DPkg::Lock::Timeout=$aptLockTimeoutSeconds update -y +apt-get -o DPkg::Lock::Timeout=$aptLockTimeoutSeconds install -y curl ca-certificates unzip +""".trim() + // curl (as curl-minimal) and ca-certificates ship in the AMI. + Distro.AmazonLinux2023 -> "dnf install -y unzip" + } + } """ ) @@ -633,7 +631,7 @@ rm ec2_init.sh set -euo pipefail export DEBIAN_FRONTEND=noninteractive -echo "[INFO] EC2 Init script started at $(date)" +echo "[INFO] EC2 Init script started on ${distro.name} at $(date)" """ ) @@ -648,7 +646,7 @@ echo "[INFO] EC2 Init script started at $(date)" cloudwatchAgent(emitter.applicationRegion) - angieInstall() + nginxInstall() ssm() @@ -659,7 +657,7 @@ echo "[INFO] EC2 Init script started at $(date)" val localHealthUrl = "http://localhost:8080${healthCheckPath}" // The single instance fills the bucket name via terraform templatefile() and the - // region is a compile-time constant. The app listens on appPort behind Angie. + // region is a compile-time constant. The app listens on appPort behind nginx. instanceRedeployScript( $$"""BUCKET="${deployment_bucket}" REGION="$$applicationRegion"""", @@ -689,8 +687,8 @@ echo "[INFO] Running first-time application deploy..." # === Start Services === echo "[INFO] Starting services..." -systemctl enable angie -systemctl restart angie +systemctl enable nginx +systemctl restart nginx """ ) @@ -722,10 +720,21 @@ echo "[INFO] EC2 Init script completed in $BOOT_DURATION seconds" } /** - * Download + install the CloudWatch agent .deb. The scaling builder installs the agent via the + * Install the CloudWatch agent (a downloaded .deb on Ubuntu, dnf on Amazon Linux). The scaling builder installs the agent via the * AWS-managed `amazon-cloudwatch-agent-linux` component instead, so it only needs [cloudwatchAgentConfig]. */ private fun StringBuilder.cloudwatchAgentInstall(applicationRegion: String) { + if (distro == Distro.AmazonLinux2023) { + // Packaged in the AL2023 repositories. + appendLine( + """ +# === Install CloudWatch Agent === +echo "[INFO] Installing CloudWatch Agent at $(date)" +dnf install -y amazon-cloudwatch-agent +""" + ) + return + } appendLine( $$""" # === Install CloudWatch Agent === @@ -765,9 +774,11 @@ rm -rf aws/ awscliv2.zip ) } - private fun StringBuilder.angieInstall() { - - fun outputServer(domain: String, includeUpgrade: Boolean): String = $$""" + /** + * The `server` blocks for [domain]: a catch-all that drops unknown hosts, an HTTP-to-HTTPS redirect, + * and the TLS proxy to the app. + */ + private fun nginxServers(domain: String, includeUpgrade: Boolean): String = $$""" # Drop requests for any other host name or a bare IP server { listen 80 default_server; @@ -778,7 +789,7 @@ server { return 444; } -# HTTP: redirect to HTTPS (Angie answers ACME challenges before this) +# HTTP: redirect to HTTPS (nginx-module-acme answers ACME challenges before this) server { listen 80; listen [::]:80; @@ -792,9 +803,11 @@ server { listen [::]:443 ssl; http2 on; - acme letsencrypt; - ssl_certificate $acme_cert_letsencrypt; - ssl_certificate_key $acme_cert_key_letsencrypt; + acme_certificate letsencrypt; + ssl_certificate $acme_certificate; + ssl_certificate_key $acme_certificate_key; + # Variable certificate paths are otherwise re-read on every handshake. + ssl_certificate_cache max=2; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305; @@ -831,22 +844,47 @@ $${ } """ + /** Installs nginx and nginx-module-acme from nginx.org's repository, then writes the proxy config. */ + private fun StringBuilder.nginxInstall() { + val repository = when (distro) { + // nginx.org's packages over Ubuntu's own nginx, which nginx-module-acme is not built against. + Distro.Ubuntu2404, Distro.Ubuntu2604 -> $$""" +install -d -m 0755 /etc/apt/keyrings +curl -fsSL -o /etc/apt/keyrings/nginx.asc https://nginx.org/keys/nginx_signing.key +echo "deb [signed-by=/etc/apt/keyrings/nginx.asc] https://nginx.org/packages/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") nginx" \ + > /etc/apt/sources.list.d/nginx.list +printf 'Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n' > /etc/apt/preferences.d/99nginx +apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds update -y +apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds install -y nginx nginx-module-acme""" + + // priority=9 prefers nginx.org's packages over AL2023's own nginx, which ships no ACME module. + Distro.AmazonLinux2023 -> """ +cat > /etc/yum.repos.d/nginx.repo << 'NGINX_REPO_EOF' +[nginx-stable] +name=nginx stable repo +baseurl=https://nginx.org/packages/amzn/2023/${'$'}basearch/ +gpgcheck=1 +enabled=1 +gpgkey=https://nginx.org/keys/nginx_signing.key +module_hotfixes=true +priority=9 +NGINX_REPO_EOF +dnf install -y nginx nginx-module-acme""" + } + // language="Shell Script" appendLine( $$""" -# === Install Angie + ACME module === -echo "[INFO] Installing Angie $(date)" -curl -o /etc/apt/trusted.gpg.d/angie-signing.gpg \ - https://angie.software/keys/angie-signing.gpg -echo "deb https://download.angie.software/angie/$(. /etc/os-release && echo "$ID/$VERSION_ID $VERSION_CODENAME") main" \ - | tee /etc/apt/sources.list.d/angie.list > /dev/null -apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds update -y -apt-get -o DPkg::Lock::Timeout=$$aptLockTimeoutSeconds install -y angie - -# === Angie config (built-in ACME client handles cert issuance + renewal) === -echo "[INFO] Creating server.conf for Angie $(date)" -rm -f /etc/angie/http.d/default.conf -cat > /etc/angie/http.d/server.conf << 'NGX_EOF' +# === Install nginx + ACME module === +echo "[INFO] Installing nginx $(date)"$$repository + +# === nginx config (nginx-module-acme handles cert issuance + renewal) === +echo "[INFO] Creating server.conf for nginx $(date)" +# The ACME module is dynamic, and load_module is only valid at the top level of nginx.conf. +grep -q 'ngx_http_acme_module' /etc/nginx/nginx.conf \ + || sed -i '1i load_module modules/ngx_http_acme_module.so;' /etc/nginx/nginx.conf +rm -f /etc/nginx/conf.d/default.conf +cat > /etc/nginx/conf.d/server.conf << 'NGX_EOF' resolver 8.8.8.8 1.1.1.1 ipv6=off; resolver_timeout 5s; @@ -862,9 +900,13 @@ upstream app { keepalive_requests 1000; } -acme_client letsencrypt https://acme-v02.api.letsencrypt.org/directory; -$${outputServer(domain, wsDomain == domain)} -$${if (wsDomain != domain) outputServer(wsDomain, true) else ""} +acme_issuer letsencrypt { + uri https://acme-v02.api.letsencrypt.org/directory; + state_path /var/cache/nginx/acme-letsencrypt; + accept_terms_of_service; +} +$${nginxServers(domain, wsDomain == domain)} +$${if (wsDomain != domain) nginxServers(wsDomain, true) else ""} NGX_EOF """ ) diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/otel-collector-ec2.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/otel-collector-ec2.kt index 2a4b0c66c..1d4c0666c 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/otel-collector-ec2.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/otel-collector-ec2.kt @@ -290,6 +290,7 @@ public fun TerraformNeed.otelXRay( emitter.provisioningFragments += adotProvisioningFragment( adotVersion = adotVersion, arch = if (emitter.instanceArchitecture == TerraformAwsEc2BuilderBase.CPUArchitecture.Arm) "arm64" else "amd64", + distro = emitter.distro, region = emitter.applicationRegion, namespace = emitter.projectPrefix, enableMetrics = enableMetrics, @@ -300,12 +301,13 @@ public fun TerraformNeed.otelXRay( } /** - * Builds the shell fragment that installs the ADOT collector `.deb`, writes its config to the - * package's default config path, and `enable`s the packaged systemd service. + * Builds the shell fragment that installs the ADOT collector package (`.deb` or `.rpm` per [distro]), + * writes its config to the package's default config path, and `enable`s the packaged systemd service. */ private fun adotProvisioningFragment( adotVersion: String, arch: String, + distro: TerraformAwsEc2BuilderBase.Distro, region: String, namespace: String, enableMetrics: Boolean, @@ -351,9 +353,19 @@ exporters: return buildString { appendLine("# === AWS Distro for OpenTelemetry collector ===") appendLine("echo \"[INFO] Installing ADOT collector $adotVersion at \$(date)\"") - appendLine("curl -fsSL -o /tmp/aws-otel-collector.deb https://aws-otel-collector.s3.amazonaws.com/ubuntu/$arch/$adotVersion/aws-otel-collector.deb") - appendLine("dpkg -i /tmp/aws-otel-collector.deb") - appendLine("rm -f /tmp/aws-otel-collector.deb") + when (distro) { + TerraformAwsEc2BuilderBase.Distro.Ubuntu2404, TerraformAwsEc2BuilderBase.Distro.Ubuntu2604 -> { + appendLine("curl -fsSL -o /tmp/aws-otel-collector.deb https://aws-otel-collector.s3.amazonaws.com/ubuntu/$arch/$adotVersion/aws-otel-collector.deb") + appendLine("dpkg -i /tmp/aws-otel-collector.deb") + appendLine("rm -f /tmp/aws-otel-collector.deb") + } + + TerraformAwsEc2BuilderBase.Distro.AmazonLinux2023 -> { + appendLine("curl -fsSL -o /tmp/aws-otel-collector.rpm https://aws-otel-collector.s3.amazonaws.com/amazon_linux/$arch/$adotVersion/aws-otel-collector.rpm") + appendLine("dnf install -y /tmp/aws-otel-collector.rpm") + appendLine("rm -f /tmp/aws-otel-collector.rpm") + } + } appendLine() appendLine("cat > /opt/aws/aws-otel-collector/etc/config.yaml << 'ADOT_CONFIG_EOF'") appendLine(config) diff --git a/deploy-aws-ec2/src/test/kotlin/com/lightningkite/lightningserver/terraform/awsec2/Ec2BuilderGenerationTest.kt b/deploy-aws-ec2/src/test/kotlin/com/lightningkite/lightningserver/terraform/awsec2/Ec2BuilderGenerationTest.kt index 2d94efb54..b07ece153 100644 --- a/deploy-aws-ec2/src/test/kotlin/com/lightningkite/lightningserver/terraform/awsec2/Ec2BuilderGenerationTest.kt +++ b/deploy-aws-ec2/src/test/kotlin/com/lightningkite/lightningserver/terraform/awsec2/Ec2BuilderGenerationTest.kt @@ -245,7 +245,7 @@ class Ec2BuilderGenerationTest { assertContains(types, "aws_instance") assertContains(types, "aws_eip") // IMDSv2 must be enforced on the instance. - val httpTokens = d.terraformRoot.findResource("aws_instance", "ubuntu")!! + val httpTokens = d.terraformRoot.findResource("aws_instance", "main")!! .let { it["metadata_options"]!!.jsonObject["http_tokens"]!!.jsonPrimitive.content } assertEquals("required", httpTokens) } @@ -286,6 +286,38 @@ class Ec2BuilderGenerationTest { assertNull(d.terraformRoot.findResource("aws_autoscaling_policy", "requests")) } + @Test + fun scalingPinsBaseAmiToSalt() { + val d = ScalingDeployment() + d.write() + val pin = d.terraformRoot.findResource("terraform_data", "base_ami")!! + val triggers = pin["triggers_replace"]!!.jsonObject + assertEquals("\${local.image_salt}", triggers["salt"]!!.jsonPrimitive.content) + assertEquals("Ubuntu2404", triggers["distro"]!!.jsonPrimitive.content) + val ignore = pin["lifecycle"]!!.jsonObject["ignore_changes"]!!.jsonArray.map { it.jsonPrimitive.content } + assertEquals(listOf("input"), ignore) + val recipe = d.terraformRoot.findResource("aws_imagebuilder_image_recipe", "this")!! + assertEquals("\${terraform_data.base_ami.output.id}", recipe["parent_image"]!!.jsonPrimitive.content) + assertContains(recipe["version"]!!.jsonPrimitive.content, "terraform_data.base_ami.output.name") + // The pin's own input must be the only path from the live lookup into the image, or a new + // Ubuntu release could still force a re-bake. + val image = File(d.terraformRoot, "image.tf.json").readText() + assertEquals(2, Regex("""data\.aws_ami\.base""").findAll(image).count()) + } + + @Test + fun singleInstanceIgnoresBaseAmiChanges() { + val d = SingleDeployment() + d.write() + val instance = d.terraformRoot.findResource("aws_instance", "main")!! + val ignore = instance["lifecycle"]!!.jsonObject["ignore_changes"]!!.jsonArray.map { it.jsonPrimitive.content } + assertEquals(listOf("ami"), ignore) + // Replacements still need the live lookup, so they move to the latest AMI. + assertEquals("\${data.aws_ami.base.id}", instance["ami"]!!.jsonPrimitive.content) + // No terraform_data pin: its unknown output would replace existing instances on the first apply. + assertNull(d.terraformRoot.findResource("terraform_data", "base_ami")) + } + @Test fun swapConfiguredOnlyWhenRequested() { val plain = SingleDeployment() @@ -529,6 +561,180 @@ class Ec2BuilderGenerationTest { assertContains(File(d.terraformRoot, "ec2_init.sh").readText(), "openssl enc -d $cipherArgs") } + // === Distro === + + inner class DistroSingleDeployment( + name: String, + override val distro: TerraformAwsEc2BuilderBase.Distro, + ) : TerraformAwsSingleEc2Builder(TestServer) { + override val storageBucket = "test-tf-state" + override val region: Region = Region.US_WEST_2 + override val displayName = "Distro $name" + override val domainZone = "example.com" + override val domain = "$name.example.com" + override val debug = true + override val emergencyContact = EmailAddress("ops@example.com") + override val instanceType = "t4g.medium" + override val instanceArchitecture = CPUArchitecture.Arm + override val applicationVpc = AwsVpc.Default + override val terraformRoot = File(tmpRoot, "distro-$name") + override fun TestServer.settings() = fulfillGlobals(cacheUrl = null) + } + + inner class AmazonLinuxScalingDeployment : TerraformAwsScalingEc2Builder(TestServer) { + override val storageBucket = "test-tf-state" + override val region: Region = Region.US_WEST_2 + override val displayName = "AL Scaling" + override val domainZone = "example.com" + override val domain = "al-scaling.example.com" + override val debug = true + override val emergencyContact = EmailAddress("ops@example.com") + override val instanceType = "t4g.medium" + override val instanceArchitecture = CPUArchitecture.Arm + override val distro = Distro.AmazonLinux2023 + override val applicationVpc = terraformManagedVPC( + ipPrefix = "10.0", + availabilityZones = listOf("us-west-2a", "us-west-2b"), + natGateway = AwsVpc.NatGateway.Single, + ) + override val terraformRoot = File(tmpRoot, "al-scaling") + override fun TestServer.settings() = fulfillGlobals("redis://cache:6379") + } + + /** Finds a data source block (`data..`) across all generated files. */ + private fun File.findData(type: String, name: String): JsonObject? { + listFiles { f -> f.name.endsWith(".tf.json") }?.forEach { file -> + (Json.parseToJsonElement(file.readText()).jsonObject["data"] as? JsonObject) + ?.get(type)?.jsonObject?.get(name)?.let { return it.jsonObject } + } + return null + } + + private fun assertNoDebianTooling(script: String, file: String) { + for (tool in listOf("apt-get", "dpkg", "snap ", "/etc/apt", "reboot-required")) { + assertFalse(script.contains(tool), "$file must not use $tool on Amazon Linux") + } + } + + @Test + fun singleAmazonLinuxGenerates() { + val d = DistroSingleDeployment("al", TerraformAwsEc2BuilderBase.Distro.AmazonLinux2023) + d.write() + val init = File(d.terraformRoot, "ec2_init.sh").readText() + val base = File(d.terraformRoot, "ec2_init_base.sh").readText() + assertOnlyTemplateVariables(init) + assertOnlyTemplateVariables(base, allowed = setOf("deployment_bucket", "deployment_script_key")) + assertNoDebianTooling(init, "ec2_init.sh") + assertNoDebianTooling(base, "ec2_init_base.sh") + + // Packages come from the latest release, not the one the AMI is locked to. + assertContains(init, "dnf -y --releasever=latest upgrade") + assertContains(init, "dnf install -y java-17-amazon-corretto-headless openssl unzip") + assertContains(init, "dnf install -y amazon-cloudwatch-agent") + assertContains(init, "systemctl enable amazon-ssm-agent") + // os-update moves to the latest release too, and asks dnf whether a reboot is needed. + assertContains(init, "DNF_OPTS=\"-y --releasever=latest\"") + assertContains(init, "dnf needs-restarting -r") + + // nginx from nginx.org with its ACME module loaded at the top level of nginx.conf. + assertContains(init, "baseurl=https://nginx.org/packages/amzn/2023/\$basearch/") + assertContains(init, "dnf install -y nginx nginx-module-acme") + assertContains(init, "sed -i '1i load_module modules/ngx_http_acme_module.so;' /etc/nginx/nginx.conf") + assertContains(init, "acme_certificate letsencrypt;") + assertContains(init, "ssl_certificate \$acme_certificate;") + assertContains(init, "systemctl restart nginx") + + val ami = d.terraformRoot.findData("aws_ami", "base")!! + assertEquals(listOf("amazon"), ami["owners"]!!.jsonArray.map { it.jsonPrimitive.content }) + } + + @Test + fun singleUbuntuInstallsNginx() { + val d = SingleDeployment() + d.write() + val init = File(d.terraformRoot, "ec2_init.sh").readText() + assertOnlyTemplateVariables(init) + assertContains(init, "https://nginx.org/packages/ubuntu") + assertContains(init, "Pin: origin nginx.org") + assertContains(init, "install -y nginx nginx-module-acme") + assertContains(init, "acme_certificate letsencrypt;") + assertContains(init, "systemctl restart nginx") + assertFalse(init.contains("angie"), "Angie is no longer installed") + } + + @Test + fun singleUbuntu2604Generates() { + val d = DistroSingleDeployment("resolute", TerraformAwsEc2BuilderBase.Distro.Ubuntu2604) + d.write() + val ami = d.terraformRoot.findData("aws_ami", "base")!! + val namePattern = ami["filter"]!!.jsonArray.map { it.jsonObject } + .single { it["name"]!!.jsonPrimitive.content == "name" }["values"]!!.jsonArray.single().jsonPrimitive.content + assertEquals("ubuntu/images/hvm-ssd-gp3/ubuntu-resolute-26.04-arm64-server-*", namePattern) + val init = File(d.terraformRoot, "ec2_init.sh").readText() + + // The install scripts otherwise match 24.04's and the instance ignores AMI changes, so naming the + // distro in the init script is what makes a release change replace the instance. + assertContains(init, "EC2 Init script started on Ubuntu2604") + val noble = DistroSingleDeployment("resolute", TerraformAwsEc2BuilderBase.Distro.Ubuntu2404) + noble.write() + assertNotEquals(init, File(noble.terraformRoot, "ec2_init.sh").readText()) + } + + @Test + fun scalingUbuntu2604Generates() { + val d = object : TerraformAwsScalingEc2Builder(TestServer) { + override val storageBucket = "test-tf-state" + override val region: Region = Region.US_WEST_2 + override val displayName = "Resolute Scaling" + override val domainZone = "example.com" + override val domain = "resolute-scaling.example.com" + override val debug = true + override val emergencyContact = EmailAddress("ops@example.com") + override val instanceType = "t4g.medium" + override val instanceArchitecture = CPUArchitecture.Arm + override val distro = Distro.Ubuntu2604 + override val applicationVpc = terraformManagedVPC( + ipPrefix = "10.0", + availabilityZones = listOf("us-west-2a", "us-west-2b"), + natGateway = AwsVpc.NatGateway.Single, + ) + override val terraformRoot = File(tmpRoot, "resolute-scaling") + override fun TestServer.settings() = fulfillGlobals("redis://cache:6379") + } + d.write() + val pin = d.terraformRoot.findResource("terraform_data", "base_ami")!! + assertEquals("Ubuntu2604", pin["triggers_replace"]!!.jsonObject["distro"]!!.jsonPrimitive.content) + assertEquals("\${data.aws_ami.base.id}", pin["input"]!!.jsonObject["id"]!!.jsonPrimitive.content) + val template = d.terraformRoot.findResource("aws_launch_template", "app")!! + assertEquals("/dev/sda1", template["block_device_mappings"]!!.jsonObject["device_name"]!!.jsonPrimitive.content) + assertContains(File(d.terraformRoot, "update-fleet.sh").readText(), "/var/run/reboot-required") + } + + @Test + fun scalingAmazonLinuxGenerates() { + val d = AmazonLinuxScalingDeployment() + d.write() + val component = File(d.terraformRoot, "image_data.yaml").readText() + assertNoDebianTooling(component, "image_data.yaml") + assertContains(component, "dnf -y --releasever=latest upgrade") + + // The fleet's reboot probe must ask dnf; the Ubuntu marker file never exists here. + val fleet = File(d.terraformRoot, "update-fleet.sh").readText() + assertContains(fleet, "dnf needs-restarting -r") + assertFalse(fleet.contains("/var/run/reboot-required")) + + // The root volume is only resized when the mapping names the AMI's root device. + val recipe = d.terraformRoot.findResource("aws_imagebuilder_image_recipe", "this")!! + assertEquals("/dev/xvda", recipe["block_device_mapping"]!!.jsonObject["device_name"]!!.jsonPrimitive.content) + val template = d.terraformRoot.findResource("aws_launch_template", "app")!! + assertEquals("/dev/xvda", template["block_device_mappings"]!!.jsonObject["device_name"]!!.jsonPrimitive.content) + + // Switching distro replaces the pin, re-resolving it to the new distro's latest AMI. + val pin = d.terraformRoot.findResource("terraform_data", "base_ami")!! + assertEquals("AmazonLinux2023", pin["triggers_replace"]!!.jsonObject["distro"]!!.jsonPrimitive.content) + assertEquals("\${data.aws_ami.base.id}", pin["input"]!!.jsonObject["id"]!!.jsonPrimitive.content) + } + @Test fun settingsNeverLandOnDiskBeforeEncryption() { val d = SingleDeployment() diff --git a/docs-guide/drafts/deploy-ec2.md b/docs-guide/drafts/deploy-ec2.md index abca35d4d..e261d97c1 100644 --- a/docs-guide/drafts/deploy-ec2.md +++ b/docs-guide/drafts/deploy-ec2.md @@ -43,7 +43,7 @@ The module provides two concrete builders: | Class | Use case | |---|---| -| `TerraformAwsSingleEc2Builder` | One instance, Elastic IP, Angie reverse proxy with Let's Encrypt. Simplest / cheapest; no HA. | +| `TerraformAwsSingleEc2Builder` | One instance, Elastic IP, nginx reverse proxy with Let's Encrypt. Simplest / cheapest; no HA. | | `TerraformAwsScalingEc2Builder` | Auto Scaling Group behind an Application Load Balancer, golden AMI via EC2 Image Builder. Production-grade HA. | The rest of this page covers both. Most properties are shared via @@ -273,7 +273,7 @@ diff and applies only what changed. | Resource | Purpose | |---|---| -| `aws_instance.ubuntu` | Ubuntu 24.04 EC2 instance | +| `aws_instance.main` | EC2 instance running the configured `distro` (Ubuntu 24.04 by default) | | `aws_eip.main` | Elastic IP (static public address) | | `aws_s3_bucket.deployment` | Holds the distribution zip and encrypted settings | | `aws_iam_role.ec2` | EC2 instance role (S3, SSM, CloudWatch) | @@ -283,7 +283,7 @@ diff and applies only what changed. | `aws_sns_topic.emergency` | Alert notifications to `emergencyContact` | | CloudWatch alarms | System status check, high CPU, high memory, high disk | -The instance runs **Angie** (nginx fork) as a reverse proxy on port 443 with +The instance runs **nginx** (with `nginx-module-acme`) as a reverse proxy on port 443 with automatic Let's Encrypt certificate issuance and renewal. The application listens on `127.0.0.1:8080` (not exposed publicly). diff --git a/docs-guide/drafts/deploy-vm.md b/docs-guide/drafts/deploy-vm.md index e96ff2436..161d36737 100644 --- a/docs-guide/drafts/deploy-vm.md +++ b/docs-guide/drafts/deploy-vm.md @@ -338,9 +338,9 @@ Set `"realIpHeader": "X-Forwarded-For"` in `settings.json` under the engine's config key so Lightning Server logs the client's real IP rather than `127.0.0.1`. -The `deploy-aws-ec2` module uses **Angie** (an nginx fork with a built-in ACME -client) for the same role on single-instance EC2 deployments, so TLS -certificates are issued and renewed automatically without Certbot. +The `deploy-aws-ec2` module uses nginx with its `nginx-module-acme` module for +the same role on single-instance EC2 deployments, so TLS certificates are issued +and renewed automatically without Certbot. --- From 13d7232ade5b996c3ab4127aeef256d36e612700 Mon Sep 17 00:00:00 2001 From: Brady Svedin Date: Wed, 4 Nov 2026 11:33:47 -0700 Subject: [PATCH 2/2] Demo deployment updates --- demo/build.gradle.kts | 129 ++-- .../lightningserver/demo/AwsHandler.kt | 6 - .../lightningserver/demo/BlogEndpoints.kt | 2 +- .../lightningserver/demo/Server.kt | 75 +-- .../lightningserver/demo/UserAuth.kt | 36 ++ .../lightningserver/demo/ec2-deploy.kt | 272 ++++++-- .../demo/endpoints/AuthExamplesEndpoints.kt | 7 +- .../endpoints/ServiceExamplesEndpoints.kt | 11 +- .../demo/endpoints/UserEndpoints.kt | 48 ++ .../demo/{deploy.kt => lambdaDeploy.kt} | 89 ++- .../lightningserver/demo/models/User.kt | 24 - .../demo/{ => models}/models.kt | 2 +- .../demo/AuthExamplesEndpointsTest.kt | 32 +- .../lightningserver/demo/LoginFlowTest.kt | 8 +- .../demo/ServiceExamplesEndpointsTest.kt | 22 +- .../lightningserver/demo/TestModelTest.kt | 1 + .../.terraform.lock.hcl | 6 + .../{lkec2 => ec2-scaling}/alb.tf.json | 15 +- .../{lkec2 => ec2-scaling}/asg.tf.json | 14 +- demo/terraform/{lkec2 => ec2-scaling}/boot.sh | 2 +- .../{lkec2 => ec2-scaling}/cloud.tf.json | 4 +- demo/terraform/ec2-scaling/deployment.tf.json | 349 ++++++++++ .../{lkec2 => ec2-scaling}/dns.tf.json | 4 +- demo/terraform/ec2-scaling/files.tf.json | 67 ++ demo/terraform/ec2-scaling/image.tf.json | 187 ++++++ demo/terraform/ec2-scaling/image_data.yaml | 554 ++++++++++++++++ .../{lkec2 => ec2-scaling}/main.tf.json | 2 +- .../{lkec2 => ec2-scaling}/monitoring.tf.json | 10 +- .../{lkec2 => ec2-scaling}/network.tf.json | 8 +- .../{lkec2 => ec2-scaling}/outputs.tf.json | 2 +- .../{lkec2 => ec2-scaling}/redeploy-fleet.sh | 72 ++- .../{lkec2 => ec2-scaling}/redeploy.tf.json | 2 +- .../{lk => ec2-scaling}/secretBasis.tf.json | 0 demo/terraform/ec2-scaling/update-fleet.sh | 342 ++++++++++ demo/terraform/ec2-scaling/valkey.tf.json | 27 + demo/terraform/ec2-single/.terraform.lock.hcl | 145 +++++ .../{lkec2 => ec2-single}/deployment.tf.json | 200 +++--- demo/terraform/ec2-single/dns.tf.json | 31 + demo/terraform/ec2-single/ec2.tf.json | 94 +++ demo/terraform/ec2-single/ec2_init.sh | 597 ++++++++++++++++++ demo/terraform/ec2-single/ec2_init_base.sh | 50 ++ demo/terraform/ec2-single/eip.tf.json | 18 + .../{lkec2 => ec2-single}/files.tf.json | 5 +- demo/terraform/ec2-single/main.tf.json | 50 ++ demo/terraform/ec2-single/monitoring.tf.json | 93 +++ demo/terraform/ec2-single/network.tf.json | 70 ++ demo/terraform/ec2-single/outputs.tf.json | 8 + demo/terraform/ec2-single/redeploy.sh | 175 +++++ demo/terraform/ec2-single/redeploy.tf.json | 26 + .../{lkec2 => ec2-single}/secretBasis.tf.json | 0 .../{lk => lambda}/.terraform.lock.hcl | 7 + demo/terraform/{lk => lambda}/cloud.tf.json | 0 .../terraform/{lk => lambda}/database.tf.json | 0 demo/terraform/{lk => lambda}/email.tf.json | 0 .../{lk => lambda}/emailInbound.tf.json | 0 demo/terraform/{lk => lambda}/files.tf.json | 0 .../{lk => lambda}/grafanaAlerts.tf.json | 0 demo/terraform/{lk => lambda}/http.tf.json | 0 demo/terraform/{lk => lambda}/lambda.tf.json | 121 ++-- .../{lk => lambda}/lambdaAlarms.tf.json | 0 demo/terraform/{lk => lambda}/main.tf.json | 0 .../{lk => lambda}/schedules.tf.json | 0 demo/terraform/lambda/secretBasis.tf.json | 11 + demo/terraform/lambda/variables.tf.json | 6 + demo/terraform/{lk => lambda}/ws.tf.json | 2 + demo/terraform/lk/variables.tf.json | 24 - demo/terraform/lkec2/database.tf.json | 51 -- demo/terraform/lkec2/email.tf.json | 149 ----- demo/terraform/lkec2/emailInbound.tf.json | 88 --- demo/terraform/lkec2/image.tf.json | 133 ---- demo/terraform/lkec2/redis.tf.json | 24 - demo/terraform/lkec2/variables.tf.json | 22 - .../aws/ec2/TerraformAwsEc2BuilderBase.kt | 16 +- .../aws/ec2/TerraformAwsSingleEc2Builder.kt | 4 +- gradle/libs.versions.toml | 1 + 75 files changed, 3717 insertions(+), 935 deletions(-) delete mode 100644 demo/src/main/kotlin/com/lightningkite/lightningserver/demo/AwsHandler.kt create mode 100644 demo/src/main/kotlin/com/lightningkite/lightningserver/demo/UserAuth.kt create mode 100644 demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/UserEndpoints.kt rename demo/src/main/kotlin/com/lightningkite/lightningserver/demo/{deploy.kt => lambdaDeploy.kt} (71%) delete mode 100644 demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/User.kt rename demo/src/main/kotlin/com/lightningkite/lightningserver/demo/{ => models}/models.kt (96%) rename demo/terraform/{lkec2 => ec2-scaling}/.terraform.lock.hcl (95%) rename demo/terraform/{lkec2 => ec2-scaling}/alb.tf.json (92%) rename demo/terraform/{lkec2 => ec2-scaling}/asg.tf.json (89%) rename demo/terraform/{lkec2 => ec2-scaling}/boot.sh (91%) rename demo/terraform/{lkec2 => ec2-scaling}/cloud.tf.json (95%) create mode 100644 demo/terraform/ec2-scaling/deployment.tf.json rename demo/terraform/{lkec2 => ec2-scaling}/dns.tf.json (87%) create mode 100644 demo/terraform/ec2-scaling/files.tf.json create mode 100644 demo/terraform/ec2-scaling/image.tf.json create mode 100644 demo/terraform/ec2-scaling/image_data.yaml rename demo/terraform/{lkec2 => ec2-scaling}/main.tf.json (95%) rename demo/terraform/{lkec2 => ec2-scaling}/monitoring.tf.json (90%) rename demo/terraform/{lkec2 => ec2-scaling}/network.tf.json (89%) rename demo/terraform/{lkec2 => ec2-scaling}/outputs.tf.json (79%) rename demo/terraform/{lkec2 => ec2-scaling}/redeploy-fleet.sh (61%) rename demo/terraform/{lkec2 => ec2-scaling}/redeploy.tf.json (89%) rename demo/terraform/{lk => ec2-scaling}/secretBasis.tf.json (100%) create mode 100644 demo/terraform/ec2-scaling/update-fleet.sh create mode 100644 demo/terraform/ec2-scaling/valkey.tf.json create mode 100644 demo/terraform/ec2-single/.terraform.lock.hcl rename demo/terraform/{lkec2 => ec2-single}/deployment.tf.json (69%) create mode 100644 demo/terraform/ec2-single/dns.tf.json create mode 100644 demo/terraform/ec2-single/ec2.tf.json create mode 100644 demo/terraform/ec2-single/ec2_init.sh create mode 100644 demo/terraform/ec2-single/ec2_init_base.sh create mode 100644 demo/terraform/ec2-single/eip.tf.json rename demo/terraform/{lkec2 => ec2-single}/files.tf.json (92%) create mode 100644 demo/terraform/ec2-single/main.tf.json create mode 100644 demo/terraform/ec2-single/monitoring.tf.json create mode 100644 demo/terraform/ec2-single/network.tf.json create mode 100644 demo/terraform/ec2-single/outputs.tf.json create mode 100644 demo/terraform/ec2-single/redeploy.sh create mode 100644 demo/terraform/ec2-single/redeploy.tf.json rename demo/terraform/{lkec2 => ec2-single}/secretBasis.tf.json (100%) rename demo/terraform/{lk => lambda}/.terraform.lock.hcl (95%) rename demo/terraform/{lk => lambda}/cloud.tf.json (100%) rename demo/terraform/{lk => lambda}/database.tf.json (100%) rename demo/terraform/{lk => lambda}/email.tf.json (100%) rename demo/terraform/{lk => lambda}/emailInbound.tf.json (100%) rename demo/terraform/{lk => lambda}/files.tf.json (100%) rename demo/terraform/{lk => lambda}/grafanaAlerts.tf.json (100%) rename demo/terraform/{lk => lambda}/http.tf.json (100%) rename demo/terraform/{lk => lambda}/lambda.tf.json (83%) rename demo/terraform/{lk => lambda}/lambdaAlarms.tf.json (100%) rename demo/terraform/{lk => lambda}/main.tf.json (100%) rename demo/terraform/{lk => lambda}/schedules.tf.json (100%) create mode 100644 demo/terraform/lambda/secretBasis.tf.json create mode 100644 demo/terraform/lambda/variables.tf.json rename demo/terraform/{lk => lambda}/ws.tf.json (99%) delete mode 100644 demo/terraform/lk/variables.tf.json delete mode 100644 demo/terraform/lkec2/database.tf.json delete mode 100644 demo/terraform/lkec2/email.tf.json delete mode 100644 demo/terraform/lkec2/emailInbound.tf.json delete mode 100644 demo/terraform/lkec2/image.tf.json delete mode 100644 demo/terraform/lkec2/redis.tf.json delete mode 100644 demo/terraform/lkec2/variables.tf.json diff --git a/demo/build.gradle.kts b/demo/build.gradle.kts index d528b85d5..bb9d049d4 100644 --- a/demo/build.gradle.kts +++ b/demo/build.gradle.kts @@ -9,71 +9,72 @@ plugins { group = "com.lightningkite.lightningserver" dependencies { - api(project(":core")) - api(project(":engine-ktor")) - api(project(":typed")) - api(project(":load-test")) - api(project(":engine-aws-serverless")) - api(project(":deploy-aws-ec2")) - api(project(":engine-jdk-server")) - api(project(":engine-netty")) - api(project(":sessions")) - api(project(":sessions-email")) -// api(project(":sessions-oauth")) -// api(project(":sessions-oauth-shared")) - api(project(":sessions-shared")) - api(project(":secret-source-aws")) - api(project(":sessions-sms")) - api(project(":sessions-totp")) - api(project(":sessions-webauthn")) - api(project(":sessions-oauth")) - api(project(":files")) - api(libs.services.pubsub) - api(libs.services.pubsub.redis) - api(libs.services.pubsub.aws) - api(libs.services.pubsub.test) - api(libs.services.sms) - api(libs.services.sms.test) - api(libs.services.sms.twilio) - api(libs.services.test) - api(libs.services.notifications.test) - api(libs.services.notifications.fcm) - api(libs.services.notifications) - api(libs.services.http.client) - api(libs.services.files.test) - api(libs.services.files.s3) - api(libs.services.files.client) - api(libs.services.files.clamav) - api(libs.services.files) - api(libs.services.email.test) - api(libs.services.email.javasmtp) - api(libs.services.email) - api(libs.services.database.test) + implementation(project(":core")) + implementation(project(":engine-ktor")) + implementation(project(":typed")) + implementation(project(":load-test")) + implementation(project(":engine-aws-serverless")) + implementation(project(":deploy-aws-ec2")) + implementation(project(":engine-jdk-server")) + implementation(project(":engine-netty")) + implementation(project(":sessions")) + implementation(project(":sessions-email")) +// implementation(project(":sessions-oauth")) +// implementation(project(":sessions-oauth-shared")) + implementation(project(":sessions-shared")) + implementation(project(":secret-source-aws")) + implementation(project(":sessions-sms")) + implementation(project(":sessions-totp")) + implementation(project(":sessions-webauthn")) + implementation(project(":sessions-oauth")) + implementation(project(":files")) + implementation(libs.aws.signin) + implementation(libs.services.pubsub) + implementation(libs.services.pubsub.redis) + implementation(libs.services.pubsub.aws) + implementation(libs.services.pubsub.test) + implementation(libs.services.sms) + implementation(libs.services.sms.test) + implementation(libs.services.sms.twilio) + implementation(libs.services.test) + implementation(libs.services.notifications.test) + implementation(libs.services.notifications.fcm) + implementation(libs.services.notifications) + implementation(libs.services.http.client) + implementation(libs.services.files.test) + implementation(libs.services.files.s3) + implementation(libs.services.files.client) + implementation(libs.services.files.clamav) + implementation(libs.services.files) + implementation(libs.services.email.test) + implementation(libs.services.email.javasmtp) + implementation(libs.services.email) + implementation(libs.services.database.test) ksp(libs.services.database.processor) - api(libs.services.database.mongodb) - api(libs.services.database.postgres) - api(libs.services.database.jsonfile) -// api(libs.services.DatabaseCassandra) - api(libs.services.database) - api(libs.services.data) - api(libs.services.cache.test) - api(libs.services.cache.redis) - api(libs.services.cache.memcached) - api(libs.services.cache.dynamodb) - api(libs.services.cache) - api(libs.services.basis) - api(libs.services.aws.client) - api(libs.services.email.inbound) - api(libs.services.email.inbound.sendgrid) - api(libs.services.email.inbound.mailgun) - api(libs.services.email.inbound.ses) - api(libs.services.email.inbound.imap) - api(libs.services.sms.inbound) - api(libs.services.sms.inbound.twilio) - api(libs.services.phonecall) - api(libs.services.phonecall.twilio) - api(libs.services.phonecall.test) - api(libs.services.voiceagent.openai) + implementation(libs.services.database.mongodb) + implementation(libs.services.database.postgres) + implementation(libs.services.database.jsonfile) +// implementation(libs.services.DatabaseCassandra) + implementation(libs.services.database) + implementation(libs.services.data) + implementation(libs.services.cache.test) + implementation(libs.services.cache.redis) + implementation(libs.services.cache.memcached) + implementation(libs.services.cache.dynamodb) + implementation(libs.services.cache) + implementation(libs.services.basis) + implementation(libs.services.aws.client) + implementation(libs.services.email.inbound) + implementation(libs.services.email.inbound.sendgrid) + implementation(libs.services.email.inbound.mailgun) + implementation(libs.services.email.inbound.ses) + implementation(libs.services.email.inbound.imap) + implementation(libs.services.sms.inbound) + implementation(libs.services.sms.inbound.twilio) + implementation(libs.services.phonecall) + implementation(libs.services.phonecall.twilio) + implementation(libs.services.phonecall.test) + implementation(libs.services.voiceagent.openai) implementation(libs.kotlinerCli) testImplementation(libs.kotlin.test) diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/AwsHandler.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/AwsHandler.kt deleted file mode 100644 index 893d8b7e2..000000000 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/AwsHandler.kt +++ /dev/null @@ -1,6 +0,0 @@ -package com.lightningkite.lightningserver.demo - -import com.lightningkite.lightningserver.engine.awsserverless.AwsAdapter - -class AwsHandler : AwsAdapter(Server.build()) { -} \ No newline at end of file diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/BlogEndpoints.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/BlogEndpoints.kt index 233c9f7d0..58cd58200 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/BlogEndpoints.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/BlogEndpoints.kt @@ -12,7 +12,7 @@ import com.lightningkite.services.database.ModelPermissions object BlogEndpoints : ServerBuilder() { // The correct way of doing it val info = Server.database.modelInfo( - auth = Server.UserAuth.require(), + auth = UserAuth.require(), tableName = "BlogPost", permissions = { if (auth.fetch().isSuperUser) diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt index 553d26d9f..ac54d47f5 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/Server.kt @@ -10,9 +10,11 @@ import com.lightningkite.lightningserver.cors.CorsSettings import com.lightningkite.lightningserver.definition.* import com.lightningkite.lightningserver.definition.builder.* import com.lightningkite.lightningserver.demo.endpoints.* +import com.lightningkite.lightningserver.demo.models.User import com.lightningkite.lightningserver.files.Files import com.lightningkite.lightningserver.files.UploadEarlyEndpoint import com.lightningkite.lightningserver.http.* +import com.lightningkite.lightningserver.pathing.PathSpec0 import com.lightningkite.lightningserver.pathing.fullUrl import com.lightningkite.lightningserver.runtime.* import com.lightningkite.lightningserver.serialization.StandardWithExternalModule @@ -54,8 +56,6 @@ import com.lightningkite.services.voiceagent.openai.OpenAIVoiceAgentService import io.ktor.http.decodeURLQueryComponent import io.ktor.http.encodeURLQueryComponent import kotlinx.coroutines.flow.Flow -import kotlinx.serialization.* -import kotlinx.serialization.builtins.* import kotlin.time.* import kotlin.uuid.* @@ -84,6 +84,7 @@ object Server : ServerBuilder() { // Baseline security headers (X-Content-Type-Options, and HSTS over https). Installed first so it runs // outermost and applies to every response, including CORS-processed and error responses. val securityHeaders = install(SecurityHeadersInterceptor()) + // v4-style access log: one line per request naming the resolved principal (or "anonymous") and IP. val accessLog = install(AccessLogInterceptor()) val corsInterceptor = install(CorsInterceptor(cors)) @@ -111,66 +112,22 @@ object Server : ServerBuilder() { // Seed an admin user. This runs as a pre-deploy task (once per deploy, before the new version // serves), and `doOnce` guards the actual insert so the seed happens only once ever, not on // every deploy - the sanctioned pattern for "run exactly once" pre-deploy work. - val setupAdmins = path.path("setup-admins2") bind PreDeployTask { - doOnce("setup-admins2", database) { - userInfo.table().insertOne( + val setupAdmins = path.path("setup-admins2") bind predeployOnce(database) { + UserEndpoints.info.table().insertOne( User( email = "joseph@lightningkite.com", isSuperUser = true, phone = "+18013693729".toPhoneNumber() ) ) - } } - object UserAuth : PrincipalType { - override val idSerializer: KSerializer = Uuid.serializer() - override val subjectSerializer: KSerializer = User.Companion.serializer() - override val name: String get() = User.serializer().descriptor.serialName.substringAfterLast('.') - - context(server: ServerRuntime) - override suspend fun fetch(id: Uuid): User = - userInfo.table().get(id) ?: throw com.lightningkite.lightningserver.NotFoundException() - - context(server: ServerRuntime) - override suspend fun fetchByProperty(property: String, value: String): User? { - return when (property) { - "email" -> userInfo.table().findOne(Condition { it.email eq value }) ?: userInfo.table() - .insertOne(User(email = value)) - - else -> super.fetchByProperty(property, value) - } - } - } - val userInfo: ModelInfo = database.modelInfo( - auth = UserAuth.require() or AuthRequirement.None, - tableName = "User", - permissions = { - val user = authOrNull?.fetch() - val everyone: Condition = Condition.Always - val self: Condition = Condition { it._id eqNn user?._id } - val admin: Condition = if (user?.isSuperUser == true) Condition.Always else Condition.Never - ModelPermissions( - create = Condition.Never, - read = everyone, - readMask = mask { - it.hashedPassword.mask(value = "", unless = self or admin) - it.phone.mask(value = null, unless = self or admin) - it.isSuperUser.mask(value = false, unless = self or admin) - }, - update = self or admin, - delete = self or admin - ) - } - ) // A named object rather than an anonymous `object : ServerBuilder() { ... }` - Kotlin widens a // public property's type to its nearest supertype when the initializer is an anonymous object, // so `user.rest` would be invisible from other files (e.g. tests) with the anonymous form. - object UserEndpoints : ServerBuilder() { - val rest = path.path("rest") module ModelRestEndpoints(Server.userInfo) - } + val user = path.path("user") include UserEndpoints val uploadEarly = path.path("upload") module UploadEarlyEndpoint(files, database, Runtime.Constant(listOf())) @@ -240,7 +197,7 @@ object Server : ServerBuilder() { context(serverRuntime: ServerRuntime) override suspend fun handle( - request: WebSocketConnectRequest, + request: WebSocketConnectRequest, waitForFullConnect: suspend () -> Unit, incoming: Flow, send: suspend (WebSocketFrame) -> Unit, @@ -280,12 +237,18 @@ object Server : ServerBuilder() { val proofOtp = path.path("proof").path("otp") module TimeBasedOTPProofEndpoints(database, cache) val proofPassword = path.path("proof").path("password") module PasswordProofEndpoints(database, cache) val proofDevices = path.path("proof").path("devices") module KnownDeviceProofEndpoints(database, cache) - val proofOauth = path.path("proof").path("github") module OauthProofEndpoints( - provider = OauthProviderInfo.github, - cache = cache, - credentials = githubOauth, - continueUiAuthUrl = { autosignIn.location.path.resolved().fullUrl() + "?proof=" + serverRuntime.externalSerialization.json.encodeToString(Proof.serializer(), it).encodeURLQueryComponent() + "&backend=" + generalSettings().publicUrl.encodeURLQueryComponent() } - ) + val proofOauth: OauthProofEndpoints + get() = path.path("proof").path("github") module OauthProofEndpoints( + provider = OauthProviderInfo.github, + cache = cache, + credentials = githubOauth, + continueUiAuthUrl = { + autosignIn.location.path.resolved() + .fullUrl() + "?proof=" + serverRuntime.externalSerialization.json.encodeToString(Proof.serializer(), it) + .encodeURLQueryComponent() + "&backend=" + generalSettings().publicUrl.encodeURLQueryComponent() + } + ) + /** * Continuation target for [proofOauth]: the OAuth provider redirects the browser here with a * signed proof of the user's identity attached. Completes the login with that single proof and diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/UserAuth.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/UserAuth.kt new file mode 100644 index 000000000..19102dc4d --- /dev/null +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/UserAuth.kt @@ -0,0 +1,36 @@ +package com.lightningkite.lightningserver.demo + +import com.lightningkite.lightningserver.NotFoundException +import com.lightningkite.lightningserver.auth.PrincipalType +import com.lightningkite.lightningserver.demo.endpoints.UserEndpoints +import com.lightningkite.lightningserver.demo.models.* +import com.lightningkite.lightningserver.runtime.ServerRuntime +import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.eq +import com.lightningkite.services.database.findOne +import com.lightningkite.services.database.get +import com.lightningkite.services.database.insertOne +import kotlinx.serialization.KSerializer +import kotlinx.serialization.builtins.serializer +import kotlin.uuid.Uuid + + +object UserAuth : PrincipalType { + override val idSerializer: KSerializer = Uuid.serializer() + override val subjectSerializer: KSerializer = User.Companion.serializer() + override val name: String get() = User.serializer().descriptor.serialName.substringAfterLast('.') + + context(server: ServerRuntime) + override suspend fun fetch(id: Uuid): User = + UserEndpoints.info.table().get(id) ?: throw NotFoundException() + + context(server: ServerRuntime) + override suspend fun fetchByProperty(property: String, value: String): User? { + return when (property) { + "email" -> UserEndpoints.info.table().findOne(Condition { it.email eq value }) ?: UserEndpoints.info.table() + .insertOne(User(email = value)) + + else -> super.fetchByProperty(property, value) + } + } +} \ No newline at end of file diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/ec2-deploy.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/ec2-deploy.kt index b4b34977c..e94104dea 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/ec2-deploy.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/ec2-deploy.kt @@ -1,25 +1,40 @@ package com.lightningkite.lightningserver.demo -//import com.lightningkite.services.database.cassandra.awsKeyspaces import com.lightningkite.lightningserver.cors.CorsSettings import com.lightningkite.lightningserver.definition.* import com.lightningkite.lightningserver.engine.local.engineCache import com.lightningkite.lightningserver.engine.local.enginePubSub +import com.lightningkite.lightningserver.sessions.proofs.oauth.OauthProviderCredentials import com.lightningkite.lightningserver.terraform.* import com.lightningkite.lightningserver.terraform.aws.ec2.TerraformAwsScalingEc2Builder +import com.lightningkite.lightningserver.terraform.aws.ec2.TerraformAwsSingleEc2Builder import com.lightningkite.lightningserver.terraform.aws.ec2.otelGrafanaCloud import com.lightningkite.services.LoggingSettings +import com.lightningkite.services.cache.Cache import com.lightningkite.services.cache.redis.awsElasticacheRedis +import com.lightningkite.services.cache.redis.awsElasticacheValkey import com.lightningkite.services.cache.redis.redis +import com.lightningkite.services.data.DataSize +import com.lightningkite.services.data.DataSize.Companion.gibibytes import com.lightningkite.services.data.EmailAddress import com.lightningkite.services.data.toEmailAddress +import com.lightningkite.services.database.Database import com.lightningkite.services.database.mongodb.awsDocumentDb +import com.lightningkite.services.email.EmailInboundService +import com.lightningkite.services.email.EmailService import com.lightningkite.services.email.javasmtp.awsSesDomainConfiguration import com.lightningkite.services.email.javasmtp.awsSesSmtp import com.lightningkite.services.email.ses.awsSesInbound import com.lightningkite.services.files.s3.awsS3Bucket +import com.lightningkite.services.notifications.NotificationService +import com.lightningkite.services.phonecall.PhoneCallService +import com.lightningkite.services.pubsub.PubSub import com.lightningkite.services.pubsub.redis.redis +import com.lightningkite.services.sms.SMS +import com.lightningkite.services.sms.SmsInboundService +import com.lightningkite.services.telemetry.TelemetryBackend import com.lightningkite.services.terraform.* +import com.lightningkite.services.voiceagent.VoiceAgentService import io.github.oshai.kotlinlogging.Level import software.amazon.awssdk.regions.Region import java.io.File @@ -28,21 +43,21 @@ import kotlin.time.Duration.Companion.seconds object TestEc2Scaling : TerraformAwsScalingEc2Builder(Server) { - override val displayName: String = "Lightning Server Demo" - override val projectPrefix: String = "LightningServerEC2SDemo" + override val displayName: String = "Lightning Server EC2 Scaling Demo" + override val projectPrefix: String = "ec2-scaling-demo" override val debug: Boolean = true override val region: Region = Region.US_WEST_2 override val instanceArchitecture: CPUArchitecture = CPUArchitecture.Arm override val instanceType: String = "t4g.micro" - override val terraformRoot: File = File("demo/terraform/lkec2") + override val terraformRoot: File = File("demo/terraform/ec2-scaling") override val storageBucket: String = "lightningkite-terraform" override val storageEncryptionEnabled: Boolean = true override val domainZone: String = "cs.lightningkite.com" - override val domain: String = "lightningserver2.cs.lightningkite.com" + override val domain: String = "scaling-demo.cs.lightningkite.com" override val emergencyContact: EmailAddress = "joseph@lightningkite.com".toEmailAddress() override val applicationVpc: AwsVpc.VpcInfo = terraformManagedVPC( @@ -55,22 +70,26 @@ object TestEc2Scaling : TerraformAwsScalingEc2Builder(Server) { natGateway = AwsVpc.NatGateway.Single ) + override val distro: Distro = Distro.AmazonLinux2023 + override val swapSize: DataSize = 1.gibibytes + override val secretsSource: SecretSource = - AwsSecretSource(profile = "lk", idPrefix = "lightning-server-demo", region = Region.US_WEST_2) + AwsSecretSource(profile = "lk", idPrefix = "ec2-scaling-demo", region = Region.US_WEST_2) override fun Server.settings() { - database.awsDocumentDb( - // AwsManaged keeps the cluster on the AWS-managed key for now; switch to - // KmsKeySource.CreateDedicated to give it a dedicated CMK (recreates the cluster). - kmsKey = KmsKeySource.AwsManaged, - instanceClass = "db.t4g.medium", - instanceCount = 1, - engineVersion = "5.0", - backupRetentionPeriod = 1, - tls = true, - // Test deployment: skip the final snapshot so teardown is clean. - skipFinalSnapshot = true, - ) +// database.awsDocumentDb( +// // AwsManaged keeps the cluster on the AWS-managed key for now; switch to +// // KmsKeySource.CreateDedicated to give it a dedicated CMK (recreates the cluster). +// kmsKey = KmsKeySource.AwsManaged, +// instanceClass = "db.t4g.medium", +// instanceCount = 1, +// engineVersion = "5.0", +// backupRetentionPeriod = 1, +// tls = true, +// // Test deployment: skip the final snapshot so teardown is clean. +// skipFinalSnapshot = true, +// ) + database.direct(Database.Settings()) files.awsS3Bucket(signedUrlDuration = 1.days) secretBasis.generated() loggingSettings.direct( @@ -93,7 +112,8 @@ object TestEc2Scaling : TerraformAwsScalingEc2Builder(Server) { // Run an on-box Grafana Alloy collector and ship telemetry to Grafana Cloud. Replace the // instance id with your Grafana Cloud OTLP username/stack id, and supply the // `grafana_cloud_api_key` variable (write-scoped access-policy token) via editVars(). - telemetrySettings.otelGrafanaCloud(grafanaCloudInstanceId = "000000") +// telemetrySettings.otelGrafanaCloud(grafanaCloudInstanceId = "000000") + telemetrySettings.direct(TelemetryBackend.Settings()) cors.direct( CorsSettings( limitToDomains = listOf("*"), @@ -105,27 +125,187 @@ object TestEc2Scaling : TerraformAwsScalingEc2Builder(Server) { forbidOnMatchFail = false ) ) - newSecret.byVariable() - val sesConfig = awsSesDomainConfiguration("email", "joseph@lightningkite.com".toEmailAddress()) - email.awsSesSmtp(sesConfig) - emailInbound.awsSesInbound( - sesConfig, - "https://lightningserver.cs.lightningkite.com/assistant-channels/email/webhook" +// newSecret.byVariable() + newSecret.direct("Some Value") + email.direct(EmailService.Settings()) + emailInbound.direct(EmailInboundService.Settings()) +// val sesConfig = awsSesDomainConfiguration("email", "joseph@lightningkite.com".toEmailAddress()) +// email.awsSesSmtp(sesConfig) +// emailInbound.awsSesInbound( +// sesConfig, +// "https://lightningserver.cs.lightningkite.com/assistant-channels/email/webhook" +// ) + sms.direct(SMS.Settings()) + smsInbound.direct(SmsInboundService.Settings()) + phoneCall.direct(PhoneCallService.Settings()) + voiceAgent.direct(VoiceAgentService.Settings()) + notifications.direct(NotificationService.Settings("console")) +// sms.byVariable() +// smsInbound.byVariable() +// phoneCall.byVariable() +// voiceAgent.byVariable() +// notifications.byVariable() + + // Scaling requires a real cache solution, you cannot use ram + val valkey = awsElasticacheValkey("valkey") + cache.redis(valkey) + pubsub.redis(valkey) + enginePubSub.redis(valkey) + engineCache.redis(valkey) + + githubOauth.direct(OauthProviderCredentials("", "")) + } + + object Ec2ScalingDeploy { + @JvmStatic + fun main(vararg args: String) { + ProcessBuilder("./gradlew", "demo:distZip").inheritIO().start().waitFor() + deploy() + } + } + + object Ec2ScalingEdit { + @JvmStatic + fun main(vararg args: String) = editVars() + } + + object Ec2ScalingDestroy { + @JvmStatic + fun main(vararg args: String) = terraform("destroy", "--auto-approve") + } + + object Ec2ScalingWrite { + @JvmStatic + fun main(vararg args: String) = write() + } + + object Ec2ScalingShell { + @JvmStatic + fun main(vararg args: String) { + write() + println() + println("Entering Terraform Shell") + while (true) { + val next = readlnOrNull()?.also { if (it.isBlank()) continue } ?: break + try { + terraform(*next.split(' ').toTypedArray()) + } catch (_: Throwable) { + } + } + } + } + +} + + +object TestEc2Single : TerraformAwsSingleEc2Builder(Server) { + override val displayName: String = "Lightning Server EC2 Demo" + override val projectPrefix: String = "ec2-demo" + override val debug: Boolean = true + + override val region: Region = Region.US_WEST_2 + override val instanceArchitecture: CPUArchitecture = CPUArchitecture.Arm + override val instanceType: String = "t4g.micro" + + override val terraformRoot: File = File("demo/terraform/ec2-single") + + override val storageBucket: String = "lightningkite-terraform" + override val storageEncryptionEnabled: Boolean = true + + override val domainZone: String = "cs.lightningkite.com" + override val domain: String = "ec2-demo.cs.lightningkite.com" + override val emergencyContact: EmailAddress = "joseph@lightningkite.com".toEmailAddress() + + override val applicationVpc: AwsVpc.EC2Safe = AwsVpc.Default + + override val distro: Distro = Distro.AmazonLinux2023 + + override val secretsSource: SecretSource = + AwsSecretSource(profile = "lk", idPrefix = "ec2-demo", region = Region.US_WEST_2) + + override fun Server.settings() { +// database.awsDocumentDb( +// // AwsManaged keeps the cluster on the AWS-managed key for now; switch to +// // KmsKeySource.CreateDedicated to give it a dedicated CMK (recreates the cluster). +// kmsKey = KmsKeySource.AwsManaged, +// instanceClass = "db.t4g.medium", +// instanceCount = 1, +// engineVersion = "5.0", +// backupRetentionPeriod = 1, +// tls = true, +// // Test deployment: skip the final snapshot so teardown is clean. +// skipFinalSnapshot = true, +// ) + database.direct(Database.Settings()) + files.awsS3Bucket(signedUrlDuration = 1.days) + secretBasis.generated() + loggingSettings.direct( + LoggingSettings( + default = LoggingSettings.ContextSettings( + level = Level.INFO, + filePattern = null, + toConsole = true, + additive = false, + ), logger = mapOf( + "org.mongodb" to LoggingSettings.ContextSettings( + level = Level.WARN, + filePattern = null, + toConsole = true, + additive = false, + ) + ) + ) ) - sms.byVariable() - smsInbound.byVariable() - phoneCall.byVariable() - voiceAgent.byVariable() - - val redis = awsElasticacheRedis("redis") - cache.redis(redis) - pubsub.redis(redis) - enginePubSub.redis(redis) - engineCache.redis(redis) - githubOauth.byVariable() + // Run an on-box Grafana Alloy collector and ship telemetry to Grafana Cloud. Replace the + // instance id with your Grafana Cloud OTLP username/stack id, and supply the + // `grafana_cloud_api_key` variable (write-scoped access-policy token) via editVars(). +// telemetrySettings.otelGrafanaCloud(grafanaCloudInstanceId = "000000") + telemetrySettings.direct(TelemetryBackend.Settings()) + cors.direct( + CorsSettings( + limitToDomains = listOf("*"), + limitToHeaders = listOf("*"), + limitToMethods = listOf("*"), + exposedHeaders = listOf("*"), + allowCredentials = true, + cacheLength = 5.seconds, + forbidOnMatchFail = false + ) + ) +// newSecret.byVariable() + newSecret.direct("Some Value") + email.direct(EmailService.Settings()) + emailInbound.direct(EmailInboundService.Settings()) +// val sesConfig = awsSesDomainConfiguration("email", "joseph@lightningkite.com".toEmailAddress()) +// email.awsSesSmtp(sesConfig) +// emailInbound.awsSesInbound( +// sesConfig, +// "https://lightningserver.cs.lightningkite.com/assistant-channels/email/webhook" +// ) + sms.direct(SMS.Settings()) + smsInbound.direct(SmsInboundService.Settings()) + phoneCall.direct(PhoneCallService.Settings()) + voiceAgent.direct(VoiceAgentService.Settings()) + notifications.direct(NotificationService.Settings("console")) +// sms.byVariable() +// smsInbound.byVariable() +// phoneCall.byVariable() +// voiceAgent.byVariable() +// notifications.byVariable() + +// val redis = awsElasticacheRedis("redis") +// cache.redis(redis) +// pubsub.redis(redis) +// enginePubSub.redis(redis) +// engineCache.redis(redis) + cache.direct(Cache.Settings()) + pubsub.direct(PubSub.Settings()) + enginePubSub.direct(PubSub.Settings()) + engineCache.direct(Cache.Settings()) + githubOauth.direct(OauthProviderCredentials("", "")) } - object DoDeploy { + object Ec2SingleDeploy { @JvmStatic fun main(vararg args: String) { ProcessBuilder("./gradlew", "demo:distZip").inheritIO().start().waitFor() @@ -133,26 +313,34 @@ object TestEc2Scaling : TerraformAwsScalingEc2Builder(Server) { } } - object DoEdit { + object Ec2SingleEdit { @JvmStatic fun main(vararg args: String) = editVars() } - object DoDestroy { + object Ec2SingleDestroy { @JvmStatic fun main(vararg args: String) = terraform("destroy", "--auto-approve") } - object DoWrite { + object Ec2SingleWrite { @JvmStatic fun main(vararg args: String) = write() } - object DoValidate { + object Ec2SingleShell { @JvmStatic fun main(vararg args: String) { write() - terraform("validate") + println() + println("Entering Terraform Shell") + while (true) { + val next = readlnOrNull()?.also { if (it.isBlank()) continue } ?: break + try { + terraform(*next.split(' ').toTypedArray()) + } catch (_: Throwable) { + } + } } } diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/AuthExamplesEndpoints.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/AuthExamplesEndpoints.kt index e3426d8a5..e5ae9fc92 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/AuthExamplesEndpoints.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/AuthExamplesEndpoints.kt @@ -8,6 +8,7 @@ import com.lightningkite.lightningserver.auth.or import com.lightningkite.lightningserver.auth.require import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.demo.Server +import com.lightningkite.lightningserver.demo.UserAuth import com.lightningkite.lightningserver.http.get import com.lightningkite.lightningserver.typed.ApiHttpHandler import com.lightningkite.lightningserver.typed.auth @@ -41,7 +42,7 @@ object AuthExamplesEndpoints : ServerBuilder() { val whoAmI = path.path("auth-examples").path("whoami").get bind ApiHttpHandler( summary = "Who Am I", description = "Reads the authenticated caller's identity from the session.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { _: Unit -> val user = auth.fetch() WhoAmIResponse(id = auth.id, email = user.email, isSuperUser = user.isSuperUser) @@ -57,7 +58,7 @@ object AuthExamplesEndpoints : ServerBuilder() { val greet = path.path("auth-examples").path("greet").get bind ApiHttpHandler( summary = "Greet", description = "Greets anonymous callers generically and logged-in callers by email.", - auth = Server.UserAuth.require() or AuthRequirement.None, + auth = UserAuth.require() or AuthRequirement.None, implementation = { _: Unit -> authOrNull?.fetch()?.let { "Welcome back, ${it.email}!" } ?: "Hello, anonymous visitor!" } @@ -73,7 +74,7 @@ object AuthExamplesEndpoints : ServerBuilder() { val adminOnly = path.path("auth-examples").path("admin-only").get bind ApiHttpHandler( summary = "Admin Only", description = "Requires the caller's isSuperUser flag; returns 403 for everyone else.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { _: Unit -> val user = auth.fetch() if (!user.isSuperUser) throw ForbiddenException("This endpoint requires super-user access.") diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/ServiceExamplesEndpoints.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/ServiceExamplesEndpoints.kt index fd591930a..5b626b144 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/ServiceExamplesEndpoints.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/ServiceExamplesEndpoints.kt @@ -3,6 +3,7 @@ package com.lightningkite.lightningserver.demo.endpoints import com.lightningkite.lightningserver.auth.require import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.demo.Server +import com.lightningkite.lightningserver.demo.UserAuth import com.lightningkite.lightningserver.http.get import com.lightningkite.lightningserver.http.post import com.lightningkite.lightningserver.typed.ApiHttpHandler @@ -34,7 +35,7 @@ object ServiceExamplesEndpoints : ServerBuilder() { val sendEmail = path.path("service-examples").path("email").post bind ApiHttpHandler( summary = "Send Demo Email", description = "Sends a plain-text message through the configured EmailService.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { to: EmailAddress -> Server.email().send( Email( @@ -53,7 +54,7 @@ object ServiceExamplesEndpoints : ServerBuilder() { val sendSms = path.path("service-examples").path("sms").post bind ApiHttpHandler( summary = "Send Demo SMS", description = "Sends a message through the configured SMS service.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { to: PhoneNumber -> Server.sms().send(to, "Lightning Server Demo message.") "Sent to ${to.raw} via ${Server.sms()::class.simpleName}." @@ -68,7 +69,7 @@ object ServiceExamplesEndpoints : ServerBuilder() { val placeCall = path.path("service-examples").path("phone-call").post bind ApiHttpHandler( summary = "Place Demo Phone Call", description = "Starts a call, speaks a line, then hangs up.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { to: PhoneNumber -> val phone = Server.phoneCall() val callId = phone.startCall(to, OutboundCallOptions()) @@ -87,7 +88,7 @@ object ServiceExamplesEndpoints : ServerBuilder() { val pushNotification = path.path("service-examples").path("notify").post bind ApiHttpHandler( summary = "Push Demo Notification", description = "Sends a push notification to the given device token via the configured NotificationService.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { deviceToken: String -> val results = Server.notifications().send( listOf(deviceToken), @@ -107,7 +108,7 @@ object ServiceExamplesEndpoints : ServerBuilder() { val readSecret = path.path("service-examples").path("secret").get bind ApiHttpHandler( summary = "Read Demo Secret", description = "Returns the current value of the someSecret setting.", - auth = Server.UserAuth.require(), + auth = UserAuth.require(), implementation = { _: Unit -> "someSecret is currently: ${Server.newSecret()}" } diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/UserEndpoints.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/UserEndpoints.kt new file mode 100644 index 000000000..5522a4a7e --- /dev/null +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/endpoints/UserEndpoints.kt @@ -0,0 +1,48 @@ +package com.lightningkite.lightningserver.demo.endpoints + +import com.lightningkite.lightningserver.auth.AuthRequirement +import com.lightningkite.lightningserver.auth.fetch +import com.lightningkite.lightningserver.auth.or +import com.lightningkite.lightningserver.auth.require +import com.lightningkite.lightningserver.definition.builder.ServerBuilder +import com.lightningkite.lightningserver.demo.Server.database +import com.lightningkite.lightningserver.demo.models.* +import com.lightningkite.lightningserver.demo.UserAuth +import com.lightningkite.lightningserver.typed.ModelInfo +import com.lightningkite.lightningserver.typed.ModelRestEndpoints +import com.lightningkite.lightningserver.typed.modelInfo +import com.lightningkite.lightningserver.typed.sdk.module +import com.lightningkite.services.database.Condition +import com.lightningkite.services.database.ModelPermissions +import com.lightningkite.services.database.condition +import com.lightningkite.services.database.eqNn +import com.lightningkite.services.database.mask +import com.lightningkite.services.database.or +import kotlin.uuid.Uuid + +object UserEndpoints : ServerBuilder() { + + val info: ModelInfo = database.modelInfo( + auth = UserAuth.require() or AuthRequirement.None, + tableName = "User", + permissions = { + val user = authOrNull?.fetch() + val everyone: Condition = Condition.Always + val self: Condition = Condition { it._id eqNn user?._id } + val admin: Condition = if (user?.isSuperUser == true) Condition.Always else Condition.Never + ModelPermissions( + create = Condition.Never, + read = everyone, + readMask = mask { + it.hashedPassword.mask(value = "", unless = self or admin) + it.phone.mask(value = null, unless = self or admin) + it.isSuperUser.mask(value = false, unless = self or admin) + }, + update = self or admin, + delete = self or admin + ) + } + ) + + val rest = path.path("rest") module ModelRestEndpoints(info) +} \ No newline at end of file diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/deploy.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/lambdaDeploy.kt similarity index 71% rename from demo/src/main/kotlin/com/lightningkite/lightningserver/demo/deploy.kt rename to demo/src/main/kotlin/com/lightningkite/lightningserver/demo/lambdaDeploy.kt index 28686ee07..ecdce9c3c 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/deploy.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/lambdaDeploy.kt @@ -1,9 +1,9 @@ package com.lightningkite.lightningserver.demo -//import com.lightningkite.services.database.cassandra.awsKeyspaces import com.lightningkite.lightningserver.cors.CorsSettings import com.lightningkite.lightningserver.definition.* import com.lightningkite.lightningserver.engine.awsserverless.AwsAdapter +import com.lightningkite.lightningserver.sessions.proofs.oauth.OauthProviderCredentials import com.lightningkite.lightningserver.terraform.* import com.lightningkite.lightningserver.terraform.awsserverless.* import com.lightningkite.services.LoggingSettings @@ -16,12 +16,16 @@ import com.lightningkite.services.email.javasmtp.awsSesSmtp import com.lightningkite.services.email.ses.awsSesInbound import com.lightningkite.services.files.s3.awsS3Bucket import com.lightningkite.services.notifications.NotificationService +import com.lightningkite.services.phonecall.PhoneCallService import com.lightningkite.services.pubsub.aws.dynamoDb +import com.lightningkite.services.sms.SMS +import com.lightningkite.services.sms.SmsInboundService import com.lightningkite.services.terraform.AwsVpc import com.lightningkite.services.terraform.TerraformProvider import com.lightningkite.services.terraform.TerraformProviderImport import com.lightningkite.services.terraform.byVariable import com.lightningkite.services.terraform.direct +import com.lightningkite.services.voiceagent.VoiceAgentService import io.github.oshai.kotlinlogging.Level import kotlinx.serialization.json.JsonObject import software.amazon.awssdk.regions.Region @@ -31,8 +35,9 @@ import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds +class AwsHandler : AwsAdapter(Server.build()) -object LkEnv : TerraformAwsServerlessDomainBuilder(Server) { +object TestLambda : TerraformAwsServerlessDomainBuilder(Server) { override val handler: KClass = AwsHandler::class override val useCloudFrontForWebSocket: Boolean get() = true @@ -41,7 +46,7 @@ object LkEnv : TerraformAwsServerlessDomainBuilder(Server) { override val timeout = 15.minutes override val projectPrefix: String = "LightningServerDemo" - override val terraformRoot: File = File("demo/terraform/lk") + override val terraformRoot: File = File("demo/terraform/lambda") override val storageBucket: String = "lightningkite-terraform" override val storageBucketPath: String = "lightningserverdemo" @@ -109,45 +114,69 @@ object LkEnv : TerraformAwsServerlessDomainBuilder(Server) { forbidOnMatchFail = false ) ) - newSecret.byVariable() +// newSecret.byVariable() + newSecret.direct("Some Value") val sesConfig = awsSesDomainConfiguration("email", "joseph@lightningkite.com".toEmailAddress()) email.awsSesSmtp(sesConfig) emailInbound.awsSesInbound( sesConfig, "https://lightningserver.cs.lightningkite.com/assistant-channels/email/webhook" ) - sms.byVariable() - smsInbound.byVariable() - pubsub.dynamoDb() - phoneCall.byVariable() - voiceAgent.byVariable() - githubOauth.byVariable() + sms.direct(SMS.Settings()) + smsInbound.direct(SmsInboundService.Settings()) + phoneCall.direct(PhoneCallService.Settings()) + voiceAgent.direct(VoiceAgentService.Settings()) notifications.direct(NotificationService.Settings("console")) + githubOauth.direct(OauthProviderCredentials("", "")) +// sms.byVariable() +// smsInbound.byVariable() +// phoneCall.byVariable() +// voiceAgent.byVariable() +// githubOauth.byVariable() + + pubsub.dynamoDb() } -} -object LkEnvDeploy { - @JvmStatic - fun main(vararg args: String) { - ProcessBuilder("./gradlew", "demo:lambda").inheritIO().start().waitFor() - LkEnv.deploy(autoApprove = true) + object LambdaDeploy { + @JvmStatic + fun main(vararg args: String) { + ProcessBuilder("./gradlew", "demo:lambda").inheritIO().start().waitFor() + deploy(autoApprove = true) + } } -} -object LkEnvEdit { - @JvmStatic - fun main(vararg args: String) { - println("EDIT TIME") - LkEnv.editVars() + object LambdaEdit { + @JvmStatic + fun main(vararg args: String) { + println("EDIT TIME") + editVars() + } } -} -object LkEnvDestroy { - @JvmStatic - fun main(vararg args: String) = LkEnv.terraform("destroy", "--auto-approve") -} + object LambdaDestroy { + @JvmStatic + fun main(vararg args: String) = terraform("destroy", "--auto-approve") + } + + object LambdaWrite { + @JvmStatic + fun main(vararg args: String) = write() + } -object LkEnvWrite { - @JvmStatic - fun main(vararg args: String) = LkEnv.write() + object LambdaShell { + @JvmStatic + fun main(vararg args: String) { + write() + println() + println("Entering Terraform Shell") + while (true) { + val next = readlnOrNull()?.also { if (it.isBlank()) continue } ?: break + try { + terraform(*next.split(' ').toTypedArray()) + } catch (_: Throwable) { + } + } + } + } } + diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/User.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/User.kt deleted file mode 100644 index 86cb02e87..000000000 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/User.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.lightningkite.lightningserver.demo.models - -import com.lightningkite.services.data.Queryable -import com.lightningkite.services.database.* -import kotlin.uuid.Uuid - -/** - * User model for authentication and authorization. - * - * This model demonstrates: - * - HasId interface for database primary key - * - HasEmail interface for email-based authentication - * - HasPassword interface for password hashing - * - Queryable for type-safe query DSL - */ -@Queryable -data class User( - override val _id: Uuid = Uuid.random(), - override val email: String, - override val hashedPassword: String = "", - val displayName: String = "", - val isSuperUser: Boolean = false, - val bio: String? = null, -) : HasId, HasEmail, HasPassword diff --git a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models.kt b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/models.kt similarity index 96% rename from demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models.kt rename to demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/models.kt index 286a56fec..b1b13f55e 100644 --- a/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models.kt +++ b/demo/src/main/kotlin/com/lightningkite/lightningserver/demo/models/models.kt @@ -1,4 +1,4 @@ -package com.lightningkite.lightningserver.demo +package com.lightningkite.lightningserver.demo.models import com.lightningkite.services.data.* import com.lightningkite.services.database.* diff --git a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/AuthExamplesEndpointsTest.kt b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/AuthExamplesEndpointsTest.kt index 7c2a12e49..9ec6aca3b 100644 --- a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/AuthExamplesEndpointsTest.kt +++ b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/AuthExamplesEndpointsTest.kt @@ -2,6 +2,8 @@ package com.lightningkite.lightningserver.demo import com.lightningkite.lightningserver.auth.Authentication import com.lightningkite.lightningserver.demo.endpoints.AuthExamplesEndpoints +import com.lightningkite.lightningserver.demo.endpoints.UserEndpoints +import com.lightningkite.lightningserver.demo.models.User import com.lightningkite.lightningserver.http.HttpStatus import com.lightningkite.lightningserver.runtime.test.execute import com.lightningkite.lightningserver.typed.test @@ -17,8 +19,8 @@ class AuthExamplesEndpointsTest { @Test fun whoAmIReturnsTheCallersOwnIdentity() = runBlocking { TestHelper.testServer { - val user = execute { Server.userInfo.table().insertOne(User(email = "whoami@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "whoami@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) val result = AuthExamplesEndpoints.whoAmI.test(auth, Unit) @@ -47,8 +49,8 @@ class AuthExamplesEndpointsTest { @Test fun greetIsPersonalForLoggedInCallers() = runBlocking { TestHelper.testServer { - val user = execute { Server.userInfo.table().insertOne(User(email = "greet@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "greet@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) val result = AuthExamplesEndpoints.greet.test(auth, Unit) @@ -68,8 +70,8 @@ class AuthExamplesEndpointsTest { @Test fun adminOnlyRejectsALoggedInNonAdminFromItsHandlerBody() = runBlocking { TestHelper.testServer { - val user = execute { Server.userInfo.table().insertOne(User(email = "regular@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "regular@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) val exception = assertFailsWith { AuthExamplesEndpoints.adminOnly.test(auth, Unit) @@ -83,9 +85,9 @@ class AuthExamplesEndpointsTest { fun adminOnlyAdmitsALoggedInSuperUserFromItsHandlerBody() = runBlocking { TestHelper.testServer { val admin = execute { - Server.userInfo.table().insertOne(User(email = "admin@example.com", isSuperUser = true))!! + UserEndpoints.info.table().insertOne(User(email = "admin@example.com", isSuperUser = true))!! } - val auth = Authentication(Server.UserAuth, id = admin._id, sessionId = null) + val auth = Authentication(UserAuth, id = admin._id, sessionId = null) val result = AuthExamplesEndpoints.adminOnly.test(auth, Unit) @@ -94,7 +96,7 @@ class AuthExamplesEndpointsTest { } /** - * Proves that ModelPermissions.readMask on Server.userInfo actually masks fields for a + * Proves that ModelPermissions.readMask on UserEndpoints.info actually masks fields for a * non-self, non-admin caller - the concrete manifestation the task asked for, rather than a * new endpoint duplicating what GET /user/rest/{id} already does. */ @@ -102,20 +104,20 @@ class AuthExamplesEndpointsTest { fun aStrangerSeesAnotherUsersHashedPasswordMasked() = runBlocking { TestHelper.testServer { val (target, stranger) = execute { - val target = Server.userInfo.table().insertOne( + val target = UserEndpoints.info.table().insertOne( User(email = "target@example.com", hashedPassword = "super-secret-hash") )!! - val stranger = Server.userInfo.table().insertOne(User(email = "stranger@example.com"))!! + val stranger = UserEndpoints.info.table().insertOne(User(email = "stranger@example.com"))!! target to stranger } - val strangerAuth = Authentication(Server.UserAuth, id = stranger._id, sessionId = null) + val strangerAuth = Authentication(UserAuth, id = stranger._id, sessionId = null) - val seenByStranger = Server.UserEndpoints.rest.detail.test(target._id, strangerAuth, Unit) + val seenByStranger = UserEndpoints.rest.detail.test(target._id, strangerAuth, Unit) assertEquals("", seenByStranger.hashedPassword) // Sanity check: the target sees their own hash unmasked. - val targetAuth = Authentication(Server.UserAuth, id = target._id, sessionId = null) - val seenBySelf = Server.UserEndpoints.rest.detail.test(target._id, targetAuth, Unit) + val targetAuth = Authentication(UserAuth, id = target._id, sessionId = null) + val seenBySelf = UserEndpoints.rest.detail.test(target._id, targetAuth, Unit) assertEquals("super-secret-hash", seenBySelf.hashedPassword) } } diff --git a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/LoginFlowTest.kt b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/LoginFlowTest.kt index 4adfd62c2..94236c149 100644 --- a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/LoginFlowTest.kt +++ b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/LoginFlowTest.kt @@ -7,6 +7,8 @@ package com.lightningkite.lightningserver.demo import com.lightningkite.lightningserver.auth.Authentication import com.lightningkite.lightningserver.demo.endpoints.AuthExamplesEndpoints +import com.lightningkite.lightningserver.demo.endpoints.UserEndpoints +import com.lightningkite.lightningserver.demo.models.email import com.lightningkite.lightningserver.runtime.test.TestRunner import com.lightningkite.lightningserver.runtime.test.execute import com.lightningkite.lightningserver.runtime.test.testBlocking @@ -67,12 +69,12 @@ class LoginFlowTest { // 5. UserAuth.fetchByProperty creates the User row on first login - verify it landed. val user = assertNotNull( - execute { Server.userInfo.table().findOne(Condition { it.email eq address }) }, + execute { UserEndpoints.info.table().findOne(Condition { it.email eq address }) }, "logging in for the first time should have created the user", ) // 6. The session actually authenticates - call an auth-gated endpoint with it. - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val auth = Authentication(UserAuth, id = user._id, sessionId = null) val whoAmI = AuthExamplesEndpoints.whoAmI.test(auth, Unit) assertEquals(user._id, whoAmI.id) assertEquals(address, whoAmI.email) @@ -124,7 +126,7 @@ class LoginFlowTest { assertEquals( 1, - execute { Server.userInfo.table().count(Condition { it.email eq address }) }, + execute { UserEndpoints.info.table().count(Condition { it.email eq address }) }, "the second login should reuse the user created by the first", ) } diff --git a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/ServiceExamplesEndpointsTest.kt b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/ServiceExamplesEndpointsTest.kt index 550c52189..7810856f7 100644 --- a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/ServiceExamplesEndpointsTest.kt +++ b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/ServiceExamplesEndpointsTest.kt @@ -2,6 +2,8 @@ package com.lightningkite.lightningserver.demo import com.lightningkite.lightningserver.auth.Authentication import com.lightningkite.lightningserver.demo.endpoints.ServiceExamplesEndpoints +import com.lightningkite.lightningserver.demo.endpoints.UserEndpoints +import com.lightningkite.lightningserver.demo.models.User import com.lightningkite.lightningserver.runtime.test.TestRunner import com.lightningkite.lightningserver.runtime.test.execute import com.lightningkite.lightningserver.runtime.test.testBlocking @@ -45,8 +47,8 @@ class ServiceExamplesEndpointsTest { @Test fun sendEmailUsesTheConfiguredEmailService() = serviceTest { - val user = execute { Server.userInfo.table().insertOne(User(email = "caller@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "caller@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) ServiceExamplesEndpoints.sendEmail.test(auth, "recipient@example.com".toEmailAddress()) @@ -56,8 +58,8 @@ class ServiceExamplesEndpointsTest { @Test fun sendSmsUsesTheConfiguredSmsService() = serviceTest { - val user = execute { Server.userInfo.table().insertOne(User(email = "caller@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "caller@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) ServiceExamplesEndpoints.sendSms.test(auth, "+15555550123".toPhoneNumber()) @@ -67,8 +69,8 @@ class ServiceExamplesEndpointsTest { @Test fun placeCallStartsSpeaksAndHangsUp() = serviceTest { - val user = execute { Server.userInfo.table().insertOne(User(email = "caller@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "caller@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) ServiceExamplesEndpoints.placeCall.test(auth, "+15555550123".toPhoneNumber()) @@ -81,8 +83,8 @@ class ServiceExamplesEndpointsTest { @Test fun pushNotificationSendsToTheGivenToken() = serviceTest { - val user = execute { Server.userInfo.table().insertOne(User(email = "caller@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "caller@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) ServiceExamplesEndpoints.pushNotification.test(auth, "device-token-123") @@ -92,8 +94,8 @@ class ServiceExamplesEndpointsTest { @Test fun readSecretReturnsTheConfiguredValue() = serviceTest { - val user = execute { Server.userInfo.table().insertOne(User(email = "caller@example.com"))!! } - val auth = Authentication(Server.UserAuth, id = user._id, sessionId = null) + val user = execute { UserEndpoints.info.table().insertOne(User(email = "caller@example.com"))!! } + val auth = Authentication(UserAuth, id = user._id, sessionId = null) val result = ServiceExamplesEndpoints.readSecret.test(auth, Unit) diff --git a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/TestModelTest.kt b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/TestModelTest.kt index 1867751b3..cf83eaf64 100644 --- a/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/TestModelTest.kt +++ b/demo/src/test/kotlin/com/lightningkite/lightningserver/demo/TestModelTest.kt @@ -1,5 +1,6 @@ package com.lightningkite.lightningserver.demo +import com.lightningkite.lightningserver.demo.models.* import com.lightningkite.services.database.* import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking diff --git a/demo/terraform/lkec2/.terraform.lock.hcl b/demo/terraform/ec2-scaling/.terraform.lock.hcl similarity index 95% rename from demo/terraform/lkec2/.terraform.lock.hcl rename to demo/terraform/ec2-scaling/.terraform.lock.hcl index 19cfbcfb8..530891a73 100644 --- a/demo/terraform/lkec2/.terraform.lock.hcl +++ b/demo/terraform/ec2-scaling/.terraform.lock.hcl @@ -5,6 +5,7 @@ provider "registry.terraform.io/hashicorp/archive" { version = "2.7.1" constraints = "~> 2.7.0" hashes = [ + "h1:62VrkalDPMKB9zerCBS4iKTbvxejwnAWn/XXYZZQWD4=", "h1:A7EnRBVm4h9ryO9LwxYnKr4fy7ExPMwD5a1DsY7m1Y0=", "zh:19881bb356a4a656a865f48aee70c0b8a03c35951b7799b6113883f67f196e8e", "zh:2fcfbf6318dd514863268b09bbe19bfc958339c636bcbcc3664b45f2b8bf5cc6", @@ -25,6 +26,7 @@ provider "registry.terraform.io/hashicorp/aws" { version = "6.34.0" constraints = ">= 6.28.0, ~> 6.34.0" hashes = [ + "h1:ZGSMOPC+Du0cKJ2kV1Ni8Rnz7ezsIu+jYFEknpye5CM=", "h1:wXPejniDcbqRtL2zzaeZsmjLe7NekeYD5QjlIzUOylI=", "zh:1e49dc96bf50633583e3cbe23bb357642e7e9afe135f54e061e26af6310e50d2", "zh:45651bb4dad681f17782d99d9324de182a7bb9fbe9dd22f120fdb7fe42969cc9", @@ -49,6 +51,7 @@ provider "registry.terraform.io/hashicorp/external" { constraints = "~> 2.3.0" hashes = [ "h1:FnUk98MI5nOh3VJ16cHf8mchQLewLfN1qZG/MqNgPrI=", + "h1:smKSos4zs57pJjQrNuvGBpSWth2el9SgePPbPHo0aps=", "zh:6e89509d056091266532fa64de8c06950010498adf9070bf6ff85bc485a82562", "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", "zh:86868aec05b58dc0aa1904646a2c26b9367d69b890c9ad70c33c0d3aa7b1485a", @@ -68,6 +71,7 @@ provider "registry.terraform.io/hashicorp/local" { version = "2.7.0" constraints = "~> 2.7.0" hashes = [ + "h1:2RYa3j7m/0WmET2fqotY4CHxE1Hpk0fgn47/126l+Og=", "h1:sSwlfp2etjCaE9hIF7bJBDjRIhDCVFglEOVyiCI7vgs=", "zh:261fec71bca13e0a7812dc0d8ae9af2b4326b24d9b2e9beab3d2400fab5c5f9a", "zh:308da3b5376a9ede815042deec5af1050ec96a5a5410a2206ae847d82070a23e", @@ -89,6 +93,7 @@ provider "registry.terraform.io/hashicorp/null" { constraints = "~> 3.2.3" hashes = [ "h1:L5V05xwp/Gto1leRryuesxjMfgZwjb7oool4WS1UEFQ=", + "h1:hkf5w5B6q8e2A42ND2CjAvgvSN3puAosDmOJb3zCVQM=", "zh:59f6b52ab4ff35739647f9509ee6d93d7c032985d9f8c6237d1f8a59471bbbe2", "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", "zh:795c897119ff082133150121d39ff26cb5f89a730a2c8c26f3a9c1abf81a9c43", @@ -108,6 +113,7 @@ provider "registry.terraform.io/hashicorp/random" { version = "3.8.1" constraints = "~> 3.8.0" hashes = [ + "h1:Eexl06+6J+s75uD46+WnZtpJZYRVUMB0AiuPBifK6Jc=", "h1:u8AKlWVDTH5r9YLSeswoVEjiY72Rt4/ch7U+61ZDkiQ=", "zh:08dd03b918c7b55713026037c5400c48af5b9f468f483463321bd18e17b907b4", "zh:0eee654a5542dc1d41920bbf2419032d6f0d5625b03bd81339e5b33394a3e0ae", diff --git a/demo/terraform/lkec2/alb.tf.json b/demo/terraform/ec2-scaling/alb.tf.json similarity index 92% rename from demo/terraform/lkec2/alb.tf.json rename to demo/terraform/ec2-scaling/alb.tf.json index b5953023f..3128bf6c3 100644 --- a/demo/terraform/lkec2/alb.tf.json +++ b/demo/terraform/ec2-scaling/alb.tf.json @@ -4,7 +4,7 @@ "alb_logs": { "statement": { "resources": [ - "${aws_s3_bucket.alb_logs.arn}/LightningServerEC2SDemo/*" + "${aws_s3_bucket.alb_logs.arn}/ec2-scaling-demo/*" ], "principals": { "identifiers": [ @@ -31,10 +31,10 @@ "aws_s3_bucket_policy.alb_logs" ], "load_balancer_type": "application", - "name": "LightningServerEC2SDemo-alb", + "name": "ec2-scaling-demo-alb", "access_logs": { "bucket": "${aws_s3_bucket.alb_logs.id}", - "prefix": "LightningServerEC2SDemo", + "prefix": "ec2-scaling-demo", "enabled": true }, "ip_address_type": "dualstack", @@ -55,6 +55,9 @@ "alb_logs": { "bucket": "${aws_s3_bucket.alb_logs.id}", "rule": { + "blocked_encryption_types": [ + "SSE-C" + ], "apply_server_side_encryption_by_default": { "sse_algorithm": "AES256" } @@ -124,7 +127,7 @@ "protocol": "HTTP", "port": 8080, "vpc_id": "${module.vpc.vpc_id}", - "name": "LightningServerEC2SDemo-tg", + "name": "ec2-scaling-demo-tg", "target_type": "instance", "deregistration_delay": 30, "health_check": { @@ -142,7 +145,7 @@ "aws_s3_bucket": { "alb_logs": { "force_destroy": true, - "bucket_prefix": "lightningserverec2sdemo-alb-logs" + "bucket_prefix": "ec2-scaling-demo-alb-logs" } }, "aws_acm_certificate": { @@ -150,7 +153,7 @@ "lifecycle": { "create_before_destroy": true }, - "domain_name": "lightningserver2.cs.lightningkite.com", + "domain_name": "scaling-demo.cs.lightningkite.com", "validation_method": "DNS" } }, diff --git a/demo/terraform/lkec2/asg.tf.json b/demo/terraform/ec2-scaling/asg.tf.json similarity index 89% rename from demo/terraform/lkec2/asg.tf.json rename to demo/terraform/ec2-scaling/asg.tf.json index 304e94bdc..6916f6eb1 100644 --- a/demo/terraform/lkec2/asg.tf.json +++ b/demo/terraform/ec2-scaling/asg.tf.json @@ -2,9 +2,9 @@ "resource": { "aws_launch_template": { "app": { - "name_prefix": "LightningServerEC2SDemo-", + "name_prefix": "ec2-scaling-demo-", "block_device_mappings": { - "device_name": "/dev/sda1", + "device_name": "/dev/xvda", "ebs": { "volume_type": "gp3", "encrypted": true, @@ -24,7 +24,7 @@ "tag_specifications": { "resource_type": "instance", "tags": { - "Name": "Lightning Server Demo" + "Name": "Lightning Server EC2 Scaling Demo" } }, "vpc_security_group_ids": [ @@ -40,7 +40,7 @@ "cpu": { "autoscaling_group_name": "${aws_autoscaling_group.app.name}", "policy_type": "TargetTrackingScaling", - "name": "LightningServerEC2SDemo-cpu-target", + "name": "ec2-scaling-demo-cpu-target", "target_tracking_configuration": { "predefined_metric_specification": { "predefined_metric_type": "ASGAverageCPUUtilization" @@ -73,7 +73,7 @@ "desired_capacity" ] }, - "name_prefix": "LightningServerEC2SDemo-", + "name_prefix": "ec2-scaling-demo-", "health_check_type": "ELB", "desired_capacity": 2, "vpc_zone_identifier": "${module.vpc.private_subnets}", @@ -81,12 +81,12 @@ "tag": [ { "propagate_at_launch": true, - "value": "Lightning Server Demo", + "value": "Lightning Server EC2 Scaling Demo", "key": "Name" }, { "propagate_at_launch": true, - "value": "LightningServerEC2SDemo", + "value": "ec2-scaling-demo", "key": "lightning-server-asg" } ], diff --git a/demo/terraform/lkec2/boot.sh b/demo/terraform/ec2-scaling/boot.sh similarity index 91% rename from demo/terraform/lkec2/boot.sh rename to demo/terraform/ec2-scaling/boot.sh index 4cd7bcdb6..3d1b9cfe1 100644 --- a/demo/terraform/lkec2/boot.sh +++ b/demo/terraform/ec2-scaling/boot.sh @@ -10,4 +10,4 @@ DEPLOY_ENV_EOF # rolls back to the previous version on failure; on a brand-new instance there is nothing to # roll back to, so a hard failure here leaves the instance unhealthy and the ASG replaces it. /usr/local/bin/lightning-server-redeploy -systemctl enable LightningServerEC2SDemo || true \ No newline at end of file +systemctl enable ec2-scaling-demo || true \ No newline at end of file diff --git a/demo/terraform/lkec2/cloud.tf.json b/demo/terraform/ec2-scaling/cloud.tf.json similarity index 95% rename from demo/terraform/lkec2/cloud.tf.json rename to demo/terraform/ec2-scaling/cloud.tf.json index f70289f04..61634eb2b 100644 --- a/demo/terraform/lkec2/cloud.tf.json +++ b/demo/terraform/ec2-scaling/cloud.tf.json @@ -14,7 +14,7 @@ "aws_security_group": { "internal": { "vpc_id": "${module.vpc.vpc_id}", - "name": "LightningServerEC2SDemo-private" + "name": "ec2-scaling-demo-private" } }, "aws_vpc_security_group_ingress_rule": { @@ -54,7 +54,7 @@ "10.7.2.0/24", "10.7.3.0/24" ], - "name": "LightningServerEC2SDemo", + "name": "ec2-scaling-demo", "public_subnets": [ "10.7.100.0/24", "10.7.101.0/24", diff --git a/demo/terraform/ec2-scaling/deployment.tf.json b/demo/terraform/ec2-scaling/deployment.tf.json new file mode 100644 index 000000000..3ae77aaf4 --- /dev/null +++ b/demo/terraform/ec2-scaling/deployment.tf.json @@ -0,0 +1,349 @@ +{ + "data": { + "external": { + "jar_hash": { + "program": [ + "bash", + "-c", + "f=$(ls \"${path.module}/../../build/distributions/server.zip\" | head -1) && hash=$(sha256sum \"$f\" | cut -d' ' -f1) && printf '{\"hash\":\"%s\",\"path\":\"%s\"}' \"$hash\" \"$f\"" + ] + } + } + }, + "resource": { + "aws_s3_bucket_public_access_block": { + "deployment": { + "bucket": "${aws_s3_bucket.deployment.id}", + "block_public_policy": true, + "block_public_acls": true, + "ignore_public_acls": true, + "restrict_public_buckets": true + } + }, + "aws_s3_bucket_server_side_encryption_configuration": { + "deployment": { + "bucket": "${aws_s3_bucket.deployment.id}", + "rule": { + "blocked_encryption_types": [ + "SSE-C" + ], + "apply_server_side_encryption_by_default": { + "sse_algorithm": "AES256" + } + } + } + }, + "aws_s3_bucket_lifecycle_configuration": { + "deployment": { + "bucket": "${aws_s3_bucket.deployment.id}", + "depends_on": [ + "aws_s3_bucket_versioning.deployment" + ], + "rule": [ + { + "id": "expire-noncurrent-versions", + "noncurrent_version_expiration": { + "noncurrent_days": 30 + }, + "status": "Enabled" + }, + { + "abort_incomplete_multipart_upload": { + "days_after_initiation": 7 + }, + "id": "abort-incomplete-multipart-uploads", + "status": "Enabled" + } + ] + } + }, + "aws_iam_role_policy_attachment": { + "ssm": { + "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", + "role": "${aws_iam_role.ec2.name}" + }, + "servicesAccess": { + "policy_arn": "${aws_iam_policy.servicesAccess.arn}", + "role": "${aws_iam_role.ec2.name}" + }, + "cloudwatch_agent": { + "policy_arn": "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy", + "role": "${aws_iam_role.ec2.name}" + } + }, + "null_resource": { + "upload_jar": { + "provisioner": { + "local-exec": { + "command": "aws s3 cp \"${data.external.jar_hash.result.path}\" s3://${aws_s3_bucket.deployment.id}/server.zip --region us-west-2 --progress-frequency 1" + } + }, + "depends_on": [ + "aws_s3_bucket.deployment" + ], + "triggers": { + "jar_hash": "${data.external.jar_hash.result.hash}" + } + }, + "encrypt_settings": { + "provisioner": { + "local-exec": { + "environment": { + "SETTINGS_PASS": "${random_password.settings.result}", + "SETTINGS_JSON": "${jsonencode(local.settings_raw)}" + }, + "interpreter": [ + "bash", + "-c" + ], + "command": "printf '%s' \"$SETTINGS_JSON\" | openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 -out \"${path.module}/build/settings.enc\" -pass env:SETTINGS_PASS" + } + }, + "triggers": { + "cipher": "-aes-256-cbc -pbkdf2 -iter 10000 -md sha256", + "password_hash": "${sha256(random_password.settings.result)}", + "settings_hash": "${sha256(jsonencode(local.settings_raw))}" + } + }, + "upload_settings": { + "provisioner": { + "local-exec": { + "command": "aws s3 cp \"${path.module}/build/settings.enc\" s3://${aws_s3_bucket.deployment.id}/settings.enc --region us-west-2" + } + }, + "depends_on": [ + "null_resource.encrypt_settings", + "aws_s3_bucket.deployment" + ], + "triggers": { + "encrypted": "${null_resource.encrypt_settings.id}" + } + } + }, + "aws_iam_policy": { + "servicesAccess": { + "path": "/ec2/scaling/demo/servicesAccess/", + "name": "ec2-scaling-demo-servicesAccess", + "description": "Access to Lightning Server EC2 Scaling Demo services", + "policy": "${jsonencode(local.servicesAccessPolicy)}" + } + }, + "aws_ssm_parameter": { + "settings_password": { + "name": "/ec2-scaling-demo/settings-password", + "description": "AES-256 passphrase used to encrypt/decrypt the Lightning Server EC2 Scaling Demo settings bundle", + "type": "SecureString", + "value": "${random_password.settings.result}" + } + }, + "aws_iam_role": { + "ec2": { + "name": "ec2-scaling-demo-ec2-role", + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}]}" + } + }, + "random_password": { + "settings": { + "special": true, + "length": 32, + "override_special": "-_" + } + }, + "aws_s3_bucket_versioning": { + "deployment": { + "bucket": "${aws_s3_bucket.deployment.id}", + "versioning_configuration": { + "status": "Enabled" + } + } + }, + "aws_iam_instance_profile": { + "ec2": { + "role": "${aws_iam_role.ec2.name}", + "name": "ec2-scaling-demo-ec2-profile" + } + }, + "aws_s3_bucket": { + "deployment": { + "force_destroy": true, + "bucket_prefix": "ec2-scaling-demo-deploy" + } + } + }, + "locals": { + "settings_raw": { + "cache": "redis://${aws_elasticache_replication_group.valkey.primary_endpoint_address}:${aws_elasticache_replication_group.valkey.port}/0", + "cors": { + "limitToDomains": [ + "*" + ], + "limitToHeaders": [ + "*" + ], + "limitToMethods": [ + "*" + ], + "exposedHeaders": [ + "*" + ], + "allowCredentials": true, + "cacheLength": "PT5S", + "forbidOnMatchFail": false + }, + "secretBasis": "${random_password.secretBasis.result}", + "ktorRunConfig": { + "host": "0.0.0.0", + "port": 8080, + "realIpHeader": "X-Forwarded-For" + }, + "engine-cache": "redis://${aws_elasticache_replication_group.valkey.primary_endpoint_address}:${aws_elasticache_replication_group.valkey.port}/0", + "phoneCall": "test", + "githubOauth": { + "id": "", + "secret": "" + }, + "engine-pubSub": "redis://${aws_elasticache_replication_group.valkey.primary_endpoint_address}:${aws_elasticache_replication_group.valkey.port}/0", + "nettyRunConfig": { + "host": "0.0.0.0", + "port": 8080, + "realIpHeader": "X-Forwarded-For" + }, + "general": { + "projectName": "Lightning Server EC2 Scaling Demo", + "publicUrl": "https://scaling-demo.cs.lightningkite.com", + "wsUrl": "wss://scaling-demo.cs.lightningkite.com", + "debug": true, + "emergencyContact": "joseph@lightningkite.com" + }, + "database": "ram", + "emailInbound": "console", + "sms": "console", + "files": "s3://${aws_s3_bucket.files.bucket}.s3-${aws_s3_bucket.files.region}.amazonaws.com/?signedUrlDuration=1d", + "logging": { + "default": { + "filePattern": null, + "toConsole": true, + "level": "INFO", + "additive": false + }, + "logger": { + "org.mongodb": { + "filePattern": null, + "toConsole": true, + "level": "WARN", + "additive": false + } + } + }, + "telemetry": { + "url": "noop", + "batching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "metricReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "traceReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "logReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 20480, + "maxSize": 5120, + "exportTimeout": "PT30S" + }, + "batchingLimits": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "spanLimits": { + "maxAttributeValueLength": 1024, + "maxNumberOfAttributes": 128, + "maxNumberOfEvents": 128, + "maxNumberOfLinks": 128, + "maxNumberOfAttributesPerEvent": 32, + "maxNumberOfAttributesPerLink": 32 + }, + "logLimits": { + "maxBodyLength": 8192, + "maxStackTraceDepth": 50 + }, + "sampling": null, + "maxSpansPerSecond": null, + "maxLogsPerSecond": null + }, + "someSecret": "Some Value", + "voiceAgent": "test", + "smsInbound": "console", + "email": "console", + "notifications": "console", + "pubSub": "redis://${aws_elasticache_replication_group.valkey.primary_endpoint_address}:${aws_elasticache_replication_group.valkey.port}/0" + }, + "servicesAccessPolicy": { + "Version": "2012-10-17", + "Statement": [ + { + "Action": [ + "s3:ListBucket", + "s3:GetBucketLocation" + ], + "Effect": "Allow", + "Resource": [ + "${aws_s3_bucket.files.arn}" + ] + }, + { + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Effect": "Allow", + "Resource": [ + "${aws_s3_bucket.files.arn}/*" + ] + }, + { + "Action": [ + "s3:GetObject" + ], + "Effect": "Allow", + "Resource": [ + "${aws_s3_bucket.deployment.arn}/*" + ] + }, + { + "Action": [ + "logs:CreateLogStream", + "logs:PutLogEvents", + "logs:DescribeLogStreams" + ], + "Effect": "Allow", + "Resource": [ + "${aws_cloudwatch_log_group.application.arn}:*" + ] + }, + { + "Action": [ + "ssm:GetParameter" + ], + "Effect": "Allow", + "Resource": [ + "${aws_ssm_parameter.settings_password.arn}" + ] + } + ] + } + } +} \ No newline at end of file diff --git a/demo/terraform/lkec2/dns.tf.json b/demo/terraform/ec2-scaling/dns.tf.json similarity index 87% rename from demo/terraform/lkec2/dns.tf.json rename to demo/terraform/ec2-scaling/dns.tf.json index 5a7272ef8..c2e015b51 100644 --- a/demo/terraform/lkec2/dns.tf.json +++ b/demo/terraform/ec2-scaling/dns.tf.json @@ -10,7 +10,7 @@ "aws_route53_record": { "alias_a": { "zone_id": "${data.aws_route53_zone.main.zone_id}", - "name": "lightningserver2.cs.lightningkite.com", + "name": "scaling-demo.cs.lightningkite.com", "alias": { "zone_id": "${aws_lb.app.zone_id}", "evaluate_target_health": true, @@ -20,7 +20,7 @@ }, "alias_aaaa": { "zone_id": "${data.aws_route53_zone.main.zone_id}", - "name": "lightningserver2.cs.lightningkite.com", + "name": "scaling-demo.cs.lightningkite.com", "alias": { "zone_id": "${aws_lb.app.zone_id}", "evaluate_target_health": true, diff --git a/demo/terraform/ec2-scaling/files.tf.json b/demo/terraform/ec2-scaling/files.tf.json new file mode 100644 index 000000000..d600c2fb5 --- /dev/null +++ b/demo/terraform/ec2-scaling/files.tf.json @@ -0,0 +1,67 @@ +{ + "resource": { + "aws_s3_bucket_cors_configuration": { + "files": { + "bucket": "${aws_s3_bucket.files.bucket}", + "cors_rule": [ + { + "allowed_methods": [ + "PUT", + "POST" + ], + "allowed_headers": [ + "*" + ], + "expose_headers": [ + "ETag" + ], + "max_age_seconds": 3000, + "allowed_origins": [ + "*" + ] + }, + { + "allowed_methods": [ + "GET", + "HEAD" + ], + "allowed_headers": [ + "*" + ], + "allowed_origins": [ + "*" + ] + } + ] + } + }, + "aws_s3_bucket_public_access_block": { + "files": { + "bucket": "${aws_s3_bucket.files.id}", + "block_public_policy": true, + "block_public_acls": true, + "ignore_public_acls": true, + "restrict_public_buckets": true + } + }, + "aws_s3_bucket_server_side_encryption_configuration": { + "files": { + "bucket": "${aws_s3_bucket.files.id}", + "rule": { + "blocked_encryption_types": [ + "SSE-C" + ], + "apply_server_side_encryption_by_default": { + "sse_algorithm": "AES256" + } + } + } + }, + "aws_s3_bucket": { + "files": { + "force_destroy": true, + "bucket_prefix": "ec2-scaling-demo-files" + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-scaling/image.tf.json b/demo/terraform/ec2-scaling/image.tf.json new file mode 100644 index 000000000..1dec0b73e --- /dev/null +++ b/demo/terraform/ec2-scaling/image.tf.json @@ -0,0 +1,187 @@ +{ + "data": { + "aws_ami": { + "base": { + "filter": [ + { + "values": [ + "al2023-ami-2023.*-kernel-*-arm64" + ], + "name": "name" + }, + { + "values": [ + "arm64" + ], + "name": "architecture" + }, + { + "values": [ + "hvm" + ], + "name": "virtualization-type" + } + ], + "most_recent": true, + "owners": [ + "amazon" + ] + } + } + }, + "resource": { + "aws_iam_role_policy_attachment": { + "imagebuilder_core": { + "policy_arn": "arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder", + "role": "${aws_iam_role.imagebuilder.name}" + }, + "imagebuilder_ssm": { + "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", + "role": "${aws_iam_role.imagebuilder.name}" + } + }, + "aws_cloudwatch_log_group": { + "imagebuilder": { + "retention_in_days": 30, + "name": "/aws/imagebuilder/ec2-scaling-demo" + } + }, + "aws_imagebuilder_image": { + "this": { + "image_tests_configuration": { + "image_tests_enabled": false + }, + "logging_configuration": { + "log_group_name": "${aws_cloudwatch_log_group.imagebuilder.name}" + }, + "infrastructure_configuration_arn": "${aws_imagebuilder_infrastructure_configuration.this.arn}", + "image_recipe_arn": "${aws_imagebuilder_image_recipe.this.arn}", + "distribution_configuration_arn": "${aws_imagebuilder_distribution_configuration.this.arn}" + } + }, + "aws_iam_role": { + "imagebuilder": { + "name": "ec2-scaling-demo-imagebuilder-role", + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}]}" + } + }, + "aws_imagebuilder_distribution_configuration": { + "this": { + "name": "ec2-scaling-demo-dist", + "distribution": { + "ami_distribution_configuration": { + "name": "ec2-scaling-demo-{{ imagebuilder:buildDate }}" + }, + "region": "us-west-2" + } + } + }, + "terraform_data": { + "base_ami": { + "lifecycle": { + "ignore_changes": [ + "input" + ] + }, + "input": { + "name": "${data.aws_ami.base.name}", + "id": "${data.aws_ami.base.id}" + }, + "triggers_replace": { + "distro": "AmazonLinux2023", + "salt": "${local.image_salt}" + } + } + }, + "aws_iam_instance_profile": { + "imagebuilder": { + "role": "${aws_iam_role.imagebuilder.name}", + "name": "ec2-scaling-demo-imagebuilder-profile" + } + }, + "aws_imagebuilder_component": { + "install": { + "depends_on": [ + "aws_s3_object.image_data" + ], + "name": "ec2-scaling-demo-install", + "version": "1.${regex(\"[0-9]{8}\", terraform_data.base_ami.output.name)}.${local.image_data_version}", + "uri": "s3://${aws_s3_bucket.deployment.id}/${aws_s3_object.image_data.key}", + "platform": "Linux" + } + }, + "aws_imagebuilder_image_recipe": { + "this": { + "lifecycle": { + "create_before_destroy": true + }, + "component": [ + { + "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/aws-cli-version-2-linux/x.x.x" + }, + { + "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/amazon-cloudwatch-agent-linux/x.x.x" + }, + { + "component_arn": "${aws_imagebuilder_component.install.arn}" + } + ], + "block_device_mapping": { + "device_name": "/dev/xvda", + "ebs": { + "volume_type": "gp3", + "encrypted": true, + "volume_size": 20, + "delete_on_termination": true + } + }, + "name": "ec2-scaling-demo-recipe", + "parent_image": "${terraform_data.base_ami.output.id}", + "version": "1.${regex(\"[0-9]{8}\", terraform_data.base_ami.output.name)}.${local.image_data_version}" + } + }, + "aws_s3_object": { + "image_data": { + "bucket": "${aws_s3_bucket.deployment.id}", + "content_type": "text/yaml", + "key": "imagebuilder/component-${local.image_data_version}.yaml", + "content": "${local.image_data}" + } + }, + "aws_imagebuilder_infrastructure_configuration": { + "this": { + "instance_types": [ + "t4g.micro" + ], + "terminate_instance_on_failure": true, + "instance_profile_name": "${aws_iam_instance_profile.imagebuilder.name}", + "instance_metadata_options": { + "http_tokens": "required", + "http_put_response_hop_limit": 2 + }, + "name": "ec2-scaling-demo-infra", + "subnet_id": "${module.vpc.private_subnets[0]}", + "security_group_ids": [ + "${aws_security_group.instance.id}" + ] + } + } + }, + "locals": { + "image_components": [ + { + "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/aws-cli-version-2-linux/x.x.x" + }, + { + "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/amazon-cloudwatch-agent-linux/x.x.x" + } + ], + "image_recipe_inputs": { + "base_ami": "${terraform_data.base_ami.output.id}", + "volume_size": 20 + }, + "image_data": "${templatefile(\"${path.module}/image_data.yaml\", { })}", + "image_salt": "1", + "image_data_version": "${max(1, parseint(substr(sha256(jsonencode([local.image_data, local.image_salt, local.image_components, local.image_recipe_inputs])), 0, 7), 16))}" + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-scaling/image_data.yaml b/demo/terraform/ec2-scaling/image_data.yaml new file mode 100644 index 000000000..15065ea64 --- /dev/null +++ b/demo/terraform/ec2-scaling/image_data.yaml @@ -0,0 +1,554 @@ +name: ec2-scaling-demo-install +description: Install base tooling for Lightning Server EC2 Scaling Demo +schemaVersion: 1.0 +phases: + - name: build + steps: + - name: Install + action: ExecuteBash + inputs: + commands: + - | + #!/bin/bash + set -euo pipefail + export DEBIAN_FRONTEND=noninteractive + + + # === Disable unattended upgrades === + echo "[INFO] Disabling dnf automatic update and metadata timers at $(date)" + systemctl disable --now dnf-automatic.timer dnf-automatic-install.timer || true + systemctl disable --now dnf-makecache.timer || true + systemctl mask dnf-makecache.timer || true + + # === System update + base packages === + echo "[INFO] Updating system packages at $(date)" + dnf -y --releasever=latest upgrade + dnf install -y java-17-amazon-corretto-headless openssl unzip + dnf -y autoremove + + + # === Swap === + echo "[INFO] Configuring 1024MiB swap file at $(date)" + cat > /usr/local/bin/ec2-scaling-demo-swap-setup << 'SWAP_SETUP_EOF' + #!/bin/bash + set -euo pipefail + + SWAPFILE="/swapfile" + SIZE_MIB=1024 + SIZE_BYTES=$((SIZE_MIB * 1024 * 1024)) + + log() { echo "[swap-setup] $*"; } + + if swapon --show=NAME --noheadings 2>/dev/null | awk '{print $1}' | grep -qx "$SWAPFILE"; then + if [ "$(stat -c %s "$SWAPFILE")" -eq "$SIZE_BYTES" ]; then + log "$SWAPFILE is already active at $SIZE_MIB MiB" + exit 0 + fi + log "Swap size changed; rebuilding $SWAPFILE" + swapoff "$SWAPFILE" + fi + + # A reboot leaves the file on disk with swap off. Re-enabling it beats rewriting it, and on an + # instance that had to fall back to dd it is the difference between an instant boot and writing the + # whole file out again every single time. A file that is the right size but unusable (never mkswap'd, + # truncated) simply fails swapon here and gets rebuilt below. + if [ -f "$SWAPFILE" ] && [ "$(stat -c %s "$SWAPFILE")" -eq "$SIZE_BYTES" ]; then + chmod 600 "$SWAPFILE" + if swapon "$SWAPFILE" 2>/dev/null; then + log "Reusing existing $SWAPFILE at $SIZE_MIB MiB" + exit 0 + fi + log "Existing $SWAPFILE could not be enabled; rebuilding" + fi + + allocate() { + rm -f "$SWAPFILE" + if [ "$1" = "fallocate" ]; then + fallocate -l "$SIZE_MIB"M "$SWAPFILE" + else + dd if=/dev/zero of="$SWAPFILE" bs=1M count="$SIZE_MIB" status=none + fi + chmod 600 "$SWAPFILE" + mkswap "$SWAPFILE" >/dev/null + } + + # fallocate is instant but can leave unwritten extents, which swapon refuses on some filesystems; + # writing the file out with dd is the slow fallback that always produces a usable swap file. + allocate fallocate + if ! swapon "$SWAPFILE"; then + log "swapon rejected the preallocated file, rewriting it with dd" + allocate dd + swapon "$SWAPFILE" + fi + log "Swap enabled: $SIZE_MIB MiB" + SWAP_SETUP_EOF + chmod +x /usr/local/bin/ec2-scaling-demo-swap-setup + + cat > /etc/sysctl.d/60-ec2-scaling-demo-swap.conf << 'SWAP_SYSCTL_EOF' + vm.swappiness=10 + SWAP_SYSCTL_EOF + sysctl -p /etc/sysctl.d/60-ec2-scaling-demo-swap.conf >/dev/null || true + + cat > /etc/systemd/system/ec2-scaling-demo-swap.service << 'SWAP_UNIT_EOF' + [Unit] + Description=Lightning Server EC2 Scaling Demo swap file + After=local-fs.target + Before=ec2-scaling-demo.service + + [Service] + Type=oneshot + RemainAfterExit=yes + ExecStart=/usr/local/bin/ec2-scaling-demo-swap-setup + + [Install] + WantedBy=multi-user.target + SWAP_UNIT_EOF + + systemctl daemon-reload + systemctl enable ec2-scaling-demo-swap.service + + + # === CloudWatch Agent Configuration === + echo "[INFO] Creating amazon-cloudwatch-agent.json for CloudWatch $(date)" + cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json << EOF + { + "logs": { + "logs_collected": { + "files": { + "collect_list": [ + { + "file_path": "/var/log/ec2-scaling-demo/ec2_init.log", + "log_group_name": "ec2-scaling-demo-main-log", + "log_stream_name": "{instance_id}/ec2_init" + }, + { + "file_path": "/var/log/ec2-scaling-demo/server.log", + "log_group_name": "ec2-scaling-demo-main-log", + "log_stream_name": "{instance_id}/server" + }, + { + "file_path": "/var/log/ec2-scaling-demo/redeploy.log", + "log_group_name": "ec2-scaling-demo-main-log", + "log_stream_name": "{instance_id}/redeploy" + }, + { + "file_path": "/var/log/ec2-scaling-demo/os-update.log", + "log_group_name": "ec2-scaling-demo-main-log", + "log_stream_name": "{instance_id}/os-update" + } + ] + } + } + }, + "metrics": { + "metrics_collected": { + "mem": { + "measurement": ["mem_used_percent"] + }, + "disk": { + "measurement": ["disk_used_percent"], + "resources": ["/"] + } + } + } + } + EOF + + systemctl enable amazon-cloudwatch-agent + systemctl restart amazon-cloudwatch-agent + + + # === SSM Agent === + echo "[INFO] Ensuring SSM agent is installed and running at $(date)" + # Required so terraform can drive in-place jar/settings redeploys via + # `aws ssm send-command`. The AL2023 AMI ships amazon-ssm-agent as an RPM; install if missing, + # then enable + start so newly-created instances register with SSM. + rpm -q amazon-ssm-agent >/dev/null 2>&1 || dnf install -y amazon-ssm-agent + systemctl enable amazon-ssm-agent + systemctl start amazon-ssm-agent + + + # === Service User === + echo "[INFO] Creating unprivileged service user lightning-server" + id -u lightning-server >/dev/null 2>&1 || useradd --system --user-group --home-dir /var/lib/ec2-scaling-demo --no-create-home --shell /usr/sbin/nologin lightning-server + + # === Filesystem Layout === + # Code: owned by root, so the service can run it but never modify it. + install -d -o root -g root -m 0755 /opt/ec2-scaling-demo + # Config (settings.json, Config instance files): readable by the service, writable only by root. + install -d -o root -g lightning-server -m 0750 /etc/ec2-scaling-demo + # State and cache: the service's own. systemd's StateDirectory=/CacheDirectory= also manage these. + install -d -o lightning-server -g lightning-server -m 0700 /var/lib/ec2-scaling-demo + install -d -o lightning-server -g lightning-server -m 0700 /var/cache/ec2-scaling-demo + + # === Systemd Service === + echo "[INFO] Creating Systemd unit for Lightning Server EC2 Scaling Demo" + cat > /etc/systemd/system/ec2-scaling-demo.service << 'UNIT_EOF' + [Unit] + Description=Lightning Server EC2 Scaling Demo + After=network.target + Requires=network.target + + [Service] + Type=simple + User=lightning-server + Group=lightning-server + WorkingDirectory=/var/lib/ec2-scaling-demo + ExecStart=/opt/ec2-scaling-demo/server/bin/server serve + StateDirectory=ec2-scaling-demo + StateDirectoryMode=0700 + CacheDirectory=ec2-scaling-demo + CacheDirectoryMode=0700 + LogsDirectory=ec2-scaling-demo + # Apps load settings.json relative to the working directory. A read-only bind mount (not a symlink, + # which the service could swap since it owns the directory) keeps that working without letting the + # service replace it. No '-' prefix: with no settings deployed yet, the service must not start. + BindReadOnlyPaths=/etc/ec2-scaling-demo/settings.enc:/var/lib/ec2-scaling-demo/settings.json + # Settings stay encrypted on disk. '+' runs the key fetch as root outside the sandbox; it writes the + # RAM-backed, root-only file whose password systemd hands to the app. systemd loads EnvironmentFile= + # before every Exec* (ExecStartPre included), so '-' lets the key fetch run before the file exists. + ExecStartPre=+/usr/local/bin/ec2-scaling-demo-settings-key + EnvironmentFile=-/run/ec2-scaling-demo-secrets/settings.env + NoNewPrivileges=true + UMask=0077 + ProtectSystem=strict + ProtectHome=true + PrivateTmp=true + PrivateDevices=true + ProtectProc=invisible + ProtectKernelTunables=true + ProtectKernelModules=true + ProtectKernelLogs=true + ProtectControlGroups=true + ProtectClock=true + ProtectHostname=true + RestrictSUIDSGID=true + RestrictNamespaces=true + RestrictRealtime=true + RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK + LockPersonality=true + SystemCallArchitectures=native + + + Restart=always + RestartSec=5 + StandardOutput=append:/var/log/ec2-scaling-demo/server.log + StandardError=append:/var/log/ec2-scaling-demo/server.log + + + + + [Install] + WantedBy=multi-user.target + UNIT_EOF + + # === Server log file === + echo "[INFO] Preparing server log directory" + mkdir -p /var/log/ec2-scaling-demo + touch /var/log/ec2-scaling-demo/server.log + chown -R lightning-server:lightning-server /var/log/ec2-scaling-demo + + cat > /etc/logrotate.d/ec2-scaling-demo << 'LOGROTATE_EOF' + /var/log/ec2-scaling-demo/*.log { + daily + rotate 7 + compress + delaycompress + missingok + notifempty + copytruncate + su lightning-server lightning-server + } + LOGROTATE_EOF + + + # === Lightning Server Redeploy Script === + echo "[INFO] Creating Lightning Server Redeploy Script" + cat > /usr/local/bin/lightning-server-redeploy << 'REDEPLOY_EOF' + #!/bin/bash + set -euo pipefail + + log() { echo "[lightning-server-redeploy] $(date '+%Y-%m-%d %H:%M:%S') $*"; } + err() { echo "[lightning-server-redeploy] $(date '+%Y-%m-%d %H:%M:%S') ERROR: $*" >&2; } + + if [ -f /etc/lightning-server/deploy.env ]; then . /etc/lightning-server/deploy.env; fi + BUCKET="$DEPLOYMENT_BUCKET" + REGION="$AWS_REGION_NAME" + SSM_PARAM="/ec2-scaling-demo/settings-password" + APP_DIR="/opt/ec2-scaling-demo" + CONF_DIR="/etc/ec2-scaling-demo" + STATE_DIR="/var/lib/ec2-scaling-demo" + LOG_FILE="/var/log/ec2-scaling-demo/redeploy.log" + + mkdir -p "$(dirname "$LOG_FILE")" + touch "$LOG_FILE" + chown lightning-server:lightning-server "$LOG_FILE" + exec > >(tee -a "$LOG_FILE" | logger -t lightning-server-redeploy -s) 2>&1 + + log "Redeploy started at $(date)" + install -d -o root -g root -m 0755 "$APP_DIR" + install -d -o root -g lightning-server -m 0750 "$CONF_DIR" + install -d -o lightning-server -g lightning-server -m 0700 "$STATE_DIR" + + download_with_retry() { + local src="$1" dst="$2" max=5 attempt=1 + while [ $attempt -le $max ]; do + log "Downloading $src (attempt $attempt/$max)" + if aws s3 cp "$src" "$dst" --region "$REGION" --no-progress; then return 0; fi + sleep $((attempt * 5)) + attempt=$((attempt + 1)) + done + err "Failed to download $src after $max attempts" + return 1 + } + + # Roll back to the previously-working server + settings, then restart. Used when the new + # version fails to become active so the instance self-heals instead of staying down. + rollback() { + err "Rolling back to previous version" + [ -d "$APP_DIR/server-old" ] && { rm -rf "$APP_DIR/server"; mv "$APP_DIR/server-old" "$APP_DIR/server"; } + [ -f "$CONF_DIR/settings.enc.old" ] && mv -f "$CONF_DIR/settings.enc.old" "$CONF_DIR/settings.enc" + systemctl restart ec2-scaling-demo || true + } + + download_with_retry "s3://$BUCKET/server.zip" "$APP_DIR/server.zip" + [ -d "$APP_DIR/server-old" ] && rm -rf "$APP_DIR/server-old" + [ -d "$APP_DIR/server" ] && mv "$APP_DIR/server" "$APP_DIR/server-old" + log "Successful Download" + log "Unzipping server.zip" + unzip -q "$APP_DIR/server.zip" -d "$APP_DIR" + rm -f "$APP_DIR/server.zip" + # The build stays root-owned so the service can run it but never modify it. Zip entries can carry + # arbitrary modes, so normalize to readable (and executable where already so) and root-writable only. + chown -R root:root "$APP_DIR" + chmod -R u=rwX,go=rX "$APP_DIR" + + # Settings stay encrypted at rest; the service decrypts them in memory at startup. + download_with_retry "s3://$BUCKET/settings.enc" "$CONF_DIR/settings.enc.new" + SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") + # Test-decrypt (output discarded) so a bad password or corrupt file fails the deploy here rather than + # at service start. The password goes via openssl's environment, not argv: argv is world-readable. + if ! SETTINGS_PASS="$SETTINGS_PASS" openssl enc -d -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 \ + -in "$CONF_DIR/settings.enc.new" -out /dev/null -pass env:SETTINGS_PASS; then + err "Failed to decrypt settings" + rm -f "$CONF_DIR/settings.enc.new" + exit 1 + fi + chown root:lightning-server "$CONF_DIR/settings.enc.new" + chmod 640 "$CONF_DIR/settings.enc.new" + log "Verified settings decrypt" + [ -f "$CONF_DIR/settings.enc.old" ] && rm "$CONF_DIR/settings.enc.old" + [ -f "$CONF_DIR/settings.enc" ] && mv "$CONF_DIR/settings.enc" "$CONF_DIR/settings.enc.old" + mv "$CONF_DIR/settings.enc.new" "$CONF_DIR/settings.enc" + + # Mount point for the unit's read-only settings bind mount. Created as the service user: it owns + # this directory, so root must not follow anything that may have been placed here. + [ -e "$STATE_DIR/settings.json" ] || sudo -u lightning-server touch "$STATE_DIR/settings.json" + + log "Restarting Lightning Server EC2 Scaling Demo" + systemctl restart ec2-scaling-demo + sleep 5 + if ! systemctl is-active --quiet ec2-scaling-demo; then + err "Service failed to start" + tail -n 100 /var/log/ec2-scaling-demo/server.log >&2 || true + rollback + exit 1 + fi + + log "Waiting for liveness at http://localhost:8080/meta/online" + healthy=0 + for i in $(seq 1 20); do + if curl -fsS -o /dev/null --max-time 5 "http://localhost:8080/meta/online"; then healthy=1; break; fi + sleep 3 + done + if [ "$healthy" -ne 1 ]; then + err "Liveness endpoint http://localhost:8080/meta/online never returned success" + tail -n 100 /var/log/ec2-scaling-demo/server.log >&2 || true + rollback + exit 1 + fi + log "Done" + REDEPLOY_EOF + + chmod +x /usr/local/bin/lightning-server-redeploy + echo "[INFO] Creating Lightning Server Redeploy Script - DONE" + + # === Lightning Server Pre-Deploy Script === + # Runs pre-deploy tasks with the NEW build in a scratch dir, without touching the live server, so + # the current version keeps serving while migrations run. Invoked once per deploy (before the + # redeploy/cutover) - by the single-instance redeploy on the one box, and by the scaling fleet + # script on one instance. A non-zero exit aborts the deploy. + echo "[INFO] Creating Lightning Server Pre-Deploy Script" + cat > /usr/local/bin/lightning-server-predeploy << 'PREDEPLOY_EOF' + #!/bin/bash + set -euo pipefail + + log() { echo "[lightning-server-predeploy] $*"; } + err() { echo "[lightning-server-predeploy] ERROR: $*" >&2; } + + if [ -f /etc/lightning-server/deploy.env ]; then . /etc/lightning-server/deploy.env; fi + BUCKET="$DEPLOYMENT_BUCKET" + REGION="$AWS_REGION_NAME" + SSM_PARAM="/ec2-scaling-demo/settings-password" + LOG_FILE="/var/log/ec2-scaling-demo/predeploy.log" + + mkdir -p "$(dirname "$LOG_FILE")" + touch "$LOG_FILE" + chown lightning-server:lightning-server "$LOG_FILE" + exec > >(tee -a "$LOG_FILE" | logger -t lightning-server-predeploy -s) 2>&1 + + log "Pre-deploy started at $(date)" + + # Fetch the NEW build + settings into a scratch dir; the live server is never touched. mktemp makes a + # fresh root-only directory with an unguessable name: a fixed path under world-writable /var/tmp could + # be pre-created or symlinked by another user to redirect root's writes. + SCRATCH=$(mktemp -d "/var/tmp/ec2-scaling-demo-predeploy.XXXXXX") + trap 'cd /; rm -rf "$SCRATCH"' EXIT + aws s3 cp "s3://$BUCKET/server.zip" "$SCRATCH/server.zip" --region "$REGION" --no-progress + unzip -q "$SCRATCH/server.zip" -d "$SCRATCH" + + # Encrypted bytes under the name the app loads; the app decrypts them in memory (password passed below). + aws s3 cp "s3://$BUCKET/settings.enc" "$SCRATCH/settings.json" --region "$REGION" --no-progress + SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") + if ! SETTINGS_PASS="$SETTINGS_PASS" openssl enc -d -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 \ + -in "$SCRATCH/settings.json" -out /dev/null -pass env:SETTINGS_PASS; then + err "Failed to decrypt settings" + exit 1 + fi + chown -R lightning-server:lightning-server "$SCRATCH" + chmod 600 "$SCRATCH/settings.json" + + # Cap heap so this runs alongside the live server without risking OOM. Heavy migrations may need more. + log "Running pre-deploy tasks with the new version" + cd "$SCRATCH" + if LIGHTNING_SERVER_SETTINGS_DECRYPTION="$SETTINGS_PASS" runuser -u lightning-server -- env "JAVA_OPTS=-Xmx512m" ./server/bin/server predeploy; then + cd / + rm -rf "$SCRATCH" + log "Pre-deploy complete" + else + cd / + rm -rf "$SCRATCH" + err "Pre-deploy tasks failed" + exit 1 + fi + PREDEPLOY_EOF + + chmod +x /usr/local/bin/lightning-server-predeploy + echo "[INFO] Creating Lightning Server Pre-Deploy Script - DONE" + + # === Settings Key Script (ExecStartPre) === + # Runs as root before each service start: fetches the settings password from SSM into a RAM-backed, + # root-only environment file that systemd hands to the app. Nothing is written to disk. + echo "[INFO] Creating settings key script" + cat > /usr/local/bin/ec2-scaling-demo-settings-key << 'SETTINGS_KEY_EOF' + #!/bin/bash + set -euo pipefail + # systemd runs this root step with the service's environment and working directory, both pointing at + # /var/lib/ec2-scaling-demo, which the service can write. Pin them so the service cannot steer root's aws + # CLI (e.g. with a planted ~/.aws/config credential_process); the instance role supplies credentials. + cd / + export HOME=/root AWS_CONFIG_FILE=/dev/null AWS_SHARED_CREDENTIALS_FILE=/dev/null + if [ -f /etc/lightning-server/deploy.env ]; then . /etc/lightning-server/deploy.env; fi + BUCKET="$DEPLOYMENT_BUCKET" + REGION="$AWS_REGION_NAME" + SSM_PARAM="/ec2-scaling-demo/settings-password" + SECRETS_DIR="/run/ec2-scaling-demo-secrets" + install -d -o root -g root -m 0700 "$SECRETS_DIR" + SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") + umask 077 + # printf is a shell builtin, so the password never appears in any process's argv. Single quotes make + # systemd take the value literally; the password's charset (letters, digits, '-', '_') contains none. + printf "LIGHTNING_SERVER_SETTINGS_DECRYPTION='%s'\n" "$SETTINGS_PASS" > "$SECRETS_DIR/settings.env.tmp" + mv -f "$SECRETS_DIR/settings.env.tmp" "$SECRETS_DIR/settings.env" + SETTINGS_KEY_EOF + chmod 0700 /usr/local/bin/ec2-scaling-demo-settings-key + + + # === Instance Emergency Update Script === + # The "a CVE landed and we are not waiting for a rebuild" lever. On a scaling fleet + # update-fleet.sh drives it one drained instance at a time; routine patching there still + # comes from rebuilding the image and rolling the ASG. + # + # It restarts the app unconditionally (the JRE is a system package and may be replaced + # underneath a running JVM), so it is only interruption-free on an instance already + # drained from the load balancer. + # + # Usage: os-update [package ...] + # with no arguments, applies a full upgrade; otherwise upgrades only the named packages. + echo "[INFO] Creating OS Emergency Update Script" + cat > /usr/local/bin/os-update << 'UPDATE_EOF' + #!/bin/bash + set -euo pipefail + export DEBIAN_FRONTEND=noninteractive + + log() { echo "[os-update] $(date '+%Y-%m-%d %H:%M:%S') $*"; } + err() { echo "[os-update] $(date '+%Y-%m-%d %H:%M:%S') ERROR: $*" >&2; } + + LOG_FILE="/var/log/ec2-scaling-demo/os-update.log" + PACKAGES="$*" + + mkdir -p "$(dirname "$LOG_FILE")" + touch "$LOG_FILE" + chown lightning-server:lightning-server "$LOG_FILE" + exec > >(tee -a "$LOG_FILE" | logger -t os-update -s) 2>&1 + + log "OS update started" + # The repositories are locked to the release this host is on, so a plain upgrade only sees fixes + # already in that release; every fix published since would be silently missed while the update + # reported success. --releasever=latest moves to the newest release first. + DNF_OPTS="-y --releasever=latest" + if [ -n "$PACKAGES" ]; then + # `dnf upgrade` exits 0 for a package that is not installed, so a typo'd or wrong-architecture + # name would report a clean patch while changing nothing at all. Check each name up front and + # fail loudly instead. + for p in $PACKAGES; do + if ! rpm -q "$p" >/dev/null 2>&1; then + err "not installed on this host, refusing to report a successful update: $p" + exit 1 + fi + done + log "Upgrading only: $PACKAGES" + dnf $DNF_OPTS upgrade $PACKAGES + else + log "Applying full upgrade" + dnf $DNF_OPTS upgrade + # Deliberately only on the full-upgrade path. Naming packages means the operator asked for a minimal, + # auditable change to one or two packages; autoremove is a whole-system operation, which is not a + # blast radius to take on while chasing a single CVE. + dnf -y autoremove + fi + + log "Restarting Lightning Server EC2 Scaling Demo" + systemctl restart ec2-scaling-demo + sleep 5 + if ! systemctl is-active --quiet ec2-scaling-demo; then + err "Service failed to start after OS update" + tail -n 100 /var/log/ec2-scaling-demo/server.log >&2 || true + exit 1 + fi + + log "Waiting for liveness at http://localhost:8080/meta/online" + healthy=0 + for i in $(seq 1 20); do + if curl -fsS -o /dev/null --max-time 5 "http://localhost:8080/meta/online"; then healthy=1; break; fi + sleep 3 + done + if [ "$healthy" -ne 1 ]; then + err "Liveness endpoint http://localhost:8080/meta/online never returned success" + tail -n 100 /var/log/ec2-scaling-demo/server.log >&2 || true + exit 1 + fi + + # Breadcrumb for the CloudWatch log; a reboot is needed to activate a patched kernel. Callers that + # act on it (update-fleet.sh) run their own reboot check over SSM rather than reading this back, + # because SSM truncates command output at 24,000 characters per stream and a full upgrade can push + # a trailing marker past that cap. needs-restarting exits 1 when a reboot is needed. + if dnf needs-restarting -r >/dev/null 2>&1; then log "REBOOT_REQUIRED=no"; else log "REBOOT_REQUIRED=yes"; fi + log "Done" + UPDATE_EOF + + chmod +x /usr/local/bin/os-update + echo "[INFO] Creating OS Emergency Update Script - DONE" + + systemctl enable ec2-scaling-demo || true + systemctl enable amazon-cloudwatch-agent || true \ No newline at end of file diff --git a/demo/terraform/lkec2/main.tf.json b/demo/terraform/ec2-scaling/main.tf.json similarity index 95% rename from demo/terraform/lkec2/main.tf.json rename to demo/terraform/ec2-scaling/main.tf.json index 9133d6232..d1038370c 100644 --- a/demo/terraform/lkec2/main.tf.json +++ b/demo/terraform/ec2-scaling/main.tf.json @@ -39,7 +39,7 @@ "bucket": "lightningkite-terraform", "encrypt": true, "region": "us-west-2", - "key": "LightningServerEC2SDemo" + "key": "ec2-scaling-demo" } } } diff --git a/demo/terraform/lkec2/monitoring.tf.json b/demo/terraform/ec2-scaling/monitoring.tf.json similarity index 90% rename from demo/terraform/lkec2/monitoring.tf.json rename to demo/terraform/ec2-scaling/monitoring.tf.json index 6caa0b5e4..08c40692f 100644 --- a/demo/terraform/lkec2/monitoring.tf.json +++ b/demo/terraform/ec2-scaling/monitoring.tf.json @@ -16,12 +16,12 @@ }, "aws_sns_topic": { "emergency": { - "name": "LightningServerEC2SDemo_emergencies" + "name": "ec2-scaling-demo_emergencies" } }, "aws_cloudwatch_metric_alarm": { "unhealthy_hosts": { - "alarm_name": "LightningServerEC2SDemo-unhealthy-hosts", + "alarm_name": "ec2-scaling-demo-unhealthy-hosts", "statistic": "Maximum", "period": 60, "metric_name": "UnHealthyHostCount", @@ -40,7 +40,7 @@ } }, "target_5xx": { - "alarm_name": "LightningServerEC2SDemo-target-5xx", + "alarm_name": "ec2-scaling-demo-target-5xx", "statistic": "Sum", "period": 300, "metric_name": "HTTPCode_Target_5XX_Count", @@ -58,7 +58,7 @@ } }, "high_cpu": { - "alarm_name": "LightningServerEC2SDemo-high-cpu", + "alarm_name": "ec2-scaling-demo-high-cpu", "statistic": "Average", "period": 300, "metric_name": "CPUUtilization", @@ -78,7 +78,7 @@ "aws_cloudwatch_log_group": { "application": { "retention_in_days": 30, - "name": "/ec2/LightningServerEC2SDemo/application" + "name": "ec2-scaling-demo-main-log" } }, "aws_sns_topic_subscription": { diff --git a/demo/terraform/lkec2/network.tf.json b/demo/terraform/ec2-scaling/network.tf.json similarity index 89% rename from demo/terraform/lkec2/network.tf.json rename to demo/terraform/ec2-scaling/network.tf.json index 02f092b0b..a510aa916 100644 --- a/demo/terraform/lkec2/network.tf.json +++ b/demo/terraform/ec2-scaling/network.tf.json @@ -3,13 +3,13 @@ "aws_security_group": { "instance": { "vpc_id": "${module.vpc.vpc_id}", - "name": "LightningServerEC2SDemo-instance", - "description": "Lightning Server Demo application instances" + "name": "ec2-scaling-demo-instance", + "description": "Lightning Server EC2 Scaling Demo application instances" }, "alb": { "vpc_id": "${module.vpc.vpc_id}", - "name": "LightningServerEC2SDemo-alb", - "description": "Lightning Server Demo load balancer" + "name": "ec2-scaling-demo-alb", + "description": "Lightning Server EC2 Scaling Demo load balancer" } }, "aws_vpc_security_group_ingress_rule": { diff --git a/demo/terraform/lkec2/outputs.tf.json b/demo/terraform/ec2-scaling/outputs.tf.json similarity index 79% rename from demo/terraform/lkec2/outputs.tf.json rename to demo/terraform/ec2-scaling/outputs.tf.json index c2e5f4cdc..eb3dad204 100644 --- a/demo/terraform/lkec2/outputs.tf.json +++ b/demo/terraform/ec2-scaling/outputs.tf.json @@ -6,7 +6,7 @@ }, "application_url": { "description": "Application URL", - "value": "https://lightningserver2.cs.lightningkite.com" + "value": "https://scaling-demo.cs.lightningkite.com" } } } \ No newline at end of file diff --git a/demo/terraform/lkec2/redeploy-fleet.sh b/demo/terraform/ec2-scaling/redeploy-fleet.sh similarity index 61% rename from demo/terraform/lkec2/redeploy-fleet.sh rename to demo/terraform/ec2-scaling/redeploy-fleet.sh index da0e17e39..0be9a48ac 100644 --- a/demo/terraform/lkec2/redeploy-fleet.sh +++ b/demo/terraform/ec2-scaling/redeploy-fleet.sh @@ -42,7 +42,6 @@ resume_and_restore() { --targets "Id=$id,Port=$APP_PORT" --region "$REGION" || true done } -trap resume_and_restore EXIT wait_ssm_online() { local id="$1" @@ -57,14 +56,65 @@ wait_ssm_online() { return 1 } +# Sends one command via SSM, waits for it to finish, and echoes its combined stdout+stderr. +# Returns non-zero if the command failed or never finished within $attempts polls. +# +# Note that SSM returns only the first 24,000 characters of each stream, so anything the caller +# needs a reliable *answer* from (as opposed to a log to read) must print little enough to stay +# well under that cap. See needs_reboot. +# +# The remote command is interpolated into JSON, so it must not contain double quotes or +# backslashes -- use single quotes inside it. +ssm_run() { + local id="$1" timeout="$2" attempts="$3" comment="$4" remote_cmd="$5" + local cmd_id status i + + cmd_id=$(aws ssm send-command \ + --instance-ids "$id" \ + --document-name "AWS-RunShellScript" \ + --comment "$comment" \ + --parameters "$(printf '{"commands":["%s"],"executionTimeout":["%s"]}' "$remote_cmd" "$timeout")" \ + --region "$REGION" --query 'Command.CommandId' --output text) + + for i in $(seq 1 "$attempts"); do + status=$(aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'Status' --output text 2>/dev/null || echo "Pending") + case "$status" in + Success) + aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'join(``, [StandardOutputContent, StandardErrorContent])' \ + --output text || true + return 0 ;; + Cancelled|Failed|TimedOut) + err "$comment on $id finished with status: $status" + aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'StandardErrorContent' --output text >&2 || true + return 1 ;; + *) sleep 5 ;; + esac + done + err "$comment on $id did not finish within polling window" + return 1 +} + +trap resume_and_restore EXIT + +# The on-instance redeploy script validates the new build itself and self-rolls-back on failure, +# so its output is only interesting when it fails -- and ssm_run already prints stderr for us then. run_redeploy() { + ssm_run "$1" 600 180 "terraform rolling redeploy" "/usr/local/bin/lightning-server-redeploy" >/dev/null +} + +# Run pre-deploy tasks on one instance via SSM (in a scratch dir; the live server is untouched). +# Returns non-zero on any failure so the rollout can abort before touching the fleet. +run_predeploy() { local id="$1" local cmd_id cmd_id=$(aws ssm send-command \ --instance-ids "$id" \ --document-name "AWS-RunShellScript" \ - --comment "terraform rolling redeploy" \ - --parameters 'commands=/usr/local/bin/lightning-server-redeploy,executionTimeout=600' \ + --comment "terraform pre-deploy" \ + --parameters 'commands=/usr/local/bin/lightning-server-predeploy,executionTimeout=600' \ --region "$REGION" --query 'Command.CommandId' --output text) for i in $(seq 1 180); do status=$(aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ @@ -72,14 +122,14 @@ run_redeploy() { case "$status" in Success) return 0 ;; Cancelled|Failed|TimedOut) - err "redeploy on $id finished with status: $status" + err "pre-deploy on $id finished with status: $status" aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ --region "$REGION" --query 'StandardErrorContent' --output text >&2 || true return 1 ;; *) sleep 5 ;; esac done - err "redeploy on $id did not finish within polling window" + err "pre-deploy on $id did not finish within polling window" return 1 } @@ -95,6 +145,7 @@ process_instance() { aws elbv2 wait target-deregistered --target-group-arn "$TG_ARN" \ --targets "Id=$id,Port=$APP_PORT" --region "$REGION" || true + log "Running deploy script" if ! run_redeploy "$id"; then err "redeploy failed on $id (it self-heals to the previous version)" return 1 @@ -121,6 +172,17 @@ if [ -z "$IDS" ]; then exit 0 fi +# Run pre-deploy tasks once, on one instance, before rolling the fleet. The whole fleet keeps +# serving the previous version while these run; a failure aborts the rollout (the EXIT trap resumes +# ASG processes and re-registers every instance, so the fleet is left untouched and serving). +FIRST_ID="${IDS%%[[:space:]]*}" +log "Running pre-deploy tasks on $FIRST_ID before rolling the fleet" +wait_ssm_online "$FIRST_ID" || exit 1 +if ! run_predeploy "$FIRST_ID"; then + err "Pre-deploy tasks failed; aborting rollout." + exit 1 +fi + # Process in batches of $BATCH, in parallel within a batch; fail the whole run if any member fails. batch=() flush_batch() { diff --git a/demo/terraform/lkec2/redeploy.tf.json b/demo/terraform/ec2-scaling/redeploy.tf.json similarity index 89% rename from demo/terraform/lkec2/redeploy.tf.json rename to demo/terraform/ec2-scaling/redeploy.tf.json index ed831db4d..b77695d8e 100644 --- a/demo/terraform/lkec2/redeploy.tf.json +++ b/demo/terraform/ec2-scaling/redeploy.tf.json @@ -15,7 +15,7 @@ "aws_ssm_parameter.settings_password" ], "triggers": { - "settings_hash": "${local_sensitive_file.settings_raw.content_sha256}", + "settings_upload": "${null_resource.upload_settings.id}", "jar_hash": "${data.external.jar_hash.result.hash}" } } diff --git a/demo/terraform/lk/secretBasis.tf.json b/demo/terraform/ec2-scaling/secretBasis.tf.json similarity index 100% rename from demo/terraform/lk/secretBasis.tf.json rename to demo/terraform/ec2-scaling/secretBasis.tf.json diff --git a/demo/terraform/ec2-scaling/update-fleet.sh b/demo/terraform/ec2-scaling/update-fleet.sh new file mode 100644 index 000000000..cfc4fd5fc --- /dev/null +++ b/demo/terraform/ec2-scaling/update-fleet.sh @@ -0,0 +1,342 @@ +#!/usr/bin/env bash +# Rolling, in-place Emergency OS package update across the Auto Scaling Group. This is the "a CVE just +# landed and we are not waiting for an AMI bake" lever -- routine patching is meant to come from +# rebuilding the image and letting the ASG instance refresh roll the fleet, which also fixes the +# baseline that new scale-out instances launch from. This script does NOT update the AMI, so any +# instance the ASG launches afterwards is still unpatched until the next image rebuild. +# +# The ASG is told to suspend the processes that would otherwise fight us -- HealthCheck and +# ReplaceUnhealthy (so it can't terminate a drained instance) and AddToLoadBalancer/AZRebalance. +# An EXIT trap always resumes them and re-registers every in-service instance, so even an abrupt +# termination leaves the fleet serving rather than stranded. +set -euo pipefail + +APP_PORT="8080" +SUSPENDED="HealthCheck ReplaceUnhealthy AZRebalance AddToLoadBalancer" + +log() { echo "[update-fleet] $*"; } +err() { echo "[update-fleet] ERROR: $*" >&2; } + +instance_ids() { + aws autoscaling describe-auto-scaling-groups \ + --auto-scaling-group-names "$ASG_NAME" \ + --region "$REGION" \ + --query 'AutoScalingGroups[0].Instances[?LifecycleState==`InService`].InstanceId' \ + --output text +} + +# Always restore the ASG to a clean state, even on abnormal exit: resume the suspended processes +# and make sure every in-service instance is registered with the target group. +resume_and_restore() { + log "Resuming ASG processes and re-registering all in-service instances" + aws autoscaling resume-processes --auto-scaling-group-name "$ASG_NAME" \ + --scaling-processes $SUSPENDED --region "$REGION" || true + local id + for id in $(instance_ids); do + aws elbv2 register-targets --target-group-arn "$TG_ARN" \ + --targets "Id=$id,Port=$APP_PORT" --region "$REGION" || true + done +} + +wait_ssm_online() { + local id="$1" + for i in $(seq 1 60); do + status=$(aws ssm describe-instance-information \ + --filters "Key=InstanceIds,Values=$id" --region "$REGION" \ + --query 'InstanceInformationList[0].PingStatus' --output text 2>/dev/null || echo "None") + [ "$status" = "Online" ] && return 0 + sleep 5 + done + err "SSM agent never came Online for $id" + return 1 +} + +# Sends one command via SSM, waits for it to finish, and echoes its combined stdout+stderr. +# Returns non-zero if the command failed or never finished within $attempts polls. +# +# Note that SSM returns only the first 24,000 characters of each stream, so anything the caller +# needs a reliable *answer* from (as opposed to a log to read) must print little enough to stay +# well under that cap. See needs_reboot. +# +# The remote command is interpolated into JSON, so it must not contain double quotes or +# backslashes -- use single quotes inside it. +ssm_run() { + local id="$1" timeout="$2" attempts="$3" comment="$4" remote_cmd="$5" + local cmd_id status i + + cmd_id=$(aws ssm send-command \ + --instance-ids "$id" \ + --document-name "AWS-RunShellScript" \ + --comment "$comment" \ + --parameters "$(printf '{"commands":["%s"],"executionTimeout":["%s"]}' "$remote_cmd" "$timeout")" \ + --region "$REGION" --query 'Command.CommandId' --output text) + + for i in $(seq 1 "$attempts"); do + status=$(aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'Status' --output text 2>/dev/null || echo "Pending") + case "$status" in + Success) + aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'join(``, [StandardOutputContent, StandardErrorContent])' \ + --output text || true + return 0 ;; + Cancelled|Failed|TimedOut) + err "$comment on $id finished with status: $status" + aws ssm get-command-invocation --command-id "$cmd_id" --instance-id "$id" \ + --region "$REGION" --query 'StandardErrorContent' --output text >&2 || true + return 1 ;; + *) sleep 5 ;; + esac + done + err "$comment on $id did not finish within polling window" + return 1 +} + +usage() { + cat <<'USAGE' +usage: update-fleet.sh [options] + +Options: + -b, --batch N instances to update in parallel (default 1) + -p, --packages "LIST" space-separated packages to upgrade; omit for a full upgrade + -n, --no-reboot leave instances that report reboot-required un-rebooted; they are + still probed, and listed at the end of the run + -f, --force allow a --batch that covers the whole fleet (accepts an outage) + -h, --help show this help + +Example: + bash update-fleet.sh altitude-production us-west-2 "$TG_ARN" -p "openssl libssl3" +USAGE +} + +die() { err "$*"; echo >&2; usage >&2; exit 2; } + +BATCH=1 +PACKAGES="" +REBOOT=1 +FORCE=0 +POSITIONAL=() + +while [ $# -gt 0 ]; do + case "$1" in + -b|--batch) [ $# -ge 2 ] || die "$1 requires a value"; BATCH="$2"; shift 2 ;; + -p|--packages) [ $# -ge 2 ] || die "$1 requires a value"; PACKAGES="$2"; shift 2 ;; + -n|--no-reboot) REBOOT=0; shift ;; + -f|--force) FORCE=1; shift ;; + -h|--help) usage; exit 0 ;; + --) shift; POSITIONAL+=("$@"); break ;; + -*) die "unknown option: $1" ;; + *) POSITIONAL+=("$1"); shift ;; + esac +done + +[ ${#POSITIONAL[@]} -eq 3 ] || die "expected 3 arguments (asg-name, region, target-group-arn), got ${#POSITIONAL[@]}" +ASG_NAME="${POSITIONAL[0]}" +REGION="${POSITIONAL[1]}" +TG_ARN="${POSITIONAL[2]}" + +# Validated up front because a non-numeric batch would otherwise only surface deep in flush_batch, +# after the ASG processes have already been suspended. +case "$BATCH" in ''|*[!0-9]*) die "--batch must be a positive integer, got: $BATCH" ;; esac +[ "$BATCH" -ge 1 ] || die "--batch must be at least 1" + +# --packages is interpolated into the SSM parameters JSON and then run as a root shell command on +# every instance, so it is restricted to the characters real package specs need: names, versions +# (=), and architecture qualifiers (:). That keeps a stray quote from producing malformed JSON and +# a stray `;` from turning a typo into a fleet-wide root command. This is a guard against mistakes +# rather than a security boundary -- whoever runs this already holds credentials that can do worse. +PACKAGES_RE='^[a-zA-Z0-9._+:=~-]+([ ]+[a-zA-Z0-9._+:=~-]+)*$' +if [ -n "$PACKAGES" ] && ! [[ "$PACKAGES" =~ $PACKAGES_RE ]]; then + die "--packages must be a space-separated list of package names, got: $PACKAGES" +fi + +# Runs /usr/local/bin/os-update, baked into the AMI by image_data.yaml, and +# echoes its combined output so the caller can inspect it. The updater logs through `logger -s`, +# so most of its output arrives on stderr rather than stdout. +run_update() { + local id="$1" + local remote_cmd="/usr/local/bin/os-update" + [ -n "$PACKAGES" ] && remote_cmd="$remote_cmd $PACKAGES" + ssm_run "$id" 1800 360 "os update" "$remote_cmd" +} + +# Asks the instance directly whether a reboot is pending. Deliberately its own tiny command rather +# than a marker grepped out of the updater's output: a full apt upgrade easily exceeds the 24,000 +# characters SSM returns per stream, and a truncated trailing marker would look exactly like "no +# reboot needed" -- silently leaving a patched kernel un-activated, which is the one thing this +# script exists to prevent. +# +# 0 = reboot required, 1 = not required, 2 = could not determine. +needs_reboot() { + local id="$1" out + out=$(ssm_run "$id" 60 24 "reboot check" \ + "dnf needs-restarting -r >/dev/null 2>&1 && echo REBOOT_REQUIRED=no || echo REBOOT_REQUIRED=yes") || return 2 + case "$out" in + *REBOOT_REQUIRED=yes*) return 0 ;; + *REBOOT_REQUIRED=no*) return 1 ;; + *) err "unexpected reboot-check output from $id: $out"; return 2 ;; + esac +} + +# Boot id changes on every boot, so comparing it across a reboot is what actually proves the +# instance cycled. Echoes an empty string if the instance cannot be reached. +boot_id() { + local id="$1" out + out=$(ssm_run "$id" 60 12 "boot id" "cat /proc/sys/kernel/random/boot_id" 2>/dev/null) || out="" + printf '%s' "$out" | tr -d '[:space:]' +} + +# The reboot command backgrounds itself so SSM can record it before the instance goes down. Safe +# here because the instance is drained and the ASG cannot replace it. +reboot_instance() { + local id="$1" before after i + + before=$(boot_id "$id") + if [ -z "$before" ]; then + err "could not read the boot id for $id; refusing to reboot without a way to verify it" + return 1 + fi + + log "Rebooting $id (boot id $before)" + if ! ssm_run "$id" 60 12 "reboot" \ + "nohup bash -c 'sleep 3; systemctl reboot' >/dev/null 2>&1 &" >/dev/null; then + err "failed to send the reboot command to $id" + return 1 + fi + + # Poll until the boot id actually changes. Waiting for SSM to report Online is not enough on + # its own: the pre-reboot agent keeps answering until the instance finishes shutting down, so + # a slow shutdown would let us continue against an instance still running the old kernel -- + # and a reboot that never happened at all would look identical. + for i in $(seq 1 60); do + sleep 10 + after=$(boot_id "$id") + if [ -n "$after" ] && [ "$after" != "$before" ]; then + log "$id back online after reboot (boot id $before -> $after)" + return 0 + fi + done + + err "$id never reported a new boot id; it does not appear to have rebooted" + return 1 +} + +# Drain -> update -> (reboot) -> validate healthy, for one instance. Returns non-zero on failure. +process_instance() { + local id="$1" + log "=== Updating $id ===" + wait_ssm_online "$id" || return 1 + + log "Draining $id from the target group" + aws elbv2 deregister-targets --target-group-arn "$TG_ARN" \ + --targets "Id=$id,Port=$APP_PORT" --region "$REGION" + aws elbv2 wait target-deregistered --target-group-arn "$TG_ARN" \ + --targets "Id=$id,Port=$APP_PORT" --region "$REGION" || true + + log "Running update script" + local output + if ! output=$(run_update "$id"); then + err "os update failed on $id; halting before it is returned to service" + return 1 + fi + echo "$output" + + # Probed unconditionally, including under --no-reboot: "which instances are still running the + # old kernel" is the fact this whole script exists to establish, and skipping the check when we + # are not going to act on it is how a half-patched fleet gets mistaken for a patched one. + local state=0 + needs_reboot "$id" || state=$? + case "$state" in + 0) if [ "$REBOOT" != "0" ]; then + reboot_instance "$id" || return 1 + else + log "$id needs a reboot; leaving it running the old kernel (--no-reboot)" + echo "$id" >> "$PENDING_REBOOT_FILE" + fi ;; + 1) log "$id does not require a reboot" ;; + # Undetermined is fatal only when we were going to reboot -- continuing there would mean + # returning a possibly-unpatched instance to service while believing it was handled. Under + # --no-reboot nothing was going to happen anyway, so record it and carry on. + *) if [ "$REBOOT" != "0" ]; then + err "could not determine whether $id needs a reboot; halting rather than guessing" + return 1 + fi + err "could not determine whether $id needs a reboot; assuming it does" + echo "$id" >> "$PENDING_REBOOT_FILE" ;; + esac + + log "Returning $id to service" + aws elbv2 register-targets --target-group-arn "$TG_ARN" \ + --targets "Id=$id,Port=$APP_PORT" --region "$REGION" + if ! aws elbv2 wait target-in-service --target-group-arn "$TG_ARN" \ + --targets "Id=$id,Port=$APP_PORT" --region "$REGION"; then + err "$id did not become healthy after the os update" + return 1 + fi + log "$id healthy" +} + +IDS=$(instance_ids) +if [ -z "$IDS" ]; then + log "No in-service instances found; nothing to update." + exit 0 +fi + +# A batch that covers the whole fleet drains every instance at once -- an outage, not a rolling +# update. The steady-state ASG runs two instances, so `-b 2` is already the entire fleet, which is +# not obvious from a flag that just says "in parallel". Checked before anything is suspended or +# drained, so refusing costs nothing. +# +# Only an avoidable outage is refused. With a single instance in service there is no batch size +# that avoids downtime, so that case warns and proceeds rather than blocking an emergency patch +# behind a flag the operator never set. +COUNT=$(echo $IDS | wc -w) +if [ "$COUNT" -eq 1 ]; then + log "WARNING: only one instance is in service, so updating it means a brief outage." +elif [ "$BATCH" -ge "$COUNT" ] && [ "$FORCE" != "1" ]; then + err "--batch $BATCH covers all $COUNT in-service instances: every instance would be drained at" + err "once, taking the service fully down. Use a smaller --batch, or --force if that is intended." + exit 2 +fi + +# Instances that finish still needing a reboot are recorded in a file rather than a variable: +# process_instance runs in a background subshell, so an assignment there would never make it back +# to the parent. Created here, next to the trap that cleans it up. +PENDING_REBOOT_FILE=$(mktemp) + +report_pending_reboots() { + if [ -s "$PENDING_REBOOT_FILE" ]; then + err "These instances were patched but are still running the old kernel:" + while read -r pending; do err " $pending"; done < "$PENDING_REBOOT_FILE" + err "Re-run without --no-reboot, or reboot them yourself, before calling the fleet patched." + fi + rm -f "$PENDING_REBOOT_FILE" +} + +# Installed only now so the early exits above don't log a spurious restore of state never touched. +trap 'resume_and_restore; report_pending_reboots' EXIT + +log "Suspending ASG processes during update: $SUSPENDED" +aws autoscaling suspend-processes --auto-scaling-group-name "$ASG_NAME" \ + --scaling-processes $SUSPENDED --region "$REGION" + +# Process in batches of $BATCH, in parallel within a batch; fail the whole run if any member fails. +batch=() +flush_batch() { + [ ${#batch[@]} -eq 0 ] && return 0 + local pids=() id p fail=0 + for id in "${batch[@]}"; do process_instance "$id" & pids+=("$!"); done + for p in "${pids[@]}"; do wait "$p" || fail=1; done + batch=() + if [ "$fail" -ne 0 ]; then err "An update in the batch failed; halting rollout."; exit 1; fi +} + +for id in $IDS; do + batch+=("$id") + if [ ${#batch[@]} -ge "$BATCH" ]; then flush_batch; fi +done +flush_batch + +log "Fleet os update complete." +log "NOTE: the AMI is unchanged. Instances launched by scale-out are still unpatched until the" +log " image is rebuilt. Treat this as a stopgap, not the patch of record." \ No newline at end of file diff --git a/demo/terraform/ec2-scaling/valkey.tf.json b/demo/terraform/ec2-scaling/valkey.tf.json new file mode 100644 index 000000000..902c37ab2 --- /dev/null +++ b/demo/terraform/ec2-scaling/valkey.tf.json @@ -0,0 +1,27 @@ +{ + "resource": { + "aws_elasticache_replication_group": { + "valkey": { + "node_type": "cache.t4g.micro", + "engine": "valkey", + "port": 6379, + "parameter_group_name": "default.valkey9", + "description": "Valkey cache for ec2-scaling-demo-valkey", + "num_cache_clusters": 1, + "replication_group_id": "ec2-scaling-demo-valkey", + "engine_version": "9.0", + "subnet_group_name": "${aws_elasticache_subnet_group.valkey.name}", + "automatic_failover_enabled": false, + "security_group_ids": [ + "${aws_security_group.internal.id}" + ] + } + }, + "aws_elasticache_subnet_group": { + "valkey": { + "name": "ec2-scaling-demo-valkey", + "subnet_ids": "${module.vpc.private_subnets}" + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/.terraform.lock.hcl b/demo/terraform/ec2-single/.terraform.lock.hcl new file mode 100644 index 000000000..ae7d5f666 --- /dev/null +++ b/demo/terraform/ec2-single/.terraform.lock.hcl @@ -0,0 +1,145 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/archive" { + version = "2.7.1" + constraints = "~> 2.7.0" + hashes = [ + "h1:62VrkalDPMKB9zerCBS4iKTbvxejwnAWn/XXYZZQWD4=", + "zh:19881bb356a4a656a865f48aee70c0b8a03c35951b7799b6113883f67f196e8e", + "zh:2fcfbf6318dd514863268b09bbe19bfc958339c636bcbcc3664b45f2b8bf5cc6", + "zh:3323ab9a504ce0a115c28e64d0739369fe85151291a2ce480d51ccbb0c381ac5", + "zh:362674746fb3da3ab9bd4e70c75a3cdd9801a6cf258991102e2c46669cf68e19", + "zh:7140a46d748fdd12212161445c46bbbf30a3f4586c6ac97dd497f0c2565fe949", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:875e6ce78b10f73b1efc849bfcc7af3a28c83a52f878f503bb22776f71d79521", + "zh:b872c6ed24e38428d817ebfb214da69ea7eefc2c38e5a774db2ccd58e54d3a22", + "zh:cd6a44f731c1633ae5d37662af86e7b01ae4c96eb8b04144255824c3f350392d", + "zh:e0600f5e8da12710b0c52d6df0ba147a5486427c1a2cc78f31eea37a47ee1b07", + "zh:f21b2e2563bbb1e44e73557bcd6cdbc1ceb369d471049c40eb56cb84b6317a60", + "zh:f752829eba1cc04a479cf7ae7271526b402e206d5bcf1fcce9f535de5ff9e4e6", + ] +} + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.34.0" + constraints = "~> 6.34.0" + hashes = [ + "h1:ZGSMOPC+Du0cKJ2kV1Ni8Rnz7ezsIu+jYFEknpye5CM=", + "zh:1e49dc96bf50633583e3cbe23bb357642e7e9afe135f54e061e26af6310e50d2", + "zh:45651bb4dad681f17782d99d9324de182a7bb9fbe9dd22f120fdb7fe42969cc9", + "zh:5880c306a427128124585b460c53bbcab9fb3767f26f796eae204f65f111a927", + "zh:71fa9170989b3a1a6913c369bd4a792f4a3e2aab4024c2aff0911e704020b058", + "zh:8d48628fb30f11b04215e06f4dd8a3b32f5f9ea2ed116d0c81c686bf678f9185", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:a6885766588fcad887bdac8c3665e048480eda028e492759a1ea29d22b98d509", + "zh:a6ce9f5e7edc2258733e978bba147600b42a979e18575ce2c7d7dcb6d0b9911f", + "zh:c88d8b7d344e745b191509c29ca773d696da8ca3443f62b20f97982d2d33ea00", + "zh:cae90d6641728ad0219b6a84746bf86dd1dda3e31560d6495a202213ef0258b6", + "zh:cc35927d9d41878049c4221beb1d580a3dbadaca7ba39fb267e001ef9c59ccb3", + "zh:d9e1cb00dc33998e1242fb844e4e3e6cf95e57c664dc1eb55bb7d24f8324bad3", + "zh:f3dbf4a1b7020722145312eb4425f3ea356276d741e3f60fb703fc59a1e2d9fd", + "zh:faba832cc9d99a83f42aaf5a27a4c7309401200169ef04643104cfc8f522d007", + "zh:fcd3f30b91dbcc7db67d5d39268741ffa46696a230a1f2aef32d245ace54bf65", + ] +} + +provider "registry.terraform.io/hashicorp/external" { + version = "2.3.5" + constraints = "~> 2.3.0" + hashes = [ + "h1:smKSos4zs57pJjQrNuvGBpSWth2el9SgePPbPHo0aps=", + "zh:6e89509d056091266532fa64de8c06950010498adf9070bf6ff85bc485a82562", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:86868aec05b58dc0aa1904646a2c26b9367d69b890c9ad70c33c0d3aa7b1485a", + "zh:a2ce38fda83a62fa5fb5a70e6ca8453b168575feb3459fa39803f6f40bd42154", + "zh:a6c72798f4a9a36d1d1433c0372006cc9b904e8cfd60a2ae03ac5b7d2abd2398", + "zh:a8a3141d2fc71c86bf7f3c13b0b3be8a1b0f0144a47572a15af4dfafc051e28a", + "zh:aa20a1242eb97445ad26ebcfb9babf2cd675bdb81cac5f989268ebefa4ef278c", + "zh:b58a22445fb8804e933dcf835ab06c29a0f33148dce61316814783ee7f4e4332", + "zh:cb5626a661ee761e0576defb2a2d75230a3244799d380864f3089c66e99d0dcc", + "zh:d1acb00d20445f682c4e705c965e5220530209c95609194c2dc39324f3d4fcce", + "zh:d91a254ba77b69a29d8eae8ed0e9367cbf0ea6ac1a85b58e190f8cb096a40871", + "zh:f6592327673c9f85cdb6f20336faef240abae7621b834f189c4a62276ea5db41", + ] +} + +provider "registry.terraform.io/hashicorp/local" { + version = "2.7.0" + constraints = "~> 2.7.0" + hashes = [ + "h1:2RYa3j7m/0WmET2fqotY4CHxE1Hpk0fgn47/126l+Og=", + "zh:261fec71bca13e0a7812dc0d8ae9af2b4326b24d9b2e9beab3d2400fab5c5f9a", + "zh:308da3b5376a9ede815042deec5af1050ec96a5a5410a2206ae847d82070a23e", + "zh:3d056924c420464dc8aba10e1915956b2e5c4d55b11ffff79aa8be563fbfe298", + "zh:643256547b155459c45e0a3e8aab0570db59923c68daf2086be63c444c8c445b", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:7aa4d0b853f84205e8cf79f30c9b2c562afbfa63592f7231b6637e5d7a6b5b27", + "zh:7dc251bbc487d58a6ab7f5b07ec9edc630edb45d89b761dba28e0e2ba6b1c11f", + "zh:7ee0ca546cd065030039168d780a15cbbf1765a4c70cd56d394734ab112c93da", + "zh:b1d5d80abb1906e6c6b3685a52a0192b4ca6525fe090881c64ec6f67794b1300", + "zh:d81ea9856d61db3148a4fc6c375bf387a721d78fc1fea7a8823a027272a47a78", + "zh:df0a1f0afc947b8bfc88617c1ad07a689ce3bd1a29fd97318392e6bdd32b230b", + "zh:dfbcad800240e0c68c43e0866f2a751cff09777375ec701918881acf67a268da", + ] +} + +provider "registry.terraform.io/hashicorp/null" { + version = "3.2.4" + constraints = "~> 3.2.3" + hashes = [ + "h1:hkf5w5B6q8e2A42ND2CjAvgvSN3puAosDmOJb3zCVQM=", + "zh:59f6b52ab4ff35739647f9509ee6d93d7c032985d9f8c6237d1f8a59471bbbe2", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:795c897119ff082133150121d39ff26cb5f89a730a2c8c26f3a9c1abf81a9c43", + "zh:7b9c7b16f118fbc2b05a983817b8ce2f86df125857966ad356353baf4bff5c0a", + "zh:85e33ab43e0e1726e5f97a874b8e24820b6565ff8076523cc2922ba671492991", + "zh:9d32ac3619cfc93eb3c4f423492a8e0f79db05fec58e449dee9b2d5873d5f69f", + "zh:9e15c3c9dd8e0d1e3731841d44c34571b6c97f5b95e8296a45318b94e5287a6e", + "zh:b4c2ab35d1b7696c30b64bf2c0f3a62329107bd1a9121ce70683dec58af19615", + "zh:c43723e8cc65bcdf5e0c92581dcbbdcbdcf18b8d2037406a5f2033b1e22de442", + "zh:ceb5495d9c31bfb299d246ab333f08c7fb0d67a4f82681fbf47f2a21c3e11ab5", + "zh:e171026b3659305c558d9804062762d168f50ba02b88b231d20ec99578a6233f", + "zh:ed0fe2acdb61330b01841fa790be00ec6beaac91d41f311fb8254f74eb6a711f", + ] +} + +provider "registry.terraform.io/hashicorp/random" { + version = "3.8.1" + constraints = "~> 3.8.0" + hashes = [ + "h1:Eexl06+6J+s75uD46+WnZtpJZYRVUMB0AiuPBifK6Jc=", + "zh:08dd03b918c7b55713026037c5400c48af5b9f468f483463321bd18e17b907b4", + "zh:0eee654a5542dc1d41920bbf2419032d6f0d5625b03bd81339e5b33394a3e0ae", + "zh:229665ddf060aa0ed315597908483eee5b818a17d09b6417a0f52fd9405c4f57", + "zh:2469d2e48f28076254a2a3fc327f184914566d9e40c5780b8d96ebf7205f8bc0", + "zh:37d7eb334d9561f335e748280f5535a384a88675af9a9eac439d4cfd663bcb66", + "zh:741101426a2f2c52dee37122f0f4a2f2d6af6d852cb1db634480a86398fa3511", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:a902473f08ef8df62cfe6116bd6c157070a93f66622384300de235a533e9d4a9", + "zh:b85c511a23e57a2147355932b3b6dce2a11e856b941165793a0c3d7578d94d05", + "zh:c5172226d18eaac95b1daac80172287b69d4ce32750c82ad77fa0768be4ea4b8", + "zh:dab4434dba34aad569b0bc243c2d3f3ff86dd7740def373f2a49816bd2ff819b", + "zh:f49fd62aa8c5525a5c17abd51e27ca5e213881d58882fd42fec4a545b53c9699", + ] +} + +provider "registry.terraform.io/hashicorp/tls" { + version = "4.2.1" + constraints = "~> 4.2.1" + hashes = [ + "h1:F5d6bQY8UlBo0D71Sv7CsV+3aZOFz0yeNF+vufog7h4=", + "zh:0d1e7d07ac973b97fa228f46596c800de830820506ee145626f079dd6bbf8d8a", + "zh:5c7e3d4348cb4861ab812973ef493814a4b224bdd3e9d534a7c8a7c992382b86", + "zh:7c6d4a86cd7a4e9c1025c6b3a3a6a45dea202af85d870cddbab455fb1bd568ad", + "zh:7d0864755ba093664c4b2c07c045d3f5e3d7c799dda1a3ef33d17ed1ac563191", + "zh:83734f57950ab67c0d6a87babdb3f13c908cbe0a48949333f489698532e1391b", + "zh:951e3c285218ebca0cf20eaa4265020b4ef042fea9c6ade115ad1558cfe459e5", + "zh:b9543955b4297e1d93b85900854891c0e645d936d8285a190030475379c5c635", + "zh:bb1bd9e86c003d08c30c1b00d44118ed5bbbf6b1d2d6f7eaac4fa5c6ebea5933", + "zh:c9477bfe00653629cd77ddac3968475f7ad93ac3ca8bc45b56d1d9efb25e4a6e", + "zh:d4cfda8687f736d0cba664c22ec49dae1188289e214ef57f5afe6a7217854fed", + "zh:dc77ee066cf96532a48f0578c35b1eaf6dc4d8ddd0e3ae8e029a3b10676dd5d3", + "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", + ] +} diff --git a/demo/terraform/lkec2/deployment.tf.json b/demo/terraform/ec2-single/deployment.tf.json similarity index 69% rename from demo/terraform/lkec2/deployment.tf.json rename to demo/terraform/ec2-single/deployment.tf.json index 30584554a..6a86ecbac 100644 --- a/demo/terraform/lkec2/deployment.tf.json +++ b/demo/terraform/ec2-single/deployment.tf.json @@ -11,10 +11,22 @@ } }, "resource": { + "aws_s3_bucket_public_access_block": { + "deployment": { + "bucket": "${aws_s3_bucket.deployment.id}", + "block_public_policy": true, + "block_public_acls": true, + "ignore_public_acls": true, + "restrict_public_buckets": true + } + }, "aws_s3_bucket_server_side_encryption_configuration": { "deployment": { "bucket": "${aws_s3_bucket.deployment.id}", "rule": { + "blocked_encryption_types": [ + "SSE-C" + ], "apply_server_side_encryption_by_default": { "sse_algorithm": "AES256" } @@ -45,11 +57,25 @@ ] } }, + "aws_iam_role_policy_attachment": { + "ssm": { + "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", + "role": "${aws_iam_role.ec2.name}" + }, + "servicesAccess": { + "policy_arn": "${aws_iam_policy.servicesAccess.arn}", + "role": "${aws_iam_role.ec2.name}" + }, + "cloudwatch_agent": { + "policy_arn": "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy", + "role": "${aws_iam_role.ec2.name}" + } + }, "null_resource": { "upload_jar": { "provisioner": { "local-exec": { - "command": "aws s3 cp \"${data.external.jar_hash.result.path}\" s3://${aws_s3_bucket.deployment.id}/server.zip --region us-west-2" + "command": "aws s3 cp \"${data.external.jar_hash.result.path}\" s3://${aws_s3_bucket.deployment.id}/server.zip --region us-west-2 --progress-frequency 1" } }, "depends_on": [ @@ -63,16 +89,20 @@ "provisioner": { "local-exec": { "environment": { - "SETTINGS_PASS": "${random_password.settings.result}" + "SETTINGS_PASS": "${random_password.settings.result}", + "SETTINGS_JSON": "${jsonencode(local.settings_raw)}" }, - "command": "openssl enc -aes-256-cbc -pbkdf2 -iter 100000 -md sha256 -in \"${local_sensitive_file.settings_raw.filename}\" -out \"${path.module}/build/settings.enc\" -pass env:SETTINGS_PASS" + "interpreter": [ + "bash", + "-c" + ], + "command": "printf '%s' \"$SETTINGS_JSON\" | openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 -out \"${path.module}/build/settings.enc\" -pass env:SETTINGS_PASS" } }, - "depends_on": [ - "local_sensitive_file.settings_raw" - ], "triggers": { - "settings_hash": "${local_sensitive_file.settings_raw.content_sha256}" + "cipher": "-aes-256-cbc -pbkdf2 -iter 10000 -md sha256", + "password_hash": "${sha256(random_password.settings.result)}", + "settings_hash": "${sha256(jsonencode(local.settings_raw))}" } }, "upload_settings": { @@ -86,67 +116,32 @@ "aws_s3_bucket.deployment" ], "triggers": { - "settings_hash": "${local_sensitive_file.settings_raw.content_sha256}" + "encrypted": "${null_resource.encrypt_settings.id}" } } }, + "aws_iam_policy": { + "servicesAccess": { + "path": "/ec2/demo/servicesAccess/", + "name": "ec2-demo-servicesAccess", + "description": "Access to Lightning Server EC2 Demo services", + "policy": "${jsonencode(local.servicesAccessPolicy)}" + } + }, "aws_ssm_parameter": { "settings_password": { - "name": "/LightningServerEC2SDemo/settings-password", - "description": "AES-256 passphrase used to encrypt/decrypt the Lightning Server Demo settings bundle", + "name": "/ec2-demo/settings-password", + "description": "AES-256 passphrase used to encrypt/decrypt the Lightning Server EC2 Demo settings bundle", "type": "SecureString", "value": "${random_password.settings.result}" } }, "aws_iam_role": { "ec2": { - "name": "LightningServerEC2SDemo-ec2-role", + "name": "ec2-demo-ec2-role", "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}]}" } }, - "aws_iam_instance_profile": { - "ec2": { - "role": "${aws_iam_role.ec2.name}", - "name": "LightningServerEC2SDemo-ec2-profile" - } - }, - "local_sensitive_file": { - "settings_raw": { - "filename": "${path.module}/build/raw-settings.json", - "content": "${jsonencode(local.settings_raw)}" - } - }, - "aws_s3_bucket_public_access_block": { - "deployment": { - "bucket": "${aws_s3_bucket.deployment.id}", - "block_public_policy": true, - "block_public_acls": true, - "ignore_public_acls": true, - "restrict_public_buckets": true - } - }, - "aws_iam_role_policy_attachment": { - "ssm": { - "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", - "role": "${aws_iam_role.ec2.name}" - }, - "servicesAccess": { - "policy_arn": "${aws_iam_policy.servicesAccess.arn}", - "role": "${aws_iam_role.ec2.name}" - }, - "cloudwatch_agent": { - "policy_arn": "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy", - "role": "${aws_iam_role.ec2.name}" - } - }, - "aws_iam_policy": { - "servicesAccess": { - "path": "/lightningserverec2sdemo/servicesAccess/", - "name": "LightningServerEC2SDemo-servicesAccess", - "description": "Access to Lightning Server Demo services", - "policy": "${jsonencode(local.servicesAccessPolicy)}" - } - }, "random_password": { "settings": { "special": true, @@ -162,16 +157,22 @@ } } }, + "aws_iam_instance_profile": { + "ec2": { + "role": "${aws_iam_role.ec2.name}", + "name": "ec2-demo-ec2-profile" + } + }, "aws_s3_bucket": { "deployment": { "force_destroy": true, - "bucket_prefix": "lightningserverec2sdemo-deploy" + "bucket_prefix": "ec2-demo-deploy" } } }, "locals": { "settings_raw": { - "cache": "redis://${element(aws_elasticache_cluster.redis.cache_nodes, 0).address}:${element(aws_elasticache_cluster.redis.cache_nodes, 0).port}/0", + "cache": "ram", "cors": { "limitToDomains": [ "*" @@ -191,29 +192,32 @@ }, "secretBasis": "${random_password.secretBasis.result}", "ktorRunConfig": { - "host": "0.0.0.0", + "host": "127.0.0.1", "port": 8080, "realIpHeader": "X-Forwarded-For" }, - "engine-cache": "redis://${element(aws_elasticache_cluster.redis.cache_nodes, 0).address}:${element(aws_elasticache_cluster.redis.cache_nodes, 0).port}/0", - "phoneCall": "${var.phoneCall}", - "githubOauth": "${var.githubOauth}", - "engine-pubSub": "redis://${element(aws_elasticache_cluster.redis.cache_nodes, 0).address}:${element(aws_elasticache_cluster.redis.cache_nodes, 0).port}/0", + "engine-cache": "ram", + "phoneCall": "test", + "githubOauth": { + "id": "", + "secret": "" + }, + "engine-pubSub": "local", "nettyRunConfig": { - "host": "0.0.0.0", + "host": "127.0.0.1", "port": 8080, "realIpHeader": "X-Forwarded-For" }, "general": { - "projectName": "Lightning Server Demo", - "publicUrl": "https://lightningserver2.cs.lightningkite.com", - "wsUrl": "wss://lightningserver2.cs.lightningkite.com", + "projectName": "Lightning Server EC2 Demo", + "publicUrl": "https://ec2-demo.cs.lightningkite.com", + "wsUrl": "wss://ec2-demo.cs.lightningkite.com", "debug": true, "emergencyContact": "joseph@lightningkite.com" }, - "database": "mongodb://master:${random_password.database.result}@${aws_docdb_cluster.database.endpoint}:${aws_docdb_cluster.database.port}/default?replicaSet=rs0&retryWrites=false&tls=true", - "emailInbound": "ses://", - "sms": "${var.sms}", + "database": "ram", + "emailInbound": "console", + "sms": "console", "files": "s3://${aws_s3_bucket.files.bucket}.s3-${aws_s3_bucket.files.region}.amazonaws.com/?signedUrlDuration=1d", "logging": { "default": { @@ -231,12 +235,60 @@ } } }, - "telemetry": null, - "someSecret": "${var.someSecret}", - "voiceAgent": "${var.voiceAgent}", - "smsInbound": "${var.smsInbound}", - "email": "smtp://${aws_iam_access_key.email.id}:${aws_iam_access_key.email.ses_smtp_password_v4}@email-smtp.us-west-2.amazonaws.com:587?fromEmail=noreply@lightningserver2.cs.lightningkite.com", - "pubSub": "redis://${element(aws_elasticache_cluster.redis.cache_nodes, 0).address}:${element(aws_elasticache_cluster.redis.cache_nodes, 0).port}/0" + "telemetry": { + "url": "noop", + "batching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "metricReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "traceReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "logReportBatching": { + "frequency": "PT5M", + "maxQueueSize": 20480, + "maxSize": 5120, + "exportTimeout": "PT30S" + }, + "batchingLimits": { + "frequency": "PT5M", + "maxQueueSize": 2048, + "maxSize": 512, + "exportTimeout": "PT30S" + }, + "spanLimits": { + "maxAttributeValueLength": 1024, + "maxNumberOfAttributes": 128, + "maxNumberOfEvents": 128, + "maxNumberOfLinks": 128, + "maxNumberOfAttributesPerEvent": 32, + "maxNumberOfAttributesPerLink": 32 + }, + "logLimits": { + "maxBodyLength": 8192, + "maxStackTraceDepth": 50 + }, + "sampling": null, + "maxSpansPerSecond": null, + "maxLogsPerSecond": null + }, + "someSecret": "Some Value", + "voiceAgent": "test", + "smsInbound": "console", + "email": "console", + "notifications": "console", + "pubSub": "local" }, "servicesAccessPolicy": { "Version": "2012-10-17", diff --git a/demo/terraform/ec2-single/dns.tf.json b/demo/terraform/ec2-single/dns.tf.json new file mode 100644 index 000000000..cad8ad16b --- /dev/null +++ b/demo/terraform/ec2-single/dns.tf.json @@ -0,0 +1,31 @@ +{ + "data": { + "aws_route53_zone": { + "main": { + "name": "cs.lightningkite.com" + } + } + }, + "resource": { + "aws_route53_record": { + "main": { + "zone_id": "${data.aws_route53_zone.main.zone_id}", + "records": [ + "${aws_eip.main.public_ip}" + ], + "name": "ec2-demo.cs.lightningkite.com", + "type": "A", + "ttl": 300 + }, + "main_v6": { + "zone_id": "${data.aws_route53_zone.main.zone_id}", + "records": [ + "${aws_instance.main.ipv6_addresses[0]}" + ], + "name": "ec2-demo.cs.lightningkite.com", + "type": "AAAA", + "ttl": 300 + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/ec2.tf.json b/demo/terraform/ec2-single/ec2.tf.json new file mode 100644 index 000000000..a66129cff --- /dev/null +++ b/demo/terraform/ec2-single/ec2.tf.json @@ -0,0 +1,94 @@ +{ + "data": { + "aws_ami": { + "base": { + "filter": [ + { + "values": [ + "al2023-ami-2023.*-kernel-*-arm64" + ], + "name": "name" + }, + { + "values": [ + "arm64" + ], + "name": "architecture" + }, + { + "values": [ + "hvm" + ], + "name": "virtualization-type" + } + ], + "most_recent": true, + "owners": [ + "amazon" + ] + } + } + }, + "resource": { + "aws_s3_object": { + "init": { + "bucket": "${aws_s3_bucket.deployment.id}", + "content_type": "application/x-sh", + "key": "init/component-${local.ec2_init_version}.sh", + "content": "${local.ec2_init}" + } + }, + "aws_instance": { + "main": { + "depends_on": [ + "null_resource.upload_jar", + "null_resource.upload_settings", + "aws_s3_object.init", + "aws_ssm_parameter.settings_password", + "aws_iam_role_policy_attachment.servicesAccess", + "aws_iam_role_policy_attachment.ssm", + "aws_iam_role_policy_attachment.cloudwatch_agent", + "aws_s3_bucket_server_side_encryption_configuration.deployment" + ], + "iam_instance_profile": "${aws_iam_instance_profile.ec2.name}", + "metadata_options": { + "http_endpoint": "enabled", + "http_tokens": "required", + "http_put_response_hop_limit": 1 + }, + "ipv6_address_count": 1, + "user_data": "${local.ec2_base_init}", + "root_block_device": { + "volume_type": "gp3", + "encrypted": true, + "volume_size": 20, + "delete_on_termination": true, + "tags": { + "Name": "ec2-demo-root" + } + }, + "tags": { + "Name": "Lightning Server EC2 Demo" + }, + "lifecycle": { + "ignore_changes": [ + "ami" + ] + }, + "user_data_replace_on_change": true, + "vpc_security_group_ids": [ + "${aws_security_group.ec2.id}" + ], + "subnet_id": "${data.aws_subnets.main.ids[0]}", + "ami": "${data.aws_ami.base.id}", + "instance_type": "t4g.micro", + "enable_primary_ipv6": true + } + } + }, + "locals": { + "ec2_base_init": "${templatefile(\"${path.module}/ec2_init_base.sh\", { deployment_bucket = aws_s3_bucket.deployment.id, deployment_script_key = aws_s3_object.init.key })}", + "ec2_init": "${templatefile(\"${path.module}/ec2_init.sh\", { deployment_bucket = aws_s3_bucket.deployment.id })}", + "ec2_init_version": "${max(1, parseint(substr(sha256(jsonencode([local.ec2_init])), 0, 7), 16))}" + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/ec2_init.sh b/demo/terraform/ec2-single/ec2_init.sh new file mode 100644 index 000000000..7cac91212 --- /dev/null +++ b/demo/terraform/ec2-single/ec2_init.sh @@ -0,0 +1,597 @@ +#!/bin/bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive + +echo "[INFO] EC2 Init script started on AmazonLinux2023 at $(date)" + + +# === Disable unattended upgrades === +echo "[INFO] Disabling dnf automatic update and metadata timers at $(date)" +systemctl disable --now dnf-automatic.timer dnf-automatic-install.timer || true +systemctl disable --now dnf-makecache.timer || true +systemctl mask dnf-makecache.timer || true + +# === System update + base packages === +echo "[INFO] Updating system packages at $(date)" +dnf -y --releasever=latest upgrade +dnf install -y java-17-amazon-corretto-headless openssl unzip +dnf -y autoremove + + +# === Install CloudWatch Agent === +echo "[INFO] Installing CloudWatch Agent at $(date)" +dnf install -y amazon-cloudwatch-agent + + +# === CloudWatch Agent Configuration === +echo "[INFO] Creating amazon-cloudwatch-agent.json for CloudWatch $(date)" +cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json << EOF +{ + "logs": { + "logs_collected": { + "files": { + "collect_list": [ + { + "file_path": "/var/log/ec2-demo/ec2_init.log", + "log_group_name": "ec2-demo-main-log", + "log_stream_name": "{instance_id}/ec2_init" + }, + { + "file_path": "/var/log/ec2-demo/server.log", + "log_group_name": "ec2-demo-main-log", + "log_stream_name": "{instance_id}/server" + }, + { + "file_path": "/var/log/ec2-demo/redeploy.log", + "log_group_name": "ec2-demo-main-log", + "log_stream_name": "{instance_id}/redeploy" + }, + { + "file_path": "/var/log/ec2-demo/os-update.log", + "log_group_name": "ec2-demo-main-log", + "log_stream_name": "{instance_id}/os-update" + } + ] + } + } + }, + "metrics": { + "metrics_collected": { + "mem": { + "measurement": ["mem_used_percent"] + }, + "disk": { + "measurement": ["disk_used_percent"], + "resources": ["/"] + } + } + } +} +EOF + +systemctl enable amazon-cloudwatch-agent +systemctl restart amazon-cloudwatch-agent + + +# === Install nginx + ACME module === +echo "[INFO] Installing nginx $(date)" +cat > /etc/yum.repos.d/nginx.repo << 'NGINX_REPO_EOF' +[nginx-stable] +name=nginx stable repo +baseurl=https://nginx.org/packages/amzn/2023/$basearch/ +gpgcheck=1 +enabled=1 +gpgkey=https://nginx.org/keys/nginx_signing.key +module_hotfixes=true +priority=9 +NGINX_REPO_EOF +dnf install -y nginx nginx-module-acme + +# === nginx config (nginx-module-acme handles cert issuance + renewal) === +echo "[INFO] Creating server.conf for nginx $(date)" +# The ACME module is dynamic, and load_module is only valid at the top level of nginx.conf. +grep -q 'ngx_http_acme_module' /etc/nginx/nginx.conf \ + || sed -i '1i load_module modules/ngx_http_acme_module.so;' /etc/nginx/nginx.conf +rm -f /etc/nginx/conf.d/default.conf +cat > /etc/nginx/conf.d/server.conf << 'NGX_EOF' +resolver 8.8.8.8 1.1.1.1 ipv6=off; +resolver_timeout 5s; + +map $http_upgrade $connection_upgrade { + default upgrade; + '' ''; +} + +upstream app { + server 127.0.0.1:8080; + keepalive 32; + keepalive_timeout 45s; + keepalive_requests 1000; +} + +acme_issuer letsencrypt { + uri https://acme-staging-v02.api.letsencrypt.org/directory; + state_path /var/cache/nginx/acme-letsencrypt; + accept_terms_of_service; +} + +# Drop requests for any other host name or a bare IP +server { + listen 80 default_server; + listen [::]:80 default_server; + listen 443 ssl default_server; + listen [::]:443 ssl default_server; + ssl_reject_handshake on; + return 444; +} + +# HTTP: redirect to HTTPS (nginx-module-acme answers ACME challenges before this) +server { + listen 80; + listen [::]:80; + server_name ec2-demo.cs.lightningkite.com; + return 308 https://$host$request_uri; +} + +server { + server_name ec2-demo.cs.lightningkite.com; + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + + acme_certificate letsencrypt; + ssl_certificate $acme_certificate; + ssl_certificate_key $acme_certificate_key; + # Variable certificate paths are otherwise re-read on every handshake. + ssl_certificate_cache max=2; + + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305; + ssl_prefer_server_ciphers off; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 1d; + ssl_session_tickets off; + + add_header Strict-Transport-Security "max-age=63072000" always; + add_header X-Robots-Tag "noindex, nofollow, nosnippet, noarchive" always; + server_tokens off; + + client_max_body_size 10M; + + location / { + proxy_pass http://app; + proxy_http_version 1.1; + + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $server_name; + proxy_set_header X-Real-IP $remote_addr; + + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + + } +} + + +NGX_EOF + + +# === SSM Agent === +echo "[INFO] Ensuring SSM agent is installed and running at $(date)" +# Required so terraform can drive in-place jar/settings redeploys via +# `aws ssm send-command`. The AL2023 AMI ships amazon-ssm-agent as an RPM; install if missing, +# then enable + start so newly-created instances register with SSM. +rpm -q amazon-ssm-agent >/dev/null 2>&1 || dnf install -y amazon-ssm-agent +systemctl enable amazon-ssm-agent +systemctl start amazon-ssm-agent + + +# === Service User === +echo "[INFO] Creating unprivileged service user lightning-server" +id -u lightning-server >/dev/null 2>&1 || useradd --system --user-group --home-dir /var/lib/ec2-demo --no-create-home --shell /usr/sbin/nologin lightning-server + +# === Filesystem Layout === +# Code: owned by root, so the service can run it but never modify it. +install -d -o root -g root -m 0755 /opt/ec2-demo +# Config (settings.json, Config instance files): readable by the service, writable only by root. +install -d -o root -g lightning-server -m 0750 /etc/ec2-demo +# State and cache: the service's own. systemd's StateDirectory=/CacheDirectory= also manage these. +install -d -o lightning-server -g lightning-server -m 0700 /var/lib/ec2-demo +install -d -o lightning-server -g lightning-server -m 0700 /var/cache/ec2-demo + +# === Systemd Service === +echo "[INFO] Creating Systemd unit for Lightning Server EC2 Demo" +cat > /etc/systemd/system/ec2-demo.service << 'UNIT_EOF' +[Unit] +Description=Lightning Server EC2 Demo +After=network.target +Requires=network.target + +[Service] +Type=simple +User=lightning-server +Group=lightning-server +WorkingDirectory=/var/lib/ec2-demo +ExecStart=/opt/ec2-demo/server/bin/server serve +StateDirectory=ec2-demo +StateDirectoryMode=0700 +CacheDirectory=ec2-demo +CacheDirectoryMode=0700 +LogsDirectory=ec2-demo +# Apps load settings.json relative to the working directory. A read-only bind mount (not a symlink, +# which the service could swap since it owns the directory) keeps that working without letting the +# service replace it. No '-' prefix: with no settings deployed yet, the service must not start. +BindReadOnlyPaths=/etc/ec2-demo/settings.enc:/var/lib/ec2-demo/settings.json +# Settings stay encrypted on disk. '+' runs the key fetch as root outside the sandbox; it writes the +# RAM-backed, root-only file whose password systemd hands to the app. systemd loads EnvironmentFile= +# before every Exec* (ExecStartPre included), so '-' lets the key fetch run before the file exists. +ExecStartPre=+/usr/local/bin/ec2-demo-settings-key +EnvironmentFile=-/run/ec2-demo-secrets/settings.env +NoNewPrivileges=true +UMask=0077 +ProtectSystem=strict +ProtectHome=true +PrivateTmp=true +PrivateDevices=true +ProtectProc=invisible +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +ProtectClock=true +ProtectHostname=true +RestrictSUIDSGID=true +RestrictNamespaces=true +RestrictRealtime=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK +LockPersonality=true +SystemCallArchitectures=native + + +Restart=always +RestartSec=5 +StandardOutput=append:/var/log/ec2-demo/server.log +StandardError=append:/var/log/ec2-demo/server.log + + + + +[Install] +WantedBy=multi-user.target +UNIT_EOF + +# === Server log file === +echo "[INFO] Preparing server log directory" +mkdir -p /var/log/ec2-demo +touch /var/log/ec2-demo/server.log +chown -R lightning-server:lightning-server /var/log/ec2-demo + +cat > /etc/logrotate.d/ec2-demo << 'LOGROTATE_EOF' +/var/log/ec2-demo/*.log { + daily + rotate 7 + compress + delaycompress + missingok + notifempty + copytruncate + su lightning-server lightning-server +} +LOGROTATE_EOF + + +# === Lightning Server Redeploy Script === +echo "[INFO] Creating Lightning Server Redeploy Script" +cat > /usr/local/bin/lightning-server-redeploy << 'REDEPLOY_EOF' +#!/bin/bash +set -euo pipefail + +log() { echo "[lightning-server-redeploy] $(date '+%Y-%m-%d %H:%M:%S') $*"; } +err() { echo "[lightning-server-redeploy] $(date '+%Y-%m-%d %H:%M:%S') ERROR: $*" >&2; } + +BUCKET="${deployment_bucket}" +REGION="us-west-2" +SSM_PARAM="/ec2-demo/settings-password" +APP_DIR="/opt/ec2-demo" +CONF_DIR="/etc/ec2-demo" +STATE_DIR="/var/lib/ec2-demo" +LOG_FILE="/var/log/ec2-demo/redeploy.log" + +mkdir -p "$(dirname "$LOG_FILE")" +touch "$LOG_FILE" +chown lightning-server:lightning-server "$LOG_FILE" +exec > >(tee -a "$LOG_FILE" | logger -t lightning-server-redeploy -s) 2>&1 + +log "Redeploy started at $(date)" +install -d -o root -g root -m 0755 "$APP_DIR" +install -d -o root -g lightning-server -m 0750 "$CONF_DIR" +install -d -o lightning-server -g lightning-server -m 0700 "$STATE_DIR" + +download_with_retry() { + local src="$1" dst="$2" max=5 attempt=1 + while [ $attempt -le $max ]; do + log "Downloading $src (attempt $attempt/$max)" + if aws s3 cp "$src" "$dst" --region "$REGION" --no-progress; then return 0; fi + sleep $((attempt * 5)) + attempt=$((attempt + 1)) + done + err "Failed to download $src after $max attempts" + return 1 +} + +# Roll back to the previously-working server + settings, then restart. Used when the new +# version fails to become active so the instance self-heals instead of staying down. +rollback() { + err "Rolling back to previous version" + [ -d "$APP_DIR/server-old" ] && { rm -rf "$APP_DIR/server"; mv "$APP_DIR/server-old" "$APP_DIR/server"; } + [ -f "$CONF_DIR/settings.enc.old" ] && mv -f "$CONF_DIR/settings.enc.old" "$CONF_DIR/settings.enc" + systemctl restart ec2-demo || true +} + +download_with_retry "s3://$BUCKET/server.zip" "$APP_DIR/server.zip" +[ -d "$APP_DIR/server-old" ] && rm -rf "$APP_DIR/server-old" +[ -d "$APP_DIR/server" ] && mv "$APP_DIR/server" "$APP_DIR/server-old" +log "Successful Download" +log "Unzipping server.zip" +unzip -q "$APP_DIR/server.zip" -d "$APP_DIR" +rm -f "$APP_DIR/server.zip" +# The build stays root-owned so the service can run it but never modify it. Zip entries can carry +# arbitrary modes, so normalize to readable (and executable where already so) and root-writable only. +chown -R root:root "$APP_DIR" +chmod -R u=rwX,go=rX "$APP_DIR" + +# Settings stay encrypted at rest; the service decrypts them in memory at startup. +download_with_retry "s3://$BUCKET/settings.enc" "$CONF_DIR/settings.enc.new" +SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") +# Test-decrypt (output discarded) so a bad password or corrupt file fails the deploy here rather than +# at service start. The password goes via openssl's environment, not argv: argv is world-readable. +if ! SETTINGS_PASS="$SETTINGS_PASS" openssl enc -d -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 \ + -in "$CONF_DIR/settings.enc.new" -out /dev/null -pass env:SETTINGS_PASS; then + err "Failed to decrypt settings" + rm -f "$CONF_DIR/settings.enc.new" + exit 1 +fi +chown root:lightning-server "$CONF_DIR/settings.enc.new" +chmod 640 "$CONF_DIR/settings.enc.new" +log "Verified settings decrypt" +[ -f "$CONF_DIR/settings.enc.old" ] && rm "$CONF_DIR/settings.enc.old" +[ -f "$CONF_DIR/settings.enc" ] && mv "$CONF_DIR/settings.enc" "$CONF_DIR/settings.enc.old" +mv "$CONF_DIR/settings.enc.new" "$CONF_DIR/settings.enc" + +# Mount point for the unit's read-only settings bind mount. Created as the service user: it owns +# this directory, so root must not follow anything that may have been placed here. +[ -e "$STATE_DIR/settings.json" ] || sudo -u lightning-server touch "$STATE_DIR/settings.json" + +log "Restarting Lightning Server EC2 Demo" +systemctl restart ec2-demo +sleep 5 +if ! systemctl is-active --quiet ec2-demo; then + err "Service failed to start" + tail -n 100 /var/log/ec2-demo/server.log >&2 || true + rollback + exit 1 +fi + +log "Waiting for liveness at http://localhost:8080/meta/online" +healthy=0 +for i in $(seq 1 20); do + if curl -fsS -o /dev/null --max-time 5 "http://localhost:8080/meta/online"; then healthy=1; break; fi + sleep 3 +done +if [ "$healthy" -ne 1 ]; then + err "Liveness endpoint http://localhost:8080/meta/online never returned success" + tail -n 100 /var/log/ec2-demo/server.log >&2 || true + rollback + exit 1 +fi +log "Done" +REDEPLOY_EOF + +chmod +x /usr/local/bin/lightning-server-redeploy +echo "[INFO] Creating Lightning Server Redeploy Script - DONE" + +# === Lightning Server Pre-Deploy Script === +# Runs pre-deploy tasks with the NEW build in a scratch dir, without touching the live server, so +# the current version keeps serving while migrations run. Invoked once per deploy (before the +# redeploy/cutover) - by the single-instance redeploy on the one box, and by the scaling fleet +# script on one instance. A non-zero exit aborts the deploy. +echo "[INFO] Creating Lightning Server Pre-Deploy Script" +cat > /usr/local/bin/lightning-server-predeploy << 'PREDEPLOY_EOF' +#!/bin/bash +set -euo pipefail + +log() { echo "[lightning-server-predeploy] $*"; } +err() { echo "[lightning-server-predeploy] ERROR: $*" >&2; } + +BUCKET="${deployment_bucket}" +REGION="us-west-2" +SSM_PARAM="/ec2-demo/settings-password" +LOG_FILE="/var/log/ec2-demo/predeploy.log" + +mkdir -p "$(dirname "$LOG_FILE")" +touch "$LOG_FILE" +chown lightning-server:lightning-server "$LOG_FILE" +exec > >(tee -a "$LOG_FILE" | logger -t lightning-server-predeploy -s) 2>&1 + +log "Pre-deploy started at $(date)" + +# Fetch the NEW build + settings into a scratch dir; the live server is never touched. mktemp makes a +# fresh root-only directory with an unguessable name: a fixed path under world-writable /var/tmp could +# be pre-created or symlinked by another user to redirect root's writes. +SCRATCH=$(mktemp -d "/var/tmp/ec2-demo-predeploy.XXXXXX") +trap 'cd /; rm -rf "$SCRATCH"' EXIT +aws s3 cp "s3://$BUCKET/server.zip" "$SCRATCH/server.zip" --region "$REGION" --no-progress +unzip -q "$SCRATCH/server.zip" -d "$SCRATCH" + +# Encrypted bytes under the name the app loads; the app decrypts them in memory (password passed below). +aws s3 cp "s3://$BUCKET/settings.enc" "$SCRATCH/settings.json" --region "$REGION" --no-progress +SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") +if ! SETTINGS_PASS="$SETTINGS_PASS" openssl enc -d -aes-256-cbc -pbkdf2 -iter 10000 -md sha256 \ + -in "$SCRATCH/settings.json" -out /dev/null -pass env:SETTINGS_PASS; then + err "Failed to decrypt settings" + exit 1 +fi +chown -R lightning-server:lightning-server "$SCRATCH" +chmod 600 "$SCRATCH/settings.json" + +# Cap heap so this runs alongside the live server without risking OOM. Heavy migrations may need more. +log "Running pre-deploy tasks with the new version" +cd "$SCRATCH" +if LIGHTNING_SERVER_SETTINGS_DECRYPTION="$SETTINGS_PASS" runuser -u lightning-server -- env "JAVA_OPTS=-Xmx512m" ./server/bin/server predeploy; then + cd / + rm -rf "$SCRATCH" + log "Pre-deploy complete" +else + cd / + rm -rf "$SCRATCH" + err "Pre-deploy tasks failed" + exit 1 +fi +PREDEPLOY_EOF + +chmod +x /usr/local/bin/lightning-server-predeploy +echo "[INFO] Creating Lightning Server Pre-Deploy Script - DONE" + +# === Settings Key Script (ExecStartPre) === +# Runs as root before each service start: fetches the settings password from SSM into a RAM-backed, +# root-only environment file that systemd hands to the app. Nothing is written to disk. +echo "[INFO] Creating settings key script" +cat > /usr/local/bin/ec2-demo-settings-key << 'SETTINGS_KEY_EOF' +#!/bin/bash +set -euo pipefail +# systemd runs this root step with the service's environment and working directory, both pointing at +# /var/lib/ec2-demo, which the service can write. Pin them so the service cannot steer root's aws +# CLI (e.g. with a planted ~/.aws/config credential_process); the instance role supplies credentials. +cd / +export HOME=/root AWS_CONFIG_FILE=/dev/null AWS_SHARED_CREDENTIALS_FILE=/dev/null +BUCKET="${deployment_bucket}" +REGION="us-west-2" +SSM_PARAM="/ec2-demo/settings-password" +SECRETS_DIR="/run/ec2-demo-secrets" +install -d -o root -g root -m 0700 "$SECRETS_DIR" +SETTINGS_PASS=$(aws ssm get-parameter --name "$SSM_PARAM" --with-decryption --query Parameter.Value --output text --region "$REGION") +umask 077 +# printf is a shell builtin, so the password never appears in any process's argv. Single quotes make +# systemd take the value literally; the password's charset (letters, digits, '-', '_') contains none. +printf "LIGHTNING_SERVER_SETTINGS_DECRYPTION='%s'\n" "$SETTINGS_PASS" > "$SECRETS_DIR/settings.env.tmp" +mv -f "$SECRETS_DIR/settings.env.tmp" "$SECRETS_DIR/settings.env" +SETTINGS_KEY_EOF +chmod 0700 /usr/local/bin/ec2-demo-settings-key + + +# === Instance Emergency Update Script === +# The "a CVE landed and we are not waiting for a rebuild" lever. On a scaling fleet +# update-fleet.sh drives it one drained instance at a time; routine patching there still +# comes from rebuilding the image and rolling the ASG. +# +# It restarts the app unconditionally (the JRE is a system package and may be replaced +# underneath a running JVM), so it is only interruption-free on an instance already +# drained from the load balancer. +# +# Usage: os-update [package ...] +# with no arguments, applies a full upgrade; otherwise upgrades only the named packages. +echo "[INFO] Creating OS Emergency Update Script" +cat > /usr/local/bin/os-update << 'UPDATE_EOF' +#!/bin/bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive + +log() { echo "[os-update] $(date '+%Y-%m-%d %H:%M:%S') $*"; } +err() { echo "[os-update] $(date '+%Y-%m-%d %H:%M:%S') ERROR: $*" >&2; } + +LOG_FILE="/var/log/ec2-demo/os-update.log" +PACKAGES="$*" + +mkdir -p "$(dirname "$LOG_FILE")" +touch "$LOG_FILE" +chown lightning-server:lightning-server "$LOG_FILE" +exec > >(tee -a "$LOG_FILE" | logger -t os-update -s) 2>&1 + +log "OS update started" +# The repositories are locked to the release this host is on, so a plain upgrade only sees fixes +# already in that release; every fix published since would be silently missed while the update +# reported success. --releasever=latest moves to the newest release first. +DNF_OPTS="-y --releasever=latest" +if [ -n "$PACKAGES" ]; then + # `dnf upgrade` exits 0 for a package that is not installed, so a typo'd or wrong-architecture + # name would report a clean patch while changing nothing at all. Check each name up front and + # fail loudly instead. + for p in $PACKAGES; do + if ! rpm -q "$p" >/dev/null 2>&1; then + err "not installed on this host, refusing to report a successful update: $p" + exit 1 + fi + done + log "Upgrading only: $PACKAGES" + dnf $DNF_OPTS upgrade $PACKAGES +else + log "Applying full upgrade" + dnf $DNF_OPTS upgrade + # Deliberately only on the full-upgrade path. Naming packages means the operator asked for a minimal, + # auditable change to one or two packages; autoremove is a whole-system operation, which is not a + # blast radius to take on while chasing a single CVE. + dnf -y autoremove +fi + +log "Restarting Lightning Server EC2 Demo" +systemctl restart ec2-demo +sleep 5 +if ! systemctl is-active --quiet ec2-demo; then + err "Service failed to start after OS update" + tail -n 100 /var/log/ec2-demo/server.log >&2 || true + exit 1 +fi + +log "Waiting for liveness at http://localhost:8080/meta/online" +healthy=0 +for i in $(seq 1 20); do + if curl -fsS -o /dev/null --max-time 5 "http://localhost:8080/meta/online"; then healthy=1; break; fi + sleep 3 +done +if [ "$healthy" -ne 1 ]; then + err "Liveness endpoint http://localhost:8080/meta/online never returned success" + tail -n 100 /var/log/ec2-demo/server.log >&2 || true + exit 1 +fi + +# Breadcrumb for the CloudWatch log; a reboot is needed to activate a patched kernel. Callers that +# act on it (update-fleet.sh) run their own reboot check over SSM rather than reading this back, +# because SSM truncates command output at 24,000 characters per stream and a full upgrade can push +# a trailing marker past that cap. needs-restarting exits 1 when a reboot is needed. +if dnf needs-restarting -r >/dev/null 2>&1; then log "REBOOT_REQUIRED=no"; else log "REBOOT_REQUIRED=yes"; fi +log "Done" +UPDATE_EOF + +chmod +x /usr/local/bin/os-update +echo "[INFO] Creating OS Emergency Update Script - DONE" + + + +echo "[INFO] Reloading systemd configuration..." +systemctl daemon-reload + +systemctl enable ec2-demo + +# First-time deploy uses the same script that subsequent SSM-driven redeploys +# will use, so there's exactly one code path that knows how to deploy the server. +echo "[INFO] Running first-time application deploy..." +/usr/local/bin/lightning-server-redeploy + +# === Start Services === +echo "[INFO] Starting services..." +systemctl enable nginx +systemctl restart nginx + + +# Verify CloudWatch agent started (non-fatal if it fails) +if ! systemctl is-active --quiet amazon-cloudwatch-agent; then + echo "[WARN] CloudWatch agent failed to start. Logs may not be collected." + echo "[WARN] Check: journalctl -u amazon-cloudwatch-agent" +fi + +BOOT_END=$(date +%s) +BOOT_DURATION=$((BOOT_END - BOOT_START)) +echo "[INFO] EC2 Init script completed in $BOOT_DURATION seconds" + diff --git a/demo/terraform/ec2-single/ec2_init_base.sh b/demo/terraform/ec2-single/ec2_init_base.sh new file mode 100644 index 000000000..acf5a42d4 --- /dev/null +++ b/demo/terraform/ec2-single/ec2_init_base.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -euo pipefail +export DEBIAN_FRONTEND=noninteractive + +export BOOT_START=$(date +%s) + +# === Logging Setup === +WORKING_DIR="/var/lib/ec2-demo-init" +mkdir -p -m 0700 "$WORKING_DIR" +cd "$WORKING_DIR" + +mkdir -p /var/log/ec2-demo +touch /var/log/ec2-demo/ec2_init.log +exec > >(tee /var/log/ec2-demo/ec2_init.log | logger -t ec2_init -s) 2>&1 + +# === Bootstrap packages === +# Just enough to fetch ec2_init.sh; the full system update and package install happen there. +echo "[INFO] Installing bootstrap packages..." +dnf install -y unzip + + +# === Install AWS CLI v2 === +echo "[INFO] Installing AWS CLI V2 at $(date)" +curl https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip -o "awscliv2.zip" +unzip -q awscliv2.zip +./aws/install +rm -rf aws/ awscliv2.zip + + + +download_with_retry() { + local src="$1" dst="$2" max=5 attempt=1 + while [ $attempt -le $max ]; do + echo "[INFO] Downloading $src (attempt $attempt/$max)" + if aws s3 cp "$src" "$dst" --region "us-west-2" --no-progress; then return 0; fi + sleep $((attempt * 5)) + attempt=$((attempt + 1)) + done + echo "[ERROR] Failed to download $src after $max attempts" + return 1 +} + +echo "[INFO] Downloading EC2 Init script at $(date)" +download_with_retry "s3://${deployment_bucket}/${deployment_script_key}" "ec2_init.sh" +chmod +x ec2_init.sh + +echo "[INFO] Running EC2 Init script at $(date)" +./ec2_init.sh +rm ec2_init.sh + diff --git a/demo/terraform/ec2-single/eip.tf.json b/demo/terraform/ec2-single/eip.tf.json new file mode 100644 index 000000000..7739270ed --- /dev/null +++ b/demo/terraform/ec2-single/eip.tf.json @@ -0,0 +1,18 @@ +{ + "resource": { + "aws_eip_association": { + "main": { + "instance_id": "${aws_instance.main.id}", + "allocation_id": "${aws_eip.main.id}" + } + }, + "aws_eip": { + "main": { + "domain": "vpc", + "tags": { + "Name": "Lightning Server EC2 Demo" + } + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/lkec2/files.tf.json b/demo/terraform/ec2-single/files.tf.json similarity index 92% rename from demo/terraform/lkec2/files.tf.json rename to demo/terraform/ec2-single/files.tf.json index d7d3cea62..3b2fece0e 100644 --- a/demo/terraform/lkec2/files.tf.json +++ b/demo/terraform/ec2-single/files.tf.json @@ -48,6 +48,9 @@ "files": { "bucket": "${aws_s3_bucket.files.id}", "rule": { + "blocked_encryption_types": [ + "SSE-C" + ], "apply_server_side_encryption_by_default": { "sse_algorithm": "AES256" } @@ -57,7 +60,7 @@ "aws_s3_bucket": { "files": { "force_destroy": true, - "bucket_prefix": "lightningserverec2sdemo-files" + "bucket_prefix": "ec2-demo-files" } } } diff --git a/demo/terraform/ec2-single/main.tf.json b/demo/terraform/ec2-single/main.tf.json new file mode 100644 index 000000000..1c3e98f29 --- /dev/null +++ b/demo/terraform/ec2-single/main.tf.json @@ -0,0 +1,50 @@ +{ + "provider": { + "aws": [ + { + "region": "us-west-2" + } + ] + }, + "terraform": { + "required_providers": { + "random": { + "source": "hashicorp/random", + "version": "~> 3.8.0" + }, + "external": { + "source": "hashicorp/external", + "version": "~> 2.3.0" + }, + "null": { + "source": "hashicorp/null", + "version": "~> 3.2.3" + }, + "archive": { + "source": "hashicorp/archive", + "version": "~> 2.7.0" + }, + "tls": { + "source": "hashicorp/tls", + "version": "~> 4.2.1" + }, + "aws": { + "source": "hashicorp/aws", + "version": "~> 6.34.0" + }, + "local": { + "source": "hashicorp/local", + "version": "~> 2.7.0" + } + }, + "required_version": "~> 1.0", + "backend": { + "s3": { + "bucket": "lightningkite-terraform", + "encrypt": true, + "region": "us-west-2", + "key": "ec2-demo" + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/monitoring.tf.json b/demo/terraform/ec2-single/monitoring.tf.json new file mode 100644 index 000000000..f57ef3ce5 --- /dev/null +++ b/demo/terraform/ec2-single/monitoring.tf.json @@ -0,0 +1,93 @@ +{ + "resource": { + "aws_sns_topic": { + "emergency": { + "name": "ec2-demo_emergencies" + } + }, + "aws_cloudwatch_metric_alarm": { + "high_memory": { + "alarm_name": "ec2-demo-high-memory", + "statistic": "Average", + "period": 300, + "metric_name": "mem_used_percent", + "evaluation_periods": 3, + "alarm_description": "High memory utilization (CWAgent mem_used_percent)", + "namespace": "CWAgent", + "comparison_operator": "GreaterThanThreshold", + "alarm_actions": [ + "${aws_sns_topic.emergency.arn}" + ], + "threshold": 90, + "dimensions": { + "InstanceId": "${aws_instance.main.id}" + } + }, + "system_status_check": { + "alarm_name": "ec2-demo-system-status-check-failed", + "statistic": "Maximum", + "period": 60, + "metric_name": "StatusCheckFailed_System", + "evaluation_periods": 2, + "alarm_description": "EC2 system status check failing", + "treat_missing_data": "breaching", + "namespace": "AWS/EC2", + "comparison_operator": "GreaterThanThreshold", + "alarm_actions": [ + "${aws_sns_topic.emergency.arn}" + ], + "threshold": 0, + "dimensions": { + "InstanceId": "${aws_instance.main.id}" + } + }, + "high_disk": { + "alarm_name": "ec2-demo-high-disk", + "statistic": "Average", + "period": 300, + "metric_name": "disk_used_percent", + "evaluation_periods": 3, + "alarm_description": "High root-volume disk utilization (CWAgent disk_used_percent)", + "namespace": "CWAgent", + "comparison_operator": "GreaterThanThreshold", + "alarm_actions": [ + "${aws_sns_topic.emergency.arn}" + ], + "threshold": 85, + "dimensions": { + "InstanceId": "${aws_instance.main.id}" + } + }, + "high_cpu": { + "alarm_name": "ec2-demo-high-cpu", + "period": 300, + "statistic": "Average", + "metric_name": "CPUUtilization", + "evaluation_periods": 3, + "alarm_description": "High CPU utilization", + "comparison_operator": "GreaterThanThreshold", + "namespace": "AWS/EC2", + "alarm_actions": [ + "${aws_sns_topic.emergency.arn}" + ], + "threshold": 90, + "dimensions": { + "InstanceId": "${aws_instance.main.id}" + } + } + }, + "aws_cloudwatch_log_group": { + "application": { + "retention_in_days": 30, + "name": "ec2-demo-main-log" + } + }, + "aws_sns_topic_subscription": { + "emergency_primary": { + "protocol": "email", + "endpoint": "joseph@lightningkite.com", + "topic_arn": "${aws_sns_topic.emergency.arn}" + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/network.tf.json b/demo/terraform/ec2-single/network.tf.json new file mode 100644 index 000000000..ccde0f447 --- /dev/null +++ b/demo/terraform/ec2-single/network.tf.json @@ -0,0 +1,70 @@ +{ + "data": { + "aws_subnets": { + "main": { + "filter": { + "values": [ + "${data.aws_vpc.default.id}" + ], + "name": "vpc-id" + } + } + }, + "aws_vpc": { + "default": { + "default": true + } + } + }, + "resource": { + "aws_security_group": { + "ec2": { + "vpc_id": "${data.aws_vpc.default.id}", + "name": "ec2-demo-ec2", + "description": "Lightning Server EC2 Demo single-instance access" + } + }, + "aws_vpc_security_group_ingress_rule": { + "http_v6": { + "cidr_ipv6": "::/0", + "security_group_id": "${aws_security_group.ec2.id}", + "to_port": 80, + "from_port": 80, + "ip_protocol": "tcp" + }, + "http": { + "cidr_ipv4": "0.0.0.0/0", + "security_group_id": "${aws_security_group.ec2.id}", + "to_port": 80, + "from_port": 80, + "ip_protocol": "tcp" + }, + "https": { + "cidr_ipv4": "0.0.0.0/0", + "security_group_id": "${aws_security_group.ec2.id}", + "to_port": 443, + "from_port": 443, + "ip_protocol": "tcp" + }, + "https_v6": { + "cidr_ipv6": "::/0", + "security_group_id": "${aws_security_group.ec2.id}", + "to_port": 443, + "from_port": 443, + "ip_protocol": "tcp" + } + }, + "aws_vpc_security_group_egress_rule": { + "access_outside": { + "cidr_ipv4": "0.0.0.0/0", + "security_group_id": "${aws_security_group.ec2.id}", + "ip_protocol": -1 + }, + "access_outside_v6": { + "cidr_ipv6": "::/0", + "security_group_id": "${aws_security_group.ec2.id}", + "ip_protocol": -1 + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/outputs.tf.json b/demo/terraform/ec2-single/outputs.tf.json new file mode 100644 index 000000000..bce207d39 --- /dev/null +++ b/demo/terraform/ec2-single/outputs.tf.json @@ -0,0 +1,8 @@ +{ + "output": { + "application_url": { + "description": "Application URL", + "value": "https://ec2-demo.cs.lightningkite.com" + } + } +} \ No newline at end of file diff --git a/demo/terraform/ec2-single/redeploy.sh b/demo/terraform/ec2-single/redeploy.sh new file mode 100644 index 000000000..c2cb2334e --- /dev/null +++ b/demo/terraform/ec2-single/redeploy.sh @@ -0,0 +1,175 @@ +#!/usr/bin/env bash +# Triggered by null_resource.redeploy_app when the jar or settings hash +# changes. Tells the running EC2 instance to run /usr/local/bin/lightning-server-redeploy +# (installed by ec2_init.sh) via SSM Run Command. The on-instance script does +# the actual stop/fetch/decrypt/start work. +set -euo pipefail + +INSTANCE_ID="${1:?usage: redeploy.sh [region]}" +REGION="${2:-us-west-2}" + +log() { echo "[redeploy] $*"; } +err() { echo "[redeploy] ERROR: $*" >&2; } + +log "Waiting for SSM agent on $INSTANCE_ID..." +for i in $(seq 1 60); do + status=$(aws ssm describe-instance-information \ + --filters "Key=InstanceIds,Values=$INSTANCE_ID" \ + --region "$REGION" \ + --query 'InstanceInformationList[0].PingStatus' \ + --output text 2>/dev/null || echo "None") + if [ "$status" = "Online" ]; then + log "SSM agent online" + break + fi + if [ "$i" = "60" ]; then + err "SSM agent never reported Online for $INSTANCE_ID (last status: $status)" + exit 1 + fi + sleep 5 +done + +# Wait for cloud-init (ec2_init.sh) to finish so the redeploy scripts are +# guaranteed to be installed. cloud-init returns 2 for a completed-but- +# degraded boot; accept that outcome only when both required scripts exist. +log "Waiting for cloud-init to complete on $INSTANCE_ID..." +WAIT_CMD_ID=$(aws ssm send-command \ + --instance-ids "$INSTANCE_ID" \ + --document-name "AWS-RunShellScript" \ + --comment "terraform redeploy: wait for cloud-init" \ + --parameters 'commands=["set +e; cloud-init status --wait; cloud_init_exit=$?; set -e; if [ \"$cloud_init_exit\" -eq 0 ]; then exit 0; fi; if [ \"$cloud_init_exit\" -eq 2 ] && [ -x /usr/local/bin/lightning-server-redeploy ] && [ -x /usr/local/bin/lightning-server-predeploy ]; then echo \"cloud-init completed degraded; required deployment scripts are present\"; exit 0; fi; echo \"cloud-init did not complete provisioning (exit $cloud_init_exit)\" >&2; exit \"$cloud_init_exit\""],executionTimeout=900' \ + --region "$REGION" \ + --query 'Command.CommandId' \ + --output text) + +for i in $(seq 1 180); do + status=$(aws ssm get-command-invocation \ + --command-id "$WAIT_CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'Status' \ + --output text 2>/dev/null || echo "Pending") + case "$status" in + Success) + log "cloud-init complete" + break + ;; + Cancelled|Failed|TimedOut) + err "cloud-init wait finished with status: $status" + aws ssm get-command-invocation \ + --command-id "$WAIT_CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'StandardErrorContent' \ + --output text >&2 || true + exit 1 + ;; + *) + sleep 5 + ;; + esac + if [ "$i" = "180" ]; then + err "cloud-init did not complete within polling window" + exit 1 + fi +done + +# Run pre-deploy tasks first (new build in a scratch dir; the running server is untouched). If they +# fail, abort without redeploying so the current version keeps serving. +log "Sending SSM command to run /usr/local/bin/lightning-server-predeploy..." +PRE_CMD_ID=$(aws ssm send-command \ + --instance-ids "$INSTANCE_ID" \ + --document-name "AWS-RunShellScript" \ + --comment "terraform pre-deploy" \ + --parameters 'commands=/usr/local/bin/lightning-server-predeploy,executionTimeout=600' \ + --region "$REGION" \ + --query 'Command.CommandId' \ + --output text) +log "Pre-deploy command ID: $PRE_CMD_ID — polling for completion..." +for i in $(seq 1 180); do + status=$(aws ssm get-command-invocation \ + --command-id "$PRE_CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'Status' \ + --output text 2>/dev/null || echo "Pending") + case "$status" in + Success) + log "Pre-deploy succeeded" + break + ;; + Cancelled|Failed|TimedOut) + err "Pre-deploy finished with status: $status — aborting without redeploy" + aws ssm get-command-invocation \ + --command-id "$PRE_CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'StandardErrorContent' \ + --output text >&2 || true + exit 1 + ;; + *) + sleep 5 + ;; + esac + if [ "$i" = "180" ]; then + err "Pre-deploy did not finish within polling window" + exit 1 + fi +done + +log "Sending SSM command to run /usr/local/bin/lightning-server-redeploy..." +CMD_ID=$(aws ssm send-command \ + --instance-ids "$INSTANCE_ID" \ + --document-name "AWS-RunShellScript" \ + --comment "terraform redeploy: jar/settings refresh" \ + --parameters 'commands=/usr/local/bin/lightning-server-redeploy,executionTimeout=600' \ + --region "$REGION" \ + --query 'Command.CommandId' \ + --output text) + +log "Command ID: $CMD_ID — polling for completion..." +for i in $(seq 1 180); do + status=$(aws ssm get-command-invocation \ + --command-id "$CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'Status' \ + --output text 2>/dev/null || echo "Pending") + case "$status" in + Success) + log "Command succeeded" + aws ssm get-command-invocation \ + --command-id "$CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'StandardOutputContent' \ + --output text + exit 0 + ;; + Cancelled|Failed|TimedOut) + err "SSM command finished with status: $status" + echo "--- stdout ---" >&2 + aws ssm get-command-invocation \ + --command-id "$CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'StandardOutputContent' \ + --output text >&2 || true + echo "--- stderr ---" >&2 + aws ssm get-command-invocation \ + --command-id "$CMD_ID" \ + --instance-id "$INSTANCE_ID" \ + --region "$REGION" \ + --query 'StandardErrorContent' \ + --output text >&2 || true + exit 1 + ;; + *) + sleep 5 + ;; + esac +done + +err "SSM command did not finish within polling window" +exit 1 \ No newline at end of file diff --git a/demo/terraform/ec2-single/redeploy.tf.json b/demo/terraform/ec2-single/redeploy.tf.json new file mode 100644 index 000000000..f7fb3a202 --- /dev/null +++ b/demo/terraform/ec2-single/redeploy.tf.json @@ -0,0 +1,26 @@ +{ + "resource": { + "null_resource": { + "redeploy_app": { + "provisioner": { + "local-exec": { + "command": "bash ${path.module}/redeploy.sh ${aws_instance.main.id} us-west-2" + } + }, + "depends_on": [ + "null_resource.upload_jar", + "null_resource.upload_settings", + "aws_instance.main", + "aws_iam_role_policy_attachment.ssm", + "aws_iam_role_policy_attachment.servicesAccess", + "aws_eip_association.main", + "aws_ssm_parameter.settings_password" + ], + "triggers": { + "settings_upload": "${null_resource.upload_settings.id}", + "jar_hash": "${data.external.jar_hash.result.hash}" + } + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/lkec2/secretBasis.tf.json b/demo/terraform/ec2-single/secretBasis.tf.json similarity index 100% rename from demo/terraform/lkec2/secretBasis.tf.json rename to demo/terraform/ec2-single/secretBasis.tf.json diff --git a/demo/terraform/lk/.terraform.lock.hcl b/demo/terraform/lambda/.terraform.lock.hcl similarity index 95% rename from demo/terraform/lk/.terraform.lock.hcl rename to demo/terraform/lambda/.terraform.lock.hcl index 051b7f252..b4330e3e6 100644 --- a/demo/terraform/lk/.terraform.lock.hcl +++ b/demo/terraform/lambda/.terraform.lock.hcl @@ -6,6 +6,7 @@ provider "registry.terraform.io/grafana/grafana" { constraints = "~> 4.27.0" hashes = [ "h1:Ds0+IB4LfXwGFEbPxOL3o+7qRpIwEEXPR7YPCGBOj/Q=", + "h1:hZyRm1VYHr60TKceT91tLcZNowOF/BOXhQ27CS/o68Y=", "zh:0f34f656c80c5e0e08308420c549449ace6ffd81e9e4150f82018e81fdace753", "zh:24ad9cf1928c7bd4766ac50837b8ce0ba3f5195b1d907a86757432d768e99b20", "zh:2e43f252efba0a2124940acce045719d231a41b5e1f2c7ad1679de40d170bc06", @@ -33,6 +34,7 @@ provider "registry.terraform.io/hashicorp/archive" { version = "2.8.0" hashes = [ "h1:WB6H5ksIZiyq1lQlD/PWeh+tn4FLsbSjVnRW3+4xe2Y=", + "h1:jdmKm+xl6ZcQrijxapnZ94RVuz/G4vk7hsIa1N0VT5Q=", "zh:0d14713fdc259fb377d0b899ad3c650a34194bd52194c863303ef22a65a580e2", "zh:369b56040c7a8085d04e7e8ffac1e2b321a3170e502f788819bc34b868ec016f", "zh:4d1a3b983ed6af5a52bfe12794674ae55cbadfa6021b37106ade68b433ad216a", @@ -53,6 +55,7 @@ provider "registry.terraform.io/hashicorp/aws" { version = "6.34.0" constraints = "~> 6.34.0" hashes = [ + "h1:ZGSMOPC+Du0cKJ2kV1Ni8Rnz7ezsIu+jYFEknpye5CM=", "h1:wXPejniDcbqRtL2zzaeZsmjLe7NekeYD5QjlIzUOylI=", "zh:1e49dc96bf50633583e3cbe23bb357642e7e9afe135f54e061e26af6310e50d2", "zh:45651bb4dad681f17782d99d9324de182a7bb9fbe9dd22f120fdb7fe42969cc9", @@ -75,6 +78,7 @@ provider "registry.terraform.io/hashicorp/aws" { provider "registry.terraform.io/hashicorp/local" { version = "2.9.0" hashes = [ + "h1:9rBZCMNpxKwMlRbWH2QpwD3kqUCAejdOZQ/aiiDObXQ=", "h1:m24fjcInWvTVZ1XSo2MaNuKPe+X/gfG8SIi09rA7a7M=", "zh:0baa4566cf77f1ff52f4293d1c8536202dd23edc197c3196413a28343c3ac3a0", "zh:16b5559c3c07088ddad11a9bb9e9c0799999363c2958e9a5be2bcbbf2cd9ca64", @@ -96,6 +100,7 @@ provider "registry.terraform.io/hashicorp/null" { version = "3.3.0" hashes = [ "h1:a14TKo7Xvg4W8+H1VA6p+oLZTLxVQnYUD8LOaOs14A8=", + "h1:l+dm3lhmu4ys7GbvIldfn544olSPH0DOiYruuFSfQkY=", "zh:021748b5ea3b5f6956f2e75c42c5cdc113b391fb98ac71364a4965d23b37000f", "zh:3b27956f8541d46704fda234e0d535c2ae2a4b33411848b1ee262a1ec03568b0", "zh:3de4ed47d6d0f4d8edba4a5092c7c9799950eda63989d8d0d2586e6afcb0aa20", @@ -116,6 +121,7 @@ provider "registry.terraform.io/hashicorp/random" { version = "3.9.0" hashes = [ "h1:OO+IuvQJSPmWdN8AyyIEvPJbLvDQpgX/zbktoa9KsJE=", + "h1:UlBuNVuCGJ39tTv2c5gz2NRZnQbXfbIWbTzWcth5o74=", "zh:161ad0bd9a75768c82f53fb6e7172a9d8be2d4889b012645a34795031aaf1bf1", "zh:19dc9a5b17729725ccfc4f45b0500af0ee5bc6b6b160c7adb8f2bf617d2c80ea", "zh:269eda8fe42daa7974d5a34d166c3ba9defe80cde86c01e4dadcfdf2e1f05e5f", @@ -137,6 +143,7 @@ provider "registry.terraform.io/mongodb/mongodbatlas" { constraints = "~> 2.7.0" hashes = [ "h1:9K59gSC6HM5dUyQXvSR3wEh+/kT0+sRZjtwY3PSkrPU=", + "h1:svsd/akb6n/p+laOvYua4QpXvV9puAV1P0ZHvMXNWaU=", "zh:0521190da065a1e0d75e0a2310fd2fe81c2f3b4a5d0700f280dc9fcd4852824f", "zh:070cd7744eb384772cc58c6d0a686d9c7a429a8fd477731933ec9a42f6ddd2f8", "zh:1211664b4d9b1a9a2c660c561c31da9860cb5c04c8d75ea31f536689a7d8fdd7", diff --git a/demo/terraform/lk/cloud.tf.json b/demo/terraform/lambda/cloud.tf.json similarity index 100% rename from demo/terraform/lk/cloud.tf.json rename to demo/terraform/lambda/cloud.tf.json diff --git a/demo/terraform/lk/database.tf.json b/demo/terraform/lambda/database.tf.json similarity index 100% rename from demo/terraform/lk/database.tf.json rename to demo/terraform/lambda/database.tf.json diff --git a/demo/terraform/lk/email.tf.json b/demo/terraform/lambda/email.tf.json similarity index 100% rename from demo/terraform/lk/email.tf.json rename to demo/terraform/lambda/email.tf.json diff --git a/demo/terraform/lk/emailInbound.tf.json b/demo/terraform/lambda/emailInbound.tf.json similarity index 100% rename from demo/terraform/lk/emailInbound.tf.json rename to demo/terraform/lambda/emailInbound.tf.json diff --git a/demo/terraform/lk/files.tf.json b/demo/terraform/lambda/files.tf.json similarity index 100% rename from demo/terraform/lk/files.tf.json rename to demo/terraform/lambda/files.tf.json diff --git a/demo/terraform/lk/grafanaAlerts.tf.json b/demo/terraform/lambda/grafanaAlerts.tf.json similarity index 100% rename from demo/terraform/lk/grafanaAlerts.tf.json rename to demo/terraform/lambda/grafanaAlerts.tf.json diff --git a/demo/terraform/lk/http.tf.json b/demo/terraform/lambda/http.tf.json similarity index 100% rename from demo/terraform/lk/http.tf.json rename to demo/terraform/lambda/http.tf.json diff --git a/demo/terraform/lk/lambda.tf.json b/demo/terraform/lambda/lambda.tf.json similarity index 83% rename from demo/terraform/lk/lambda.tf.json rename to demo/terraform/lambda/lambda.tf.json index c4193984f..118f42d3b 100644 --- a/demo/terraform/lk/lambda.tf.json +++ b/demo/terraform/lambda/lambda.tf.json @@ -4,7 +4,6 @@ "lambda": { "depends_on": [ "null_resource.lambda_jar_source", - "null_resource.settings_reread", "local_file.lambda_collector_yaml" ], "output_path": "${path.module}/build/lambda.jar", @@ -17,24 +16,21 @@ } }, "resource": { - "null_resource": { - "settings_reread": { - "provisioner": { - "local-exec": { - "environment": { - "SETTINGS_PASS": "${random_password.settings.result}" - }, - "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", - "command": "openssl enc -d -aes-256-cbc -md sha256 -out \"${local_sensitive_file.settings_raw.filename}.decrypted.json\" -in \"${path.module}/build/lambda/settings.enc\" -pass env:SETTINGS_PASS" - } - }, - "depends_on": [ - "null_resource.lambda_jar_source" - ], - "triggers": { - "settingsRawHash": "${local_sensitive_file.settings_raw.content_sha256}" - } + "aws_iam_role_policy_attachment": { + "insights_policy": { + "policy_arn": "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy", + "role": "${aws_iam_role.main_exec.id}" }, + "main_policy_exec": { + "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "role": "${aws_iam_role.main_exec.name}" + }, + "servicesAccess": { + "policy_arn": "${aws_iam_policy.servicesAccess.arn}", + "role": "${aws_iam_role.main_exec.name}" + } + }, + "null_resource": { "lambda_jar_source": { "provisioner": { "local-exec": [ @@ -48,10 +44,11 @@ }, { "environment": { - "SETTINGS_PASS": "${random_password.settings.result}" + "SETTINGS_PASS": "${random_password.settings.result}", + "SETTINGS_JSON": "${jsonencode(local.settings_raw)}" }, "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", - "command": "openssl enc -aes-256-cbc -md sha256 -in \"${local_sensitive_file.settings_raw.filename}\" -out \"${path.module}/build/lambda/settings.enc\" -pass env:SETTINGS_PASS" + "command": "${local.is_windows ? \"$OutputEncoding = New-Object System.Text.UTF8Encoding $false; $env:SETTINGS_JSON | openssl enc -aes-256-cbc -md sha256 -out \\\"${path.module}/build/lambda/settings.enc\\\" -pass env:SETTINGS_PASS\" : \"printf '%s' \\\"$SETTINGS_JSON\\\" | openssl enc -aes-256-cbc -md sha256 -out \\\"${path.module}/build/lambda/settings.enc\\\" -pass env:SETTINGS_PASS\"}" }, { "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", @@ -60,17 +57,24 @@ ] }, "triggers": { + "packageMarker": "${local_file.lambda_package_marker.id}", "lambda_collector_yamlHash": "${local_file.lambda_collector_yaml.content_sha256}", "buildHash": "${sha256(join(\"\", [for f in fileset(\"${path.module}/../../build/dist/lambda\", \"**\") : filesha256(\"${path.module}/../../build/dist/lambda/${f}\")]))}", - "settingsHash": "${local_sensitive_file.settings_raw.content_sha256}" + "settingsHash": "${sha256(jsonencode(local.settings_raw))}" } }, "predeploy": { "provisioner": { - "local-exec": { - "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", - "command": "${local.is_windows ? \"aws lambda invoke --function-name ${aws_lambda_function.main.function_name} --qualifier ${aws_lambda_function.main.version} --cli-binary-format base64 --payload eyJwcmVkZXBsb3kiOnRydWV9 --region us-west-2 ${path.module}/build/predeploy-out.json | Out-Null; if(-not(Select-String -Path ${path.module}/build/predeploy-out.json -Pattern predeploy-ok -Quiet)){exit 1}\" : \"aws lambda invoke --function-name ${aws_lambda_function.main.function_name} --qualifier ${aws_lambda_function.main.version} --cli-binary-format base64 --payload eyJwcmVkZXBsb3kiOnRydWV9 --region us-west-2 ${path.module}/build/predeploy-out.json > /dev/null && grep -q predeploy-ok ${path.module}/build/predeploy-out.json\"}" - } + "local-exec": [ + { + "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", + "command": "aws lambda wait function-active --function-name ${aws_lambda_function.main.function_name} --qualifier '${aws_lambda_function.main.version}' --region us-west-2" + }, + { + "interpreter": "${local.is_windows ? [\"PowerShell\", \"-Command\"] : []}", + "command": "${local.is_windows ? \"aws lambda invoke --function-name ${aws_lambda_function.main.function_name} --qualifier '${aws_lambda_function.main.version}' --cli-binary-format base64 --payload eyJwcmVkZXBsb3kiOnRydWV9 --region us-west-2 ${path.module}/build/predeploy-out.json | Out-Null; if(-not(Select-String -Path ${path.module}/build/predeploy-out.json -Pattern predeploy-ok -Quiet)){exit 1}\" : \"aws lambda invoke --function-name ${aws_lambda_function.main.function_name} --qualifier '${aws_lambda_function.main.version}' --cli-binary-format base64 --payload eyJwcmVkZXBsb3kiOnRydWV9 --region us-west-2 ${path.module}/build/predeploy-out.json > /dev/null && grep -q predeploy-ok ${path.module}/build/predeploy-out.json\"}" + } + ] }, "depends_on": [ "aws_lambda_function.main" @@ -80,6 +84,12 @@ } } }, + "aws_cloudwatch_log_group": { + "main": { + "retention_in_days": 30, + "name": "LightningServerDemo-main-log" + } + }, "aws_lambda_permission": { "scheduled_tasks": { "principal": "events.amazonaws.com", @@ -92,38 +102,6 @@ "source_arn": "arn:aws:events:us-west-2:${data.aws_caller_identity.lambda_current.account_id}:rule/LightningServerDemo*" } }, - "aws_iam_role": { - "main_exec": { - "name": "LightningServerDemo-main-exec", - "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Sid\":\"\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"}}]}" - } - }, - "local_sensitive_file": { - "settings_raw": { - "filename": "${path.module}/build/raw-settings.json", - "content": "${jsonencode(local.settings_raw)}" - } - }, - "aws_iam_role_policy_attachment": { - "insights_policy": { - "policy_arn": "arn:aws:iam::aws:policy/CloudWatchLambdaInsightsExecutionRolePolicy", - "role": "${aws_iam_role.main_exec.id}" - }, - "main_policy_exec": { - "policy_arn": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", - "role": "${aws_iam_role.main_exec.name}" - }, - "servicesAccess": { - "policy_arn": "${aws_iam_policy.servicesAccess.arn}", - "role": "${aws_iam_role.main_exec.name}" - } - }, - "aws_cloudwatch_log_group": { - "main": { - "retention_in_days": 30, - "name": "LightningServerDemo-main-log" - } - }, "aws_iam_policy": { "servicesAccess": { "path": "/lightningserverdemo/servicesAccess/", @@ -143,6 +121,12 @@ "function_version": "${aws_lambda_function.main.version}" } }, + "aws_iam_role": { + "main_exec": { + "name": "LightningServerDemo-main-exec", + "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Sid\":\"\",\"Principal\":{\"Service\":\"lambda.amazonaws.com\"}}]}" + } + }, "random_password": { "settings": { "special": true, @@ -209,6 +193,10 @@ "lambda_collector_yaml": { "filename": "${path.module}/build/collector.yaml", "content": "receivers:\n otlp:\n protocols:\n grpc:\n endpoint: localhost:4317\n http:\n endpoint: localhost:4318\nexporters:\n otlphttp:\n endpoint: https://otlp-gateway-prod-us-west-0.grafana.net/otlp\n headers:\n Authorization: \"$${env:OTLP_HEADER_AUTHORIZATION}\"\nservice:\n pipelines:\n traces:\n receivers: [otlp]\n exporters: [otlphttp]\n metrics:\n receivers: [otlp]\n exporters: [otlphttp]\n logs:\n receivers: [otlp]\n exporters: [otlphttp]\n" + }, + "lambda_package_marker": { + "filename": "${path.module}/build/.lambda-package", + "content": "Marks this build directory as holding the generated Lambda package.\n" } } }, @@ -233,8 +221,11 @@ "forbidOnMatchFail": false }, "secretBasis": "${random_password.secretBasis.result}", - "phoneCall": "${var.phoneCall}", - "githubOauth": "${var.githubOauth}", + "phoneCall": "test", + "githubOauth": { + "id": "", + "secret": "" + }, "general": { "projectName": "Lightning Server Demo", "publicUrl": "https://lightningserver.cs.lightningkite.com", @@ -244,7 +235,7 @@ }, "database": "mongodb+srv://LightningServerDemodatabase-main:${random_password.database.result}@${replace(mongodbatlas_advanced_cluster.database.connection_strings.standard_srv, \"mongodb+srv://\", \"\")}/default?retryWrites=true&w=majority&atlasSearch=true", "emailInbound": "ses://", - "sms": "${var.sms}", + "sms": "console", "files": "s3://${aws_s3_bucket.files.bucket}.s3-${aws_s3_bucket.files.region}.amazonaws.com/?signedUrlDuration=1d", "logging": { "default": { @@ -273,12 +264,12 @@ "exportTimeout": "PT5S" } }, - "someSecret": "${var.someSecret}", - "voiceAgent": "${var.voiceAgent}", - "smsInbound": "${var.smsInbound}", + "someSecret": "Some Value", + "voiceAgent": "test", + "smsInbound": "console", "email": "smtp://${aws_iam_access_key.email.id}:${aws_iam_access_key.email.ses_smtp_password_v4}@email-smtp.us-west-2.amazonaws.com:587?fromEmail=noreply@lightningserver.cs.lightningkite.com", - "pubSub": "dynamodb-pubsub://us-west-2/LightningServerDemo_pubSub_pubsub?pollInterval=15", - "notifications": "console" + "notifications": "console", + "pubSub": "dynamodb-pubsub://us-west-2/LightningServerDemo_pubSub_pubsub?pollInterval=15" }, "is_windows": "${substr(pathexpand(\"~\"), 0, 1) == \"/\" ? false : true}", "servicesAccessPolicy": { diff --git a/demo/terraform/lk/lambdaAlarms.tf.json b/demo/terraform/lambda/lambdaAlarms.tf.json similarity index 100% rename from demo/terraform/lk/lambdaAlarms.tf.json rename to demo/terraform/lambda/lambdaAlarms.tf.json diff --git a/demo/terraform/lk/main.tf.json b/demo/terraform/lambda/main.tf.json similarity index 100% rename from demo/terraform/lk/main.tf.json rename to demo/terraform/lambda/main.tf.json diff --git a/demo/terraform/lk/schedules.tf.json b/demo/terraform/lambda/schedules.tf.json similarity index 100% rename from demo/terraform/lk/schedules.tf.json rename to demo/terraform/lambda/schedules.tf.json diff --git a/demo/terraform/lambda/secretBasis.tf.json b/demo/terraform/lambda/secretBasis.tf.json new file mode 100644 index 000000000..d479dd9c7 --- /dev/null +++ b/demo/terraform/lambda/secretBasis.tf.json @@ -0,0 +1,11 @@ +{ + "resource": { + "random_password": { + "secretBasis": { + "special": true, + "length": 88, + "override_special": "+/" + } + } + } +} \ No newline at end of file diff --git a/demo/terraform/lambda/variables.tf.json b/demo/terraform/lambda/variables.tf.json new file mode 100644 index 000000000..9df3070b1 --- /dev/null +++ b/demo/terraform/lambda/variables.tf.json @@ -0,0 +1,6 @@ +{ + "variable": { + "grafana_cloud_service_account_token": {}, + "grafana_cloud_api_key": {} + } +} \ No newline at end of file diff --git a/demo/terraform/lk/ws.tf.json b/demo/terraform/lambda/ws.tf.json similarity index 99% rename from demo/terraform/lk/ws.tf.json rename to demo/terraform/lambda/ws.tf.json index e749f7664..2589e3337 100644 --- a/demo/terraform/lk/ws.tf.json +++ b/demo/terraform/lambda/ws.tf.json @@ -63,6 +63,7 @@ }, "aws_acm_certificate_validation": { "ws": { + "provider": "aws.acm", "certificate_arn": "${aws_acm_certificate.ws.arn}", "validation_record_fqdns": [ "${aws_route53_record.ws.fqdn}" @@ -184,6 +185,7 @@ "aws_acm_certificate": { "ws": { "domain_name": "ws.lightningserver.cs.lightningkite.com", + "provider": "aws.acm", "validation_method": "DNS" } }, diff --git a/demo/terraform/lk/variables.tf.json b/demo/terraform/lk/variables.tf.json deleted file mode 100644 index c857aa899..000000000 --- a/demo/terraform/lk/variables.tf.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "variable": { - "grafana_cloud_service_account_token": {}, - "sms": { - "type": "string" - }, - "someSecret": { - "type": "string" - }, - "voiceAgent": { - "type": "string" - }, - "grafana_cloud_api_key": {}, - "smsInbound": { - "type": "string" - }, - "phoneCall": { - "type": "string" - }, - "githubOauth": { - "type": "map(any)" - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/database.tf.json b/demo/terraform/lkec2/database.tf.json deleted file mode 100644 index 7e36390ad..000000000 --- a/demo/terraform/lkec2/database.tf.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "resource": { - "aws_docdb_subnet_group": { - "database": { - "name": "lightningserverec2sdemo-database", - "subnet_ids": "${module.vpc.private_subnets}" - } - }, - "aws_docdb_cluster": { - "database": { - "backup_retention_period": 1, - "engine": "docdb", - "master_password": "${random_password.database.result}", - "deletion_protection": false, - "vpc_security_group_ids": [ - "${aws_security_group.internal.id}" - ], - "storage_encrypted": true, - "db_subnet_group_name": "${aws_docdb_subnet_group.database.name}", - "cluster_identifier": "lightningserverec2sdemo-database", - "engine_version": "5.0", - "skip_final_snapshot": true, - "master_username": "master" - } - }, - "random_password": { - "database": { - "special": true, - "length": 32, - "override_special": "-_" - } - }, - "aws_vpc_security_group_ingress_rule": { - "database_docdb": { - "referenced_security_group_id": "${aws_security_group.internal.id}", - "security_group_id": "${aws_security_group.internal.id}", - "to_port": 27017, - "from_port": 27017, - "ip_protocol": "tcp" - } - }, - "aws_docdb_cluster_instance": { - "database_0": { - "identifier": "lightningserverec2sdemo-database-0", - "instance_class": "db.t4g.medium", - "auto_minor_version_upgrade": true, - "cluster_identifier": "${aws_docdb_cluster.database.id}" - } - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/email.tf.json b/demo/terraform/lkec2/email.tf.json deleted file mode 100644 index e79b17d57..000000000 --- a/demo/terraform/lkec2/email.tf.json +++ /dev/null @@ -1,149 +0,0 @@ -{ - "data": { - "aws_iam_policy_document": { - "email": { - "statement": { - "resources": [ - "*" - ], - "actions": [ - "ses:SendRawEmail" - ] - } - } - } - }, - "resource": { - "aws_ses_domain_mail_from": { - "email": { - "domain": "${aws_ses_domain_identity.email.domain}", - "mail_from_domain": "mail.lightningserver2.cs.lightningkite.com" - } - }, - "aws_iam_access_key": { - "email": { - "user": "${aws_iam_user.email.name}" - } - }, - "null_resource": { - "email_depends_on_domain": { - "depends_on": [ - "aws_ses_domain_identity.email", - "aws_ses_domain_dkim.email_dkim" - ] - } - }, - "aws_iam_policy": { - "email": { - "name": "LightningServerEC2SDemo-email-policy", - "description": "Allows sending of e-mails via Simple Email Service", - "policy": "${data.aws_iam_policy_document.email.json}" - } - }, - "aws_route53_record": { - "email_verification": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "${aws_ses_domain_identity.email.verification_token}" - ], - "name": "_amazonses.lightningserver2.cs.lightningkite.com", - "type": "TXT", - "ttl": "600" - }, - "email_mail_from_mx": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "10 feedback-smtp.us-west-2.amazonses.com" - ], - "name": "${aws_ses_domain_mail_from.email.mail_from_domain}", - "type": "MX", - "ttl": "600" - }, - "email_mail_from_spf": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "v=spf1 include:amazonses.com -all" - ], - "name": "${aws_ses_domain_mail_from.email.mail_from_domain}", - "type": "TXT", - "ttl": "300" - }, - "email_dkim": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "${element(aws_ses_domain_dkim.email_dkim.dkim_tokens, count.index)}.dkim.amazonses.com" - ], - "count": 3, - "name": "${element(aws_ses_domain_dkim.email_dkim.dkim_tokens, count.index)}._domainkey.lightningserver2.cs.lightningkite.com", - "type": "CNAME", - "ttl": "600" - }, - "email_dmarc": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "v=DMARC1;p=quarantine;pct=75;rua=mailto:joseph@lightningkite.com" - ], - "name": "_dmarc.lightningserver2.cs.lightningkite.com", - "type": "TXT", - "ttl": "300" - }, - "email_spf": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "v=spf1 include:amazonses.com -all" - ], - "name": "lightningserver2.cs.lightningkite.com", - "type": "TXT", - "ttl": "300" - } - }, - "aws_iam_user_policy_attachment": { - "email": { - "policy_arn": "${aws_iam_policy.email.arn}", - "user": "${aws_iam_user.email.name}" - } - }, - "aws_vpc_endpoint": { - "email": { - "private_dns_enabled": true, - "vpc_id": "${module.vpc.vpc_id}", - "vpc_endpoint_type": "Interface", - "service_name": "com.amazonaws.us-west-2.email-smtp", - "subnet_ids": "${module.vpc.private_subnets}", - "security_group_ids": [ - "${aws_security_group.email.id}" - ] - } - }, - "aws_security_group": { - "email": { - "vpc_id": "${module.vpc.vpc_id}", - "name": "LightningServerEC2SDemo-email-security-group" - } - }, - "aws_vpc_security_group_ingress_rule": { - "email": { - "cidr_ipv4": "10.7.0.0/16", - "security_group_id": "${aws_security_group.email.id}", - "to_port": 587, - "from_port": 587, - "ip_protocol": "tcp" - } - }, - "aws_iam_user": { - "email": { - "name": "LightningServerEC2SDemo-email-user" - } - }, - "aws_ses_domain_identity": { - "email": { - "domain": "lightningserver2.cs.lightningkite.com" - } - }, - "aws_ses_domain_dkim": { - "email_dkim": { - "domain": "${aws_ses_domain_identity.email.domain}" - } - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/emailInbound.tf.json b/demo/terraform/lkec2/emailInbound.tf.json deleted file mode 100644 index 45a55ec77..000000000 --- a/demo/terraform/lkec2/emailInbound.tf.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "output": { - "emailInbound_sns_topic_arn": { - "description": "SNS topic ARN for subscribing to inbound emails", - "value": "${aws_sns_topic.emailInbound.arn}" - }, - "emailInbound_sns_topic_name": { - "description": "SNS topic name for inbound emails", - "value": "${aws_sns_topic.emailInbound.name}" - } - }, - "data": { - "aws_caller_identity": { - "emailInbound": {} - } - }, - "resource": { - "aws_sns_topic": { - "emailInbound": { - "name": "LightningServerEC2SDemo-emailInbound-email-inbound" - } - }, - "null_resource": { - "emailInbound_depends_on_domain": { - "depends_on": [ - "aws_ses_domain_identity.email", - "aws_ses_domain_dkim.email_dkim" - ] - } - }, - "aws_ses_receipt_rule_set": { - "emailInbound": { - "rule_set_name": "LightningServerEC2SDemo-emailInbound-rules" - } - }, - "aws_ses_active_receipt_rule_set": { - "emailInbound": { - "rule_set_name": "${aws_ses_receipt_rule_set.emailInbound.rule_set_name}" - } - }, - "aws_ses_receipt_rule": { - "emailInbound": { - "sns_action": { - "topic_arn": "${aws_sns_topic.emailInbound.arn}", - "position": 1, - "encoding": "UTF-8" - }, - "depends_on": [ - "aws_ses_active_receipt_rule_set.emailInbound" - ], - "recipients": [ - "lightningserver2.cs.lightningkite.com" - ], - "scan_enabled": true, - "name": "LightningServerEC2SDemo-emailInbound-receive", - "rule_set_name": "${aws_ses_receipt_rule_set.emailInbound.rule_set_name}", - "tls_policy": "Require", - "enabled": true - } - }, - "aws_route53_record": { - "emailInbound_inbound_mx": { - "zone_id": "${data.aws_route53_zone.main.zone_id}", - "records": [ - "10 inbound-smtp.us-west-2.amazonaws.com" - ], - "name": "lightningserver2.cs.lightningkite.com", - "type": "MX", - "ttl": "600" - } - }, - "aws_sns_topic_subscription": { - "emailInbound_webhook": { - "protocol": "https", - "endpoint": "https://lightningserver.cs.lightningkite.com/assistant-channels/email/webhook", - "topic_arn": "${aws_sns_topic.emailInbound.arn}", - "raw_message_delivery": false, - "endpoint_auto_confirms": false - } - }, - "aws_sns_topic_policy": { - "emailInbound": { - "arn": "${aws_sns_topic.emailInbound.arn}", - "policy": "\n {\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"AllowSESPublish\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"ses.amazonaws.com\"\n },\n \"Action\": \"sns:Publish\",\n \"Resource\": \"${aws_sns_topic.emailInbound.arn}\",\n \"Condition\": {\n \"StringEquals\": {\n \"AWS:SourceAccount\": \"${data.aws_caller_identity.emailInbound.account_id}\"\n }\n }\n }\n ]\n }\n " - } - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/image.tf.json b/demo/terraform/lkec2/image.tf.json deleted file mode 100644 index 2dc1fc97d..000000000 --- a/demo/terraform/lkec2/image.tf.json +++ /dev/null @@ -1,133 +0,0 @@ -{ - "data": { - "aws_ami": { - "ubuntu": { - "filter": [ - { - "values": [ - "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-*" - ], - "name": "name" - }, - { - "values": [ - "arm64" - ], - "name": "architecture" - }, - { - "values": [ - "hvm" - ], - "name": "virtualization-type" - } - ], - "most_recent": true, - "owners": [ - "099720109477" - ] - } - } - }, - "resource": { - "aws_iam_role_policy_attachment": { - "imagebuilder_core": { - "policy_arn": "arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder", - "role": "${aws_iam_role.imagebuilder.name}" - }, - "imagebuilder_ssm": { - "policy_arn": "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore", - "role": "${aws_iam_role.imagebuilder.name}" - } - }, - "aws_imagebuilder_image": { - "this": { - "image_tests_configuration": { - "image_tests_enabled": false - }, - "infrastructure_configuration_arn": "${aws_imagebuilder_infrastructure_configuration.this.arn}", - "image_recipe_arn": "${aws_imagebuilder_image_recipe.this.arn}", - "distribution_configuration_arn": "${aws_imagebuilder_distribution_configuration.this.arn}" - } - }, - "aws_iam_role": { - "imagebuilder": { - "name": "LightningServerEC2SDemo-imagebuilder-role", - "assume_role_policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}}]}" - } - }, - "aws_imagebuilder_distribution_configuration": { - "this": { - "name": "LightningServerEC2SDemo-dist", - "distribution": { - "ami_distribution_configuration": { - "name": "LightningServerEC2SDemo-{{ imagebuilder:buildDate }}" - }, - "region": "us-west-2" - } - } - }, - "aws_iam_instance_profile": { - "imagebuilder": { - "role": "${aws_iam_role.imagebuilder.name}", - "name": "LightningServerEC2SDemo-imagebuilder-profile" - } - }, - "aws_imagebuilder_component": { - "install": { - "data": "name: LightningServerEC2SDemo-install\ndescription: Install base tooling for Lightning Server Demo\nschemaVersion: 1.0\nphases:\n - name: build\n steps:\n - name: Install\n action: ExecuteBash\n inputs:\n commands:\n - |\n #!/bin/bash\n set -euo pipefail\n export DEBIAN_FRONTEND=noninteractive\n apt-get -o DPkg::Lock::Timeout=600 update -y\n apt-get -o DPkg::Lock::Timeout=600 install -y openjdk-17-jre-headless openssl curl gnupg ca-certificates unzip\n \n # === CloudWatch Agent Configuration ===\n echo \"[INFO] Creating amazon-cloudwatch-agent.json for CloudWatch $(date)\"\n cat > /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json << EOF\n {\n \"logs\": {\n \"logs_collected\": {\n \"files\": {\n \"collect_list\": [\n {\n \"file_path\": \"/var/log/LightningServerEC2SDemo/ec2_init.log\",\n \"log_group_name\": \"/ec2/LightningServerEC2SDemo/application\",\n \"log_stream_name\": \"{instance_id}/ec2_init\"\n },\n {\n \"file_path\": \"/var/log/LightningServerEC2SDemo/server.log\",\n \"log_group_name\": \"/ec2/LightningServerEC2SDemo/application\",\n \"log_stream_name\": \"{instance_id}/server\"\n },\n {\n \"file_path\": \"/var/log/LightningServerEC2SDemo/redeploy.log\",\n \"log_group_name\": \"/ec2/LightningServerEC2SDemo/application\",\n \"log_stream_name\": \"{instance_id}/redeploy\"\n }\n ]\n }\n }\n },\n \"metrics\": {\n \"metrics_collected\": {\n \"mem\": {\n \"measurement\": [\"mem_used_percent\"]\n },\n \"disk\": {\n \"measurement\": [\"disk_used_percent\"],\n \"resources\": [\"/\"]\n }\n }\n }\n }\n EOF\n \n systemctl enable amazon-cloudwatch-agent\n systemctl restart amazon-cloudwatch-agent\n \n \n # === SSM Agent ===\n echo \"[INFO] Ensuring SSM agent is installed and running at $(date)\"\n # Required so terraform can drive in-place jar/settings redeploys via\n # `aws ssm send-command`. Ubuntu 24.04 ships amazon-ssm-agent as a snap; install if missing,\n # then enable + start so newly-created instances register with SSM.\n if ! snap list amazon-ssm-agent >/dev/null 2>&1; then\n snap install amazon-ssm-agent --classic\n systemctl enable snap.amazon-ssm-agent.amazon-ssm-agent.service\n systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service\n fi\n \n \n # === Systemd Service ===\n echo \"[INFO] Creating Systemd unit for Lightning Server Demo\"\n cat > /etc/systemd/system/LightningServerEC2SDemo.service << 'UNIT_EOF'\n [Unit]\n Description=Lightning Server Demo\n After=network.target\n Requires=network.target\n \n [Service]\n Type=simple\n User=ubuntu\n WorkingDirectory=/opt/lightning-server\n ExecStart=/opt/lightning-server/server/bin/server serve\n \n Restart=always\n RestartSec=5\n StandardOutput=append:/var/log/LightningServerEC2SDemo/server.log\n StandardError=append:/var/log/LightningServerEC2SDemo/server.log\n \n Environment=JAVA_OPTS=-Xmx512m\n \n \n [Install]\n WantedBy=multi-user.target\n UNIT_EOF\n \n # === Server log file ===\n echo \"[INFO] Preparing server log directory\"\n mkdir -p /var/log/LightningServerEC2SDemo\n touch /var/log/LightningServerEC2SDemo/server.log\n chown -R ubuntu:ubuntu /var/log/LightningServerEC2SDemo\n \n cat > /etc/logrotate.d/LightningServerEC2SDemo << 'LOGROTATE_EOF'\n /var/log/LightningServerEC2SDemo/*.log {\n daily\n rotate 7\n compress\n delaycompress\n missingok\n notifempty\n copytruncate\n su ubuntu ubuntu\n }\n LOGROTATE_EOF\n \n \n # === Lightning Server Redeploy Script ===\n echo \"[INFO] Creating Lightning Server Redeploy Script\"\n cat > /usr/local/bin/lightning-server-redeploy << 'REDEPLOY_EOF'\n #!/bin/bash\n set -euo pipefail\n \n log() { echo \"[lightning-server-redeploy] $*\"; }\n err() { echo \"[lightning-server-redeploy] ERROR: $*\" >&2; }\n \n if [ -f /etc/lightning-server/deploy.env ]; then . /etc/lightning-server/deploy.env; fi\n BUCKET=\"$DEPLOYMENT_BUCKET\"\n REGION=\"$AWS_REGION_NAME\"\n SSM_PARAM=\"/LightningServerEC2SDemo/settings-password\"\n APP_DIR=\"/opt/lightning-server\"\n LOG_FILE=\"/var/log/LightningServerEC2SDemo/redeploy.log\"\n \n mkdir -p \"$(dirname \"$LOG_FILE\")\"\n touch \"$LOG_FILE\"\n chown ubuntu:ubuntu \"$LOG_FILE\"\n exec > >(tee -a \"$LOG_FILE\" | logger -t lightning-server-redeploy -s) 2>&1\n \n log \"Redeploy started at $(date)\"\n mkdir -p \"$APP_DIR\"\n \n download_with_retry() {\n local src=\"$1\" dst=\"$2\" max=5 attempt=1\n while [ $attempt -le $max ]; do\n log \"Downloading $src (attempt $attempt/$max)\"\n if aws s3 cp \"$src\" \"$dst\" --region \"$REGION\" --no-progress; then return 0; fi\n sleep $((attempt * 5))\n attempt=$((attempt + 1))\n done\n err \"Failed to download $src after $max attempts\"\n return 1\n }\n \n # Roll back to the previously-working server + settings, then restart. Used when the new\n # version fails to become active so the instance self-heals instead of staying down.\n rollback() {\n err \"Rolling back to previous version\"\n [ -d \"$APP_DIR/server-old\" ] && { rm -rf \"$APP_DIR/server\"; mv \"$APP_DIR/server-old\" \"$APP_DIR/server\"; }\n [ -f \"$APP_DIR/settings.json.old\" ] && mv -f \"$APP_DIR/settings.json.old\" \"$APP_DIR/settings.json\"\n chown -R ubuntu:ubuntu \"$APP_DIR\"\n systemctl restart LightningServerEC2SDemo || true\n }\n \n download_with_retry \"s3://$BUCKET/server.zip\" \"$APP_DIR/server.zip\"\n [ -d \"$APP_DIR/server-old\" ] && rm -rf \"$APP_DIR/server-old\"\n [ -d \"$APP_DIR/server\" ] && mv \"$APP_DIR/server\" \"$APP_DIR/server-old\"\n log \"Successful Download\"\n log \"Unziping server.zip\"\n unzip -q \"$APP_DIR/server.zip\" -d $APP_DIR\n \n download_with_retry \"s3://$BUCKET/settings.enc\" \"$APP_DIR/settings.enc\"\n SETTINGS_PASS=$(aws ssm get-parameter --name \"$SSM_PARAM\" --with-decryption --query Parameter.Value --output text --region \"$REGION\")\n if ! openssl enc -d -aes-256-cbc -pbkdf2 -iter 100000 -md sha256 \\\n -in \"$APP_DIR/settings.enc\" -out \"$APP_DIR/settings.json.new\" -pass pass:\"$SETTINGS_PASS\"; then\n err \"Failed to decrypt settings\"\n exit 1\n fi\n log \"Successfully decrypted settings\"\n [ -f \"$APP_DIR/settings.json.old\" ] && rm \"$APP_DIR/settings.json.old\"\n [ -f \"$APP_DIR/settings.json\" ] && mv \"$APP_DIR/settings.json\" \"$APP_DIR/settings.json.old\"\n mv \"$APP_DIR/settings.json.new\" \"$APP_DIR/settings.json\"\n rm -f \"$APP_DIR/settings.enc\"\n \n chown -R ubuntu:ubuntu \"$APP_DIR\"\n chmod 600 \"$APP_DIR/settings.json\"\n \n log \"Restarting Lightning Server Demo\"\n systemctl restart LightningServerEC2SDemo\n sleep 5\n if ! systemctl is-active --quiet LightningServerEC2SDemo; then\n err \"Service failed to start\"\n tail -n 100 /var/log/LightningServerEC2SDemo/server.log >&2 || true\n rollback\n exit 1\n fi\n \n log \"Waiting for liveness at http://localhost:8080/meta/online\"\n healthy=0\n for i in $(seq 1 20); do\n if curl -fsS -o /dev/null --max-time 5 \"http://localhost:8080/meta/online\"; then healthy=1; break; fi\n sleep 3\n done\n if [ \"$healthy\" -ne 1 ]; then\n err \"Liveness endpoint http://localhost:8080/meta/online never returned success\"\n tail -n 100 /var/log/LightningServerEC2SDemo/server.log >&2 || true\n rollback\n exit 1\n fi\n log \"Done\"\n REDEPLOY_EOF\n \n chmod +x /usr/local/bin/lightning-server-redeploy\n echo \"[INFO] Creating Lightning Server Redeploy Script - DONE\"\n \n systemctl enable LightningServerEC2SDemo || true\n systemctl enable amazon-cloudwatch-agent || true", - "name": "LightningServerEC2SDemo-install", - "version": "1.0.45942", - "platform": "Linux" - } - }, - "aws_imagebuilder_image_recipe": { - "this": { - "lifecycle": { - "create_before_destroy": true - }, - "component": [ - { - "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/aws-cli-version-2-linux/x.x.x" - }, - { - "component_arn": "arn:aws:imagebuilder:us-west-2:aws:component/amazon-cloudwatch-agent-linux/x.x.x" - }, - { - "component_arn": "${aws_imagebuilder_component.install.arn}" - } - ], - "block_device_mapping": { - "device_name": "/dev/sda1", - "ebs": { - "volume_type": "gp3", - "encrypted": true, - "volume_size": 20, - "delete_on_termination": true - } - }, - "name": "LightningServerEC2SDemo-recipe", - "parent_image": "${data.aws_ami.ubuntu.id}", - "version": "1.0.45942" - } - }, - "aws_imagebuilder_infrastructure_configuration": { - "this": { - "instance_types": [ - "t4g.micro" - ], - "terminate_instance_on_failure": true, - "instance_profile_name": "${aws_iam_instance_profile.imagebuilder.name}", - "instance_metadata_options": { - "http_tokens": "required", - "http_put_response_hop_limit": 2 - }, - "name": "LightningServerEC2SDemo-infra", - "subnet_id": "${module.vpc.private_subnets[0]}", - "security_group_ids": [ - "${aws_security_group.instance.id}" - ] - } - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/redis.tf.json b/demo/terraform/lkec2/redis.tf.json deleted file mode 100644 index 2b7b6a35c..000000000 --- a/demo/terraform/lkec2/redis.tf.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "resource": { - "aws_elasticache_subnet_group": { - "redis": { - "name": "LightningServerEC2SDemo-redis", - "subnet_ids": "${module.vpc.private_subnets}" - } - }, - "aws_elasticache_cluster": { - "redis": { - "cluster_id": "lightningserverec2sdemo-redis", - "node_type": "cache.t4g.micro", - "engine": "redis", - "port": 6379, - "parameter_group_name": "default.redis7", - "subnet_group_name": "${aws_elasticache_subnet_group.redis.name}", - "security_group_ids": [ - "${aws_security_group.internal.id}" - ], - "num_cache_nodes": 1 - } - } - } -} \ No newline at end of file diff --git a/demo/terraform/lkec2/variables.tf.json b/demo/terraform/lkec2/variables.tf.json deleted file mode 100644 index 155967286..000000000 --- a/demo/terraform/lkec2/variables.tf.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "variable": { - "sms": { - "type": "string" - }, - "someSecret": { - "type": "string" - }, - "voiceAgent": { - "type": "string" - }, - "smsInbound": { - "type": "string" - }, - "phoneCall": { - "type": "string" - }, - "githubOauth": { - "type": "map(any)" - } - } -} \ No newline at end of file diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt index 955633372..9a120c3de 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsEc2BuilderBase.kt @@ -5,6 +5,7 @@ import com.lightningkite.lightningserver.definition.builder.ServerBuilder import com.lightningkite.lightningserver.engine.local.engineCache import com.lightningkite.lightningserver.engine.local.enginePubSub import com.lightningkite.lightningserver.terraform.* +import com.lightningkite.services.Untested import com.lightningkite.services.data.DataSize import com.lightningkite.services.data.DataSize.Companion.mebibytes import com.lightningkite.services.data.EmailAddress @@ -152,6 +153,7 @@ public abstract class TerraformAwsEc2BuilderBase( Ubuntu2404, /** Ubuntu 26.04 LTS (Resolute). */ + @Untested Ubuntu2604, /** @@ -261,11 +263,11 @@ public abstract class TerraformAwsEc2BuilderBase( public open val swapSwappiness: Int get() = 10 /** Max body size for any request. */ - public open val maxBodySize: DataSize = 10.mebibytes + public open val maxBodySize: DataSize get() = 10.mebibytes /** IP Stack Configuration. */ - public open val enableIPv4: Boolean = true - public open val enableIPv6: Boolean = true + public open val enableIPv4: Boolean get() = true + public open val enableIPv6: Boolean get() = true // === Logging Configuration === @@ -275,7 +277,7 @@ public abstract class TerraformAwsEc2BuilderBase( // === Customization Hooks === /** Additional packages to install on EC2 instances, named as [distro]'s package manager knows them. */ - public open val additionalPackages: List = emptyList() + public open val additionalPackages: List get() = emptyList() public enum class JavaVersion(public val outputString: String) { V_8("8"), @@ -322,7 +324,7 @@ public abstract class TerraformAwsEc2BuilderBase( protected val projectLogName: String get() = "$projectPrefix-main-log" /** Additional systemd environment variables. */ - public open val systemdEnvironment: Map = emptyMap() + public open val systemdEnvironment: Map get() = emptyMap() public enum class FileType { Config, @@ -354,12 +356,12 @@ public abstract class TerraformAwsEc2BuilderBase( /** * List of raw Bash scripts to be used in the setup script. * */ - public open val customInstallScriptsRaw: List = emptyList() + public open val customInstallScriptsRaw: List get() = emptyList() /** * List of shell files to be used in the setup script. * */ - public open val customInstallScripts: List = emptyList() + public open val customInstallScripts: List get() = emptyList() /** * Shell fragments run during instance provisioning — in the cloud-init `user_data` for the diff --git a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt index 21588cb06..a624b1284 100644 --- a/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt +++ b/deploy-aws-ec2/src/main/kotlin/com/lightningkite/lightningserver/terraform/aws/ec2/TerraformAwsSingleEc2Builder.kt @@ -92,9 +92,9 @@ public abstract class TerraformAwsSingleEc2Builder( // === SSH access (optional, for debugging) === // sshAllowed with the related IP enabling is what will allow an ssh connection. - public open val sshAllowedV4CIDR: List = + public open val sshAllowedV4CIDR: List get() = emptyList() // Example: 0.0.0.0/0, would allow everyone in the world to attempt to ssh in - public open val sshAllowedV6CIDR: List = + public open val sshAllowedV6CIDR: List get() = emptyList() // Example: ::/0, would allow everyone in the world to attempt to ssh in diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d9a61feca..038f4f7bf 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -33,6 +33,7 @@ vanniktechMavenPublish = "0.37.0" webauthn4jCore = "0.31.10.RELEASE" [libraries] +aws-signin = { module = "software.amazon.awssdk:signin", version = { ref = "awsVersion" } } androidDesugaring = { module = "com.android.tools:desugar_jdk_libs", version = { ref = "androidDesugaring" } } aws-apiGateway = { module = "software.amazon.awssdk:apigatewaymanagementapi", version = { ref = "awsVersion" } } aws-lambda = { module = "software.amazon.awssdk:lambda", version = { ref = "awsVersion" } }