name: Test Artifact

on:
  workflow_call:
    inputs:
      distro-slug:
        required: true
        type: string
        description: The OS slug to run tests against
      platform:
        required: true
        type: string
        description: The platform being tested
      arch:
        required: true
        type: string
        description: The platform arch being tested
      pkg-type:
        required: true
        type: string
        description: The platform arch being tested
      salt-version:
        type: string
        required: true
        description: The Salt version of the packages to install and test
      cache-prefix:
        required: true
        type: string
        description: Seed used to invalidate caches
      testing-releases:
        required: true
        type: string
        description: A JSON list of releases to test upgrades against
      nox-version:
        required: true
        type: string
        description: The nox version to install
      python-version:
        required: false
        type: string
        description: The python version to run tests with
        default: "3.10"
      fips:
        required: false
        type: boolean
        default: false
        description: Test run with FIPS enabled
      package-name:
        required: false
        type: string
        description: The onedir package name to use
        default: salt
      nox-session:
        required: false
        type: string
        description: The nox session to run
        default: ci-test-onedir
      skip-code-coverage:
        required: false
        type: boolean
        description: Skip code coverage
        default: false

env:
  COLUMNS: 190
  AWS_MAX_ATTEMPTS: "10"
  AWS_RETRY_MODE: "adaptive"
  PIP_INDEX_URL: https://pypi-proxy.saltstack.net/root/local/+simple/
  PIP_EXTRA_INDEX_URL: https://pypi.org/simple
  PIP_DISABLE_PIP_VERSION_CHECK: "1"
  RAISE_DEPRECATIONS_RUNTIME_ERRORS: "1"
  USE_S3_CACHE: 'true'

