#
# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This file is a part of the vllm-ascend project.
#
# CANN_QUAY_URL (optional): Registry URL of the CANN base image.
ARG CANN_QUAY_URL="quay.io/ascend/cann"
# CANN_VERSION (optional): CANN toolkit version used to select the base image tag.
ARG CANN_VERSION="9.1.0"

FROM ${CANN_QUAY_URL}:${CANN_VERSION}-910b-ubuntu22.04-py3.12

# Build-time arguments (declared once at the top of the stage for clarity).
# PIP_INDEX_URL (optional): Primary pip index mirror URL for Python packages.
ARG PIP_INDEX_URL="https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
# PUBLIC_PIP_INDEX_URL (optional): Public pip index used to restore config after internal-mirror builds.
ARG PUBLIC_PIP_INDEX_URL="https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple"
# MOONCAKE_INDEX_URL (optional): Extra pip index URL for the mooncake-transfer-engine package.
ARG MOONCAKE_INDEX_URL="https://mirrors.aliyun.com/pypi/web/simple"
# PYTORCH_INDEX_URL (optional): Extra pip index URL for PyTorch wheels.
ARG PYTORCH_INDEX_URL="https://download.pytorch.org/whl/cpu/"
# ASCEND_INDEX_URL (optional): Extra pip index URL for Ascend/CANN Python packages.
ARG ASCEND_INDEX_URL="https://mirrors.huaweicloud.com/ascend/repos/pypi"
# APTMIRROR (optional): Internal apt mirror host; empty to use the public Ubuntu mirrors.
ARG APTMIRROR=""
# GIT_PROXY (optional): Internal GitHub proxy prefix; empty for direct GitHub access.
ARG GIT_PROXY=""
# PIP_TRUSTED_HOST (optional): Extra pip trusted host; empty for none.
ARG PIP_TRUSTED_HOST=""
# MOONCAKE_TAG (optional): Version tag of the mooncake-transfer-engine-npu package.
ARG MOONCAKE_TAG=0.3.11.post1
# VLLM_REPO (optional): Git repository URL of vLLM.
ARG VLLM_REPO=https://github.com/vllm-project/vllm.git
# VLLM_TAG (optional): vLLM release tag to clone when VLLM_COMMIT is empty.
ARG VLLM_TAG=v0.27.1
# VLLM_COMMIT (optional): Exact vLLM commit to build; empty to fall back to VLLM_TAG.
ARG VLLM_COMMIT=""
# SOC_VERSION (optional): Ascend SoC version used for custom kernel compilation.
ARG SOC_VERSION="ascend910b1"
# COMPILE_CUSTOM_KERNELS (optional): Whether to compile custom Ascend kernels (1 = yes, 0 = no).
ARG COMPILE_CUSTOM_KERNELS=1
# RUSTUP_DIST_SERVER (optional, empty if unset): Internal rustup dist server mirror for the Rust frontend.
ARG RUSTUP_DIST_SERVER
# RUSTUP_UPDATE_ROOT (optional, empty if unset): Internal rustup update root mirror for the Rust frontend.
ARG RUSTUP_UPDATE_ROOT
# CRATES_IO_INDEX (optional): Internal crates.io sparse index mirror; empty to use the public index.
ARG CRATES_IO_INDEX=""
# BUILD_TYPE (optional): Build type: 'release' or 'daily' (daily installs extra deps).
ARG BUILD_TYPE="release"
# MEMCACHE_VERSION (optional, empty if unset): memcache package version for daily builds.
ARG MEMCACHE_VERSION
# MEMCACHE_DATE (optional, empty if unset): memcache package build date for daily builds.
ARG MEMCACHE_DATE
# MEMFABRIC_VERSION (optional, empty if unset): memfabric package version for daily builds.
ARG MEMFABRIC_VERSION
# MEMFABRIC_DATE (optional, empty if unset): memfabric package build date for daily builds.
ARG MEMFABRIC_DATE
# TORCH_NPU_VERSION (optional, empty if unset): torch_npu version for daily builds.
ARG TORCH_NPU_VERSION
# TORCH_NPU_DATE (optional, empty if unset): torch_npu build date for daily builds.
ARG TORCH_NPU_DATE
# TRITON_ASCEND_VERSION (optional, empty if unset): triton-ascend version for daily builds.
ARG TRITON_ASCEND_VERSION
# TRITON_ASCEND_PACKAGE_VERSION (optional, empty if unset): triton-ascend package version for daily builds.
ARG TRITON_ASCEND_PACKAGE_VERSION
# DAILY_DEPS_MODE (optional): Daily deps install mode: 'full' or 'torch_npu_only'.
ARG DAILY_DEPS_MODE="full"

WORKDIR /workspace

