diff --git a/.github/workflows/ami-build.yml b/.github/workflows/ami-build.yml index 284895cc..891a0cde 100644 --- a/.github/workflows/ami-build.yml +++ b/.github/workflows/ami-build.yml @@ -2,17 +2,18 @@ name: Build AMI # This workflow should be triggered MANUALLY when AMI infrastructure needs updating. -# Node software updates are handled automatically via Docker :latest tag. +# The AMI runs the node release that is the latest release when it is built +# (TN_NODE_TAG in /opt/tn/.env). Operators move a node to another release with +# `sudo tn-node-update `. # # When to rebuild AMI: # ✅ Infrastructure changes (scripts, services, docker-compose) # ✅ Base OS updates (Ubuntu patches) # ✅ AWS Marketplace submission -# ✅ Major version releases +# ✅ Major version releases, so that new nodes start on them # # When NOT to rebuild: -# ❌ Regular node software updates (use Docker image workflow instead) -# ❌ Bug fixes (users get them via :latest tag) +# ❌ Regular node software updates (operators run tn-node-update) 'on': workflow_dispatch: @@ -57,10 +58,11 @@ jobs: - name: Get latest release version id: get-version run: | - # Get latest release tag from GitHub API - LATEST_VERSION=$(gh release list --limit 1 --json tagName --jq '.[0].tagName') + # The latest published release; the AMI runs its node image. + LATEST_VERSION=$(gh release view --json tagName --jq '.tagName') if [ -z "$LATEST_VERSION" ]; then - LATEST_VERSION="manual" + echo "::error::No published release for the AMI to run" + exit 1 fi echo "Latest release version: $LATEST_VERSION" echo "version=$LATEST_VERSION" >> "$GITHUB_OUTPUT" @@ -85,6 +87,8 @@ jobs: cdk --version - name: Deploy/Update AMI pipeline infrastructure + env: + NODE_TAG: ${{ steps.get-version.outputs.version }} run: | cd deployments/infra echo "Destroying existing AMI pipeline to ensure fresh components..." @@ -93,6 +97,7 @@ jobs: cdk destroy AMI-Pipeline-${{ env.STAGE }}-Stack \ --app "go run ami-cdk.go" \ --context stage=${{ env.STAGE }} \ + --context nodeTag="$NODE_TAG" \ --force || echo "Stack didn't exist or failed to destroy, continuing..." echo "Deploying fresh AMI pipeline infrastructure for stage: ${{ env.STAGE }}..." @@ -102,6 +107,7 @@ jobs: cdk deploy AMI-Pipeline-${{ env.STAGE }}-Stack \ --app "go run ami-cdk.go" \ --context stage=${{ env.STAGE }} \ + --context nodeTag="$NODE_TAG" \ --require-approval never # Get pipeline ARN after deployment @@ -237,7 +243,7 @@ jobs: echo " https://aws.amazon.com/marketplace/management/products" - name: Update latest release with AMI details - if: env.AMI_ID && steps.get-version.outputs.version != 'manual' + if: env.AMI_ID uses: actions/github-script@v7 env: VERSION: ${{ steps.get-version.outputs.version }} diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e54c05f8..b4f595ac 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -53,7 +53,17 @@ jobs: with: node-version: '20' - name: Run infra tests - run: go test -count=1 ./config/ ./config/node/ ./lib/tn/ ./lib/constructs/validator_set/ + run: go test -count=1 ./config/ ./config/node/ ./lib/tn/ ./lib/constructs/validator_set/ ./stacks/ + + # Tests the check that release.yaml and publish-node-image.yaml run on each + # release page. + release-upgrade-line: + runs-on: ubuntu-latest + if: ${{ !github.event.pull_request.draft }} + steps: + - uses: actions/checkout@v4 + - name: Test the upgrade line check + run: scripts/release/test-check-upgrade-line.sh acceptance-test: runs-on: ubuntu-latest diff --git a/.github/workflows/publish-node-image.yaml b/.github/workflows/publish-node-image.yaml index 52bf84f5..a271636d 100644 --- a/.github/workflows/publish-node-image.yaml +++ b/.github/workflows/publish-node-image.yaml @@ -29,6 +29,15 @@ jobs: - name: Checkout repository uses: actions/checkout@v4 + # A release whose page does not open with the upgrade line gets no image, + # and latest does not move (docs/release-process.md). A manual run has no + # release page, so it skips the check. + - name: Check the upgrade line + if: github.event_name == 'release' + env: + RELEASE_BODY: ${{ github.event.release.body }} + run: printf '%s' "$RELEASE_BODY" | scripts/release/check-upgrade-line.sh + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index f1ecee7c..e3434d51 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -26,6 +26,15 @@ jobs: with: token: ${{ secrets.GITHUB_TOKEN }} + # A release whose page does not open with the upgrade line gets no binaries + # (docs/release-process.md). Editing the page to add the line runs this + # workflow again. A manual run has no release page, so it skips the check. + - name: Check the upgrade line + if: github.event_name == 'release' + env: + RELEASE_BODY: ${{ github.event.release.body }} + run: printf '%s' "$RELEASE_BODY" | scripts/release/check-upgrade-line.sh + - name: Set Version id: vars run: | diff --git a/README.md b/README.md index 7b3424d6..2dfff439 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,8 @@ Steps and best practices for upgrading TN nodes: [Node Upgrade Guide](./docs/node-upgrade-guide.md) +Each release page opens with a line that says whether your node must install the release and by which block. To get release notices, choose **Watch → Custom → Releases** on this repository. Maintainers publish releases as described in the [Release Process](./docs/release-process.md). + ## SDKs diff --git a/deployments/infra/README.md b/deployments/infra/README.md index 7d6709c2..74fad28c 100644 --- a/deployments/infra/README.md +++ b/deployments/infra/README.md @@ -326,7 +326,7 @@ This directory contains infrastructure for automated AMI building using AWS EC2 - **Automated AMI Building**: EC2 Image Builder pipeline for creating TrufNetwork node AMIs - **Docker-in-AMI**: Pre-installed Docker with docker-compose for container orchestration -- **Always-Latest Strategy**: Containers pull latest images on startup +- **Release Tags**: The node containers run the release in `TN_NODE_TAG` in `/opt/tn/.env`, and `sudo tn-node-update ` moves them to another release - **MCP Server Integration**: PostgreSQL MCP server for AI agent access via SSE transport - **Current Region Distribution**: AMI distribution in deployment region (multi-region planned) - **GitHub Actions Integration**: Automated builds triggered by releases @@ -345,9 +345,11 @@ This directory contains infrastructure for automated AMI building using AWS EC2 cd deployments/infra # Deploy using isolated AMI CDK app (✅ Tested and Working) +# nodeTag is the node release the AMI runs, a tag from https://github.com/trufnetwork/node/releases cdk --app 'go run ami-cdk.go' deploy \ --context stage=dev \ --context devPrefix=test-$(whoami) \ + --context nodeTag=v2.6.8 \ --require-approval never ``` @@ -402,8 +404,8 @@ curl http://localhost:8000/ # MCP server (returns 404 - normal) #### Update Node Images ```bash -# On AMI instances, update to latest images -sudo update-node +# On AMI instances, install a node release by its tag +sudo tn-node-update v2.6.9 ``` ### AMI Architecture @@ -418,12 +420,13 @@ The AMI includes: - PostgreSQL MCP Server (crystaldba/postgres-mcp:latest) - Will need to be adjusted later on - **Configuration Scripts**: - `/usr/local/bin/tn-node-configure` - Initial setup - - `/usr/local/bin/update-node` - Update to latest images + - `/usr/local/bin/tn-node-update` - Install a node release by its tag - **SystemD Service**: `tn-node.service` for service management - **File Structure**: - `/opt/tn/` - Main application directory - `/opt/tn/docker-compose.yml` - Container orchestration - - `/opt/tn/.env` - Environment configuration + - `/opt/tn/.env` - Environment configuration, with the node release in `TN_NODE_TAG` + - `/opt/tn/ami-node-tag` - The node release the AMI was built with ### Local Testing diff --git a/deployments/infra/stacks/ami-scripts/tn-node-configure.sh b/deployments/infra/stacks/ami-scripts/tn-node-configure.sh new file mode 100755 index 00000000..08ab8a68 --- /dev/null +++ b/deployments/infra/stacks/ami-scripts/tn-node-configure.sh @@ -0,0 +1,64 @@ +#!/bin/bash +set -e +TN_DIR="${TN_DIR:-/opt/tn}" +PRIVATE_KEY="" +ENABLE_MCP=false +NETWORK="" +while [[ $# -gt 0 ]]; do + case $1 in + --private-key) PRIVATE_KEY="$2"; shift 2;; + --enable-mcp) ENABLE_MCP=true; shift;; + --network) NETWORK="$2"; shift 2;; + *) echo "Unknown option"; exit 1;; + esac +done +RECONFIGURE=false +[ -f "$TN_DIR/.env" ] && RECONFIGURE=true +if [ -n "$NETWORK" ]; then + CHAIN_ID="$NETWORK" + NETWORK_TYPE="custom" +else + CHAIN_ID="tn-v2.1" + NETWORK_TYPE="mainnet" +fi +cd "$TN_DIR" +# The node release this AMI was built with. A reconfigure keeps the release +# that tn-node-update set. +NODE_TAG=$(cat ami-node-tag) +if [ "$RECONFIGURE" = true ]; then + [ -n "$PRIVATE_KEY" ] && { echo "Error: Cannot change key"; exit 1; } + [ -n "$NETWORK" ] && { echo "Error: Cannot change network"; exit 1; } + grep -q "TN_PRIVATE_KEY=" .env && EXISTING_KEY=$(grep "TN_PRIVATE_KEY=" .env | cut -d'=' -f2) + grep -q "CHAIN_ID=" .env && CHAIN_ID=$(grep "CHAIN_ID=" .env | cut -d'=' -f2) + grep -q "NETWORK_TYPE=" .env && NETWORK_TYPE=$(grep "NETWORK_TYPE=" .env | cut -d'=' -f2) + grep -q "^TN_NODE_TAG=" .env && NODE_TAG=$(grep "^TN_NODE_TAG=" .env | tail -n 1 | cut -d'=' -f2) + sudo systemctl stop tn-node || true + sudo -u tn docker compose down || true +fi +cat > .env << ENVEOF +TN_NODE_TAG=$NODE_TAG +CHAIN_ID=$CHAIN_ID +NETWORK_TYPE=$NETWORK_TYPE +ENVEOF +[ "$ENABLE_MCP" = true ] && echo "COMPOSE_PROFILES=mcp" >> .env +if [ "$RECONFIGURE" = false ] && [ -n "$PRIVATE_KEY" ]; then + echo "TN_PRIVATE_KEY=$PRIVATE_KEY" >> .env +elif [ "$RECONFIGURE" = true ] && [ -n "$EXISTING_KEY" ]; then + echo "TN_PRIVATE_KEY=$EXISTING_KEY" >> .env +fi +sudo chown tn:tn .env +sudo chmod 600 .env +sudo systemctl daemon-reload +sudo systemctl enable tn-node +sudo systemctl start tn-node +MAX_WAIT=60 +ELAPSED=0 +while [ $ELAPSED -lt $MAX_WAIT ]; do + sudo -u tn docker compose ps --status running 2>/dev/null | grep -q tn-node && break + sleep 2 + ELAPSED=$((ELAPSED + 2)) +done +echo "Done. Status: $(sudo systemctl is-active tn-node)" +if [ "$ENABLE_MCP" = true ]; then + echo "MCP: http://$(curl -s --max-time 2 http://169.254.169.254/latest/meta-data/public-ipv4 || echo localhost):8000/sse" +fi diff --git a/deployments/infra/stacks/ami-scripts/tn-node-update.sh b/deployments/infra/stacks/ami-scripts/tn-node-update.sh new file mode 100755 index 00000000..a49c222d --- /dev/null +++ b/deployments/infra/stacks/ami-scripts/tn-node-update.sh @@ -0,0 +1,57 @@ +#!/bin/bash +# Installs a TN node release on a node built from the TN AMI. +# +# sudo tn-node-update v2.6.9 runs the release tagged v2.6.9 +# sudo tn-node-update pulls the release the node runs now +# +# The tag is stored as TN_NODE_TAG in /opt/tn/.env. The script pulls that node +# image and runs docker compose up for tn-node, which recreates the node +# containers only when their image or configuration changed. Postgres and the +# MCP server keep running. +set -euo pipefail + +TN_DIR="${TN_DIR:-/opt/tn}" +ENV_FILE="$TN_DIR/.env" + +if [ $# -gt 1 ]; then + echo "Usage: tn-node-update [release tag, for example v2.6.9]" >&2 + exit 1 +fi +if [ ! -f "$ENV_FILE" ]; then + echo "Error: $ENV_FILE not found. Run tn-node-configure first." >&2 + exit 1 +fi + +CURRENT=$(grep '^TN_NODE_TAG=' "$ENV_FILE" | tail -n 1 | cut -d= -f2- || true) +if [ $# -eq 1 ]; then + TAG=$1 +else + TAG=$CURRENT + if [ -z "$TAG" ]; then + echo "Error: $ENV_FILE has no TN_NODE_TAG. Pass the release tag, for example: tn-node-update v2.6.9" >&2 + exit 1 + fi +fi +# Release tags are on https://github.com/trufnetwork/node/releases. latest is +# refused so that the node runs the release its operator chose. +if ! [[ $TAG =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]] || [ "$TAG" = latest ]; then + echo "Error: '$TAG' is not a release tag. Pass one from https://github.com/trufnetwork/node/releases, for example v2.6.9" >&2 + exit 1 +fi + +cd "$TN_DIR" +# Pull before .env changes, so a tag with no image leaves the node as it was. +sudo -u tn env TN_NODE_TAG="$TAG" docker compose pull tn-postgres-roles tn-node + +if [ "$TAG" != "$CURRENT" ]; then + if grep -q '^TN_NODE_TAG=' "$ENV_FILE"; then + sed -i "s/^TN_NODE_TAG=.*/TN_NODE_TAG=$TAG/" "$ENV_FILE" + else + echo "TN_NODE_TAG=$TAG" >> "$ENV_FILE" + fi + chown tn:tn "$ENV_FILE" + chmod 600 "$ENV_FILE" +fi + +sudo -u tn docker compose up -d tn-node +echo "tn-node runs ghcr.io/trufnetwork/node:$TAG" diff --git a/deployments/infra/stacks/ami_pipeline_stack.go b/deployments/infra/stacks/ami_pipeline_stack.go index f66eaba8..193650bc 100644 --- a/deployments/infra/stacks/ami_pipeline_stack.go +++ b/deployments/infra/stacks/ami_pipeline_stack.go @@ -3,6 +3,9 @@ package stacks import ( _ "embed" "encoding/base64" + "fmt" + "regexp" + "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awsiam" "github.com/aws/aws-cdk-go/awscdk/v2/awsimagebuilder" @@ -15,8 +18,42 @@ import ( //go:embed docker-compose.template.yml var dockerComposeTemplate string -func getEncodedDockerCompose() string { - return base64.StdEncoding.EncodeToString([]byte(dockerComposeTemplate)) +//go:embed ami-scripts/tn-node-configure.sh +var tnNodeConfigureScript string + +//go:embed ami-scripts/tn-node-update.sh +var tnNodeUpdateScript string + +// encode returns a file as base64, for a component command to write it. +func encode(file string) string { + return base64.StdEncoding.EncodeToString([]byte(file)) +} + +// contextNodeTag is the CDK context value that names the node release an AMI +// is built with, such as v2.6.8. The AMI writes it to /opt/tn/ami-node-tag, +// and tn-node-configure copies it to TN_NODE_TAG in /opt/tn/.env. +const contextNodeTag = "nodeTag" + +// nodeTagPattern is a Docker image tag. tn-node-update checks its argument +// with the same pattern. +var nodeTagPattern = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$`) + +// validateNodeTag accepts the image tag of a node release and refuses latest, +// so that an AMI runs the release it was built with. +func validateNodeTag(tag string) error { + if tag == "latest" || !nodeTagPattern.MatchString(tag) { + return fmt.Errorf("%q is not a node release tag such as v2.6.8", tag) + } + return nil +} + +func amiNodeTag(scope constructs.Construct) string { + tag, _ := scope.Node().TryGetContext(jsii.String(contextNodeTag)).(string) + if err := validateNodeTag(tag); err != nil { + panic(fmt.Sprintf("context variable '%s': %v. Pass the release the AMI runs, for example -c %s=v2.6.8", + contextNodeTag, err, contextNodeTag)) + } + return tag } type AmiPipelineStackProps struct { @@ -24,15 +61,16 @@ type AmiPipelineStackProps struct { } type AmiPipelineStackExports struct { - PipelineArn string - DockerComponentArn string - ConfigComponentArn string - WelcomeComponentArn string - RecipeArn string - InfraConfigArn string - DistributionArn string - S3BucketName string - InstanceProfileArn string + PipelineArn string + DockerComponentArn string + ConfigComponentArn string + CommandsComponentArn string + WelcomeComponentArn string + RecipeArn string + InfraConfigArn string + DistributionArn string + S3BucketName string + InstanceProfileArn string } func AmiPipelineStack(scope constructs.Construct, id string, props *AmiPipelineStackProps) (awscdk.Stack, AmiPipelineStackExports) { @@ -48,6 +86,7 @@ func AmiPipelineStack(scope constructs.Construct, id string, props *AmiPipelineS stage := config.GetStage(stack) devPrefix := config.GetDevPrefix(stack) + nodeTag := amiNodeTag(stack) // Helper function to construct names with dev prefix nameWithPrefix := func(name string) string { @@ -210,10 +249,18 @@ phases: inputs: commands: - | - echo "` + getEncodedDockerCompose() + `" | base64 -d > /opt/tn/docker-compose.yml + echo "` + encode(dockerComposeTemplate) + `" | base64 -d > /opt/tn/docker-compose.yml - sudo chown tn:tn /opt/tn/docker-compose.yml - sudo chmod 644 /opt/tn/docker-compose.yml + # The node release the AMI runs until tn-node-update moves it. + - name: WriteNodeTag + action: ExecuteBash + inputs: + commands: + - echo "` + nodeTag + `" | sudo tee /opt/tn/ami-node-tag > /dev/null + - sudo chown tn:tn /opt/tn/ami-node-tag + - name: CreateSystemdService action: ExecuteBash inputs: @@ -238,69 +285,34 @@ phases: WantedBy=multi-user.target EOF + - name: PrepareServices + action: ExecuteBash + inputs: + commands: + - sudo systemctl daemon-reload +`), + }) + + // Component 2: the tn-node-configure and tn-node-update commands (split to stay under 16KB limit) + commandsComponent := awsimagebuilder.NewCfnComponent(stack, jsii.String("TNCommandsComponent"), &awsimagebuilder.CfnComponentProps{ + Name: jsii.String(nameWithPrefix("tn-commands-setup-" + string(stage))), + Platform: jsii.String("Linux"), + Version: jsii.String("1.0.0"), + Description: jsii.String("Install the TRUF.NETWORK node configure and update commands"), + Data: jsii.String(` +name: TNCommandsComponent +description: Install the TRUF.NETWORK node configure and update commands +schemaVersion: 1.0 + +phases: + - name: build + steps: - name: CreateConfigurationScript action: ExecuteBash inputs: commands: - | - sudo tee /usr/local/bin/tn-node-configure > /dev/null << 'EOF' - #!/bin/bash - set -e - PRIVATE_KEY="" - ENABLE_MCP=false - NETWORK="" - while [[ $# -gt 0 ]]; do - case $1 in - --private-key) PRIVATE_KEY="$2"; shift 2;; - --enable-mcp) ENABLE_MCP=true; shift;; - --network) NETWORK="$2"; shift 2;; - *) echo "Unknown option"; exit 1;; - esac - done - RECONFIGURE=false - [ -f /opt/tn/.env ] && RECONFIGURE=true - if [ -n "$NETWORK" ]; then - CHAIN_ID="$NETWORK" - NETWORK_TYPE="custom" - else - CHAIN_ID="tn-v2.1" - NETWORK_TYPE="mainnet" - fi - cd /opt/tn - if [ "$RECONFIGURE" = true ]; then - [ -n "$PRIVATE_KEY" ] && { echo "Error: Cannot change key"; exit 1; } - [ -n "$NETWORK" ] && { echo "Error: Cannot change network"; exit 1; } - grep -q "TN_PRIVATE_KEY=" .env && EXISTING_KEY=$(grep "TN_PRIVATE_KEY=" .env | cut -d'=' -f2) - grep -q "CHAIN_ID=" .env && CHAIN_ID=$(grep "CHAIN_ID=" .env | cut -d'=' -f2) - grep -q "NETWORK_TYPE=" .env && NETWORK_TYPE=$(grep "NETWORK_TYPE=" .env | cut -d'=' -f2) - sudo systemctl stop tn-node || true - sudo -u tn docker compose down || true - fi - cat > .env << ENVEOF - CHAIN_ID=$CHAIN_ID - NETWORK_TYPE=$NETWORK_TYPE - ENVEOF - [ "$ENABLE_MCP" = true ] && echo "COMPOSE_PROFILES=mcp" >> .env - if [ "$RECONFIGURE" = false ] && [ -n "$PRIVATE_KEY" ]; then - echo "TN_PRIVATE_KEY=$PRIVATE_KEY" >> .env - elif [ "$RECONFIGURE" = true ] && [ -n "$EXISTING_KEY" ]; then - echo "TN_PRIVATE_KEY=$EXISTING_KEY" >> .env - fi - sudo chown tn:tn .env - sudo chmod 600 .env - sudo systemctl daemon-reload - sudo systemctl enable tn-node - sudo systemctl start tn-node - MAX_WAIT=60 - ELAPSED=0 - while [ $ELAPSED -lt $MAX_WAIT ]; do - sudo -u tn docker compose ps --status running 2>/dev/null | grep -q tn-node && break - sleep 2 - ELAPSED=$((ELAPSED + 2)) - done - echo "Done. Status: $(sudo systemctl is-active tn-node)" - [ "$ENABLE_MCP" = true ] && echo "MCP: http://$(curl -s --max-time 2 http://169.254.169.254/latest/meta-data/public-ipv4 || echo localhost):8000/sse" - EOF + echo "` + encode(tnNodeConfigureScript) + `" | base64 -d | sudo tee /usr/local/bin/tn-node-configure > /dev/null - sudo chmod +x /usr/local/bin/tn-node-configure - name: CreateUpdateScript @@ -308,25 +320,12 @@ phases: inputs: commands: - | - sudo tee /usr/local/bin/tn-node-update > /dev/null << 'EOF' - #!/bin/bash - set -e - cd /opt/tn - sudo -u tn docker compose pull - sudo -u tn docker compose up -d --force-recreate - echo "Updated: $(sudo systemctl is-active tn-node)" - EOF + echo "` + encode(tnNodeUpdateScript) + `" | base64 -d | sudo tee /usr/local/bin/tn-node-update > /dev/null - sudo chmod +x /usr/local/bin/tn-node-update - - - name: PrepareServices - action: ExecuteBash - inputs: - commands: - - sudo systemctl daemon-reload `), }) - // Component 2: Welcome messages (split to stay under 16KB limit) + // Component 3: Welcome messages (split to stay under 16KB limit) welcomeComponent := awsimagebuilder.NewCfnComponent(stack, jsii.String("TNWelcomeComponent"), &awsimagebuilder.CfnComponentProps{ Name: jsii.String(nameWithPrefix("tn-welcome-setup-" + string(stage))), Platform: jsii.String("Linux"), @@ -367,8 +366,8 @@ phases: After configuration, your node will start automatically and begin syncing! - 📦 To update to the latest software: - sudo tn-node-update + 📦 To install a node release, pass its tag from https://github.com/trufnetwork/node/releases: + sudo tn-node-update 🔒 Security Group Ports: - Port 6600 (P2P): Recommended for two-way peer connections @@ -408,8 +407,8 @@ phases: echo "" echo "After configuration, your node will start automatically and begin syncing!" echo "" - echo "📦 To update to the latest software:" - echo "sudo tn-node-update" + echo "📦 To install a node release, pass its tag from https://github.com/trufnetwork/node/releases:" + echo "sudo tn-node-update " echo "" echo "🔒 Security Group Ports:" echo "- Port 6600 (P2P): Recommended for two-way peer connections" @@ -441,6 +440,9 @@ phases: { ComponentArn: configComponent.AttrArn(), }, + { + ComponentArn: commandsComponent.AttrArn(), + }, { ComponentArn: welcomeComponent.AttrArn(), }, @@ -502,15 +504,16 @@ phases: }) exports := AmiPipelineStackExports{ - PipelineArn: *imagePipeline.AttrArn(), - DockerComponentArn: *dockerComponent.AttrArn(), - ConfigComponentArn: *configComponent.AttrArn(), - WelcomeComponentArn: *welcomeComponent.AttrArn(), - RecipeArn: *imageRecipe.AttrArn(), - InfraConfigArn: *infraConfig.AttrArn(), - DistributionArn: *distributionConfig.AttrArn(), - S3BucketName: *artifactsBucket.BucketName(), - InstanceProfileArn: *instanceProfile.AttrArn(), + PipelineArn: *imagePipeline.AttrArn(), + DockerComponentArn: *dockerComponent.AttrArn(), + ConfigComponentArn: *configComponent.AttrArn(), + CommandsComponentArn: *commandsComponent.AttrArn(), + WelcomeComponentArn: *welcomeComponent.AttrArn(), + RecipeArn: *imageRecipe.AttrArn(), + InfraConfigArn: *infraConfig.AttrArn(), + DistributionArn: *distributionConfig.AttrArn(), + S3BucketName: *artifactsBucket.BucketName(), + InstanceProfileArn: *instanceProfile.AttrArn(), } return stack, exports diff --git a/deployments/infra/stacks/ami_pipeline_stack_test.go b/deployments/infra/stacks/ami_pipeline_stack_test.go new file mode 100644 index 00000000..b6111bc9 --- /dev/null +++ b/deployments/infra/stacks/ami_pipeline_stack_test.go @@ -0,0 +1,300 @@ +package stacks + +import ( + "encoding/base64" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/aws/aws-cdk-go/awscdk/v2" + "github.com/aws/aws-cdk-go/awscdk/v2/assertions" + "github.com/aws/jsii-runtime-go" + "gopkg.in/yaml.v3" +) + +func TestValidateNodeTag(t *testing.T) { + for _, tag := range []string{"v2.6.8", "2.6.8", "v2.7.0-rc.1", "sha-9b23167"} { + if err := validateNodeTag(tag); err != nil { + t.Errorf("validateNodeTag(%q) = %v, want nil", tag, err) + } + } + for _, tag := range []string{"", "latest", "-v2.6.8", ".v2", "v2.6.8; reboot", "v2.6.8\n", "a b", "a/b", strings.Repeat("a", 129)} { + if err := validateNodeTag(tag); err == nil { + t.Errorf("validateNodeTag(%q) = nil, want an error", tag) + } + } +} + +// The AMI's node services run the release in TN_NODE_TAG, with no fallback. +func TestComposeTemplateRunsNodeTag(t *testing.T) { + var compose struct { + Services map[string]struct { + Image string `yaml:"image"` + } `yaml:"services"` + } + if err := yaml.Unmarshal([]byte(dockerComposeTemplate), &compose); err != nil { + t.Fatal(err) + } + const want = "ghcr.io/trufnetwork/node:${TN_NODE_TAG:?run tn-node-update to set it in /opt/tn/.env}" + for _, name := range []string{"tn-postgres-roles", "tn-node"} { + if got := compose.Services[name].Image; got != want { + t.Errorf("service %s runs %q, want %q", name, got, want) + } + } + + if exec.Command("docker", "compose", "version").Run() != nil { + t.Log("docker compose is not installed; skipping the interpolation check") + return + } + dir := t.TempDir() + writeFile(t, filepath.Join(dir, "docker-compose.yml"), dockerComposeTemplate, 0o644) + images := func(env string) (string, error) { + writeFile(t, filepath.Join(dir, ".env"), env, 0o600) + cmd := exec.Command("docker", "compose", "config", "--images") + cmd.Dir = dir + cmd.Env = withoutNodeTag(os.Environ()) + out, err := cmd.CombinedOutput() + return string(out), err + } + out, err := images("TN_NODE_TAG=v2.6.8\nCHAIN_ID=tn-v2.1\nNETWORK_TYPE=mainnet\n") + if err != nil || strings.Count(out, "ghcr.io/trufnetwork/node:v2.6.8\n") != 2 { + t.Errorf("with TN_NODE_TAG=v2.6.8 in .env, docker compose config --images: %v\n%s", err, out) + } + out, err = images("CHAIN_ID=tn-v2.1\nNETWORK_TYPE=mainnet\n") + if err == nil || !strings.Contains(out, "required variable TN_NODE_TAG is missing a value") { + t.Errorf("with no TN_NODE_TAG in .env, docker compose config should fail, got: %v\n%s", err, out) + } +} + +// The AMI components write the node tag, the compose file and the two +// commands, and each stays under Image Builder's limit on component data. +func TestAMIComponents(t *testing.T) { + ctx := map[string]interface{}{"stage": "dev", contextNodeTag: "v2.6.8"} + app := awscdk.NewApp(&awscdk.AppProps{Context: &ctx}) + stack, _ := AmiPipelineStack(app, "AmiTest", &AmiPipelineStackProps{}) + + data := map[string]string{} // component name to its data + components := *assertions.Template_FromStack(stack, nil).FindResources(jsii.String("AWS::ImageBuilder::Component"), nil) + for _, c := range components { + props := (*c)["Properties"].(map[string]interface{}) + name, _ := props["Name"].(string) + d, _ := props["Data"].(string) + data[name] = d + t.Logf("component %s has %d characters of data", name, len(d)) + if len(d) > 16000 { + t.Errorf("component %s has %d characters of data, Image Builder takes at most 16000", name, len(d)) + } + } + + if !strings.Contains(data["tn-config-setup-dev"], `echo "v2.6.8" | sudo tee /opt/tn/ami-node-tag > /dev/null`) { + t.Error("tn-config-setup-dev does not write the node tag to /opt/tn/ami-node-tag") + } + for _, f := range []struct{ component, path, content string }{ + {"tn-config-setup-dev", "/opt/tn/docker-compose.yml", dockerComposeTemplate}, + {"tn-commands-setup-dev", "/usr/local/bin/tn-node-configure", tnNodeConfigureScript}, + {"tn-commands-setup-dev", "/usr/local/bin/tn-node-update", tnNodeUpdateScript}, + } { + m := regexp.MustCompile(`echo "([A-Za-z0-9+/=]+)" \| base64 -d[^\n]*` + regexp.QuoteMeta(f.path)).FindStringSubmatch(data[f.component]) + if m == nil { + t.Errorf("%s does not write %s", f.component, f.path) + continue + } + if got, err := base64.StdEncoding.DecodeString(m[1]); err != nil || string(got) != f.content { + t.Errorf("%s writes %s with other content (decode error: %v)", f.component, f.path, err) + } + } +} + +// fakeHost is an AMI's /opt/tn with fake sudo, docker, systemctl, chown and curl. +type fakeHost struct { + dir, bin, log string +} + +func newFakeHost(t *testing.T) *fakeHost { + t.Helper() + h := &fakeHost{dir: t.TempDir(), bin: t.TempDir()} + h.log = filepath.Join(h.bin, "docker.log") + writeFile(t, filepath.Join(h.dir, "ami-node-tag"), "v2.6.8\n", 0o644) + fakes := map[string]string{ + // runs the command as the current user + "sudo": `if [ "$1" = -u ]; then shift 2; fi; exec "$@"`, + // records each call with the TN_NODE_TAG it gets from the environment and from .env + "docker": `echo "$* | env=${TN_NODE_TAG-} .env=$(grep '^TN_NODE_TAG=' "$TN_DIR/.env" 2>/dev/null | cut -d= -f2)" >> "$FAKE_LOG" +case "$*" in + "compose pull"*) exit "${FAKE_PULL_EXIT:-0}" ;; + "compose ps"*) echo tn-node ;; +esac`, + "systemctl": `[ "$1" = is-active ] && echo active; exit 0`, + "chown": `exit 0`, + "curl": `echo 203.0.113.7`, + } + for name, body := range fakes { + writeFile(t, filepath.Join(h.bin, name), "#!/bin/bash\n"+body+"\n", 0o755) + } + return h +} + +// run runs a script as root would on the AMI, and returns its output and the +// docker calls it made. +func (h *fakeHost) run(t *testing.T, script string, env []string, args ...string) (string, []string, error) { + t.Helper() + path := filepath.Join(h.bin, "script.sh") + writeFile(t, path, script, 0o755) + _ = os.Remove(h.log) + cmd := exec.Command("bash", append([]string{path}, args...)...) + cmd.Env = append(withoutNodeTag(os.Environ()), + "PATH="+h.bin+string(os.PathListSeparator)+os.Getenv("PATH"), + "TN_DIR="+h.dir, "FAKE_LOG="+h.log) + cmd.Env = append(cmd.Env, env...) + out, err := cmd.CombinedOutput() + var calls []string + if raw, readErr := os.ReadFile(h.log); readErr == nil { + calls = strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") + } + return string(out), calls, err +} + +func (h *fakeHost) env(t *testing.T) string { + t.Helper() + raw, err := os.ReadFile(filepath.Join(h.dir, ".env")) + if err != nil { + t.Fatal(err) + } + return string(raw) +} + +func TestNodeUpdateScript(t *testing.T) { + const configured = "CHAIN_ID=tn-v2.1\nTN_NODE_TAG=v2.6.8\nNETWORK_TYPE=mainnet\nTN_PRIVATE_KEY=1111\n" + cases := []struct { + name string + env string // .env before the run; empty means no .env + args []string + pullErr bool + wantErr bool + calls []string + wantEnv string // .env after the run; empty means unchanged + }{ + { + name: "a new tag is pulled, then set, then run", + env: configured, args: []string{"v2.6.9"}, + calls: []string{ + "compose pull tn-postgres-roles tn-node | env=v2.6.9 .env=v2.6.8", + "compose up -d tn-node | env= .env=v2.6.9", + }, + wantEnv: "CHAIN_ID=tn-v2.1\nTN_NODE_TAG=v2.6.9\nNETWORK_TYPE=mainnet\nTN_PRIVATE_KEY=1111\n", + }, + { + name: "no tag keeps the current one", + env: configured, + calls: []string{ + "compose pull tn-postgres-roles tn-node | env=v2.6.8 .env=v2.6.8", + "compose up -d tn-node | env= .env=v2.6.8", + }, + }, + { + name: "a tag with no image leaves .env and the node alone", + env: configured, args: []string{"v9.9.9"}, pullErr: true, wantErr: true, + calls: []string{"compose pull tn-postgres-roles tn-node | env=v9.9.9 .env=v2.6.8"}, + }, + { + name: "a .env without a tag gets the one passed", + env: "CHAIN_ID=tn-v2.1\n", args: []string{"v2.6.9"}, + calls: []string{ + "compose pull tn-postgres-roles tn-node | env=v2.6.9 .env=", + "compose up -d tn-node | env= .env=v2.6.9", + }, + wantEnv: "CHAIN_ID=tn-v2.1\nTN_NODE_TAG=v2.6.9\n", + }, + {name: "a .env without a tag needs one passed", env: "CHAIN_ID=tn-v2.1\n", wantErr: true}, + {name: "latest is refused", env: configured, args: []string{"latest"}, wantErr: true}, + {name: "an empty tag is refused", env: configured, args: []string{""}, wantErr: true}, + {name: "a tag with a command in it is refused", env: configured, args: []string{"v2.6.9;reboot"}, wantErr: true}, + {name: "a tag that reads as a flag is refused", env: configured, args: []string{"--force"}, wantErr: true}, + {name: "two arguments are refused", env: configured, args: []string{"v2.6.9", "v2.6.10"}, wantErr: true}, + {name: "a node that is not configured is refused", args: []string{"v2.6.9"}, wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := newFakeHost(t) + if tc.env != "" { + writeFile(t, filepath.Join(h.dir, ".env"), tc.env, 0o600) + } + var env []string + if tc.pullErr { + env = append(env, "FAKE_PULL_EXIT=1") + } + out, calls, err := h.run(t, tnNodeUpdateScript, env, tc.args...) + if (err != nil) != tc.wantErr { + t.Fatalf("error = %v, want error %v; output:\n%s", err, tc.wantErr, out) + } + if strings.Join(calls, "\n") != strings.Join(tc.calls, "\n") { + t.Errorf("docker calls:\n%s\nwant:\n%s", strings.Join(calls, "\n"), strings.Join(tc.calls, "\n")) + } + if tc.env == "" { + return + } + want := tc.wantEnv + if want == "" { + want = tc.env + } + if got := h.env(t); got != want { + t.Errorf(".env after the run:\n%s\nwant:\n%s", got, want) + } + if info, err := os.Stat(filepath.Join(h.dir, ".env")); err != nil || info.Mode().Perm() != 0o600 { + t.Errorf(".env mode: %v, %v; want 0600", info.Mode().Perm(), err) + } + }) + } +} + +// tn-node-configure sets the AMI's release, and a reconfigure keeps the release +// tn-node-update set. +func TestNodeConfigureScriptKeepsNodeTag(t *testing.T) { + h := newFakeHost(t) + key := strings.Repeat("1", 64) + + if out, _, err := h.run(t, tnNodeConfigureScript, nil, "--private-key", key); err != nil { + t.Fatalf("configure: %v\n%s", err, out) + } + if got, want := h.env(t), "TN_NODE_TAG=v2.6.8\nCHAIN_ID=tn-v2.1\nNETWORK_TYPE=mainnet\nTN_PRIVATE_KEY="+key+"\n"; got != want { + t.Fatalf(".env after configure:\n%s\nwant:\n%s", got, want) + } + + if out, _, err := h.run(t, tnNodeUpdateScript, nil, "v2.6.9"); err != nil { + t.Fatalf("update: %v\n%s", err, out) + } + out, _, err := h.run(t, tnNodeConfigureScript, nil, "--enable-mcp") + if err != nil { + t.Fatalf("reconfigure: %v\n%s", err, out) + } + if got, want := h.env(t), "TN_NODE_TAG=v2.6.9\nCHAIN_ID=tn-v2.1\nNETWORK_TYPE=mainnet\nCOMPOSE_PROFILES=mcp\nTN_PRIVATE_KEY="+key+"\n"; got != want { + t.Errorf(".env after reconfigure:\n%s\nwant:\n%s", got, want) + } + if !strings.Contains(out, "MCP: http://203.0.113.7:8000/sse") { + t.Errorf("reconfigure output has no MCP address:\n%s", out) + } +} + +func writeFile(t *testing.T, path, content string, mode os.FileMode) { + t.Helper() + if err := os.WriteFile(path, []byte(content), mode); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, mode); err != nil { + t.Fatal(err) + } +} + +// withoutNodeTag drops TN_NODE_TAG, which would override .env for compose. +func withoutNodeTag(env []string) []string { + var out []string + for _, kv := range env { + if !strings.HasPrefix(kv, "TN_NODE_TAG=") { + out = append(out, kv) + } + } + return out +} diff --git a/deployments/infra/stacks/docker-compose.template.yml b/deployments/infra/stacks/docker-compose.template.yml index 7a484417..01d99207 100644 --- a/deployments/infra/stacks/docker-compose.template.yml +++ b/deployments/infra/stacks/docker-compose.template.yml @@ -21,8 +21,10 @@ services: # Sets up the Postgres roles the node connects as. It runs before the node on # every start and is safe to run again. A new database takes TCP connections # only once the image has set it up, so it waits for that first. + # TN_NODE_TAG, the node release, comes from /opt/tn/.env. tn-node-configure + # writes the release the AMI was built with, and tn-node-update changes it. tn-postgres-roles: - image: ghcr.io/trufnetwork/node:latest + image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:?run tn-node-update to set it in /opt/tn/.env} container_name: tn-postgres-roles entrypoint: ["sh", "-c", "for i in $$(seq 60); do pg_isready --host=tn-postgres --username=postgres --quiet && break; sleep 1; done; exec psql --host=tn-postgres --username=postgres --no-psqlrc --set=ON_ERROR_STOP=1 --file=/app/postgres-roles.sql"] depends_on: @@ -33,7 +35,7 @@ services: restart: "no" tn-node: - image: ghcr.io/trufnetwork/node:latest + image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:?run tn-node-update to set it in /opt/tn/.env} container_name: tn-node entrypoint: "" env_file: diff --git a/docs/ami-deployment-guide.md b/docs/ami-deployment-guide.md index 7a5b5b01..d68739a5 100644 --- a/docs/ami-deployment-guide.md +++ b/docs/ami-deployment-guide.md @@ -260,20 +260,48 @@ sudo systemctl status tn-node ### Updates +The node runs the release in `TN_NODE_TAG` in `/opt/tn/.env`. A new node runs the release the AMI was built with. To install another release, pass its tag from the [release page](https://github.com/trufnetwork/node/releases): + ```bash -# Update to latest Docker images +# Run release v2.6.9: set TN_NODE_TAG, pull the image and recreate the node containers +sudo tn-node-update v2.6.9 + +# Without a tag, pull the release the node runs now sudo tn-node-update -# Manual update process -cd /opt/tn -sudo -u tn docker compose pull -sudo -u tn docker compose up -d --force-recreate +# The release set in .env (the file is readable by the tn user only) +sudo grep TN_NODE_TAG /opt/tn/.env + +# The image and release the running node container uses +docker inspect --format '{{ .Config.Image }} {{ index .Config.Labels "org.opencontainers.image.version" }}' tn-node # Check status after update sudo systemctl status tn-node docker ps ``` +`tn-node-update` pulls the image before it changes `.env`, so a tag that has no image leaves the node as it was. Postgres and the MCP server keep running, and the node restarts only when its image or configuration changed. When a release is required by a block, install it before that block; see [Required In-Place Upgrade](node-upgrade-guide.md#required-in-place-upgrade). + +#### Nodes From an Older AMI + +An AMI built before `tn-node-update` took a tag has no `/opt/tn/ami-node-tag` file. Its compose file names a fixed node image tag, `latest` on most builds, and its update command takes no tag: it pulls every image in the compose file, Postgres included, and recreates the containers. That command is `tn-node-update`, or `update-node` on the earliest builds. To make such a node run a release tag, change it once. This keeps `.env`, the node key and the data: + +```bash +cd /opt/tn +# 1. The release to run, here v2.6.9 +echo 'TN_NODE_TAG=v2.6.9' | sudo tee -a .env > /dev/null +# 2. Pull it; if the tag has no image, stop here and fix the tag in .env +sudo -u tn docker pull ghcr.io/trufnetwork/node:v2.6.9 +# 3. Read the node image from TN_NODE_TAG instead of latest +sudo sed -i 's|\(image: ghcr.io/trufnetwork/node:\).*|\1${TN_NODE_TAG:?set TN_NODE_TAG in /opt/tn/.env}|' docker-compose.yml +# 4. Recreate the node containers; Postgres and the MCP server keep running +sudo -u tn docker compose up -d tn-node +``` + +To move such a node to another release later, change the tag in `.env` (`sudo sed -i 's/^TN_NODE_TAG=.*/TN_NODE_TAG=v2.7.0/' /opt/tn/.env`), then repeat steps 2 and 4 with that tag. Do not run its old update command. Its `tn-node-configure` rewrites `.env` without `TN_NODE_TAG`; if you run it, add the line back, or the node does not start. + +If its `docker-compose.yml` has no `tn-postgres-roles` service, the node connects to Postgres as a `kwild` role that is a superuser, and these steps leave that as it is. To move it off that role, see [Moving an Existing Node Off the Superuser Role](node-operator-guide.md#moving-an-existing-node-off-the-superuser-role). + ## Troubleshooting ### Common Issues diff --git a/docs/aws-deployment-guide.md b/docs/aws-deployment-guide.md index 5f0f4098..894e6899 100644 --- a/docs/aws-deployment-guide.md +++ b/docs/aws-deployment-guide.md @@ -519,10 +519,10 @@ sudo apt update && sudo apt upgrade -y **If using AMI deployment**: ```bash -# Update Docker images -sudo tn-node-update -# Or manually: cd /opt/tn && sudo -u tn docker compose pull && sudo systemctl restart tn-node +# Install a node release by its tag from https://github.com/trufnetwork/node/releases +sudo tn-node-update v2.6.9 ``` +See [Updates](ami-deployment-guide.md#updates) in the AMI guide. **If using manual setup**: ```bash diff --git a/docs/container-image-guide.md b/docs/container-image-guide.md index 858e51a8..17050247 100644 --- a/docs/container-image-guide.md +++ b/docs/container-image-guide.md @@ -42,7 +42,7 @@ services: # creates the Postgres roles the node connects as. It runs before the node on every start, # once Postgres takes TCP connections postgres-roles: - image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:-latest} + image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:?set TN_NODE_TAG in .env to a release tag} entrypoint: ["sh", "-c", "for i in $$(seq 60); do pg_isready --host=postgres --username=postgres --quiet && break; sleep 1; done; exec psql --host=postgres --username=postgres --no-psqlrc --set=ON_ERROR_STOP=1 --file=/app/postgres-roles.sql"] restart: "no" depends_on: @@ -50,7 +50,7 @@ services: condition: service_healthy tn-node: - image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:-latest} + image: ghcr.io/trufnetwork/node:${TN_NODE_TAG:?set TN_NODE_TAG in .env to a release tag} restart: unless-stopped depends_on: postgres: @@ -72,10 +72,10 @@ services: -Compose automatically loads variables from a `.env` file in the same directory. At a minimum set the node image tag you want to run (for example the latest release) and optionally pre-fill auto-setup values: +Compose automatically loads variables from a `.env` file in the same directory. Set `TN_NODE_TAG` to the release you want to run, a tag from the [release page](https://github.com/trufnetwork/node/releases). The stack does not start without it. Each release image is tagged with and without the leading `v` (`v2.6.8` and `2.6.8`). Optionally pre-fill auto-setup values: ```dotenv -TN_NODE_TAG=v0.15.0 +TN_NODE_TAG=v2.6.8 SETUP_CHAIN_ID=truflation-dev # Leave empty to let the container derive the owner from the generated node key SETUP_DB_OWNER= @@ -127,4 +127,5 @@ For throwaway networks you can skip the steps above. Leave `SETUP_DB_OWNER` blan ## Maintenance tips - Back up the `~/truf-node/tn_data` directory; it contains the node identity, admin certificates, and blockstore. - To rotate configuration, stop the stack, edit files under `~/truf-node/tn_data`, then start the stack again. The entrypoint leaves existing files untouched. +- To upgrade, set `TN_NODE_TAG` in `.env` to the new release, then run `docker compose pull tn-node postgres-roles` and `docker compose up -d`. Compose recreates the containers whose image changed. When a release is required by a block, upgrade before that block; see [Required In-Place Upgrade](node-upgrade-guide.md#required-in-place-upgrade). - Testing a new image? Set `TN_NODE_TAG` to the candidate tag and point the compose stack at a fresh host directory so you can diff auto-generated config before promoting it to production. diff --git a/docs/node-upgrade-guide.md b/docs/node-upgrade-guide.md index fa641107..f2c58360 100644 --- a/docs/node-upgrade-guide.md +++ b/docs/node-upgrade-guide.md @@ -1,7 +1,26 @@ # Node Upgrade Guide Keeping your node up-to-date ensures you benefit from the latest performance improvements, bug-fixes, and security patches. -This page describes the **most common upgrade path – an in-place binary upgrade that does *not* change consensus rules** (i.e. no schema or protocol breaking changes). +This page describes the **most common upgrade path – an in-place upgrade**: you replace the binary or the image and keep your data. A release that changes how blocks run from some block on is required by that block; see [Required In-Place Upgrade](#required-in-place-upgrade). A network migration to a new genesis is covered under [Breaking Changes & Migrations](#breaking-changes--migrations). + +--- + +## Is the Upgrade Required? + +Each release page opens with one line that says whether your node must install the release: + +```text +Upgrade: optional. +Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), required on testnet from block 16300000 (about 2026-12-03 12:00 UTC). +Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), optional on testnet. +Upgrade: optional on mainnet, required on testnet from block 16300000 (about 2026-12-03 12:00 UTC). +``` + +The blocks and times above are examples. `optional` means a node on the release before keeps following the chain. `required ... from block N` means your node must run this release, or a later one, before that network reaches block `N`. The time is an estimate from the block rate; the block is what counts. + +A release that is required on mainnet is published at least 7 days before its mainnet block. Releases up to v2.6.8 were published before this line, so their pages do not carry it. + +Release notices go out on the [release page](https://github.com/trufnetwork/node/releases). To get them, choose **Watch → Custom → Releases** on the [repository](https://github.com/trufnetwork/node), or follow the feed at . --- @@ -34,17 +53,17 @@ If you manage `kwild` with another init system or inside Docker Compose, use the ## 3. Install the Latest `kwild` Binary -1. **Download** – grab the newest release from GitHub: +1. **Download** – grab the release you are installing from GitHub. `` is its version without the `v`, such as `2.6.9`: ```bash - curl -L "https://github.com/trufnetwork/node/releases/latest/download/tn__linux_amd64.tar.gz" \ + curl -L "https://github.com/trufnetwork/node/releases/download/v/tn__linux_amd64.tar.gz" \ -o kwild.tgz tar -xzf kwild.tgz kwild ``` Note: This extracts the `kwild` binary to your current directory. - Or, **build from source** in your clone: + Or, **build from source** in your clone, at the release tag: ```bash - git pull && task build + git fetch --tags && git checkout v && task build ``` Note: This builds the binary to `.build/kwild` in your repository directory. @@ -217,6 +236,55 @@ kwild blacklist list ``` --- +## Required In-Place Upgrade + +A required release changes how blocks run from the block its release page names. It runs every block before that one the same way as the release before it, so you can install it at any time before the block. A node that still runs an older release when the network reaches the block stops there; see [If Your Node Stopped at a Block](#if-your-node-stopped-at-a-block). + +1. Read the first line of the release page, for example: + ```text + Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), optional on testnet. + ``` + A mainnet node must run this release, or a later one, before mainnet reaches block 3300000. On testnet the release is optional. +2. Check how far your node is from that block: + ```bash + curl -s http://127.0.0.1:8484/api/v1/health | jq '.services.user.block_height' + ``` +3. Install the release before the block: + * **Binary** (for example with systemd): follow steps 1 to 5 above with the release's version. + * **Docker Compose**, as in the [Container Image Guide](container-image-guide.md): set `TN_NODE_TAG` in `.env` to the release tag, such as `v2.6.9`, then run: + ```bash + docker compose pull tn-node postgres-roles + docker compose up -d + ``` + * **AMI**: run `sudo tn-node-update v2.6.9` with the release tag. See [Updates](ami-deployment-guide.md#updates) in the AMI guide. A node built from an older AMI, one with no `/opt/tn/ami-node-tag` file, has an update command that takes no tag; follow [Nodes From an Older AMI](ami-deployment-guide.md#nodes-from-an-older-ami) instead. +4. Check that your node reports the release, as in [Check the version](#3-install-the-latest-kwild-binary), and that its height keeps advancing. + +### If Your Node Stopped at a Block + +A node that runs an older release stops at the first block it computes differently from the network. `kwild` logs: + +```text +processAndCommit: AppHash mismatch, halting the node. expected: , received: +``` + +When the node halts while following the chain, this text is the `reason` of the log line `Received halt signal, stopping the consensus engine`. When it halts while catching up, for example after a restart, the text is part of the error `kwild` stops with, such as `failed to apply block at height: : error: processAndCommit: AppHash mismatch, halting the node. ...`. A validator that ran the block as a proposal logs `Incorrect AppHash, halting the node. received: , computed: ` instead. + +The node does not commit that block. Its writes stay in Postgres transactions that `kwild` rolls back when it stops or starts, the block is not stored, and the node stays at the block before it. Started again on the same release, it applies the block again and stops at the same place, so `Restart=always` or `restart: unless-stopped` only repeats the stop. + +To recover: + +1. On the [release page](https://github.com/trufnetwork/node/releases), find the release that is required from that block on. +2. Install it as in step 3 of [Required In-Place Upgrade](#required-in-place-upgrade). +3. Start the node, if the install step did not. It applies the block again with the new release and continues from there. You do not need to reset the node or restore a snapshot. +4. Check that the height passes the block: + ```bash + curl -s http://127.0.0.1:8484/api/v1/health | jq '.services.user.block_height' + ``` + +If the node stops at the same block while `kwild version` prints the required release, reach out on Discord or open a GitHub issue with the log lines. + +--- + ## What About PostgreSQL & Other Components? *Minor* Kwil releases do **not** require a database upgrade. @@ -256,7 +324,7 @@ note: When the network requires a fork due to consensus changes or critical issues, you'll need to reset your node with a new genesis file. **Prerequisites:** -- Check official announcements for specific migration instructions +- Read the [release page](https://github.com/trufnetwork/node/releases) of the release that moves the network: it gives the migration instructions - Ensure you have the latest `truf-node-operator` repository (`git pull`) **Recovery Steps:** @@ -275,7 +343,7 @@ See: * [Migrations overview](https://docs.kwil.com/docs/node/migrations) * [Zero-downtime migrations guide](https://docs.kwil.com/docs/node/migrations/zero-downtime-migrations) -If your target version mentions a *migration required* flag in the release notes, **contact the TRUF.NETWORK team before proceeding**. +If the release page of your target version says it needs a network migration, **contact the TRUF.NETWORK team before proceeding**. --- diff --git a/docs/release-process.md b/docs/release-process.md new file mode 100644 index 00000000..5ed3b31c --- /dev/null +++ b/docs/release-process.md @@ -0,0 +1,81 @@ +# Release Process + +This page is for maintainers who publish a TN node release. Node operators read the result on the release page, and the [Node Upgrade Guide](node-upgrade-guide.md#is-the-upgrade-required) explains it to them. + +## The Upgrade Line + +The release notes open with one line that says whether node operators must install the release. `release.yaml` and `publish-node-image.yaml` check that line before they build anything. A release without it gets no binaries and no image, and the `latest` image tag does not move. + +The line is exactly one of these four forms: + +- Optional on both networks: + ```text + Upgrade: optional. + ``` +- Required on both networks: + ```text + Upgrade: required on mainnet from block (about UTC), required on testnet from block (about UTC). + ``` +- Required on mainnet only: + ```text + Upgrade: required on mainnet from block (about UTC), optional on testnet. + ``` +- Required on testnet only: + ```text + Upgrade: optional on mainnet, required on testnet from block (about UTC). + ``` + +For example: + +```text +Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), required on testnet from block 16300000 (about 2026-12-03 12:00 UTC). +``` + +The check is strict: + +- The line is the first line of the notes, with no heading, blank line or formatting before or around it. The generated "What's Changed" list starts on the next line. +- Mainnet comes first, then testnet. +- A block is a whole number with no separators and no leading zero. +- The time is in UTC, written `YYYY-MM-DD HH:MM`. It is an estimate from the block rate; the block is what counts. +- A Windows line end (`\r\n`), which GitHub's editor can save, is accepted. Anything else around the line is not. + +To check notes before you publish them: + +```bash +scripts/release/check-upgrade-line.sh < notes.md +``` + +`scripts/release/test-check-upgrade-line.sh` tests the check against every form and a list of near misses. CI runs it. + +## Optional or Required + +A release is required on a network when a node that still runs the release before it would compute a different app hash for a block that network will produce. For example, the release: + +- changes how blocks, transactions or actions run from a block height or a network parameter on, or +- adds a method that an action or a migration on that network will call. + +A release that changes nothing a block computes, such as tooling, documentation or a fix outside block execution, is optional. + +A required release must run every block before its block the same way as the release before it, so that operators can install it at any time before the block. + +## Notice for a Required Release + +- Publish a required release at least 7 days before its mainnet block, and state its testnet block on the same line. +- Pick each block from the measured block rate, as in [Pick the activation height](maa-rollout.md#pick-the-activation-height), and round the time. +- A migration that needs the new release, for example one whose actions call a method only that release has, is applied on a network only after the release's block on that network. +- Where the change waits on an on-chain network parameter that the release adds, as `maa_exec` waits on `maa_activation_height`, the release's block is the earliest block in which the resolution that sets the parameter may pass, not the height that resolution sets. A node on an older release cannot read the parameter and halts once that resolution passes, whatever height it sets (see [Failure modes and rollback](maa-rollout.md#failure-modes-and-rollback)). If operators need more time, hold the resolution back and edit the release notes to the new block and time. After the resolution has passed, a follow-up resolution can still move the activation height later (see [Re-scheduling](maa-rollout.md#re-scheduling)), but that only delays the change on upgraded nodes and gives no more time to a node on an older release. +- A height written into the code moves only with a new release. + +## Where Release Notices Go Out + +Release notices go out on the [release page](https://github.com/trufnetwork/node/releases). Operators get them by choosing **Watch → Custom → Releases** on this repository, or from the feed at . + +## Publishing a Release + +1. Draft the release from its tag, generate the notes, and put the upgrade line first. +2. Check the notes with `scripts/release/check-upgrade-line.sh`. +3. Publish. `release.yaml` builds the four `kwild` tarballs and uploads them to the release. `publish-node-image.yaml` pushes the image as `v`, ``, `sha-` and `latest`. +4. If the line was missing or wrong, both workflows fail before they build. Edit the release to fix the line. `release.yaml` runs again on the edit and uploads the binaries. `publish-node-image.yaml` runs only when a release is published, so run **Publish Node Image** by hand on the release tag with **Also tag this build as latest**. A manual run has no release notes to read, so it skips the check. +5. After a required release, run **Build AMI** so that nodes launched from the AMI start on it. + +Every edit of the release notes runs `release.yaml` again, which builds and uploads the binaries again. diff --git a/scripts/release/check-upgrade-line.sh b/scripts/release/check-upgrade-line.sh new file mode 100755 index 00000000..aca8cd59 --- /dev/null +++ b/scripts/release/check-upgrade-line.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Checks that a release body, read from stdin, opens with the upgrade line. +# The forms are in docs/release-process.md: +# +# Upgrade: optional. +# Upgrade: required on mainnet from block (about UTC), required on testnet from block (about UTC). +# Upgrade: required on mainnet from block (about UTC), optional on testnet. +# Upgrade: optional on mainnet, required on testnet from block (about UTC). +# +# Usage: scripts/release/check-upgrade-line.sh < release-notes.md +set -euo pipefail + +block='[1-9][0-9]*' +time='[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) ([01][0-9]|2[0-3]):[0-5][0-9] UTC' +required() { printf 'required on %s from block %s \\(about %s\\)' "$1" "$block" "$time"; } +optional() { printf 'optional on %s' "$1"; } + +forms=( + 'Upgrade: optional\.' + "Upgrade: $(required mainnet), $(required testnet)\\." + "Upgrade: $(required mainnet), $(optional testnet)\\." + "Upgrade: $(optional mainnet), $(required testnet)\\." +) + +line='' +IFS= read -r line || true +# GitHub's release editor saves CRLF line ends. +line=${line%$'\r'} + +for form in "${forms[@]}"; do + if [[ $line =~ ^${form}$ ]]; then + echo "Upgrade line: $line" + exit 0 + fi +done + +error() { + if [ "${GITHUB_ACTIONS:-}" = true ]; then + echo "::error::$1" >&2 + else + echo "error: $1" >&2 + fi +} + +if [ -z "$line" ]; then + error "the release body must open with the upgrade line, but its first line is empty" +else + # Shown for the reader; control characters are replaced so the line prints as one line. + error "the release body must open with the upgrade line, but its first line is: ${line//[[:cntrl:]]/?}" +fi +cat >&2 <<'EOF' +The first line must be exactly one of these, with your blocks and times: + Upgrade: optional. + Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), required on testnet from block 16300000 (about 2026-12-03 12:00 UTC). + Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), optional on testnet. + Upgrade: optional on mainnet, required on testnet from block 16300000 (about 2026-12-03 12:00 UTC). +See docs/release-process.md. +EOF +exit 1 diff --git a/scripts/release/test-check-upgrade-line.sh b/scripts/release/test-check-upgrade-line.sh new file mode 100755 index 00000000..d9b95484 --- /dev/null +++ b/scripts/release/test-check-upgrade-line.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Tests scripts/release/check-upgrade-line.sh against the forms in +# docs/release-process.md. Run: scripts/release/test-check-upgrade-line.sh +set -euo pipefail + +check="$(dirname "$0")/check-upgrade-line.sh" +failed=0 + +expect() { + local want=$1 name=$2 body=$3 got=accepted + printf '%s' "$body" | GITHUB_ACTIONS='' "$check" >/dev/null 2>&1 || got=rejected + if [ "$got" = "$want" ]; then + echo "ok $want: $name" + else + echo "FAIL want $want, got $got: $name" + failed=$((failed + 1)) + fi +} + +notes=$'\n## What\'s Changed\n* chore: an example change by @someone in https://github.com/trufnetwork/node/pull/1\n' +both='Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), required on testnet from block 16300000 (about 2026-12-03 12:00 UTC).' +mainnet='Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), optional on testnet.' +testnet='Upgrade: optional on mainnet, required on testnet from block 16300000 (about 2026-12-03 12:00 UTC).' + +expect accepted 'optional, alone' 'Upgrade: optional.' +expect accepted 'optional, with a trailing newline' $'Upgrade: optional.\n' +expect accepted 'optional, then the notes' "Upgrade: optional.$notes" +expect accepted 'optional, with CRLF line ends' $'Upgrade: optional.\r\n## What\'s Changed\r\n' +expect accepted 'required on both networks' "$both$notes" +expect accepted 'required on mainnet only' "$mainnet$notes" +expect accepted 'required on testnet only' "$testnet$notes" +expect accepted 'earliest valid time' 'Upgrade: optional on mainnet, required on testnet from block 1 (about 2026-01-01 00:00 UTC).' +expect accepted 'latest valid time' 'Upgrade: optional on mainnet, required on testnet from block 1 (about 2026-12-31 23:59 UTC).' + +expect rejected 'empty body' '' +expect rejected 'blank first line' $'\nUpgrade: optional.' +expect rejected 'generated notes only' "${notes#$'\n'}" +expect rejected 'line in the second line' "## Notes"$'\n''Upgrade: optional.' +expect rejected 'lower case' 'upgrade: optional.' +expect rejected 'capital Optional' 'Upgrade: Optional.' +expect rejected 'no full stop' 'Upgrade: optional' +expect rejected 'leading space' ' Upgrade: optional.' +expect rejected 'trailing space' 'Upgrade: optional. ' +expect rejected 'bold' '**Upgrade: optional.**' +expect rejected 'heading' '## Upgrade: optional.' +expect rejected 'text after the line' 'Upgrade: optional. Nothing to do.' +expect rejected 'optional, long form' 'Upgrade: optional on mainnet, optional on testnet.' +expect rejected 'required without blocks' 'Upgrade: required.' +expect rejected 'required on mainnet, testnet left out' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC).' +expect rejected 'testnet before mainnet' 'Upgrade: required on testnet from block 16300000 (about 2026-12-03 12:00 UTC), optional on mainnet.' +expect rejected 'second required left out' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), on testnet from block 16300000 (about 2026-12-03 12:00 UTC).' +expect rejected 'unknown network' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00 UTC), optional on devnet.' +expect rejected 'block with separators' 'Upgrade: required on mainnet from block 3,300,000 (about 2026-12-10 12:00 UTC), optional on testnet.' +expect rejected 'block with a leading zero' 'Upgrade: required on mainnet from block 03300000 (about 2026-12-10 12:00 UTC), optional on testnet.' +expect rejected 'block 0' 'Upgrade: required on mainnet from block 0 (about 2026-12-10 12:00 UTC), optional on testnet.' +expect rejected 'no block' 'Upgrade: required on mainnet from block (about 2026-12-10 12:00 UTC), optional on testnet.' +expect rejected 'no time' 'Upgrade: required on mainnet from block 3300000, optional on testnet.' +expect rejected 'time without about' 'Upgrade: required on mainnet from block 3300000 (2026-12-10 12:00 UTC), optional on testnet.' +expect rejected 'time without UTC' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00), optional on testnet.' +expect rejected 'ISO time' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10T12:00Z), optional on testnet.' +expect rejected 'time with seconds' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 12:00:00 UTC), optional on testnet.' +expect rejected 'month 13' 'Upgrade: required on mainnet from block 3300000 (about 2026-13-10 12:00 UTC), optional on testnet.' +expect rejected 'day 32' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-32 12:00 UTC), optional on testnet.' +expect rejected 'hour 24' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 24:00 UTC), optional on testnet.' +expect rejected 'one-digit hour' 'Upgrade: required on mainnet from block 3300000 (about 2026-12-10 9:00 UTC), optional on testnet.' + +if [ "$failed" -ne 0 ]; then + echo "$failed case(s) failed" + exit 1 +fi +echo "all cases passed" diff --git a/scripts/test-ami.sh b/scripts/test-ami.sh index 6a25050a..cabd39fc 100755 --- a/scripts/test-ami.sh +++ b/scripts/test-ami.sh @@ -38,7 +38,7 @@ TESTS_FAILED=0 # Test 1: CDK Synthesis echo "1. Testing CDK synthesis..." cd deployments/infra -if cdk --app 'go run ami-cdk.go' synth --context stage=dev --context devPrefix=test > /dev/null 2>&1; then +if cdk --app 'go run ami-cdk.go' synth --context stage=dev --context devPrefix=test --context nodeTag=v2.6.8 > /dev/null 2>&1; then echo -e "${GREEN}✅ CDK synthesis successful${NC}" TESTS_PASSED=$((TESTS_PASSED + 1)) else @@ -109,6 +109,7 @@ cp deployments/infra/stacks/docker-compose.template.yml /tmp/test-docker-compose # Create dummy .env file for validation (docker-compose expects it) cat > /tmp/.env << 'EOF' +TN_NODE_TAG=v2.6.8 CHAIN_ID=tn-v2.1 NETWORK_TYPE=mainnet EOF @@ -404,6 +405,7 @@ cp deployments/infra/stacks/docker-compose.template.yml /tmp/tn-test-compose.yml # Create .env file in same directory (docker-compose expects .env relative to compose file) cat > /tmp/.env << 'EOF' +TN_NODE_TAG=v2.6.8 CHAIN_ID=tn-v2.1 NETWORK_TYPE=mainnet EOF @@ -445,15 +447,15 @@ rm -f /tmp/tn-test-compose.yml /tmp/.env # Test 10: Update Script Workflow echo "10. Testing update script workflow..." -echo "Simulating the always-latest container update workflow..." +echo "Simulating the tagged container update workflow (go test ./stacks/ runs the real script)..." cat > /tmp/tn-update-test.sh << 'EOF' #!/bin/bash set -e -echo "🔄 Updating TrufNetwork node to latest version..." +echo "🔄 Updating TrufNetwork node to release v2.6.9..." -echo "📦 Pulling latest images..." +echo "📦 Pulling the release image..." # Detect Docker Compose command if docker compose version >/dev/null 2>&1; then COMPOSE="docker compose" @@ -465,15 +467,12 @@ else fi echo "✓ Using $COMPOSE" -echo "✓ Simulated pulling ghcr.io/trufnetwork/node:latest" -echo "✓ Simulated pulling ghcr.io/trufnetwork/kwil-postgres:16.8-1" -echo "✓ Simulated pulling ghcr.io/trufnetwork/postgres-mcp:latest" - -echo "🔄 Restarting services..." -echo "✓ Stopping existing containers" -echo "✓ Starting containers with latest images" -echo "✅ Services updated to latest version!" -echo "All containers are now running the latest images." +echo "✓ Simulated pulling ghcr.io/trufnetwork/node:v2.6.9" +echo "✓ Simulated setting TN_NODE_TAG=v2.6.9 in /opt/tn/.env" + +echo "🔄 Recreating the node containers..." +echo "✓ Postgres and MCP keep running" +echo "✅ tn-node runs ghcr.io/trufnetwork/node:v2.6.9" EOF chmod +x /tmp/tn-update-test.sh