jobs:

  generate-matrix:
    name: Generate Matrix
    runs-on:
      # We need to run on our self-hosted runners because we need proper credentials
      # for boto3 to scan through our repositories.
      - self-hosted
      - linux
      - x86_64
    outputs:
      pkg-matrix-include: ${{ steps.generate-pkg-matrix.outputs.matrix }}
      build-reports: ${{ steps.generate-pkg-matrix.outputs.build-reports }}
    steps:

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(shuf -i 1-30 -n 1); echo "Sleeping $t seconds"; sleep "$t"

      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Setup Python Tools Scripts
        uses: ./.github/actions/setup-python-tools-scripts
        with:
          cache-prefix: ${{ inputs.cache-prefix }}

      - name: Generate Package Test Matrix
        id: generate-pkg-matrix
        run: |
          tools ci pkg-matrix ${{ inputs.distro-slug }} \
            ${{ inputs.pkg-type }} --testing-releases ${{ join(fromJSON(inputs.testing-releases), ' ') }}

  test:
    name: Test
    runs-on:
      - self-hosted
      - linux
      - bastion
    timeout-minutes: 120  # 2 Hours - More than this and something is wrong
    needs:
      - generate-matrix
    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJSON(needs.generate-matrix.outputs.pkg-matrix-include) }}

    steps:

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(python3 -c 'import random, sys; sys.stdout.write(str(random.randint(1, 15)))'); echo "Sleeping $t seconds"; sleep "$t"

      - name: "Set `TIMESTAMP` environment variable"
        shell: bash
        run: |
          echo "TIMESTAMP=$(date +%s)" | tee -a "$GITHUB_ENV"

      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Download Packages
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.package-name }}-${{ inputs.salt-version }}-${{ inputs.arch }}-${{ inputs.pkg-type }}
          path: artifacts/pkg/

      - name: Download Onedir Tarball as an Artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.package-name }}-${{ inputs.salt-version }}-onedir-${{ inputs.platform }}-${{ inputs.arch }}.tar.xz
          path: artifacts/

      - name: Decompress Onedir Tarball
        shell: bash
        run: |
          python3 -c "import os; os.makedirs('artifacts', exist_ok=True)"
          cd artifacts
          tar xvf ${{ inputs.package-name }}-${{ inputs.salt-version }}-onedir-${{ inputs.platform }}-${{ inputs.arch }}.tar.xz

      - name: List Packages
        run: |
          tree artifacts/pkg/

      - name: Download nox.linux.${{ inputs.arch }}.tar.* artifact for session ${{ inputs.nox-session }}
        uses: actions/download-artifact@v4
        with:
          name: nox-linux-${{ inputs.arch }}-${{ inputs.nox-session }}

      - name: Setup Python Tools Scripts
        uses: ./.github/actions/setup-python-tools-scripts
        with:
          cache-prefix: ${{ inputs.cache-prefix }}

      - name: Get Salt Project GitHub Actions Bot Environment
        run: |
          TOKEN=$(curl -sS -f -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 30")
          SPB_ENVIRONMENT=$(curl -sS -f -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/tags/instance/spb:environment)
          echo "SPB_ENVIRONMENT=$SPB_ENVIRONMENT" >> "$GITHUB_ENV"

      - name: Start VM
        id: spin-up-vm
        run: |
          tools --timestamps vm create --environment "${SPB_ENVIRONMENT}" --retries=2 ${{ inputs.distro-slug }}

      - name: List Free Space
        run: |
          tools --timestamps vm ssh ${{ inputs.distro-slug }} -- df -h || true

      - name: Upload Checkout To VM
        run: |
          tools --timestamps vm rsync ${{ inputs.distro-slug }}

      - name: Decompress .nox Directory
        run: |
          tools --timestamps vm decompress-dependencies ${{ inputs.distro-slug }}

      - name: Downgrade importlib-metadata
        if: ${{ contains(fromJSON('["amazonlinux-2", "centos-7"]'), inputs.distro-slug) && contains(fromJSON('["upgrade-classic", "downgrade-classic"]'), matrix.tests-chunk) }}
        run: |
          # This step can go away once we stop testing classic packages upgrade/downgrades to/from 3005.x
          tools --timestamps vm ssh ${{ inputs.distro-slug }} -- "sudo python3 -m pip install -U 'importlib-metadata<=4.13.0' 'virtualenv<=20.21.1'"

      - name: Show System Info
        run: |
          tools --timestamps --timeout-secs=1800 vm test --skip-requirements-install --print-system-information-only \
            --nox-session=${{ inputs.nox-session }}-pkgs ${{ inputs.distro-slug }} -- ${{ matrix.tests-chunk }}

      - name: Run Package Tests
        run: |
          tools --timestamps --no-output-timeout-secs=1800 --timeout-secs=14400 vm test --skip-requirements-install ${{ inputs.fips && '--fips ' || '' }}\
          --nox-session=${{ inputs.nox-session }}-pkgs --rerun-failures ${{ inputs.distro-slug }} -- ${{ matrix.tests-chunk }} \
          ${{ matrix.version && format('--prev-version={0}', matrix.version) || ''}}

      - name: Download Test Run Artifacts
        id: download-artifacts-from-vm
        if: always() && steps.spin-up-vm.outcome == 'success'
        run: |
          tools --timestamps vm download-artifacts ${{ inputs.distro-slug }}
          # Delete the salt onedir, we won't need it anymore and it will prevent
          # from it showing in the tree command below
          rm -rf artifacts/salt*
          tree -a artifacts

      - name: Destroy VM
        if: always()
        run: |
          tools --timestamps vm destroy --no-wait ${{ inputs.distro-slug }} || true

      - name: Upload Test Run Artifacts
        if: always() && steps.download-artifacts-from-vm.outcome == 'success'
        uses: actions/upload-artifact@v4
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}${{ inputs.fips && '-fips' || '' }}-${{ inputs.pkg-type }}-${{ inputs.arch }}-${{ matrix.tests-chunk }}-${{ matrix.version || 'no-version'}}-${{ env.TIMESTAMP }}
          path: |
            artifacts
            !artifacts/pkg/*
            !artifacts/salt/*
            !artifacts/salt-*.tar.*

  report:
    name: Report
    runs-on: ubuntu-latest
    if: always() && fromJSON(needs.generate-matrix.outputs.build-reports) && needs.test.result != 'cancelled' && needs.test.result != 'skipped'
    needs:
      - generate-matrix
      - test

    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(shuf -i 1-30 -n 1); echo "Sleeping $t seconds"; sleep "$t"

      - name: Merge Test Run Artifacts
        continue-on-error: true
        uses: actions/upload-artifact/merge@v4
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}${{ inputs.fips && '-fips' || '' }}-${{ inputs.pkg-type }}
          pattern: pkg-testrun-artifacts-${{ inputs.distro-slug }}${{ inputs.fips && '-fips' || '' }}-${{ inputs.pkg-type }}-*
          separate-directories: true
          delete-merged: true

      - name: Download Test Run Artifacts
        id: download-test-run-artifacts
        uses: actions/download-artifact@v4
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}${{ inputs.fips && '-fips' || '' }}-${{ inputs.pkg-type }}
          path: artifacts

      - name: Show Test Run Artifacts
        if: always() && steps.download-test-run-artifacts.outcome == 'success'
        run: |
          tree -a artifacts


Test Artifact

name: Test Artifact

on:
  workflow_call:
    inputs:
      distro-slug:
        required: true
        type: string
        description: The OS slug to run tests against
      platform:
        required: true
        type: string
        description: The platform being tested
      arch:
        required: true
        type: string
        description: The platform arch being tested
      pkg-type:
        required: true
        type: string
        description: The platform arch being tested
      salt-version:
        type: string
        required: true
        description: The Salt version of the packages to install and test
      cache-prefix:
        required: true
        type: string
        description: Seed used to invalidate caches
      testing-releases:
        required: true
        type: string
        description: A JSON list of releases to test upgrades against
      nox-version:
        required: true
        type: string
        description: The nox version to install
      python-version:
        required: false
        type: string
        description: The python version to run tests with
        default: "3.10"
      fips:
        required: false
        type: boolean
        default: false
        description: Test run with FIPS enabled
      package-name:
        required: false
        type: string
        description: The onedir package name to use
        default: salt
      nox-session:
        required: false
        type: string
        description: The nox session to run
        default: ci-test-onedir
      skip-code-coverage:
        required: false
        type: boolean
        description: Skip code coverage
        default: false

env:
  COLUMNS: 190
  AWS_MAX_ATTEMPTS: "10"
  AWS_RETRY_MODE: "adaptive"
  PIP_INDEX_URL: https://pypi-proxy.saltstack.net/root/local/+simple/
  PIP_EXTRA_INDEX_URL: https://pypi.org/simple
  PIP_DISABLE_PIP_VERSION_CHECK: "1"
  RAISE_DEPRECATIONS_RUNTIME_ERRORS: "1"

jobs:

  generate-matrix:
    name: Generate Matrix
    runs-on:
      # We need to run on our self-hosted runners because we need proper credentials
      # for boto3 to scan through our repositories.
      - self-hosted
      - linux
      - x86_64
    outputs:
      pkg-matrix-include: ${{ steps.generate-pkg-matrix.outputs.matrix }}
      build-reports: ${{ steps.generate-pkg-matrix.outputs.build-reports }}
    steps:

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(shuf -i 1-30 -n 1); echo "Sleeping $t seconds"; sleep "$t"

      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Setup Python Tools Scripts
        uses: ./.github/actions/setup-python-tools-scripts
        with:
          cache-prefix: ${{ inputs.cache-prefix }}

      - name: Generate Package Test Matrix
        id: generate-pkg-matrix
        run: |
          tools ci pkg-matrix ${{ inputs.fips && '--fips ' || '' }}${{ inputs.distro-slug }} \
            ${{ inputs.pkg-type }} --testing-releases ${{ join(fromJSON(inputs.testing-releases), ' ') }}

  test:
    name: Test
    runs-on:
      - self-hosted
      - linux
      - bastion
    timeout-minutes: 120  # 2 Hours - More than this and something is wrong
    needs:
      - generate-matrix
    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJSON(needs.generate-matrix.outputs.pkg-matrix-include) }}

    steps:

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(python3 -c 'import random, sys; sys.stdout.write(str(random.randint(1, 15)))'); echo "Sleeping $t seconds"; sleep "$t"

      - name: "Set `TIMESTAMP` environment variable"
        shell: bash
        run: |
          echo "TIMESTAMP=$(date +%s)" | tee -a "$GITHUB_ENV"

      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: Download Packages
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.package-name }}-${{ inputs.salt-version }}-${{ inputs.arch }}-${{ inputs.pkg-type }}
          path: artifacts/pkg/

      - name: Download Onedir Tarball as an Artifact
        uses: actions/download-artifact@v4
        with:
          name: ${{ inputs.package-name }}-${{ inputs.salt-version }}-onedir-${{ inputs.platform }}-${{ inputs.arch }}.tar.xz
          path: artifacts/

      - name: Decompress Onedir Tarball
        shell: bash
        run: |
          python3 -c "import os; os.makedirs('artifacts', exist_ok=True)"
          cd artifacts
          tar xvf ${{ inputs.package-name }}-${{ inputs.salt-version }}-onedir-${{ inputs.platform }}-${{ inputs.arch }}.tar.xz

      - name: List Packages
        run: |
          tree artifacts/pkg/

      - name: Download nox.windows.${{ inputs.arch }}.tar.* artifact for session ${{ inputs.nox-session }}
        uses: actions/download-artifact@v4
        with:
          name: nox-windows-${{ inputs.arch }}-${{ inputs.nox-session }}

      - name: Setup Python Tools Scripts
        uses: ./.github/actions/setup-python-tools-scripts
        with:
          cache-prefix: ${{ inputs.cache-prefix }}

      - name: Get Salt Project GitHub Actions Bot Environment
        run: |
          TOKEN=$(curl -sS -f -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 30")
          SPB_ENVIRONMENT=$(curl -sS -f -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/tags/instance/spb:environment)
          echo "SPB_ENVIRONMENT=$SPB_ENVIRONMENT" >> "$GITHUB_ENV"

      - name: Start VM
        id: spin-up-vm
        run: |
          tools --timestamps vm create --environment "${SPB_ENVIRONMENT}" --retries=2 ${{ inputs.distro-slug }}

      - name: List Free Space
        run: |
          tools --timestamps vm ssh ${{ inputs.distro-slug }} -- df -h || true

      - name: Upload Checkout To VM
        run: |
          tools --timestamps vm rsync ${{ inputs.distro-slug }}

      - name: Decompress .nox Directory
        run: |
          tools --timestamps vm decompress-dependencies ${{ inputs.distro-slug }}

      - name: Downgrade importlib-metadata
        if: ${{ contains(fromJSON('["amazonlinux-2", "centos-7"]'), inputs.distro-slug) && contains(fromJSON('["upgrade-classic", "downgrade-classic"]'), matrix.tests-chunk) }}
        run: |
          # This step can go away once we stop testing classic packages upgrade/downgrades to/from 3005.x
          tools --timestamps vm ssh ${{ inputs.distro-slug }} -- "sudo python3 -m pip install -U 'importlib-metadata<=4.13.0' 'virtualenv<=20.21.1'"

      - name: Show System Info
        run: |
          tools --timestamps --timeout-secs=1800 vm test --skip-requirements-install --print-system-information-only \
            --nox-session=${{ inputs.nox-session }}-pkgs ${{ inputs.distro-slug }} -- ${{ matrix.tests-chunk }}

      - name: Run Package Tests
        run: |
          tools --timestamps --no-output-timeout-secs=1800 --timeout-secs=14400 vm test --skip-requirements-install ${{ matrix.fips && '--fips ' || '' }}\
          --nox-session=${{ inputs.nox-session }}-pkgs --rerun-failures ${{ inputs.distro-slug }} -- ${{ matrix.tests-chunk }} \
          ${{ matrix.version && format('--prev-version={0}', matrix.version) || ''}}

      - name: Download Test Run Artifacts
        id: download-artifacts-from-vm
        if: always() && steps.spin-up-vm.outcome == 'success'
        run: |
          tools --timestamps vm download-artifacts ${{ inputs.distro-slug }}
          # Delete the salt onedir, we won't need it anymore and it will prevent
          # from it showing in the tree command below
          rm -rf artifacts/salt*
          tree -a artifacts

      - name: Destroy VM
        if: always()
        run: |
          tools --timestamps vm destroy --no-wait ${{ inputs.distro-slug }} || true

      - name: Upload Test Run Artifacts
        if: always() && steps.download-artifacts-from-vm.outcome == 'success'
        uses: actions/upload-artifact@v4
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}-${{ inputs.pkg-type }}-${{ inputs.arch }}-${{ matrix.tests-chunk }}-${{ matrix.version || 'no-version'}}-${{ env.TIMESTAMP }}
          path: |
            artifacts
            !artifacts/pkg/*
            !artifacts/salt/*
            !artifacts/salt-*.tar.*

  report:
    name: Report
    runs-on: ubuntu-latest
    if: always() && fromJSON(needs.generate-matrix.outputs.build-reports) && needs.test.result != 'cancelled' && needs.test.result != 'skipped'
    needs:
      - generate-matrix
      - test

    steps:
      - name: Checkout Source Code
        uses: actions/checkout@v4

      - name: "Throttle Builds"
        shell: bash
        run: |
          t=$(shuf -i 1-30 -n 1); echo "Sleeping $t seconds"; sleep "$t"

      - name: Merge Test Run Artifacts
        uses: actions/upload-artifact/merge@v4
        continue-on-error: true
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}-${{ inputs.pkg-type }}
          pattern: pkg-testrun-artifacts-${{ inputs.distro-slug }}-${{ inputs.pkg-type }}-*
          separate-directories: true
          delete-merged: true

      - name: Download Test Run Artifacts
        id: download-test-run-artifacts
        uses: actions/download-artifact@v4
        with:
          name: pkg-testrun-artifacts-${{ inputs.distro-slug }}-${{ inputs.pkg-type }}
          path: artifacts

      - name: Show Test Run Artifacts
        if: always() && steps.download-test-run-artifacts.outcome == 'success'
        run: |
          tree -a artifacts