# Note: Install CANN 910B (A2) ops-transformer package
ARG TARGETPLATFORM
RUN ARCH=${TARGETPLATFORM:-$(uname -m)}; \
    case "$ARCH" in \
        "linux/arm64"|"aarch64") \
            OPS_TRANSFORMER_URL="https://ascend-cann-open.obs.cn-north-4.myhuaweicloud.com/CANN/temp_ops-transformer/cann-910b-ops-transformer_9.2.0_linux-aarch64.run"; \
            OPS_TRANSFORMER_EXP_URL="https://ascend-cann-open.obs.cn-north-4.myhuaweicloud.com/CANN/temp_ops-transformer/260904/cann-ops-transformer-experimental_910b_linux-aarch64.run" ;; \
        "linux/amd64"|"x86_64") \
            OPS_TRANSFORMER_URL="https://ascend-cann-open.obs.cn-north-4.myhuaweicloud.com/CANN/temp_ops-transformer/cann-910b-ops-transformer_9.2.0_linux-x86_64.run"; \
            OPS_TRANSFORMER_EXP_URL="https://ascend-cann-open.obs.cn-north-4.myhuaweicloud.com/CANN/temp_ops-transformer/260907/build_out/cann-ops-transformer-experimental_910b_linux-x86_64.run" ;; \
        *) echo "Skipping unsupported architecture: $ARCH" && exit 0 ;; \
    esac && \
    wget --quiet "$OPS_TRANSFORMER_URL" -O /tmp/cann-910b-ops-transformer.run && \
    chmod +x /tmp/cann-910b-ops-transformer.run && \
    /tmp/cann-910b-ops-transformer.run --full --quiet --install-for-all && \
    rm -f /tmp/cann-910b-ops-transformer.run && \
    wget --quiet "$OPS_TRANSFORMER_EXP_URL" -O /tmp/cann-ops-transformer-experimental_910b.run && \
    chmod +x /tmp/cann-ops-transformer-experimental_910b.run && \
    /tmp/cann-ops-transformer-experimental_910b.run --quiet --install-for-all --force && \
    rm -f /tmp/cann-ops-transformer-experimental_910b.run

