name: Build almalinux docker images

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - release/*
    tags:
      # NOTE: Binary build pipelines should only get triggered on release candidate or nightly builds
      # Release candidate tags look like: v1.11.0-rc1
      - v[0-9]+.[0-9]+.[0-9]+-rc[0-9]+
    paths:
      - '.ci/docker/almalinux/*'
      - '.ci/docker/common/*'
      - .github/workflows/build-almalinux-images.yml
  pull_request:
    paths:
      - '.ci/docker/almalinux/*'
      - '.ci/docker/common/*'
      - .github/workflows/build-almalinux-images.yml

env:
  DOCKER_REGISTRY: "docker.io"
  DOCKER_BUILDKIT: 1
  WITH_PUSH: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release')) }}

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}-${{ github.event_name == 'workflow_dispatch' }}
  cancel-in-progress: true

jobs:
  build-docker:
    if: github.repository_owner == 'pytorch'
    environment: ${{ (github.ref == 'refs/heads/main' || startsWith(github.event.ref, 'refs/tags/v')) && 'docker-build' || '' }}
    runs-on: linux.9xlarge.ephemeral
    strategy:
      matrix:
        cuda_version: ["11.8", "12.4", "12.6", "cpu"]
    env:
      CUDA_VERSION: ${{ matrix.cuda_version }}
    steps:
      - name: Checkout PyTorch
        uses: pytorch/pytorch/.github/actions/checkout-pytorch@release/2.7
        with:
          submodules: false
      - name: Calculate docker image
        if: env.WITH_PUSH == 'false'
        uses: pytorch/test-infra/.github/actions/calculate-docker-image@release/2.7
        with:
            docker-image-name: almalinux-builder${{ matrix.cuda_version == 'cpu' && '-' || '-cuda' }}${{matrix.cuda_version}}
            docker-build-dir:  .ci/docker/almalinux
            always-rebuild: true
            push: true
      - name: Authenticate if WITH_PUSH
        if: env.WITH_PUSH == 'true'
        env:
          DOCKER_TOKEN: ${{ secrets.DOCKER_TOKEN }}
          DOCKER_ID: ${{ secrets.DOCKER_ID }}
        run: |
          if [[ "${WITH_PUSH}" == true ]]; then
            echo "${DOCKER_TOKEN}" | docker login -u "${DOCKER_ID}" --password-stdin
          fi
      - name: Build Docker Image
        if: env.WITH_PUSH == 'true'
        uses: nick-fields/retry@v3.0.0
        with:
          shell: bash
          timeout_minutes: 90
          max_attempts: 3
          retry_wait_seconds: 90
          command: |
            .ci/docker/almalinux/build.sh almalinux-builder${{ matrix.cuda_version == 'cpu' && ':' || ':cuda' }}${{matrix.cuda_version}}
