From f7052b281cec00296cab08c5d076272726002820 Mon Sep 17 00:00:00 2001 From: Ramon Roche Date: Wed, 9 Sep 2026 15:56:19 -0700 Subject: [PATCH] feat(ros2): add PX4 ROS development containers Provide a supported Jazzy environment for SIH/Gazebo development and source builds, with pinned tooling and reproducible multi-architecture image publishing. Separate package and container assets from ROS source preparation, and keep checkout workspaces fresh through a Python CLI. Assisted-by: Copilot:gpt-6-astra --- .github/labeler.yml | 1 + .github/workflows/build_deb_package.yml | 85 ++++---- .github/workflows/python_checks.yml | 7 +- .github/workflows/ros_dev_container.yml | 117 +++++++++++ .gitignore | 1 + .../{ => containers}/Dockerfile.gazebo | 44 ++-- Tools/packaging/containers/Dockerfile.ros2 | 118 +++++++++++ .../packaging/{ => containers}/Dockerfile.sih | 30 ++- Tools/packaging/containers/docker-bake.hcl | 67 ++++++ Tools/packaging/containers/prepare_context.sh | 34 ++++ Tools/packaging/containers/px4-entrypoint.sh | 21 ++ Tools/packaging/containers/px4-network.sh | 17 ++ .../containers/ros2-dev-entrypoint.sh | 6 + Tools/packaging/containers/ros2-entrypoint.sh | 8 + .../containers/ros2-install-dependencies.sh | 42 ++++ .../{ => containers}/test_sih_mission.py | 4 +- Tools/packaging/{ => deb/gazebo}/postinst | 0 Tools/packaging/{ => deb/gazebo}/postrm | 0 .../packaging/{ => deb/gazebo}/px4-gazebo.sh | 0 Tools/packaging/{ => deb}/sih/postinst | 0 Tools/packaging/{ => deb}/sih/postrm | 0 Tools/packaging/px4-entrypoint.sh | 35 ---- Tools/ros2/prepare_workspace.py | 106 ++++++++++ Tools/ros2/ros2.repos | 9 + Tools/ros2/test_prepare_workspace.py | 153 ++++++++++++++ cmake/package.cmake | 4 +- docs/en/SUMMARY.md | 2 + docs/en/dev_setup/sitl_container_builds.md | 191 ++++++++++++++++++ docs/en/simulation/gazebo_container_gui.md | 154 ++++++++++++++ .../simulation/px4_sitl_prebuilt_packages.md | 120 +++++++++-- platforms/posix/CMakeLists.txt | 2 +- 31 files changed, 1254 insertions(+), 124 deletions(-) create mode 100644 .github/workflows/ros_dev_container.yml rename Tools/packaging/{ => containers}/Dockerfile.gazebo (69%) create mode 100644 Tools/packaging/containers/Dockerfile.ros2 rename Tools/packaging/{ => containers}/Dockerfile.sih (61%) create mode 100644 Tools/packaging/containers/docker-bake.hcl create mode 100644 Tools/packaging/containers/prepare_context.sh create mode 100644 Tools/packaging/containers/px4-entrypoint.sh create mode 100644 Tools/packaging/containers/px4-network.sh create mode 100755 Tools/packaging/containers/ros2-dev-entrypoint.sh create mode 100644 Tools/packaging/containers/ros2-entrypoint.sh create mode 100644 Tools/packaging/containers/ros2-install-dependencies.sh rename Tools/packaging/{ => containers}/test_sih_mission.py (96%) rename Tools/packaging/{ => deb/gazebo}/postinst (100%) rename Tools/packaging/{ => deb/gazebo}/postrm (100%) rename Tools/packaging/{ => deb/gazebo}/px4-gazebo.sh (100%) rename Tools/packaging/{ => deb}/sih/postinst (100%) rename Tools/packaging/{ => deb}/sih/postrm (100%) delete mode 100644 Tools/packaging/px4-entrypoint.sh create mode 100755 Tools/ros2/prepare_workspace.py create mode 100644 Tools/ros2/ros2.repos create mode 100644 Tools/ros2/test_prepare_workspace.py create mode 100644 docs/en/dev_setup/sitl_container_builds.md create mode 100644 docs/en/simulation/gazebo_container_gui.md diff --git a/.github/labeler.yml b/.github/labeler.yml index 20d959b09f6..521f4dcb8e0 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -123,6 +123,7 @@ - src/drivers/uavcan/** - src/drivers/uavcannode/** - platforms/ros2/** + - Tools/ros2/** - msg/translation_node/** "scope:navigation": diff --git a/.github/workflows/build_deb_package.yml b/.github/workflows/build_deb_package.yml index 2ec0203f368..f7dcbdbec96 100644 --- a/.github/workflows/build_deb_package.yml +++ b/.github/workflows/build_deb_package.yml @@ -8,6 +8,9 @@ on: - 'cmake/package.cmake' - 'platforms/posix/CMakeLists.txt' - 'Tools/packaging/**' + - 'Tools/ros2/ros2.repos' + - 'Tools/setup/ubuntu.sh' + - 'Tools/setup/requirements.txt' - 'boards/px4/sitl/sih.px4board' - '.github/workflows/build_deb_package.yml' - '.github/actions/build-deb/**' @@ -89,6 +92,8 @@ jobs: - name: Fix git in container run: | + # Ubuntu's container hook otherwise empties the APT cache after every install. + rm -f /etc/apt/apt.conf.d/docker-clean apt-get update && apt-get install -y git git config --global --add safe.directory $(realpath .) @@ -105,8 +110,8 @@ jobs: uses: actions/cache@v5 with: path: /var/cache/apt/archives - key: apt-${{ matrix.target }}-${{ matrix.codename }}-${{ matrix.arch }}-${{ hashFiles('Tools/setup/ubuntu.sh') }} - restore-keys: apt-${{ matrix.target }}-${{ matrix.codename }}-${{ matrix.arch }}- + key: apt-v2-${{ matrix.target }}-${{ matrix.codename }}-${{ matrix.arch }}-${{ hashFiles('Tools/setup/ubuntu.sh') }} + restore-keys: apt-v2-${{ matrix.target }}-${{ matrix.codename }}-${{ matrix.arch }}- - name: Install dependencies run: ./Tools/setup/ubuntu.sh --no-nuttx ${{ matrix.setup_flags }} @@ -124,15 +129,17 @@ jobs: build-docker: name: "Build Image (${{ matrix.image }}/${{ matrix.arch }})" needs: [setup, build-deb] - runs-on: [runs-on,"runner=4cpu-linux-${{ matrix.runner }}","image=ubuntu24-full-${{ matrix.runner }}","run-id=${{ github.run_id }}",extras=s3-cache,spot=false] + runs-on: [runs-on,"runner=8cpu-linux-${{ matrix.runner }}","image=ubuntu24-full-${{ matrix.runner }}","run-id=${{ github.run_id }}",extras=s3-cache,spot=false] strategy: fail-fast: false matrix: + arch: [amd64, arm64] + image: [sih, gazebo] include: - - { image: sih, repo: px4-sitl, target: sih, arch: amd64, runner: x64, platform: "linux/amd64", dockerfile: Dockerfile.sih } - - { image: sih, repo: px4-sitl, target: sih, arch: arm64, runner: arm64, platform: "linux/arm64", dockerfile: Dockerfile.sih } - - { image: gazebo, repo: px4-sitl-gazebo, target: default, arch: amd64, runner: x64, platform: "linux/amd64", dockerfile: Dockerfile.gazebo } - - { image: gazebo, repo: px4-sitl-gazebo, target: default, arch: arm64, runner: arm64, platform: "linux/arm64", dockerfile: Dockerfile.gazebo } + - { arch: amd64, runner: x64 } + - { arch: arm64, runner: arm64 } + - { image: sih, target: sih } + - { image: gazebo, target: default } steps: - uses: runs-on/action@v2 - uses: actions/checkout@v6 @@ -146,7 +153,7 @@ jobs: path: docker-context - name: Prepare build context - run: cp Tools/packaging/px4-entrypoint.sh docker-context/ + run: bash Tools/packaging/containers/prepare_context.sh - name: Login to registries if: needs.setup.outputs.should_push == 'true' @@ -156,40 +163,51 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 + id: buildx with: driver: docker-container - platforms: ${{ matrix.platform }} + platforms: linux/${{ matrix.arch }} - - name: Build and push container image - uses: docker/build-push-action@v7 + - name: Restore ROS compiler cache + uses: actions/cache@v5 + id: ros-cache with: - context: docker-context - file: Tools/packaging/${{ matrix.dockerfile }} - tags: | - px4io/${{ matrix.repo }}:${{ needs.setup.outputs.px4_version }}-${{ matrix.arch }} - px4io/${{ matrix.repo }}:latest-${{ matrix.arch }} - ghcr.io/px4/${{ matrix.repo }}:${{ needs.setup.outputs.px4_version }}-${{ matrix.arch }} - ghcr.io/px4/${{ matrix.repo }}:latest-${{ matrix.arch }} - platforms: ${{ matrix.platform }} - load: false + path: ros-ccache + key: ros-ccache-${{ matrix.arch }}-${{ matrix.image }}-${{ github.sha }} + restore-keys: ros-ccache-${{ matrix.arch }}- + + - name: Reuse compiler cache across image layers + uses: reproducible-containers/buildkit-cache-dance@v3 + with: + builder: ${{ steps.buildx.outputs.name }} + cache-map: '{"ros-ccache": {"target": "/root/.cache/ccache", "sharing": "locked"}}' + skip-extraction: ${{ steps.ros-cache.outputs.cache-hit }} + + - name: Build and push container images + uses: docker/bake-action@v7 + env: + SIMULATOR: ${{ matrix.image }} + VERSION: ${{ needs.setup.outputs.px4_version }} + ARCH: ${{ matrix.arch }} + CACHE_GHA: "true" + with: + source: . + files: Tools/packaging/containers/docker-bake.hcl push: ${{ needs.setup.outputs.should_push == 'true' }} + sbom: true provenance: false - cache-from: type=gha,scope=sitl-${{ matrix.image }}-${{ matrix.arch }} - cache-to: type=gha,mode=max,scope=sitl-${{ matrix.image }}-${{ matrix.arch }} # --------------------------------------------------------------------------- # Deploy: create multi-arch manifests and push to registries # --------------------------------------------------------------------------- deploy: - name: "Deploy (${{ matrix.image }})" + name: "Deploy (${{ matrix.repo }})" needs: [setup, build-docker] if: needs.setup.outputs.should_push == 'true' runs-on: [runs-on,"runner=1cpu-linux-x64","image=ubuntu24-full-x64","run-id=${{ github.run_id }}",extras=s3-cache,spot=false] strategy: matrix: - include: - - { image: sih, repo: px4-sitl } - - { image: gazebo, repo: px4-sitl-gazebo } + repo: [px4-sitl, px4-sitl-gazebo, px4-sitl-ros2, px4-sitl-gazebo-ros2] steps: - uses: runs-on/action@v2 @@ -198,6 +216,8 @@ jobs: echo "${{ secrets.DOCKERHUB_TOKEN }}" | docker login -u "${{ secrets.DOCKERHUB_USERNAME }}" --password-stdin echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin + - uses: docker/setup-buildx-action@v4 + - name: Create and push multi-arch manifests run: | VERSION="${{ needs.setup.outputs.px4_version }}" @@ -205,14 +225,7 @@ jobs: for REGISTRY in px4io ghcr.io/px4; do IMAGE="${REGISTRY}/${{ matrix.repo }}" - for TAG in ${VERSION} latest; do - docker manifest create ${IMAGE}:${TAG} \ - --amend ${IMAGE}:${TAG}-arm64 \ - --amend ${IMAGE}:${TAG}-amd64 - - docker manifest annotate ${IMAGE}:${TAG} ${IMAGE}:${TAG}-arm64 --arch arm64 - docker manifest annotate ${IMAGE}:${TAG} ${IMAGE}:${TAG}-amd64 --arch amd64 - - docker manifest push ${IMAGE}:${TAG} - done + docker buildx imagetools create \ + --tag "${IMAGE}:${VERSION}" --tag "${IMAGE}:latest" \ + "${IMAGE}:${VERSION}-arm64" "${IMAGE}:${VERSION}-amd64" done diff --git a/.github/workflows/python_checks.yml b/.github/workflows/python_checks.yml index 481cb161942..458c11b228f 100644 --- a/.github/workflows/python_checks.yml +++ b/.github/workflows/python_checks.yml @@ -27,10 +27,15 @@ jobs: python-version: "3.10" - name: Install tools - run: pip install mypy types-requests flake8 + run: pip install mypy types-requests flake8 pyyaml - name: Check MAVSDK test scripts with mypy run: mypy --strict test/mavsdk_tests/*.py - name: Check MAVSDK test scripts with flake8 run: flake8 test/mavsdk_tests/*.py + + - name: Check ROS workspace tooling + run: | + flake8 Tools/ros2/*.py + python3 -m unittest discover -s Tools/ros2 -p 'test_*.py' diff --git a/.github/workflows/ros_dev_container.yml b/.github/workflows/ros_dev_container.yml new file mode 100644 index 00000000000..3b88e7072bd --- /dev/null +++ b/.github/workflows/ros_dev_container.yml @@ -0,0 +1,117 @@ +name: ROS Development Container + +on: + push: + branches: [main] + tags: ['v*'] + pull_request: + paths: + - 'Tools/packaging/containers/**' + - 'Tools/ros2/ros2.repos' + - 'Tools/setup/ubuntu.sh' + - 'Tools/setup/requirements.txt' + - '.github/workflows/ros_dev_container.yml' + workflow_dispatch: + inputs: + tag: + description: 'PX4/ROS development tag (e.g. main-jazzy or v1.18-jazzy)' + type: string + default: main-jazzy + build_ref: + description: 'Source ref; empty uses the workflow ref' + type: string + default: '' + deploy_to_registry: + description: 'Publish the development image' + type: boolean + default: false + +concurrency: + group: ros2-dev-${{ github.ref }}-${{ inputs.tag || 'main-jazzy' }} + cancel-in-progress: true + +permissions: + contents: read + packages: write + +jobs: + build: + name: Build ROS Development Image (${{ matrix.arch }}) + runs-on: [runs-on,"runner=8cpu-linux-${{ matrix.runner }}","image=ubuntu24-full-${{ matrix.runner }}","run-id=${{ github.run_id }}",extras=s3-cache,spot=false] + strategy: + fail-fast: false + matrix: + include: + - { arch: amd64, runner: x64 } + - { arch: arm64, runner: arm64 } + outputs: + revision: ${{ steps.revision.outputs.sha }} + steps: + - uses: runs-on/action@v2 + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.build_ref || github.sha }} + + - name: Prepare development image context + run: bash Tools/packaging/containers/prepare_context.sh + + - name: Resolve source revision + id: revision + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + + - uses: docker/login-action@v4 + if: >- + (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || + (github.event_name == 'workflow_dispatch' && inputs.deploy_to_registry == true) + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - uses: docker/setup-buildx-action@v4 + with: + platforms: linux/${{ matrix.arch }} + + - name: Build development image without firmware + uses: docker/bake-action@v7 + env: + ARCH: ${{ matrix.arch }} + CACHE_GHA: "true" + with: + source: . + files: Tools/packaging/containers/docker-bake.hcl + targets: ros2-dev + push: >- + ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || + (github.event_name == 'workflow_dispatch' && inputs.deploy_to_registry == true) }} + sbom: true + provenance: false + set: | + ros2-dev.tags=ghcr.io/px4/px4-dev-ros2:sha-${{ steps.revision.outputs.sha }}-jazzy-${{ matrix.arch }} + ros2-dev.labels.org.opencontainers.image.source=https://github.com/PX4/PX4-Autopilot + ros2-dev.labels.org.opencontainers.image.revision=${{ steps.revision.outputs.sha }} + + deploy: + name: Publish Multi-Architecture ROS Development Image + needs: build + if: >- + (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || + (github.event_name == 'workflow_dispatch' && inputs.deploy_to_registry == true) + runs-on: [runs-on,"runner=1cpu-linux-x64","image=ubuntu24-full-x64","run-id=${{ github.run_id }}",extras=s3-cache,spot=false] + steps: + - uses: runs-on/action@v2 + - uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - uses: docker/setup-buildx-action@v4 + - name: Assemble image and SBOM indexes + env: + TAG: ${{ github.event_name == 'push' && format('{0}-jazzy', github.ref_name) || inputs.tag || 'main-jazzy' }} + REVISION: ${{ needs.build.outputs.revision }} + run: | + IMAGE=ghcr.io/px4/px4-dev-ros2 + docker buildx imagetools create \ + --tag "${IMAGE}:${TAG}" --tag "${IMAGE}:sha-${REVISION}-jazzy" \ + "${IMAGE}:sha-${REVISION}-jazzy-amd64" "${IMAGE}:sha-${REVISION}-jazzy-arm64" diff --git a/.gitignore b/.gitignore index e5dfd3b54c6..d2419c20947 100644 --- a/.gitignore +++ b/.gitignore @@ -17,6 +17,7 @@ Testing/ Packages/* build/* build_*/ +/docker-context/ cscope.out cscope.in.out cscope.po.out diff --git a/Tools/packaging/Dockerfile.gazebo b/Tools/packaging/containers/Dockerfile.gazebo similarity index 69% rename from Tools/packaging/Dockerfile.gazebo rename to Tools/packaging/containers/Dockerfile.gazebo index d04b900b4e0..e9238b81b1c 100644 --- a/Tools/packaging/Dockerfile.gazebo +++ b/Tools/packaging/containers/Dockerfile.gazebo @@ -3,24 +3,25 @@ # Runs PX4 SITL with Gazebo Harmonic. Supports X11 forwarding for GUI. # # Build: -# make px4_sitl_default && cd build/px4_sitl_default && cpack -G DEB && cd ../.. -# docker build -f Tools/packaging/Dockerfile.gazebo -t px4io/px4-sitl-gazebo:v1.17.0 build/px4_sitl_default/ +# See docs/en/dev_setup/sitl_container_builds.md for package and context preparation. # # Run (headless): -# docker run --rm -it --network host px4io/px4-sitl-gazebo:v1.17.0 +# docker run --rm -it --network host -e HEADLESS=1 px4io/px4-sitl-gazebo:v1.17.0 # -# Run (X11 GUI): -# xhost +local:docker -# docker run --rm -it --network host \ -# -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix \ -# --gpus all px4io/px4-sitl-gazebo:v1.17.0 +# X11 GUI (Linux and Windows/WSLg): +# See docs/en/simulation/gazebo_container_gui.md for display authorization, +# socket mounts and software/hardware rendering options. # # Persist flight logs on the host (ulog files): # mkdir -p ./px4-logs -# docker run --rm -it --network host \ +# docker run --rm -it --network host -e HEADLESS=1 \ # -v $(pwd)/px4-logs:/root/.local/share/px4/rootfs/fs/log \ # px4io/px4-sitl-gazebo:v1.17.0 +FROM ubuntu:24.04 AS package +COPY px4-gazebo_*.deb /tmp/ +RUN dpkg-deb -f /tmp/px4-gazebo_*.deb Depends > /tmp/px4-dependencies + FROM ubuntu:24.04 LABEL maintainer="PX4 Development Team" LABEL description="PX4 SITL with Gazebo Harmonic simulation" @@ -32,12 +33,15 @@ ENV RUNS_IN_DOCKER=true # px4-gazebo .deb) resolves from it in the install step below. RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ --mount=type=cache,target=/var/lib/apt,sharing=locked \ - apt-get update \ + rm -f /etc/apt/apt.conf.d/docker-clean \ + && apt-get update \ && apt-get install -y --no-install-recommends \ bc \ ca-certificates \ gnupg \ + libqt5svg5 \ lsb-release \ + mesa-utils \ wget \ && wget -q https://packages.osrfoundation.org/gazebo.gpg \ -O /usr/share/keyrings/pkgs-osrf-archive-keyring.gpg \ @@ -45,16 +49,19 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ > /etc/apt/sources.list.d/gazebo-stable.list \ && apt-get update -# Install px4-gazebo via apt so its Depends (Gazebo Harmonic, OpenCV, GStreamer -# core libs, gstreamer plugin packages) are resolved automatically. The binary -# is stripped after install to trim image size (~a few MB). -COPY px4-gazebo_*.deb /tmp/ +# Cache Gazebo/OpenCV/GStreamer independently of the firmware binary. +COPY --from=package /tmp/px4-dependencies /tmp/px4-dependencies RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ --mount=type=cache,target=/var/lib/apt,sharing=locked \ apt-get update \ - && apt-get install -y --no-install-recommends \ - /tmp/px4-gazebo_*.deb \ - binutils \ + && apt-get install -y --no-install-recommends binutils \ + && apt-get satisfy -y --no-install-recommends "$(cat /tmp/px4-dependencies)" \ + && rm /tmp/px4-dependencies + +COPY --from=package /tmp/px4-gazebo_*.deb /tmp/ +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + apt-get install -y --no-install-recommends /tmp/px4-gazebo_*.deb \ && strip /opt/px4-gazebo/bin/px4 \ && apt-get purge -y binutils \ && apt-get autoremove -y \ @@ -78,12 +85,15 @@ ENV PX4_GZ_WORLDS=/opt/px4-gazebo/share/gz/worlds ENV PX4_SIM_MODEL=gz_x500 ENV HOME=/root +# X11 clients cannot use the host X server's shared-memory segment in Docker. +ENV QT_X11_NO_MITSHM=1 # MAVLink, MAVSDK, DDS EXPOSE 14550/udp 14540/udp 8888/udp # Platform-adaptive entrypoint: detects Docker Desktop (macOS/Windows) via # host.docker.internal and configures MAVLink + DDS to target the host. +COPY px4-network.sh /usr/local/lib/px4/network.sh COPY px4-entrypoint.sh /opt/px4-gazebo/bin/px4-entrypoint.sh RUN chmod +x /opt/px4-gazebo/bin/px4-entrypoint.sh diff --git a/Tools/packaging/containers/Dockerfile.ros2 b/Tools/packaging/containers/Dockerfile.ros2 new file mode 100644 index 00000000000..59e0567ee89 --- /dev/null +++ b/Tools/packaging/containers/Dockerfile.ros2 @@ -0,0 +1,118 @@ +# syntax=docker/dockerfile:1 +# Build ROS independently of the changing SIH/Gazebo firmware package. +FROM ubuntu:24.04 AS ros2-base + +ENV DEBIAN_FRONTEND=noninteractive +ENV ROS_DISTRO=jazzy +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 + +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +ARG ROS_APT_SOURCE_VERSION=1.2.0 +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=bind,source=setup,target=/px4-setup \ + --mount=type=bind,source=ros2-install-dependencies.sh,target=/ros2-install-dependencies.sh \ + bash /ros2-install-dependencies.sh + +# Use Jazzy's Fast DDS/CDR and the Agent's pinned, statically linked logger. +FROM ros2-base AS agent +ARG XRCE_AGENT_REF=73622810d984349b80bbac0ef55fc0b694d62222 +ARG BUILD_JOBS=8 +RUN source /opt/ros/jazzy/setup.bash \ + && git clone https://github.com/eProsima/Micro-XRCE-DDS-Agent.git /opt/agent-source \ + && git -C /opt/agent-source checkout "${XRCE_AGENT_REF}" \ + && cmake -S /opt/agent-source -B /opt/agent-source/build \ + -DCMAKE_BUILD_TYPE=Release \ + -DUAGENT_USE_SYSTEM_FASTDDS=ON \ + -DUAGENT_USE_SYSTEM_FASTCDR=ON \ + -DUAGENT_P2P_PROFILE=OFF \ + && cmake --build /opt/agent-source/build --parallel "${BUILD_JOBS}" \ + && DESTDIR=/opt/agent-install cmake --install /opt/agent-source/build \ + && rm -rf /opt/agent-source + +FROM ros2-base AS ros2-sources +WORKDIR /opt/px4_ros2 +COPY ros2.repos /opt/px4_ros2/ros2.repos +ARG PX4_MSGS_REF +ARG PX4_ROS2_REF +RUN mkdir src && vcs import src < ros2.repos \ + && if [[ -n "${PX4_MSGS_REF}" ]]; then \ + [[ "${PX4_MSGS_REF}" =~ ^[0-9a-fA-F]{40}$ ]] \ + && git -C src/px4_msgs checkout "${PX4_MSGS_REF}" \ + && test "$(git -C src/px4_msgs rev-parse HEAD)" = "${PX4_MSGS_REF,,}"; \ + fi \ + && if [[ -n "${PX4_ROS2_REF}" ]]; then \ + [[ "${PX4_ROS2_REF}" =~ ^[0-9a-fA-F]{40}$ ]] \ + && git -C src/px4-ros2-interface-lib checkout "${PX4_ROS2_REF}" \ + && test "$(git -C src/px4-ros2-interface-lib rev-parse HEAD)" = "${PX4_ROS2_REF,,}"; \ + fi \ + && vcs export --exact src > ros2.repos \ + && cat ros2.repos \ + && rm -rf src/px4_msgs/msg src/px4_msgs/srv + +# Dependencies use package manifests, not the generated message definitions. +FROM ros2-base AS ros2-dependencies +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=bind,from=ros2-sources,source=/opt/px4_ros2/src,target=/ros_sources \ + source /opt/ros/jazzy/setup.bash \ + && apt-get update \ + && rosdep install --from-paths /ros_sources --ignore-src --rosdistro jazzy -y + +# Standalone development toolchain: no source checkouts, firmware or overlay. +FROM ros2-dependencies AS ros2-dev +COPY --from=agent /opt/agent-install/usr/local/ /usr/local/ +RUN ldconfig +COPY --chmod=755 ros2-dev-entrypoint.sh /usr/local/bin/ros2-dev-entrypoint.sh +WORKDIR /workspace +ENTRYPOINT ["/usr/local/bin/ros2-dev-entrypoint.sh"] +CMD ["/bin/bash"] + +# Definitions come from the same checkout as the parent image's PX4 package. +FROM ros2-dependencies AS ros2-builder +WORKDIR /opt/px4_ros2 +COPY --from=ros2-sources /opt/px4_ros2/ /opt/px4_ros2/ +COPY px4_msgs/ src/px4_msgs/ +ARG BUILD_JOBS=8 +RUN --mount=type=cache,target=/root/.cache/ccache,sharing=locked \ + source /opt/ros/jazzy/setup.bash \ + && export CCACHE_DIR=/root/.cache/ccache CCACHE_MAXSIZE=500M CCACHE_COMPILERCHECK=content \ + && CMAKE_BUILD_PARALLEL_LEVEL="${BUILD_JOBS}" colcon build --symlink-install \ + --executor sequential --cmake-args -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ + && ccache --show-stats + +RUN source /opt/ros/jazzy/setup.bash \ + && colcon test --packages-select px4_ros2_cpp --ctest-args -R unit_tests \ + && colcon test-result --verbose + +# Bake supplies the connected runtime parent. Install OS packages normally; +# only source-built artifacts cross over from the independent builders. +FROM sitl +ENV ROS_DISTRO=jazzy +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 +ENV RUNS_IN_DOCKER=true +SHELL ["/bin/bash", "-o", "pipefail", "-c"] + +ARG ROS_APT_SOURCE_VERSION=1.2.0 +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + --mount=type=bind,source=setup,target=/px4-setup \ + --mount=type=bind,source=ros2-install-dependencies.sh,target=/ros2-install-dependencies.sh \ + --mount=type=bind,from=ros2-sources,source=/opt/px4_ros2/src,target=/opt/px4_ros2/src \ + bash /ros2-install-dependencies.sh /opt/px4_ros2/src + +# Copy only the staged Agent/logger install, never the builder's pip packages. +COPY --from=agent /opt/agent-install/usr/local/ /usr/local/ +RUN ldconfig +# Preserve source/build/install paths, including colcon's absolute symlinks. +COPY --from=ros2-builder /opt/px4_ros2/ /opt/px4_ros2/ +COPY --chmod=755 ros2-entrypoint.sh /usr/local/bin/ros2-entrypoint.sh +# PX4 locates its ROMFS relative to the executable, not the /usr/bin symlink. +ENV PATH=/opt/px4-gazebo/bin:/opt/px4/bin:${PATH} +WORKDIR /workspace +ENTRYPOINT ["/usr/local/bin/ros2-entrypoint.sh"] +CMD ["/bin/bash"] diff --git a/Tools/packaging/Dockerfile.sih b/Tools/packaging/containers/Dockerfile.sih similarity index 61% rename from Tools/packaging/Dockerfile.sih rename to Tools/packaging/containers/Dockerfile.sih index fdd1a970cf5..9f70a19d249 100644 --- a/Tools/packaging/Dockerfile.sih +++ b/Tools/packaging/containers/Dockerfile.sih @@ -3,14 +3,13 @@ # Minimal container that runs PX4 with the SIH physics engine (no Gazebo). # # Build: -# make px4_sitl_sih && cd build/px4_sitl_sih && cpack -G DEB && cd ../.. -# docker build -f Tools/packaging/Dockerfile.sih -t px4io/px4-sitl:v1.17.0 build/px4_sitl_sih/ +# See docs/en/dev_setup/sitl_container_builds.md for package and context preparation. # # Run (Linux): # docker run --rm -it --network host px4io/px4-sitl:v1.17.0 # # Run (macOS / Windows): -# docker run --rm -it -p 14550:14550/udp -p 14540:14540/udp -p 19410:19410/udp -p 8888:8888/udp px4io/px4-sitl:v1.17.0 +# docker run --rm -it px4io/px4-sitl:v1.17.0 # # Persist flight logs on the host (ulog files): # mkdir -p ./px4-logs @@ -18,22 +17,30 @@ # -v $(pwd)/px4-logs:/root/.local/share/px4/rootfs/fs/log \ # px4io/px4-sitl:v1.17.0 +FROM ubuntu:24.04 AS package +COPY px4_*.deb /tmp/ +RUN dpkg-deb -f /tmp/px4_*.deb Depends > /tmp/px4-dependencies + FROM ubuntu:24.04 LABEL maintainer="PX4 Development Team" LABEL description="PX4 SITL with SIH physics (no simulator dependencies)" ENV DEBIAN_FRONTEND=noninteractive -# Install px4 via apt so Depends: are resolved automatically. The binary is -# stripped after install to trim image size (~a few MB). -COPY px4_*.deb /tmp/ +# Cache dependencies independently of the firmware binary. +COPY --from=package /tmp/px4-dependencies /tmp/px4-dependencies RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ --mount=type=cache,target=/var/lib/apt,sharing=locked \ - apt-get update \ - && apt-get install -y --no-install-recommends \ - /tmp/px4_*.deb \ - bc \ - binutils \ + rm -f /etc/apt/apt.conf.d/docker-clean \ + && apt-get update \ + && apt-get install -y --no-install-recommends bc binutils \ + && apt-get satisfy -y --no-install-recommends "$(cat /tmp/px4-dependencies)" \ + && rm /tmp/px4-dependencies + +COPY --from=package /tmp/px4_*.deb /tmp/ +RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ + --mount=type=cache,target=/var/lib/apt,sharing=locked \ + apt-get install -y --no-install-recommends /tmp/px4_*.deb \ && strip /opt/px4/bin/px4 \ && apt-get purge -y binutils \ && apt-get autoremove -y \ @@ -42,6 +49,7 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \ # Platform-adaptive entrypoint: detects Docker Desktop (macOS/Windows) via # host.docker.internal and configures MAVLink + DDS to target the host. +COPY px4-network.sh /usr/local/lib/px4/network.sh COPY px4-entrypoint.sh /opt/px4/bin/px4-entrypoint.sh RUN chmod +x /opt/px4/bin/px4-entrypoint.sh diff --git a/Tools/packaging/containers/docker-bake.hcl b/Tools/packaging/containers/docker-bake.hcl new file mode 100644 index 00000000000..8e833c3df72 --- /dev/null +++ b/Tools/packaging/containers/docker-bake.hcl @@ -0,0 +1,67 @@ +variable "SIMULATOR" { + default = "sih" +} + +variable "VERSION" { + default = "dev" +} + +variable "ARCH" { + default = split("/", BAKE_LOCAL_PLATFORM)[1] +} + +variable "CACHE_GHA" { + default = false +} + +variable "REPOSITORY" { + default = SIMULATOR == "sih" ? "px4-sitl" : "px4-sitl-gazebo" +} + +function "image_tags" { + params = [repository] + result = flatten([ + for registry in ["px4io", "ghcr.io/px4"] : [ + for tag in [VERSION, "latest"] : "${registry}/${repository}:${tag}-${ARCH}" + ] + ]) +} + +group "default" { + targets = ["sitl", "ros2"] +} + +target "_common" { + context = "docker-context" + platforms = ["linux/${ARCH}"] + cache-from = CACHE_GHA ? ["type=gha,scope=sitl-${SIMULATOR}-${ARCH}"] : [] +} + +target "sitl" { + inherits = ["_common"] + dockerfile = "Dockerfile.${SIMULATOR}" + tags = image_tags(REPOSITORY) +} + +target "ros2" { + inherits = ["_common"] + dockerfile = "Dockerfile.ros2" + tags = image_tags("${REPOSITORY}-ros2") + contexts = { + sitl = "target:sitl" + } + + # The child graph includes the parent, so one export caches both images. + cache-to = CACHE_GHA ? ["type=gha,mode=max,scope=sitl-${SIMULATOR}-${ARCH}"] : [] +} + +# Published independently of the packaged SITL images. +target "ros2-dev" { + context = "docker-context" + platforms = ["linux/${ARCH}"] + dockerfile = "Dockerfile.ros2" + target = "ros2-dev" + tags = ["ghcr.io/px4/px4-dev-ros2:main-jazzy-${ARCH}"] + cache-from = CACHE_GHA ? ["type=gha,scope=ros2-dev-${ARCH}"] : [] + cache-to = CACHE_GHA ? ["type=gha,mode=max,scope=ros2-dev-${ARCH}"] : [] +} diff --git a/Tools/packaging/containers/prepare_context.sh b/Tools/packaging/containers/prepare_context.sh new file mode 100644 index 00000000000..13e2b546e12 --- /dev/null +++ b/Tools/packaging/containers/prepare_context.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" +repo_dir="$(cd "$script_dir/../../.." && pwd -P)" +if [[ "${1:-}" == "--messages-only" ]]; then + if [[ $# -ne 2 || -z "$2" ]]; then + echo "Usage: $0 --messages-only PX4_MSGS_DIR" >&2 + exit 1 + fi + messages_dir="$2" +else + context_dir="${1:-docker-context}" + messages_dir="$context_dir/px4_msgs" + mkdir -p "$context_dir/setup" + cp "$script_dir"/Dockerfile.* "$script_dir"/*entrypoint.sh "$script_dir/px4-network.sh" "$context_dir/" + cp "$script_dir/ros2-install-dependencies.sh" "$repo_dir/Tools/ros2/ros2.repos" "$context_dir/" + cp "$repo_dir/Tools/setup/ubuntu.sh" "$repo_dir/Tools/setup/requirements.txt" "$context_dir/setup/" +fi + +# Refresh generated definitions when reusing a context; keep downloaded .debs. +mkdir -p "$messages_dir/msg" "$messages_dir/srv" +for destination in "$messages_dir/msg" "$messages_dir/srv"; do + destination="$(cd "$destination" && pwd -P)" + case "$destination/" in + "$repo_dir/msg/"*|"$repo_dir/srv/"*) + echo "Refusing to overwrite PX4 source definitions: $destination" >&2 + exit 1 + ;; + esac +done +rm -f "$messages_dir/msg/"*.msg "$messages_dir/srv/"*.srv +cp "$repo_dir"/msg/*.msg "$repo_dir"/msg/versioned/*.msg "$messages_dir/msg/" +cp "$repo_dir"/srv/*.srv "$messages_dir/srv/" diff --git a/Tools/packaging/containers/px4-entrypoint.sh b/Tools/packaging/containers/px4-entrypoint.sh new file mode 100644 index 00000000000..c49356c491b --- /dev/null +++ b/Tools/packaging/containers/px4-entrypoint.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Docker entrypoint for PX4 SITL containers. +# +# On Docker Desktop (macOS/Windows), host.docker.internal resolves to the +# host machine. We detect this and configure MAVLink + DDS to send to the +# host IP instead of localhost (which stays inside the container VM). +# +# On Linux with --network host, host.docker.internal does not resolve and +# PX4 defaults work without modification. + +set -e + +. /usr/local/lib/px4/network.sh + +if [ -n "$DOCKER_HOST_IP" ]; then + # Runtime-only images expect the DDS Agent on the host. + sed -i -E "s/(uxrce_dds_client start -t udp)( -h [^ ]+)?/\1 -h $DOCKER_HOST_IP/g" \ + "$PX4_PREFIX/etc/init.d-posix/rcS" +fi + +exec "$PX4_PREFIX/bin/px4" "$@" diff --git a/Tools/packaging/containers/px4-network.sh b/Tools/packaging/containers/px4-network.sh new file mode 100644 index 00000000000..06745ab8f7d --- /dev/null +++ b/Tools/packaging/containers/px4-network.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Shared host MAVLink routing; the calling entrypoint chooses the DDS destination. + +if [ -d /opt/px4-gazebo ]; then + PX4_PREFIX=/opt/px4-gazebo +else + PX4_PREFIX=/opt/px4 +fi + +# Both PX4 clients require IPv4; Docker Desktop may also return an IPv6 address. +DOCKER_HOST_IP=$(getent ahostsv4 host.docker.internal 2>/dev/null | awk '/STREAM/ {print $1; exit}') + +if [ -n "$DOCKER_HOST_IP" ]; then + # Replace an existing target as well, so repeated entrypoint calls are safe. + sed -i -E "s/(mavlink start -x)( -t [^ ]+)? -u/\1 -t $DOCKER_HOST_IP -u/g" \ + "$PX4_PREFIX/etc/init.d-posix/px4-rc.mavlink" +fi diff --git a/Tools/packaging/containers/ros2-dev-entrypoint.sh b/Tools/packaging/containers/ros2-dev-entrypoint.sh new file mode 100755 index 00000000000..2fe9e5ebfe5 --- /dev/null +++ b/Tools/packaging/containers/ros2-dev-entrypoint.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -e + +source /opt/ros/jazzy/setup.bash + +exec "$@" diff --git a/Tools/packaging/containers/ros2-entrypoint.sh b/Tools/packaging/containers/ros2-entrypoint.sh new file mode 100644 index 00000000000..8e1c4afccad --- /dev/null +++ b/Tools/packaging/containers/ros2-entrypoint.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -e + +source /usr/local/lib/px4/network.sh +source /opt/ros/jazzy/setup.bash +source /opt/px4_ros2/install/local_setup.bash + +exec "$@" diff --git a/Tools/packaging/containers/ros2-install-dependencies.sh b/Tools/packaging/containers/ros2-install-dependencies.sh new file mode 100644 index 00000000000..401763de400 --- /dev/null +++ b/Tools/packaging/containers/ros2-install-dependencies.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +set -euo pipefail + +rm -f /etc/apt/apt.conf.d/docker-clean +apt-get update +apt-get install -y --no-install-recommends ca-certificates curl +curl -fsSL "https://github.com/ros-infrastructure/ros-apt-source/releases/download/${ROS_APT_SOURCE_VERSION}/ros2-apt-source_${ROS_APT_SOURCE_VERSION}.noble_all.deb" \ + -o /ros2-apt-source.deb +apt-get install -y --no-install-recommends /ros2-apt-source.deb +rm /ros2-apt-source.deb +apt-get update +apt-get install -y --no-install-recommends \ + build-essential ccache cmake git ninja-build \ + python3-empy python3-pip ros-dev-tools ros-jazzy-ros-base + +# Keep Ubuntu/Jazzy's Python packages while satisfying PX4's shared requirements. +# Distro-only versions (e.g. ubuntu suffixes) cannot be pip constraints. +python3 - <<'PY' > /px4-python-constraints.txt +from importlib.metadata import distributions +from packaging.version import InvalidVersion, Version + +for dist in distributions(): + if not dist.metadata["Name"] or not dist.version: + continue + try: + Version(dist.version) + except InvalidVersion: + continue + print(f"{dist.metadata['Name']}=={dist.version}") +PY +RUNS_IN_DOCKER=true PIP_CONSTRAINT=/px4-python-constraints.txt PIP_NO_CACHE_DIR=1 \ + bash /px4-setup/ubuntu.sh --no-nuttx --no-sim-tools +rm /px4-python-constraints.txt + +rosdep init +rosdep update --rosdistro jazzy +if [ "$#" -gt 0 ]; then + # ROS setup scripts are not nounset-safe. + set +u + source /opt/ros/jazzy/setup.bash + rosdep install --from-paths "$1" --ignore-src --rosdistro jazzy -y +fi diff --git a/Tools/packaging/test_sih_mission.py b/Tools/packaging/containers/test_sih_mission.py similarity index 96% rename from Tools/packaging/test_sih_mission.py rename to Tools/packaging/containers/test_sih_mission.py index deeee6df843..07ef27d53ab 100644 --- a/Tools/packaging/test_sih_mission.py +++ b/Tools/packaging/containers/test_sih_mission.py @@ -13,8 +13,8 @@ Prerequisites: /path/to/mavsim-viewer -n 1 Usage: - python3 Tools/packaging/test_sih_mission.py - python3 Tools/packaging/test_sih_mission.py --speed 10 # faster-than-realtime + python3 Tools/packaging/containers/test_sih_mission.py + python3 Tools/packaging/containers/test_sih_mission.py --speed 10 # faster-than-realtime """ import asyncio diff --git a/Tools/packaging/postinst b/Tools/packaging/deb/gazebo/postinst similarity index 100% rename from Tools/packaging/postinst rename to Tools/packaging/deb/gazebo/postinst diff --git a/Tools/packaging/postrm b/Tools/packaging/deb/gazebo/postrm similarity index 100% rename from Tools/packaging/postrm rename to Tools/packaging/deb/gazebo/postrm diff --git a/Tools/packaging/px4-gazebo.sh b/Tools/packaging/deb/gazebo/px4-gazebo.sh similarity index 100% rename from Tools/packaging/px4-gazebo.sh rename to Tools/packaging/deb/gazebo/px4-gazebo.sh diff --git a/Tools/packaging/sih/postinst b/Tools/packaging/deb/sih/postinst similarity index 100% rename from Tools/packaging/sih/postinst rename to Tools/packaging/deb/sih/postinst diff --git a/Tools/packaging/sih/postrm b/Tools/packaging/deb/sih/postrm similarity index 100% rename from Tools/packaging/sih/postrm rename to Tools/packaging/deb/sih/postrm diff --git a/Tools/packaging/px4-entrypoint.sh b/Tools/packaging/px4-entrypoint.sh deleted file mode 100644 index a1d9b6c1f8a..00000000000 --- a/Tools/packaging/px4-entrypoint.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Docker entrypoint for PX4 SITL containers. -# -# On Docker Desktop (macOS/Windows), host.docker.internal resolves to the -# host machine. We detect this and configure MAVLink + DDS to send to the -# host IP instead of localhost (which stays inside the container VM). -# -# On Linux with --network host, host.docker.internal does not resolve and -# PX4 defaults work without modification. - -set -e - -# Detect install prefix (SIH uses /opt/px4, Gazebo uses /opt/px4-gazebo) -if [ -d /opt/px4-gazebo ]; then - PX4_PREFIX=/opt/px4-gazebo -else - PX4_PREFIX=/opt/px4 -fi - -# Resolve host.docker.internal to an IPv4 address. mavlink and uxrce_dds_client -# only parse IPv4, and on Docker Desktop for Windows the default `getent hosts` -# lookup can return an IPv6 ULA first, which both modules then reject. -DOCKER_HOST_IP=$(getent ahostsv4 host.docker.internal 2>/dev/null | awk '/STREAM/ {print $1; exit}') - -if [ -n "$DOCKER_HOST_IP" ]; then - # MAVLink: replace default target (127.0.0.1) with the Docker host IP - sed -i "s/mavlink start -x -u/mavlink start -x -t $DOCKER_HOST_IP -u/g" \ - "$PX4_PREFIX/etc/init.d-posix/px4-rc.mavlink" - - # DDS: point uXRCE-DDS client at the host - sed -i "s|uxrce_dds_client start -t udp|uxrce_dds_client start -t udp -h $DOCKER_HOST_IP|" \ - "$PX4_PREFIX/etc/init.d-posix/rcS" -fi - -exec "$PX4_PREFIX/bin/px4" "$@" diff --git a/Tools/ros2/prepare_workspace.py b/Tools/ros2/prepare_workspace.py new file mode 100755 index 00000000000..4d757f38734 --- /dev/null +++ b/Tools/ros2/prepare_workspace.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 + +import argparse +from pathlib import Path +import re +import shutil +import subprocess +import sys + +import yaml + + +def prepare_workspace( + workspace: Path, library_sha: str, repo_dir: Path +) -> None: + if library_sha and not re.fullmatch(r"[0-9a-fA-F]{40}", library_sha): + raise ValueError("LIBRARY_SHA must be a full 40-hex commit SHA") + if workspace.is_symlink() or ( + workspace.exists() + and (not workspace.is_dir() or any(workspace.iterdir())) + ): + raise ValueError( + f"Workspace must be a new or empty directory: {workspace}" + ) + + with (repo_dir / "Tools/ros2/ros2.repos").open() as stream: + manifest = yaml.safe_load(stream) + repositories = manifest["repositories"] + if library_sha: + repositories["px4-ros2-interface-lib"]["version"] = library_sha.lower() + for name, repository in repositories.items(): + version = repository["version"] + if repository["type"] != "git" or not ( + isinstance(version, str) and re.fullmatch(r"[0-9a-f]{40}", version) + ): + raise ValueError(f"{name}: expected an immutable git commit SHA") + if shutil.which("vcs") is None: + raise FileNotFoundError("vcs is required; install vcstool") + + sources = workspace / "src" + sources.mkdir(parents=True) + resolved_manifest = workspace / "ros2.repos" + resolved_manifest.write_text(yaml.safe_dump(manifest)) + with resolved_manifest.open() as stream: + subprocess.run( + ["vcs", "import", str(sources)], stdin=stream, check=True + ) + + for name, repository in repositories.items(): + actual = subprocess.check_output( + ["git", "-C", str(sources / name), "rev-parse", "HEAD"], text=True + ).strip() + if actual != repository["version"]: + raise ValueError( + f"{name}: expected {repository['version']}, got {actual}" + ) + print(f"{name}: {actual}", flush=True) + + subprocess.run( + [ + "bash", + str(repo_dir / "Tools/packaging/containers/prepare_context.sh"), + "--messages-only", + str(sources / "px4_msgs"), + ], + check=True, + ) + print("Resolved ROS source manifest:", flush=True) + print(resolved_manifest.read_text(), end="", flush=True) + revision = subprocess.run( + ["git", "-C", str(repo_dir), "rev-parse", "--verify", "HEAD"], + capture_output=True, text=True, + ) + if revision.returncode == 0: + print(f"PX4 source: {revision.stdout.strip()}", flush=True) + else: + print( + f"PX4 source revision unavailable: {revision.stderr.strip()}", + file=sys.stderr, + ) + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Prepare pinned ROS sources with this checkout's messages." + ) + parser.add_argument("workspace", metavar="WS_DIR") + parser.add_argument( + "library_sha", metavar="LIBRARY_SHA", nargs="?", default="" + ) + args = parser.parse_args() + if not args.workspace: + parser.error("WS_DIR must not be empty") + try: + prepare_workspace( + Path(args.workspace), args.library_sha, + Path(__file__).resolve().parents[2], + ) + except ( + ValueError, OSError, subprocess.CalledProcessError, yaml.YAMLError + ) as error: + parser.exit(1, f"{parser.prog}: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/Tools/ros2/ros2.repos b/Tools/ros2/ros2.repos new file mode 100644 index 00000000000..c3afa12c748 --- /dev/null +++ b/Tools/ros2/ros2.repos @@ -0,0 +1,9 @@ +repositories: + px4_msgs: + type: git + url: https://github.com/PX4/px4_msgs.git + version: 8fb8277cf95c4ba87094146bc8922e76c4ac0799 + px4-ros2-interface-lib: + type: git + url: https://github.com/Auterion/px4-ros2-interface-lib.git + version: 22943b5412235d2d36512d58b9073ae3de8fd1cd diff --git a/Tools/ros2/test_prepare_workspace.py b/Tools/ros2/test_prepare_workspace.py new file mode 100644 index 00000000000..b842a188896 --- /dev/null +++ b/Tools/ros2/test_prepare_workspace.py @@ -0,0 +1,153 @@ +from contextlib import ExitStack, redirect_stdout +import io +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +import yaml + +import prepare_workspace as tool + + +class PrepareWorkspaceTest(unittest.TestCase): + def setUp(self): + self.stack = ExitStack() + self.addCleanup(self.stack.close) + directory = self.stack.enter_context(tempfile.TemporaryDirectory()) + self.root = Path(directory) + self.repo = self.root / "px4" + self.manifest_path = self.repo / "Tools/ros2/ros2.repos" + self.manifest_path.parent.mkdir(parents=True) + self.manifest = {"repositories": { + "px4_msgs": { + "type": "git", "url": "https://example.invalid/messages.git", + "version": "a" * 40, + }, + "px4-ros2-interface-lib": { + "type": "git", "url": "https://example.invalid/interface.git", + "version": "b" * 40, + }, + }} + self.save_manifest() + self.workspace = self.root / "workspace" + self.run = self.stack.enter_context( + patch.object(tool.subprocess, "run") + ) + self.run.return_value = subprocess.CompletedProcess( + [], 0, stdout="c" * 40, stderr="" + ) + self.git = self.stack.enter_context( + patch.object(tool.subprocess, "check_output") + ) + self.git.side_effect = self.requested_revision + self.which = self.stack.enter_context( + patch.object(tool.shutil, "which", return_value="/usr/bin/vcs") + ) + self.stack.enter_context(redirect_stdout(io.StringIO())) + + def save_manifest(self): + self.manifest_path.write_text(yaml.safe_dump(self.manifest)) + + def requested_revision(self, command, **kwargs): + resolved = yaml.safe_load((self.workspace / "ros2.repos").read_text()) + repository = resolved["repositories"][Path(command[2]).name] + return repository["version"] + "\n" + + def test_imports_pins_and_refreshes_messages(self): + tool.prepare_workspace(self.workspace, "", self.repo) + self.assertEqual( + yaml.safe_load((self.workspace / "ros2.repos").read_text()), + self.manifest, + ) + self.assertEqual(self.git.call_count, 2) + self.assertEqual(self.run.call_args_list[0].args[0], [ + "vcs", "import", str(self.workspace / "src"), + ]) + self.assertEqual(self.run.call_args_list[1].args[0], [ + "bash", + str(self.repo / "Tools/packaging/containers/prepare_context.sh"), + "--messages-only", str(self.workspace / "src/px4_msgs"), + ]) + self.assertFalse((self.workspace / "ros2-import.repos").exists()) + + def test_empty_directory_and_uppercase_override(self): + self.workspace.mkdir() + tool.prepare_workspace(self.workspace, "D" * 40, self.repo) + resolved = yaml.safe_load((self.workspace / "ros2.repos").read_text()) + self.assertEqual( + resolved["repositories"]["px4-ros2-interface-lib"]["version"], + "d" * 40, + ) + self.assertEqual( + yaml.safe_load(self.manifest_path.read_text()), self.manifest + ) + + def test_rejects_unsafe_destinations(self): + occupied = self.root / "occupied" + occupied.mkdir() + marker = occupied / "keep" + marker.write_text("untouched") + symlink = self.root / "symlink" + symlink.symlink_to(occupied, target_is_directory=True) + dangling = self.root / "dangling" + dangling.symlink_to(self.root / "absent", target_is_directory=True) + for destination in (occupied, marker, symlink, dangling): + with self.subTest(destination=destination): + with self.assertRaisesRegex(ValueError, "new or empty"): + tool.prepare_workspace(destination, "", self.repo) + self.assertEqual(marker.read_text(), "untouched") + self.run.assert_not_called() + + def test_rejects_invalid_override_before_creating_workspace(self): + for version in ("main", "1234", "z" * 40): + with self.subTest(version=version): + with self.assertRaisesRegex(ValueError, "40-hex"): + tool.prepare_workspace(self.workspace, version, self.repo) + self.assertFalse(self.workspace.exists()) + + def test_rejects_mutable_or_non_git_manifest(self): + for change in ({"version": "main"}, {"version": 123}, {"type": "svn"}): + with self.subTest(change=change): + repository = self.manifest["repositories"]["px4_msgs"] + original = repository.copy() + repository.update(change) + self.save_manifest() + with self.assertRaisesRegex(ValueError, "immutable git"): + tool.prepare_workspace(self.workspace, "", self.repo) + repository.update(original) + self.assertFalse(self.workspace.exists()) + + def test_rejects_mismatched_checkout(self): + self.git.side_effect = None + self.git.return_value = "0" * 40 + with self.assertRaisesRegex(ValueError, "expected.*got"): + tool.prepare_workspace(self.workspace, "", self.repo) + self.assertEqual(self.run.call_count, 1) + + def test_stops_on_import_failure(self): + self.run.side_effect = subprocess.CalledProcessError( + 1, ["vcs", "import"] + ) + with self.assertRaises(subprocess.CalledProcessError): + tool.prepare_workspace(self.workspace, "", self.repo) + self.git.assert_not_called() + + def test_missing_vcs_does_not_create_workspace(self): + self.which.return_value = None + with self.assertRaisesRegex(FileNotFoundError, "vcstool"): + tool.prepare_workspace(self.workspace, "", self.repo) + self.assertFalse(self.workspace.exists()) + + def test_cli_rejects_empty_workspace(self): + with patch.object(tool.sys, "argv", ["prepare_workspace.py", ""]): + with patch.object(tool.sys, "stderr", io.StringIO()): + with self.assertRaises(SystemExit) as result: + tool.main() + self.assertEqual(result.exception.code, 2) + self.run.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/cmake/package.cmake b/cmake/package.cmake index dbbded6caf6..ee9c84d9600 100644 --- a/cmake/package.cmake +++ b/cmake/package.cmake @@ -87,7 +87,7 @@ if("${CMAKE_SYSTEM}" MATCHES "Linux") set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6, libstdc++6") set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "PX4 SITL autopilot with SIH physics (no Gazebo)") set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA - "${PX4_SOURCE_DIR}/Tools/packaging/sih/postinst;${PX4_SOURCE_DIR}/Tools/packaging/sih/postrm") + "${PX4_SOURCE_DIR}/Tools/packaging/deb/sih/postinst;${PX4_SOURCE_DIR}/Tools/packaging/deb/sih/postrm") else() set(CPACK_PACKAGING_INSTALL_PREFIX "/opt/px4-gazebo") set(CPACK_DEBIAN_PACKAGE_NAME "px4-gazebo") @@ -95,7 +95,7 @@ if("${CMAKE_SYSTEM}" MATCHES "Linux") set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6, libstdc++6, gz-harmonic, gstreamer1.0-plugins-base, gstreamer1.0-plugins-good, gstreamer1.0-plugins-bad, gstreamer1.0-plugins-ugly, gstreamer1.0-libav") set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "PX4 SITL autopilot with Gazebo Harmonic simulation resources") set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA - "${PX4_SOURCE_DIR}/Tools/packaging/postinst;${PX4_SOURCE_DIR}/Tools/packaging/postrm") + "${PX4_SOURCE_DIR}/Tools/packaging/deb/gazebo/postinst;${PX4_SOURCE_DIR}/Tools/packaging/deb/gazebo/postrm") endif() # Bake the install prefix into the px4 binary so it can locate its ROMFS diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.md index 12369ad09aa..9824dccf920 100644 --- a/docs/en/SUMMARY.md +++ b/docs/en/SUMMARY.md @@ -469,6 +469,7 @@ - [Visual Studio Code IDE](dev_setup/vscode.md) - [QGC Daily Build](dev_setup/qgc_daily_build.md) - [Building the Code](dev_setup/building_px4.md) + - [Building SITL Containers](dev_setup/sitl_container_builds.md) - [Writing your First Application](modules/hello_sky.md) - [Application/Module Template](modules/module_template.md) - [Concepts](concept/index.md) @@ -499,6 +500,7 @@ - [Multi-Vehicle Sim](sim_gazebo_classic/multi_vehicle_simulation.md) - [Simulate Failsafes](simulation/failsafes.md) - [Pre-built Packages](simulation/px4_sitl_prebuilt_packages.md) + - [Gazebo Container GUI](simulation/gazebo_container_gui.md) - [Hardware](hardware/index.md) - [Flight Controller Reference Design](hardware/reference_design.md) - [Manufacturers](hardware/manufacturers.md) diff --git a/docs/en/dev_setup/sitl_container_builds.md b/docs/en/dev_setup/sitl_container_builds.md new file mode 100644 index 00000000000..b9b15f245b1 --- /dev/null +++ b/docs/en/dev_setup/sitl_container_builds.md @@ -0,0 +1,191 @@ +# Building SITL Containers + +The [prebuilt SITL images](../simulation/px4_sitl_prebuilt_packages.md) share the existing `.deb` build and publishing workflow. +`Tools/packaging/containers/docker-bake.hcl` defines the image graph, tags and cache settings; `.github/workflows/build_deb_package.yml` supplies the simulator, architecture and version. + +## Source Layout + +Files are grouped by responsibility: + +```text +Tools/packaging/ + deb/ + gazebo/ Package lifecycle hooks and the installed Gazebo launcher + sih/ Package lifecycle hooks + containers/ + Dockerfile.* SIH, Gazebo and ROS image definitions + docker-bake.hcl Connected image build and publishing targets + prepare_context.sh Build-context staging + *-entrypoint.sh Container startup scripts + px4-network.sh Shared runtime host routing + ros2-install-dependencies.sh + test_sih_mission.py +Tools/ros2/ + prepare_workspace.py Checkout-matched ROS source workspace preparation + ros2.repos Shared immutable source pins for ROS development images +``` + +The generated `docker-context/` remains a flat staging directory; it is not the source layout. +ROS workspace preparation is separate from packaging because it is also used for source development. + +## Build And Publish Flow + +1. The package jobs build SIH and Gazebo `.deb`s for Ubuntu Noble and Jammy. +2. Four native container jobs consume the Noble packages: SIH/Gazebo on amd64/arm64. + Each job runs `Tools/packaging/containers/prepare_context.sh` to stage the package context and matching PX4 messages, then builds the runtime image and its ROS child together with Docker Bake. +3. On release tags or a manual run with deployment enabled, the jobs push architecture-specific images to Docker Hub and GHCR. + The deploy jobs combine those images into versioned and `latest` multi-architecture tags using `docker buildx imagetools create`. + +Pull requests build the same graph without publishing. +The ROS image consumes its parent directly through a Bake target context, so neither local builds nor pull requests need an unpublished parent tag in a registry. + +## Building Locally + +Run these commands from the repository root on Ubuntu 24.04 with [PX4 build dependencies](dev_env_linux_ubuntu.md) and Docker Buildx installed: + +```sh +make px4_sitl_sih +(cd build/px4_sitl_sih && cpack -G DEB) +mkdir -p docker-context +cp build/px4_sitl_sih/*.deb docker-context/ +bash Tools/packaging/containers/prepare_context.sh +SIMULATOR=sih docker buildx bake -f Tools/packaging/containers/docker-bake.hcl --load +``` + +On macOS or Windows, obtain Noble `.deb`s for the same PX4 revision and Docker architecture instead of building the packages natively, then start at the context-preparation step. +Do not combine packages from different revisions or architectures in one context. +For Gazebo, build `px4_sitl_default` and set `SIMULATOR=gazebo`. + +`ARCH` defaults to the Docker builder's local architecture and `VERSION` defaults to `dev`. +For example, an ARM64 SIH build produces `px4io/px4-sitl-ros2:dev-arm64`. +Override `VERSION` and `ARCH` through environment variables when needed. +Replace `--load` with `--print` to inspect the resolved graph without building, or add `--set ros2.tags=px4-ros2:local` to choose a local ROS image tag. + +## Cache Boundaries + +Every successful `RUN` creates a cacheable layer. +A failed step is not committed as an image layer. +Changing an input invalidates its layer and subsequent layers, not earlier ones. + +`Tools/ros2/ros2.repos` pins the ROS repositories to immutable commits for ROS images. +The interface-library pin includes the manual WaitSet ownership fixes merged in [Auterion/px4-ros2-interface-lib#222](https://github.com/Auterion/px4-ros2-interface-lib/pull/222). +To test another interface-library commit in an image, pass `--set ros2.args.PX4_ROS2_REF=<40-hex-SHA>` to Bake. +`PX4_MSGS_REF` can similarly override the message-package metadata; the definitions always come from the PX4 checkout. +The base ROS/rosdep setup, DDS Agent, message-package metadata, interface-library sources, workspace dependency installation, compilation and tests have separate cache boundaries. +Message definitions are copied after dependency installation, so changing them does not repeat `rosdep install`. +Repository checkouts live in a separate source stage and are mounted read-only for dependency installation. +The development toolchain does not inherit those source layers; only the ROS workspace builder copies the checkouts. +Changing only the ROS entrypoint does not rebuild the workspace, and changing only the test command does not recompile it. + +The Agent and ROS workspace build in independent Ubuntu 24.04/Jazzy stages, keyed to source pins and the supplied PX4 message definitions rather than the packaged firmware. +A new PX4 binary with unchanged messages reuses those compilation and test layers. +Changed messages invalidate workspace compilation and tests; cached artifacts never substitute messages from another checkout. +The final image still derives from the connected SIH/Gazebo parent and installs its Ubuntu/ROS dependencies using the same helper as the builder. +Only the source-built Agent/logger and complete ROS workspace are copied, preserving the source/build/install layout and absolute symlinks without copying the builder's operating system or package database. +The Agent installation is staged with CMake's `DESTDIR`, so copying it cannot overwrite Python packages installed separately in the destination image. +APT cache mounts are held only during installation, not during compilation or tests. +The runtime Dockerfiles extract the package's `Depends` field into a separate stage, so their dependency layers are keyed to that field rather than to every firmware binary change. +Package jobs disable Ubuntu's container cleanup hook so downloaded APT archives survive installation and can be cached between runs. + +In Actions, `CACHE_GHA=true` enables one cache per simulator and architecture. +The ROS target exports `mode=max`, covering its entire graph including the runtime parent. +The compiler cache is persisted separately with `actions/cache` and `buildkit-cache-dance`, allowing unchanged compilation units to be reused when workspace inputs change. +Ccache checks compiler contents and source/header inputs; it does not substitute an old ROS workspace for changed PX4 messages. +The container jobs use eight native CPUs, matching the Dockerfile's `BUILD_JOBS` default. +Override that build argument with Bake's `--set ros2.args.BUILD_JOBS=4` when building on a smaller machine. +Local builds use the builder's regular cache by default; standard Bake `--set` options can select other cache backends. +Cached installs do not automatically refresh upstream packages: rebuild without cache when intentionally refreshing dependencies. + +## Updating ROS Source Pins + +Source pins are maintained manually through reviewed pull requests, not advanced automatically when images are built. +Update the full commit SHA in `Tools/ros2/ros2.repos` when adopting upstream changes. +Run the container builds before accepting an update. + +The `px4_msgs` pin selects package metadata and build logic, not the message definitions used to build the workspace. +Definitions always come from the PX4 checkout, so ordinary message changes do not require a pin update. +Image and workspace-helper SHA overrides are for testing candidates; adopting a candidate requires updating the shared manifest. + +## Testing A PX4 Checkout With ROS + +The standalone `ghcr.io/px4/px4-dev-ros2:main-jazzy` image includes Jazzy, the Agent, PX4's source-build dependencies and the dependencies required by the pinned ROS repositories. +It contains no repository checkouts, packaged PX4 firmware or compiled ROS workspace, and its entrypoint sources only the Jazzy underlay. +It is published independently of the SITL package workflow, so it does not wait for `.deb` builds. +Publishing follows the same release-tag and opt-in manual policy as `px4-dev`. + +The `main-jazzy` tag names the manually published toolchain for PX4 `main` development with ROS Jazzy, not bundled firmware. +Pushing a `v*` Git tag publishes `-jazzy`, such as `v1.18.0-jazzy`, without updating `main-jazzy`. +Each publication also provides `sha--jazzy`, identifying the repository revision used to build the toolchain. +Release-line toolchains can use tags such as `v1.18-jazzy` through the manual publisher's `tag` input when that release line is maintained. +The source revision and intended PX4 release line do not change which firmware a checkout builds. + +The optional `ros2-dev` Bake target builds this image without `.deb` packages or a published SITL parent: + +```sh +bash Tools/packaging/containers/prepare_context.sh +docker buildx bake -f Tools/packaging/containers/docker-bake.hcl ros2-dev \ + --set ros2-dev.tags=px4-dev-ros2:local --load +SOURCE=$(pwd -P) +GIT_COMMON_DIR=$(git rev-parse --path-format=absolute --git-common-dir) +docker run --rm -it \ + -v "$SOURCE:$SOURCE" -v "$GIT_COMMON_DIR:$GIT_COMMON_DIR" -w "$SOURCE" \ + -e GIT_CONFIG_COUNT=1 -e GIT_CONFIG_KEY_0=safe.directory \ + -e "GIT_CONFIG_VALUE_0=$SOURCE" px4-dev-ros2:local bash +``` + +The same absolute mounts support both ordinary checkouts and git worktrees. +The Git ownership exception is scoped to this container and checkout. +Inside the container, build the current checkout; the build initialises its required submodules: + +```bash +PX4_DIR=$PWD +make px4_sitl_sih +source /opt/ros/jazzy/setup.bash +python3 Tools/ros2/prepare_workspace.py /opt/px4_ros2_ci +cd /opt/px4_ros2_ci +sudo apt-get update -qq +rosdep update --rosdistro jazzy +rosdep install --from-paths src --ignore-src --rosdistro jazzy -y +colcon build --symlink-install --cmake-args \ + -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache +colcon test --packages-select px4_ros2_cpp --ctest-args -R unit_tests +colcon test-result --verbose +source install/setup.bash +cd "$PX4_DIR" +``` + +The workspace helper requires a new or empty directory, imports the standard `ros2.repos` manifest with vcstool, and replaces message/service definitions with those from the current PX4 checkout, including removal of deleted definitions. +Each run imports the pinned repositories directly with vcstool, without reusing an existing source or compiled workspace. +It preserves all library packages, examples and Python tests. +An optional second argument selects another interface-library commit using its full 40-character SHA. +The helper prints the resolved source manifest, repository commits and PX4 commit; it does not build the workspace. + +`CACHE_GHA=true` uses an independent `ros2-dev-` image cache, without replacing the published SITL image caches. +The `ros_dev_container.yml` workflow builds the standalone target on every `main` push and on pull requests that change its watched paths, without publishing. +It publishes to GHCR only on `v*` tag pushes or manual runs with `deploy_to_registry=true`. +Manual runs use the `tag` input, which defaults to `main-jazzy`; the deployment toggle also applies when dispatching against a Git tag. +Architecture tags use `sha--jazzy-`; the final selected tag and `sha--jazzy` indexes preserve both architectures and their SBOMs. +Use `--set ros2-dev.args.PX4_ROS2_REF=<40-hex-SHA>` to build the development image with another interface-library commit. + +Both ROS development images reuse `Tools/setup/ubuntu.sh --no-nuttx --no-sim-tools` and its Python requirements. +Already installed Ubuntu/Jazzy Python versions are constrained during installation instead of gratuitously upgrading the ROS stack. +The SIH image does not acquire Gazebo or the NuttX toolchain. +Installing the complete source-build toolset increases cold image-build time and size; existing native architecture and incremental cache boundaries remain in use. + +## Container SBOMs + +The publishing workflow enables BuildKit's standard SBOM attestations for both runtime and ROS images. +These SPDX inventories describe discoverable packages in the image filesystem, including Ubuntu and ROS dependencies. +They complement, rather than replace, PX4's [source and firmware SBOM](../contribute/sbom.md). + +Each architecture is published with its attestation. +The final `imagetools create` step preserves those attestations when assembling multi-architecture indexes. +Inspect a published image with: + +```sh +docker buildx imagetools inspect px4io/px4-sitl-ros2: --format '{{json .SBOM}}' +``` + +Non-publishing pull-request builds do not publish an SBOM for inspection. +Local `--load` builds are intended for running examples; use a registry or an OCI export when retaining attestations. diff --git a/docs/en/simulation/gazebo_container_gui.md b/docs/en/simulation/gazebo_container_gui.md new file mode 100644 index 00000000000..e017b529a82 --- /dev/null +++ b/docs/en/simulation/gazebo_container_gui.md @@ -0,0 +1,154 @@ +# Gazebo Container GUI + +The [Gazebo runtime and ROS development images](px4_sitl_prebuilt_packages.md) can display the Gazebo Harmonic GUI through a Linux X server or Windows WSLg. +Both use the same X11 client libraries and Qt configuration. +The X server runs outside the application container; installing Xvfb inside the image would not forward a window to your desktop. + +The examples use software rendering to avoid depending on GPU passthrough. +Gazebo still renders the 3D scene, but performance depends on the CPU. +Leave `HEADLESS` unset or empty: `HEADLESS=0` also disables the GUI. + +## Linux + +Use Docker Engine from a local graphical-session terminal, with `DISPLAY` set and the host's `xauth` command installed. +Xorg and Wayland desktops with XWayland are supported by this X11 route. +The following command copies only the current display's authentication records into a private temporary file: + +```bash +( + set -euo pipefail + umask 077 + : "${DISPLAY:?Open a terminal in your local graphical session}" + IMAGE="${IMAGE:-px4io/px4-sitl-gazebo:latest}" + auth=$(mktemp) + trap 'rm -f "$auth"' EXIT + + xauth nlist "$DISPLAY" | + sed 's/^..../ffff/' | + xauth -f "$auth" nmerge - + if [ ! -s "$auth" ]; then + echo "No Xauthority cookie for $DISPLAY; check the host XAUTHORITY setting." >&2 + exit 1 + fi + + docker run --rm -it --name px4-gazebo --network host \ + --mount type=bind,src=/tmp/.X11-unix,dst=/tmp/.X11-unix,readonly \ + --mount "type=bind,src=$auth,dst=/tmp/px4.xauth,readonly" \ + -e "DISPLAY=$DISPLAY" -e XAUTHORITY=/tmp/px4.xauth \ + -e QT_QPA_PLATFORM=xcb -e LIBGL_ALWAYS_SOFTWARE=1 \ + -e ROS_DOMAIN_ID=83 \ + "$IMAGE" +) +``` + +The copied cookie uses a wildcard address family so the container's hostname does not need to match the host's. +Authentication remains enabled. +Only give this cookie to trusted images: it grants access to your X session. +Do not use `xhost +`, `--privileged` or shared host IPC. +The example assumes ordinary rootful Docker; rootless or user-namespace-remapped installations may require different file ownership, not world-readable cookie permissions. + +### GPU Acceleration + +Once software rendering works, remove `-e LIBGL_ALWAYS_SOFTWARE=1` and add the appropriate options before the image name: + +| Linux GPU | Docker Options | +| --- | --- | +| Intel/AMD with DRM render devices | `--device=/dev/dri` | +| NVIDIA with the host driver and NVIDIA Container Toolkit | `--gpus all -e NVIDIA_DRIVER_CAPABILITIES=compute,utility,graphics,display` | + +NVIDIA's default compute/utility capabilities alone do not provide the graphics/display libraries. +See the [NVIDIA Container Toolkit documentation](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/docker-specialized.html#driver-capabilities). +GPU access remains opt-in; the images do not force software rendering globally. + +## Windows With WSLg + +Use Windows 11, an up-to-date WSL2 Ubuntu distribution, and Docker Desktop's Linux-container backend with [WSL integration](https://docs.docker.com/desktop/features/wsl/) enabled for that distribution. +Run the commands below from its Ubuntu terminal, not PowerShell. +WSLg supplies the X server; a separate Windows X server is not required. + +```bash +( + set -euo pipefail + IMAGE="${IMAGE:-px4io/px4-sitl-gazebo:latest}" + if [ "${DISPLAY:-}" != :0 ] || [ ! -S /mnt/wslg/.X11-unix/X0 ]; then + echo "WSLg display unavailable; check WSLg and Docker Desktop WSL integration." >&2 + exit 1 + fi + + docker run --rm -it --name px4-gazebo \ + --mount type=bind,src=/mnt/wslg/.X11-unix,dst=/tmp/.X11-unix,readonly \ + -e DISPLAY=:0 -e QT_QPA_PLATFORM=xcb \ + -e LIBGL_ALWAYS_SOFTWARE=1 -e ROS_DOMAIN_ID=83 \ + "$IMAGE" +) +``` + +This follows [Microsoft's X11 container interface](https://github.com/microsoft/wslg/blob/main/samples/container/Containers.md), using the resolved WSLg socket directory. +The recipe has not yet been exercised on a Windows host with these images. +Standard WSLg does not require creating an Xauthority file or changing `xhost` access rules. +Do not replace its `DISPLAY` with a Windows host IP from older X-server instructions. +Do not forward `WAYLAND_DISPLAY`: this recipe deliberately selects Qt's XCB backend. + +If Docker cannot bind the socket, confirm integration with the Ubuntu distribution and follow [WSLg display diagnostics](https://github.com/microsoft/wslg/wiki/Diagnosing-%22cannot-open-display%22-type-issues-with-WSLg). +The software-rendering example does not require `/dev/dxg` or Windows GPU passthrough. +Windows GPU acceleration has additional driver, Mesa and Docker-backend requirements; it is not implied by Docker's support for GPU compute. + +## ROS Development Image + +Before running either platform's example, select the ROS variant: + +```bash +export IMAGE=px4io/px4-sitl-gazebo-ros2:latest +``` + +It opens a ROS-enabled shell instead of starting PX4 automatically. +In that shell, start the Agent: + +```sh +MicroXRCEAgent udp4 -p 8888 +``` + +From a second host terminal, start PX4 and the Gazebo GUI: + +```sh +docker exec -it px4-gazebo /usr/local/bin/ros2-entrypoint.sh px4-gazebo +``` + +The [ROS topic and Go-to example commands](px4_sitl_prebuilt_packages.md#go-to-example) also apply; use `px4-gazebo` as the container name. +Use distinct `ROS_DOMAIN_ID` values for independent simulations. + +## Diagnostics + +While the container is running, inspect the OpenGL implementation: + +```sh +docker exec px4-gazebo glxinfo -B +``` + +Software rendering should report a renderer such as `llvmpipe`. +Ogre 2 needs a working OpenGL 3.3-class-or-newer implementation and its required extensions; upstream recommends OpenGL 4.3 or newer. +See [Gazebo's rendering troubleshooting](https://gazebosim.org/docs/harmonic/troubleshooting/). +Successfully displaying a simple X11 window is not sufficient evidence that Gazebo can render. + +If PX4 starts but the window does not appear, launch the GUI with visible diagnostics: + +```sh +docker exec px4-gazebo gz sim -g -v 4 +``` + +For XCB plugin loading failures, add `-e QT_DEBUG_PLUGINS=1` to that `docker exec` command. +The images include Qt SVG support for GUI icons and set `QT_X11_NO_MITSHM=1` because the container and host X server do not share an IPC namespace. + +## macOS And Linux Virtual Machines + +Gazebo containers on macOS are supported headlessly, using `-e HEADLESS=1`. +XQuartz 2.8.5 accepted an authenticated X11 connection in our evaluation, but its indirect OpenGL path failed to render Gazebo with both Ogre 2 and Ogre 1. +Changing the Qt backend to software did not provide a working fallback. +The limitation was rendering, not an inability to speak X11. +For SIH, use [native Hawkeye](../sim_hawkeye/index.md) instead. + +A Linux desktop VM is another way to use and evaluate the Linux GUI path from macOS. +On Apple Silicon, use an Ubuntu 24.04 ARM64 guest and ARM64 container images. +Run Docker and the Linux commands above inside the guest, initially with software rendering. +The GUI appears on the VM's desktop without passing through XQuartz. +An isolated Linux Xvfb server can also exercise socket forwarding, authorization and Mesa rendering automatically, but does not validate desktop integration or physical GPU drivers. diff --git a/docs/en/simulation/px4_sitl_prebuilt_packages.md b/docs/en/simulation/px4_sitl_prebuilt_packages.md index 3aaf9196c3f..cbbf6fa6c9d 100644 --- a/docs/en/simulation/px4_sitl_prebuilt_packages.md +++ b/docs/en/simulation/px4_sitl_prebuilt_packages.md @@ -86,47 +86,129 @@ Tags follow PX4 versions (e.g. `v1.17.0`). ### Running +On Docker Desktop (macOS/Windows), the containers automatically send MAVLink to the host using `host.docker.internal`. +Run QGroundControl, MAVSDK or Hawkeye on the host without publishing their listening ports with Docker `-p`. + ```bash # SIH -docker run --rm -it -p 14550:14550/udp px4io/px4-sitl:latest +docker run --rm -it px4io/px4-sitl:latest -# Gazebo -docker run --rm -it -p 14550:14550/udp px4io/px4-sitl-gazebo:latest +# Gazebo (headless) +docker run --rm -it -e HEADLESS=1 px4io/px4-sitl-gazebo:latest ``` +For a visible Gazebo window on Linux or Windows/WSLg, use the [Gazebo Container GUI](gazebo_container_gui.md) instructions. +On macOS, run Gazebo headlessly or use a Linux desktop VM. + Pass environment variables with `-e`: ```bash -docker run --rm -it -p 14550:14550/udp \ +docker run --rm -it \ -e PX4_SIM_MODEL=sihsim_airplane \ px4io/px4-sitl:latest ``` -The quick-start command above only exposes the QGroundControl port. -To use MAVSDK, uXRCE-DDS (ROS 2), or MAVSim Viewer, expose the additional ports: - -```bash -docker run --rm -it \ - -p 14550:14550/udp \ - -p 14540:14540/udp \ - -p 8888:8888/udp \ - -p 19410:19410/udp \ - px4io/px4-sitl:latest -``` +The default destination ports are: | Port | Protocol | Used by | | ----- | -------- | --------------------------- | | 14550 | UDP | QGroundControl | | 14540 | UDP | MAVSDK / offboard API | | 8888 | UDP | uXRCE-DDS agent (ROS 2) | -| 19410 | UDP | SIH display (MAVSim Viewer) | +| 19410 | UDP | [Hawkeye](../sim_hawkeye/index.md) SIH visualisation | -On Linux, you can skip individual port flags and use `--network host` instead: +On Linux, add `--network host`: ```bash docker run --rm -it --network host px4io/px4-sitl:latest ``` +Alternatively, use bridged networking with `--add-host=host.docker.internal:host-gateway`. +When that hostname is unavailable, PX4 retains its localhost defaults. +The runtime images also target the host for DDS; the ROS development images keep DDS inside the container. + +### Hawkeye Visualisation + +Both `px4io/px4-sitl` and `px4io/px4-sitl-ros2` automatically stream SIH state to the host on UDP 19410. +After starting PX4, launch [Hawkeye](../sim_hawkeye/index.md) on the host: + +```sh +hawkeye -udp 19410 +``` + +Use the platform-specific networking options above; no manual MAVLink stream commands or ROS bridge are needed. +Do not publish port 19410 with Docker `-p`, because Hawkeye must bind that port on the host. + +### ROS 2 Development Images + +The ROS development variants add ROS 2 Jazzy, Micro XRCE-DDS Agent v2.4.3, `px4_msgs`, and the [PX4 ROS 2 Interface Library](../ros2/px4_ros2_interface_lib.md), including its examples and development tools. +They also include PX4 source-build dependencies for SITL, without installing the NuttX toolchain. +They support `amd64` and `arm64`, with the same version tags as the runtime images. +The ROS message definitions match the packaged PX4 firmware. + +| Image | Simulator | +| ----- | --------- | +| `px4io/px4-sitl-ros2:` | SIH, without Gazebo dependencies | +| `px4io/px4-sitl-gazebo-ros2:` | Gazebo Harmonic | + +Unlike the runtime images, these open a shell with ROS and the workspace at `/opt/px4_ros2` already sourced. +PX4 and the DDS Agent are started explicitly and communicate inside the same container. + +```sh +# Terminal 1: open the development environment and start the Agent. +docker run --rm -it --name px4-ros2 \ + -e ROS_DOMAIN_ID=83 \ + -v "$PWD:/workspace" px4io/px4-sitl-ros2:latest +MicroXRCEAgent udp4 -p 8888 + +# Terminal 2: start the packaged SIH simulator. +docker exec -it px4-ros2 /usr/local/bin/ros2-entrypoint.sh px4 + +# Terminal 3: inspect the ROS topics. +docker exec -it px4-ros2 /usr/local/bin/ros2-entrypoint.sh ros2 topic list +``` + +For headless Gazebo, use `px4io/px4-sitl-gazebo-ros2` and replace `px4` with `env HEADLESS=1 px4-gazebo`. +For a visible window, configure the container's display using [Gazebo Container GUI](gazebo_container_gui.md#ros-development-image) and leave `HEADLESS` unset. +Host ROS nodes require additional DDS networking configuration; the example keeps ROS, the Agent and PX4 together and does not require host networking. + +When testing modified PX4 firmware, rebuild the ROS workspace against its message definitions rather than using the bundled library. +Use `--entrypoint /bin/bash` and source `/opt/ros/jazzy/setup.bash` to start without the bundled workspace. +For source builds and selecting an interface-library commit, see [Testing A PX4 Checkout With ROS](../dev_setup/sitl_container_builds.md#testing-a-px4-checkout-with-ros). +The standalone `ghcr.io/px4/px4-dev-ros2:main-jazzy` toolchain provides the build tools and ROS dependencies without bundled source checkouts, firmware or a compiled workspace. + +#### Go-To Example + +With the Agent and PX4 running as above, start the bundled example from a host terminal: + +```sh +docker exec -it px4-ros2 /usr/local/bin/ros2-entrypoint.sh \ + ros2 run example_mode_goto_cpp example_mode_goto +``` + +Wait for the example to register and for PX4 to report `Ready for takeoff!`. +At the PX4 `pxh>` prompt, start a simulated take-off: + +```text +commander takeoff +``` + +Once the vehicle is hovering, activate the example: + +```text +commander mode ext1 +``` + +With only this example registered, `ext1` selects `Go-to Example`, which flies a triangular path. +Take off before selecting it: the example prevents arming while its mode is active. +Hawkeye can visualise this flight without changing the ROS setup. + +To land, enter `commander mode auto:land` at the PX4 prompt. +To stop the container, run `docker stop px4-ros2` from the host. +Use a different `ROS_DOMAIN_ID` for each independent ROS simulation to avoid cross-talk. + +For local builds, publishing, cache behaviour and SBOMs, see [Building SITL Containers](../dev_setup/sitl_container_builds.md). + ## Configuration These options apply to both `.deb` packages and containers. @@ -143,7 +225,7 @@ SIH: PX4_SIM_MODEL=sihsim_airplane px4 # Container -docker run --rm -it -p 14550:14550/udp px4io/px4-sitl:latest -e PX4_SIM_MODEL=sihsim_airplane +docker run --rm -it -e PX4_SIM_MODEL=sihsim_airplane px4io/px4-sitl:latest ``` Gazebo: @@ -153,7 +235,7 @@ Gazebo: PX4_SIM_MODEL=gz_x500 px4-gazebo # Container -docker run --rm -it -p 14550:14550/udp px4io/px4-sitl-gazebo:latest -e PX4_SIM_MODEL=gz_x500 +docker run --rm -it -e HEADLESS=1 -e PX4_SIM_MODEL=gz_x500 px4io/px4-sitl-gazebo:latest ``` See [SIH Supported Vehicles](../sim_sih/index.md#supported-vehicle-types) and [Gazebo Vehicles](../sim_gazebo_gz/vehicles.md) for the full lists. diff --git a/platforms/posix/CMakeLists.txt b/platforms/posix/CMakeLists.txt index 5264e5a7429..4263aa2354a 100644 --- a/platforms/posix/CMakeLists.txt +++ b/platforms/posix/CMakeLists.txt @@ -273,7 +273,7 @@ elseif("${PX4_BOARD}" MATCHES "sitl") if(CONFIG_MODULES_SIMULATION_GZ_BRIDGE) # Gazebo wrapper script (sets GZ_SIM_* env vars pointing at installed resources) install( - PROGRAMS ${PROJECT_SOURCE_DIR}/Tools/packaging/px4-gazebo.sh + PROGRAMS ${PROJECT_SOURCE_DIR}/Tools/packaging/deb/gazebo/px4-gazebo.sh DESTINATION bin RENAME px4-gazebo )