# Install clang-15 (for triton-ascend) and Mooncake
RUN if [ -n "$APTMIRROR" ]; then \
        cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
        sed -Ei "s@(ports|archive).ubuntu.com@${APTMIRROR#http://}@g" /etc/apt/sources.list; \
    fi && \
    apt-get update -y && \
    apt-get install -y git vim wget curl protobuf-compiler libprotobuf-dev net-tools gcc g++ cmake numactl libnuma-dev libibverbs-dev libjemalloc2 libhiredis-dev clang-15 && \
    update-alternatives --install /usr/bin/clang clang /usr/bin/clang-15 20 && \
    update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-15 20 && \
    source /usr/local/Ascend/ascend-toolkit/set_env.sh && \
    python3 -m pip install mooncake-transfer-engine-npu==${MOONCAKE_TAG} --extra-index-url ${MOONCAKE_INDEX_URL} && \
    if [ -n "$APTMIRROR" ]; then mv /etc/apt/sources.list.bak /etc/apt/sources.list; fi && \
    rm -rf /var/cache/apt/* && \
    rm -rf /var/lib/apt/lists/*

# Install modelscope (for fast download) and ray (for multinode)
RUN pip config set global.index-url ${PIP_INDEX_URL} && \
    if [ -n "$PIP_TRUSTED_HOST" ]; then pip config set global.trusted-host "$PIP_TRUSTED_HOST"; fi && \
    python3 -m pip install 'modelscope<1.38' 'ray>=2.47.1,<=2.48.0' 'protobuf>3.20.0' && \
    python3 -m pip cache purge

# Install vLLM
RUN if [ -n "$GIT_PROXY" ]; then git config --global url."${GIT_PROXY}https://github.com/".insteadOf https://github.com/; fi && \
    if [ -n "$VLLM_COMMIT" ]; then \
      git init /vllm-workspace/vllm && \
      git -C /vllm-workspace/vllm fetch --depth 1 $VLLM_REPO "$VLLM_COMMIT" && \
      git -C /vllm-workspace/vllm checkout FETCH_HEAD; \
    else \
      git clone --depth 1 -b $VLLM_TAG $VLLM_REPO /vllm-workspace/vllm; \
    fi

# In x86, triton will be installed by vllm. But in Ascend, triton doesn't work correctly. we need to uninstall it.
RUN VLLM_TARGET_DEVICE="empty" python3 -m pip install -e /vllm-workspace/vllm/[audio] --extra-index-url ${PYTORCH_INDEX_URL} && \
    python3 -m pip uninstall -y triton && \
    python3 -m pip cache purge

# Install vllm-ascend
ENV DEBIAN_FRONTEND=noninteractive
ENV SOC_VERSION=$SOC_VERSION \
    TASK_QUEUE_ENABLE=1 \
    OMP_NUM_THREADS=1
COPY . /vllm-workspace/vllm-ascend/

RUN export PIP_EXTRA_INDEX_URL="${ASCEND_INDEX_URL}" && \
    export VLLM_BATCH_INVARIANT=1 && \
    source /usr/local/Ascend/ascend-toolkit/set_env.sh && \
    source /usr/local/Ascend/nnal/atb/set_env.sh && \
    python3 -m pip install -e /vllm-workspace/vllm-ascend/ --extra-index-url ${PYTORCH_INDEX_URL} && \
    python3 -m pip uninstall -y triton triton-ascend && \
    python3 -m pip install triton-ascend==3.2.2 --extra-index-url ${ASCEND_INDEX_URL} && \
    python3 -m pip install concurrent-log-handler && \
    python3 -m pip cache purge

# Install _rust_tool_parser for the Rust frontend.
# When an internal RUSTUP_DIST_SERVER mirror is provided (CI builds), pre-install
# rustup via the rustup-init.sh bootstrap from the mirror so build_rust.sh
# doesn't reach the public https://sh.rustup.rs (unreachable from build
# containers). The bootstrap downloader hardcodes --proto '=https' (curl) and
# --https-only (wget), so strip them via sed to allow the internal http mirror.
# External builds without the mirror keep the original public install path. The
# default toolchain is read from vllm's rust-toolchain.toml (falling back to
# stable).
RUN if [ -n "$RUSTUP_DIST_SERVER" ]; then \
      TOOLCHAIN=$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' /vllm-workspace/vllm/rust-toolchain.toml) && \
      curl -fsSL "${RUSTUP_UPDATE_ROOT}/rustup-init.sh" -o /tmp/rustup-init.sh && \
      sed -i "s/--proto '=https'//g; s/--https-only//g" /tmp/rustup-init.sh && \
      sh /tmp/rustup-init.sh -y --default-toolchain "${TOOLCHAIN:-stable}" && \
      rm /tmp/rustup-init.sh; \
    fi
ENV PATH="/root/.cargo/bin:$PATH"
# Configure cargo only for internal (CI) builds: route git dependencies through
# GIT_PROXY and the crates.io sparse index through an internal mirror. External
# builds leave these build-args empty and keep the default public endpoints.
RUN if [ -n "$GIT_PROXY" ] || [ -n "$CRATES_IO_INDEX" ]; then \
      mkdir -p $HOME/.cargo; \
      if [ -n "$GIT_PROXY" ]; then \
        printf '[net]\ngit-fetch-with-cli = true\n' > $HOME/.cargo/config.toml; \
      else \
        : > $HOME/.cargo/config.toml; \
      fi; \
      if [ -n "$CRATES_IO_INDEX" ]; then \
        printf '[source.crates-io]\nreplace-with = "mirror"\n\n[source.mirror]\nregistry = "sparse+%s"\n' "$CRATES_IO_INDEX" >> $HOME/.cargo/config.toml; \
      fi; \
    fi
RUN cd /vllm-workspace/vllm && \
    export PROTOC_INCLUDE=/usr/include && \
    if [ -n "${RUSTUP_DIST_SERVER}" ]; then export RUSTUP_DIST_SERVER="${RUSTUP_DIST_SERVER}"; fi && \
    if [ -n "${RUSTUP_UPDATE_ROOT}" ]; then export RUSTUP_UPDATE_ROOT="${RUSTUP_UPDATE_ROOT}"; fi && \
    python3 -m pip install setuptools-rust && \
    ./build_rust.sh

# Append `libascend_hal.so` path (devlib) to LD_LIBRARY_PATH
RUN echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib" >> ~/.bashrc

# ===== Conditional installation based on BUILD_TYPE =====

# Install daily packages via shared script
COPY .github/workflows/scripts/install_daily_deps.sh /tmp/
RUN if [ "$BUILD_TYPE" = "daily" ]; then \
        bash /tmp/install_daily_deps.sh; \
    else \
        echo "Building release version without daily packages"; \
    fi && rm -f /tmp/install_daily_deps.sh

# Restore public package sources in the final image.
# Only builds that used internal mirrors (CI) need this: their build-args
# (PIP_INDEX_URL, GIT_PROXY, CRATES_IO_INDEX) point to cluster-internal hosts
# that are unreachable from the published image. This step resets pip/cargo/git
# to public defaults; the guard below skips it entirely for default builds.
# The script ships with the repo and is already copied in by `COPY .` above.
RUN if [ -n "$GIT_PROXY" ] || [ -n "$CRATES_IO_INDEX" ] || [ "$PIP_INDEX_URL" != "$PUBLIC_PIP_INDEX_URL" ]; then \
        bash /vllm-workspace/vllm-ascend/.github/workflows/scripts/restore_public_sources.sh; \
    fi

CMD ["/bin/bash"]
