### List and Monitor Docker Containers Source: https://context7.com/petri-hub/terrariaform/llms.txt Lists all running Docker containers, including their ID, name, image, status, resource usage (CPU and memory), creation, and start times. Requires a Bearer token. A `jq` example filters for the game server container and displays its status and memory usage in GB. ```bash # List all containers with usage statistics curl -X GET http://:3000/containers \ -H "Authorization: Bearer your-api-token-here" # Response: # [ # { # "id": "abc123def456", # "name": "terrariaform-server", # "image": "jacobsmile/tmodloader1.4:latest", # "status": "RUNNING", # "usage": { # "cpu": 15.42, # "memory": 2147483648 # }, # "createdAt": 1699999999, # "startedAt": 1700000000 # }, # { # "id": "def456ghi789", # "name": "terrariaform-api", # "image": "api:latest", # "status": "RUNNING", # "usage": { # "cpu": 2.15, # "memory": 536870912 # }, # "createdAt": 1699999999, # "startedAt": 1700000000 # } # ] # Monitor game server container specifically curl -s http://:3000/containers \ -H "Authorization: Bearer your-api-token-here" \ | jq '.[] | select(.name == "terrariaform-server") | {status, cpu: .usage.cpu, memory_gb: (.usage.memory / 1024 / 1024 / 1024)}' ``` -------------------------------- ### Bash Script: Automate EC2 Server Setup and Deployment Source: https://context7.com/petri-hub/terrariaform/llms.txt A comprehensive bash script for automating the setup of a Terraria server environment on an EC2 instance. It updates the system, formats and mounts an EBS volume, installs Docker and Docker Compose, clones the project repository, creates a .env file, and starts the application containers. ```bash #!/bin/bash set -e # Disable interactive prompts export DEBIAN_FRONTEND=noninteractive # Update system apt-get update -y apt-get upgrade -y # Wait for EBS volume while [ ! -e /dev/xvdb ]; do echo "Waiting for EBS volume..." sleep 5 done # Format and mount EBS volume if needed if ! blkid /dev/xvdb; then mkfs.ext4 /dev/xvdb fi mkdir -p /mnt/terrariaform-data mount /dev/xvdb /mnt/terrariaform-data # Persist mount across reboots if ! grep -q '/dev/xvdb' /etc/fstab; then echo '/dev/xvdb /mnt/terrariaform-data ext4 defaults,nofail 0 2' >> /etc/fstab fi # Install dependencies apt-get install -y curl docker.io docker-compose git # Enable Docker systemctl enable docker systemctl start docker # Deploy application cd /srv git clone https://github.com/Petri-Hub/terrariaform.git cd terrariaform # Create .env file from Terraform template cat > .env << 'EOF' ${env_config} EOF # Start containers docker-compose up -d echo "Terrariaform deployment complete!" ``` -------------------------------- ### Docker Compose: Orchestrate Terraria Server and API Source: https://context7.com/petri-hub/terrariaform/llms.txt Configures Docker Compose to define and manage the Terraria game server and monitoring API containers. It specifies images, ports, environment variables for server and API configuration, and volume mounts for persistent data. Includes commands for starting, viewing logs, stopping, and restarting services. ```yaml services: server: image: 'jacobsmile/tmodloader1.4:latest' container_name: 'terrariaform-server' restart: unless-stopped stdin_open: true tty: true ports: - "7777:7777" expose: - "7777" environment: - "TMOD_AUTODOWNLOAD=${SERVER_TMOD_AUTODOWNLOAD}" - "TMOD_ENABLEDMODS=${SERVER_TMOD_ENABLEDMODS}" - "TMOD_SHUTDOWN_MESSAGE=${SERVER_TMOD_SHUTDOWN_MESSAGE}" - "TMOD_AUTOSAVE_INTERVAL=${SERVER_TMOD_AUTOSAVE_INTERVAL}" - "TMOD_MOTD=${SERVER_TMOD_MOTD}" - "TMOD_PASS=${SERVER_TMOD_PASS}" - "TMOD_MAXPLAYERS=${SERVER_TMOD_MAXPLAYERS}" - "TMOD_WORLDNAME=${SERVER_TMOD_WORLDNAME}" - "TMOD_WORLDSIZE=${SERVER_TMOD_WORLDSIZE}" - "TMOD_WORLDSEED=${SERVER_TMOD_WORLDSEED}" - "TMOD_DIFFICULTY=${SERVER_TMOD_DIFFICULTY}" - "TMOD_USECONFIGFILE=${SERVER_TMOD_USECONFIGFILE}" - "UPDATE_NOTICE=${SERVER_UPDATE_NOTICE}" volumes: - "/mnt/terrariaform-data/server:/data" api: container_name: terrariaform-api build: ./services/api restart: unless-stopped ports: - "3000:3000" environment: - "API_HEALTH_CHECK_TEXT=${API_HEALTH_CHECK_TEXT}" - "API_BEARER_TOKEN=${API_BEARER_TOKEN}" ``` ```bash # Start all services docker-compose up -d # View logs docker-compose logs -f server docker-compose logs -f api # Stop services docker-compose down # Restart specific service docker-compose restart server ``` -------------------------------- ### Monitor CPU Statistics Source: https://context7.com/petri-hub/terrariaform/llms.txt Retrieves detailed CPU information, including manufacturer, model name, temperature, and usage statistics (total, system, user, and per-core). Requires a Bearer token for authentication. An integration example in TypeScript demonstrates how to fetch and display this data. ```bash # Monitor CPU usage and temperature curl -X GET http://:3000/system/cpu \ -H "Authorization: Bearer your-api-token-here" # Response: # { # "name": "Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz", # "manufacturer": "Intel", # "temperature": 45.5, # "usage": { # "total": 23.46, # "system": 8.12, # "user": 15.34, # "cores": [22.5, 24.3, 21.8, 25.1] # } # } # Integration example in TypeScript const response = await fetch('http://:3000/system/cpu', { headers: { 'Authorization': 'Bearer your-api-token-here' } }); const cpuData = await response.json(); console.log(`CPU Temperature: ${cpuData.temperature}°C`); console.log(`Total CPU Usage: ${cpuData.usage.total}%`); ``` -------------------------------- ### API Error Responses Source: https://context7.com/petri-hub/terrariaform/llms.txt Illustrates the standard error response structure for the Terrariaform API, which includes a 'message' and an 'code'. Examples show responses for unauthorized access (HTTP 401) and internal server errors (HTTP 500). ```bash # Unauthorized request (missing or invalid token) curl -X GET http://:3000/system/cpu # Response: HTTP 401 # { # "message": "unauthorized access - invalid or missing bearer token", # "code": 2 # } # CPU details retrieval error (internal server error) # Response: HTTP 500 # { # "message": "failed to retrieve CPU details", # "code": 1 # } ``` -------------------------------- ### Retrieve Memory Statistics Source: https://context7.com/petri-hub/terrariaform/llms.txt Provides system memory usage details, including total, used, and free memory in bytes. Requires a Bearer token for authentication. A bash example shows how to convert used bytes to gigabytes using `jq`. ```bash # Get memory statistics curl -X GET http://:3000/system/memory \ -H "Authorization: Bearer your-api-token-here" # Response: # { # "total": 8589934592, # "used": 4294967296, # "free": 4294967296 # } # Convert bytes to GB in bash curl -s http://:3000/system/memory \ -H "Authorization: Bearer your-api-token-here" \ | jq '.used / 1024 / 1024 / 1024 | floor' ``` -------------------------------- ### Health Check API Source: https://context7.com/petri-hub/terrariaform/llms.txt A simple GET endpoint to check if the API is operational and responsive. ```APIDOC ## GET /health ### Description Checks the health status of the API. ### Method GET ### Endpoint /health ### Parameters None ### Request Example ```bash curl -X GET http://:3000/health ``` ### Response #### Success Response (200) An empty body indicates the API is healthy. #### Response Example (No body) ``` -------------------------------- ### Retrieve System OS Information Source: https://context7.com/petri-hub/terrariaform/llms.txt Fetches detailed operating system information, including platform, distribution, codename, architecture, and release version. Requires a Bearer token for authentication. ```bash # Fetch OS information with authentication curl -X GET http://:3000/system/os \ -H "Authorization: Bearer your-api-token-here" # Response: # { # "platform": "linux", # "distro": "Debian", # "codename": "bookworm", # "arch": "x64", # "release": "12.0" # } ``` -------------------------------- ### Environment Variables: Terraria Server and API Settings Source: https://context7.com/petri-hub/terrariaform/llms.txt Defines environment variables for configuring the Terraria game server and the monitoring API. This includes settings for mods, server parameters, and API authentication. Also shows how to connect to the game server. ```bash # .env file # Mod Management SERVER_TMOD_AUTODOWNLOAD=1 SERVER_TMOD_ENABLEDMODS=CalamityMod,ThoriumMod,AlchemistNPC # Server Settings SERVER_TMOD_SHUTDOWN_MESSAGE=Server shutting down! SERVER_TMOD_AUTOSAVE_INTERVAL=10 SERVER_TMOD_MOTD=Welcome to Terrariaform Server! SERVER_TMOD_PASS=mypassword123 SERVER_TMOD_MAXPLAYERS=16 SERVER_TMOD_WORLDNAME=MyWorld SERVER_TMOD_WORLDSIZE=3 SERVER_TMOD_WORLDSEED=random SERVER_TMOD_DIFFICULTY=1 SERVER_TMOD_USECONFIGFILE=0 # Server Management SERVER_UPDATE_NOTICE=false # API Configuration API_BEARER_TOKEN=your-secure-token-here API_HEALTH_CHECK_TEXT=OK ``` ```bash # Connect to game server # In Terraria client, use: terraria.example.com:7777 # Password: mypassword123 ``` -------------------------------- ### Make Script Executable and Run Source: https://context7.com/petri-hub/terrariaform/llms.txt Shell commands to change the permissions of the monitoring script to make it executable and then run it. ```shell chmod +x monitor.sh ./monitor.sh ``` -------------------------------- ### System Service Facade TypeScript Source: https://context7.com/petri-hub/terrariaform/llms.txt Facade pattern implementation that coordinates system information retrieval across multiple specialized services. Provides static methods to retrieve operating system details, CPU metrics, and memory statistics through delegated service classes. ```typescript import { CpuService } from "./CpuService"; import { MemoryService } from "./MemoryService"; import { OperatingSystemService } from "./OperatingSystemService"; import type { CpuDetails } from "../types/CpuDetails"; import type { MemoryDetails } from "../types/MemoryDetails"; import type { OperatingSystemDetails } from "../types/OperatingSystemDetails"; export class SystemService { static async getOperatingSystemDetails(): Promise { return OperatingSystemService.getDetails(); } static async getCpuDetails(): Promise { return CpuService.getDetails(); } static async getMemoryDetails(): Promise { return MemoryService.getDetails(); } } ``` -------------------------------- ### Terraform Infrastructure Deployment and Management Source: https://context7.com/petri-hub/terrariaform/llms.txt This snippet covers the essential Terraform commands for initializing, planning, applying, and destroying AWS infrastructure. It also includes a command to output the server's IP address. The `terraform destroy` command is configured to preserve the EBS volume and Supabase database. ```bash # Initialize Terraform cd cloud/terraform terraform init # Plan deployment terraform plan # Deploy infrastructure terraform apply -auto-approve # Get server IP address terraform output server_ip # Output: 54.123.45.67 # Destroy infrastructure (preserves EBS volume and Supabase DB) terraform destroy ``` -------------------------------- ### Restart Terrariaform Server Containers Source: https://context7.com/petri-hub/terrariaform/llms.txt Shell commands to navigate to the Terrariaform project directory and restart the server containers using Docker Compose. ```shell cd /srv/terrariaform sudo docker-compose restart server ``` -------------------------------- ### System OS Information API Source: https://context7.com/petri-hub/terrariaform/llms.txt Retrieves detailed information about the server's operating system. ```APIDOC ## GET /system/os ### Description Fetches detailed information about the host operating system. ### Method GET ### Endpoint /system/os ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer your-api-token-here"). ### Request Example ```bash curl -X GET http://:3000/system/os \ -H "Authorization: Bearer your-api-token-here" ``` ### Response #### Success Response (200) - **platform** (string) - The operating system platform (e.g., "linux"). - **distro** (string) - The distribution of the operating system (e.g., "Debian"). - **codename** (string) - The codename of the OS release (e.g., "bookworm"). - **arch** (string) - The system architecture (e.g., "x64"). - **release** (string) - The OS release version (e.g., "12.0"). #### Response Example ```json { "platform": "linux", "distro": "Debian", "codename": "bookworm", "arch": "x64", "release": "12.0" } ``` ``` -------------------------------- ### CPU Monitoring API Source: https://context7.com/petri-hub/terrariaform/llms.txt Provides detailed CPU statistics, including usage, temperature, and per-core metrics. ```APIDOC ## GET /system/cpu ### Description Retrieves detailed CPU information, including real-time usage, temperature, and per-core statistics. ### Method GET ### Endpoint /system/cpu ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer your-api-token-here"). ### Request Example ```bash curl -X GET http://:3000/system/cpu \ -H "Authorization: Bearer your-api-token-here" ``` ### Response #### Success Response (200) - **name** (string) - The CPU model name. - **manufacturer** (string) - The CPU manufacturer. - **temperature** (float) - The current CPU temperature in Celsius. - **usage** (object) - CPU usage statistics. - **total** (float) - Overall CPU utilization percentage. - **system** (float) - CPU utilization by the system (kernel). - **user** (float) - CPU utilization by user processes. - **cores** (array of float) - CPU utilization percentage for each core. #### Response Example ```json { "name": "Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz", "manufacturer": "Intel", "temperature": 45.5, "usage": { "total": 23.46, "system": 8.12, "user": 15.34, "cores": [22.5, 24.3, 21.8, 25.1] } } ``` ``` -------------------------------- ### Comprehensive Monitoring Dashboard Script Source: https://context7.com/petri-hub/terrariaform/llms.txt A bash script that utilizes the Terrariaform API to fetch and display comprehensive server monitoring data, including API health, OS information, CPU usage, memory usage, and container status. Requires `curl` and `jq`. ```bash #!/bin/bash # monitor.sh - Terrariaform server monitoring dashboard API_URL="http://your-server-ip:3000" API_TOKEN="your-bearer-token" echo "=== Terrariaform Server Monitor ===" echo "" # Health Check echo "API Health:" if curl -s -o /dev/null -w "%{http_code}" "$API_URL/health" | grep -q "200"; then echo "✓ API is healthy" else echo "✗ API is down" fi echo "" # OS Information echo "Operating System:" curl -s "$API_URL/system/os" \ -H "Authorization: Bearer $API_TOKEN" \ | jq -r '" \(.distro) \(.release) (\(.arch))"' echo "" # CPU Usage echo "CPU Usage:" curl -s "$API_URL/system/cpu" \ -H "Authorization: Bearer $API_TOKEN" \ | jq -r '" Total: \(.usage.total)%\n Temperature: \(.temperature)°C\n Cores: \(.usage.cores | join("%", " "))%"' echo "" # Memory Usage echo "Memory Usage:" curl -s "$API_URL/system/memory" \ -H "Authorization: Bearer $API_TOKEN" \ | jq -r '" Total: \(.total / 1024 / 1024 / 1024 | floor)GB\n Used: \(.used / 1024 / 1024 / 1024 | floor)GB\n Free: \(.free / 1024 / 1024 / 1024 | floor)GB"' echo "" # Container Status echo "Containers:" curl -s "$API_URL/containers" \ -H "Authorization: Bearer $API_TOKEN" \ | jq -r '.[] | " \(.name): \(.status)\n CPU: \(.usage.cpu)%\n Memory: \(.usage.memory / 1024 / 1024 | floor)MB"' ``` -------------------------------- ### Terraform Vercel DNS and Project Deployment Source: https://context7.com/petri-hub/terrariaform/llms.txt This HCL snippet configures DNS records using Vercel to point a subdomain to the EC2 instance's Elastic IP. It also defines a Vercel project for a Next.js web interface, maps a custom domain, and sets up a production deployment from the master branch. ```hcl # cloud/terraform/main.tf # DNS record pointing to game server resource "vercel_dns_record" "terraria_subdomain" { domain = var.vercel_domain_name type = "A" name = var.vercel_terraria_subdomain value = aws_eip.terrariaform_elastic_ip.public_ip ttl = 60 } # Vercel project for web interface resource "vercel_project" "terrariaform_web" { name = "terrariaform-web" framework = "nextjs" root_directory = "services/web" git_repository = { type = "github" repo = "Petri-Hub/terrariaform" } } # Custom domain for web interface resource "vercel_project_domain" "terrariaform_domain" { project_id = vercel_project.terrariaform_web.id domain = var.vercel_terrariaform_subdomain } # Deploy to production resource "vercel_deployment" "terrariaform_deploy" { project_id = vercel_project.terrariaform_web.id production = true ref = "master" } ``` -------------------------------- ### Container Listing and Monitoring API Source: https://context7.com/petri-hub/terrariaform/llms.txt Lists all running Docker containers and their resource usage (CPU and memory). ```APIDOC ## GET /containers ### Description Lists all Docker containers running on the host, along with their status and resource consumption metrics (CPU and memory). ### Method GET ### Endpoint /containers ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer your-api-token-here"). ### Request Example ```bash curl -X GET http://:3000/containers \ -H "Authorization: Bearer your-api-token-here" ``` ### Response #### Success Response (200) Returns an array of container objects: - **id** (string) - The Docker container ID. - **name** (string) - The name of the container. - **image** (string) - The Docker image used by the container. - **status** (string) - The current status of the container (e.g., "RUNNING"). - **usage** (object) - Resource usage statistics. - **cpu** (float) - CPU usage percentage. - **memory** (integer) - Memory usage in bytes. - **createdAt** (integer) - Timestamp when the container was created. - **startedAt** (integer) - Timestamp when the container was started. #### Response Example ```json [ { "id": "abc123def456", "name": "terrariaform-server", "image": "jacobsmile/tmodloader1.4:latest", "status": "RUNNING", "usage": { "cpu": 15.42, "memory": 2147483648 }, "createdAt": 1699999999, "startedAt": 1700000000 }, { "id": "def456ghi789", "name": "terrariaform-api", "image": "api:latest", "status": "RUNNING", "usage": { "cpu": 2.15, "memory": 536870912 }, "createdAt": 1699999999, "startedAt": 1700000000 } ] ``` ``` -------------------------------- ### Terraform: Provision Supabase Project Source: https://context7.com/petri-hub/terrariaform/llms.txt Defines a Supabase project resource using Terraform. It configures the organization ID, project name, database password, and region. The lifecycle block prevents accidental destruction of the project. ```terraform resource "supabase_project" "terrariaform" { organization_id = var.supabase_organization_id name = "terrariaform" database_password = var.supabase_db_password region = var.supabase_region lifecycle { prevent_destroy = true } } ``` -------------------------------- ### CPU Service with Error Handling TypeScript Source: https://context7.com/petri-hub/terrariaform/llms.txt Retrieves comprehensive CPU metrics including brand, manufacturer, temperature, and usage statistics using the systeminformation library. Aggregates data from multiple concurrent API calls with Promise.all, simplifies percentage values, and provides per-core usage data. Includes error handling that throws CpuDetailsRetrievalError on failure. ```typescript import si from "systeminformation"; import { CpuDetailsRetrievalError } from "../errors/CpuDetailsRetrievalError"; import { simplifyPercentage } from "../utils/simplifyPercentage"; import type { CpuDetails } from "../types/CpuDetails"; export class CpuService { static async getDetails(): Promise { try { const [cpuInfo, currentLoad, cpuTemperature] = await Promise.all([ si.cpu(), si.currentLoad(), si.cpuTemperature(), ]); return { name: cpuInfo.brand, manufacturer: cpuInfo.manufacturer, temperature: cpuTemperature.main, usage: { total: simplifyPercentage(currentLoad.currentLoad), system: simplifyPercentage(currentLoad.currentLoadSystem), user: simplifyPercentage(currentLoad.currentLoadUser), cores: currentLoad.cpus.map((cpu) => simplifyPercentage(cpu.load) ), }, }; } catch (error) { throw new CpuDetailsRetrievalError(); } } } ``` -------------------------------- ### Check EBS Mount and View World Files Source: https://context7.com/petri-hub/terrariaform/llms.txt Shell commands to check the status of the EBS volume mounted for Terrariaform data and list the world files stored within the server's directory. ```shell df -h | grep terrariaform-data ls -lah /mnt/terrariaform-data/server/Worlds/ ``` -------------------------------- ### Terraform Variables and Configuration Source: https://context7.com/petri-hub/terrariaform/llms.txt This HCL snippet defines the input variables for the Terraform deployment, including AWS region, instance type, SSH key path, and Vercel and Supabase API credentials and identifiers. These variables are crucial for customizing the infrastructure deployment. ```hcl # terraform.tfvars aws_region = "us-east-1" aws_instance_type = "t3.medium" aws_ssh_key_path = "~/.ssh/terrariaform.pub" vercel_api_token = "your-vercel-token" vercel_team_id = "your-team-id" vercel_domain_name = "example.com" vercel_terraria_subdomain = "terraria" vercel_terrariaform_subdomain = "app" supabase_access_token = "your-supabase-token" supabase_db_password = "secure-password" supabase_region = "us-east-1" supabase_organization_id = "your-org-id" ``` -------------------------------- ### TypeScript: Hono API Service Implementation Source: https://context7.com/petri-hub/terrariaform/llms.txt Implements the monitoring API service using TypeScript with the Hono framework. It sets up routes for health checks, system information, and container management, includes authentication and error handling middleware, and defines the server port and fetch handler. ```typescript import { Hono } from "hono"; import healthRoutes from "./routes/health"; import systemRoutes from "./routes/system"; import containerRoutes from "./routes/containers"; import authMiddleware from "./middlewares/authMiddleware"; import errorHandlerMiddleware from "./middlewares/errorHandlerMiddleware"; const app = new Hono(); // Global error handler app.use("*", errorHandlerMiddleware); // Public routes app.route("/", healthRoutes); // Protected routes (require authentication) app.use("/system/*", authMiddleware); app.use("/containers/*", authMiddleware); app.route("/system", systemRoutes); app.route("/containers", containerRoutes); const port = 3000; console.log(`Server running on port ${port}`); export default { port, fetch: app.fetch, }; ``` -------------------------------- ### Container Service with Resource Monitoring TypeScript Source: https://context7.com/petri-hub/terrariaform/llms.txt Manages Docker container monitoring by retrieving container metadata and resource usage statistics. Provides methods to list all containers with CPU/memory metrics and retrieve individual container details by ID. Maps container stats to usage information with simplified percentages. ```typescript import si from "systeminformation"; import { simplifyPercentage } from "../utils/simplifyPercentage"; import type { ContainerDetails } from "../types/ContainerDetails"; export class ContainerService { static async getContainers(): Promise { const [containers, containerStats] = await Promise.all([ si.dockerContainers(), si.dockerContainerStats("*"), ]); return containers.map((container) => { const stats = containerStats.find((stat) => stat.id === container.id); return { id: container.id, name: container.name, image: container.image, status: container.state, usage: { cpu: stats ? simplifyPercentage(stats.cpuPercent) : 0, memory: stats ? stats.memUsage : 0, }, createdAt: container.created, startedAt: container.started, }; }); } static async getContainer(id: string): Promise { const containers = await this.getContainers(); return containers.find((c) => c.id === id); } } ``` -------------------------------- ### SSH Access and Docker Log Viewing Bash Source: https://context7.com/petri-hub/terrariaform/llms.txt Establishes SSH connection to EC2 instance using private key authentication and Terraform output for IP address. Provides commands to view Docker container logs in real-time for both terrariaform-server and terrariaform-api containers for debugging and monitoring. ```bash # Connect via SSH ssh -i ~/.ssh/terrariaform.pem admin@$(terraform output -raw server_ip) # View Docker logs sudo docker logs -f terrariaform-server sudo docker logs -f terrariaform-api ``` -------------------------------- ### Terraform EC2 Instance, Elastic IP, and EBS Volume Source: https://context7.com/petri-hub/terrariaform/llms.txt This HCL snippet defines the core AWS resources for the Terrariaform server: an EC2 instance with automated startup scripts, an Elastic IP for static addressing, and a persistent EBS volume for data storage. The EBS volume is configured to prevent accidental destruction. ```hcl # cloud/terraform/main.tf resource "aws_instance" "terrariaform_server" { ami = data.aws_ami.terrariaform_ami.id instance_type = var.aws_instance_type vpc_security_group_ids = [aws_security_group.terrariaform_sg.id] key_name = aws_key_pair.terrariaform_ssh_key.key_name user_data_replace_on_change = true user_data = templatefile("../scripts/startup.sh", { env_config = file("../../.env") }) tags = { Name = "terrariaform-server" } } # Elastic IP for static addressing resource "aws_eip" "terrariaform_elastic_ip" { instance = aws_instance.terrariaform_server.id } # Persistent EBS volume (survives instance termination) resource "aws_ebs_volume" "terrariaform_data" { availability_zone = aws_instance.terrariaform_server.availability_zone size = 6 type = "gp3" lifecycle { prevent_destroy = true } } resource "aws_volume_attachment" "terrariaform_data_attach" { device_name = "/dev/xvdb" volume_id = aws_ebs_volume.terrariaform_data.id instance_id = aws_instance.terrariaform_server.id force_detach = true } ``` -------------------------------- ### Error Handling Source: https://context7.com/petri-hub/terrariaform/llms.txt Standardized error response format for API requests. ```APIDOC ## Error Responses ### Description API error responses follow a consistent JSON structure, providing a message and an error code. ### Common Error Codes - **1**: Internal Server Error (e.g., failed to retrieve data). - **2**: Unauthorized Access (missing or invalid authentication token). ### Unauthorized Response Example (401) ```json { "message": "unauthorized access - invalid or missing bearer token", "code": 2 } ``` ### Internal Server Error Example (500) ```json { "message": "failed to retrieve CPU details", "code": 1 } ``` ``` -------------------------------- ### Monitor Docker Container Resources Source: https://context7.com/petri-hub/terrariaform/llms.txt Shell command to monitor the real-time resource usage (CPU, Memory) of running Docker containers. ```shell sudo docker stats ``` -------------------------------- ### Memory Statistics API Source: https://context7.com/petri-hub/terrariaform/llms.txt Returns current system memory usage, including total, used, and free memory. ```APIDOC ## GET /system/memory ### Description Retrieves current system memory usage statistics, including total, used, and free memory in bytes. ### Method GET ### Endpoint /system/memory ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., "Bearer your-api-token-here"). ### Request Example ```bash curl -X GET http://:3000/system/memory \ -H "Authorization: Bearer your-api-token-here" ``` ### Response #### Success Response (200) - **total** (integer) - Total system memory in bytes. - **used** (integer) - Used system memory in bytes. - **free** (integer) - Free system memory in bytes. #### Response Example ```json { "total": 8589934592, "used": 4294967296, "free": 4294967296 } ``` ``` -------------------------------- ### EC2 Instance Pause/Resume Operations Bash Source: https://context7.com/petri-hub/terrariaform/llms.txt AWS CLI commands to manage EC2 instance lifecycle for cost optimization. Retrieves instance ID from Terraform output, stops/starts the instance, checks status, and retrieves the updated public IP address after restart. Useful for pausing servers during off-hours. ```bash # Get instance ID INSTANCE_ID=$(terraform output -raw instance_id) # Stop server (pause) aws ec2 stop-instances --instance-ids $INSTANCE_ID # Check status aws ec2 describe-instances \ --instance-ids $INSTANCE_ID \ --query 'Reservations[0].Instances[0].State.Name' \ --output text # Start server (resume) aws ec2 start-instances --instance-ids $INSTANCE_ID # Get current IP after restart aws ec2 describe-instances \ --instance-ids $INSTANCE_ID \ --query 'Reservations[0].Instances[0].PublicIpAddress' \ --output text ``` -------------------------------- ### API Health Check Source: https://context7.com/petri-hub/terrariaform/llms.txt This endpoint checks the operational status of the Terrariaform API. It requires no authentication and returns an HTTP 200 status code if the API is responsive. ```bash # Check if API is operational curl -X GET http://:3000/health # Response: HTTP 200 (empty body) ``` -------------------------------- ### Bearer Token Authentication Middleware TypeScript Source: https://context7.com/petri-hub/terrariaform/llms.txt Validates incoming API requests using Bearer token authentication. Extracts the token from the Authorization header, compares it against the API_BEARER_TOKEN environment variable, and throws UnauthorizedError if validation fails. Integrates with Hono framework context and next middleware. ```typescript import type { Context, Next } from "hono"; import { UnauthorizedError } from "../errors/UnauthorizedError"; async function authMiddleware(context: Context, next: Next): Promise { const authHeader = context.req.header("Authorization"); if (!authHeader?.startsWith("Bearer ")) { throw new UnauthorizedError(); } const token = authHeader.substring(7); const expectedToken = process.env.API_BEARER_TOKEN; if (token !== expectedToken) { throw new UnauthorizedError(); } await next(); } export default authMiddleware; ``` -------------------------------- ### Terraform AWS Security Group Configuration Source: https://context7.com/petri-hub/terrariaform/llms.txt This HCL snippet defines an AWS security group with ingress rules for SSH (port 22), the Terraria game server (port 7777), and the monitoring API (port 3000), allowing traffic from any IP address. It also includes an egress rule allowing all outbound traffic. ```hcl # cloud/terraform/main.tf resource "aws_security_group" "terrariaform_sg" { name = "terrariaform-sg" description = "Security group for Terrariaform server" } # SSH access resource "aws_vpc_security_group_ingress_rule" "terrariaform_ssh_allow" { security_group_id = aws_security_group.terrariaform_sg.id from_port = 22 to_port = 22 ip_protocol = "tcp" cidr_ipv4 = "0.0.0.0/0" } # Terraria game port resource "aws_vpc_security_group_ingress_rule" "terrariaform_game_allow" { security_group_id = aws_security_group.terrariaform_sg.id from_port = 7777 to_port = 7777 ip_protocol = "tcp" cidr_ipv4 = "0.0.0.0/0" } # Monitoring API resource "aws_vpc_security_group_ingress_rule" "terrariaform_api_allow" { security_group_id = aws_security_group.terrariaform_sg.id from_port = 3000 to_port = 3000 ip_protocol = "tcp" cidr_ipv4 = "0.0.0.0/0" } # All outbound traffic resource "aws_vpc_security_group_egress_rule" "terrariaform_egress_allow" { security_group_id = aws_security_group.terrariaform_sg.id ip_protocol = "-1" cidr_ipv4 = "0.0.0.0/0" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.