From 40e969a8f7afdfe410a88826bdc8c82bdb6835dc Mon Sep 17 00:00:00 2001 From: Darcy Quesnel Date: Wed, 2 Dec 2026 13:24:25 -0500 Subject: [PATCH 1/2] Add local Apple container deployment for CBRAIN v8 --- .dockerignore | 8 + .gitignore | 2 + README.md | 5 + deploy/apple-container/Containerfile | 18 ++ deploy/apple-container/README.md | 94 +++++++++ deploy/apple-container/apple-container.sh | 233 ++++++++++++++++++++++ deploy/apple-container/entrypoint.sh | 62 ++++++ deploy/apple-container/local.rake | 106 ++++++++++ 8 files changed, 528 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 deploy/apple-container/Containerfile create mode 100644 deploy/apple-container/README.md create mode 100755 deploy/apple-container/apple-container.sh create mode 100755 deploy/apple-container/entrypoint.sh create mode 100644 deploy/apple-container/local.rake diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..c54b3942e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.git +.local +**/log/* +**/tmp/* +**/.bundle +**/config/database.yml +**/config/initializers/config_portal.rb +**/config/initializers/config_bourreau.rb diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..120627544 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# Local Apple container deployment credentials +.local/ diff --git a/README.md b/README.md index 4a3b5e3db..7b4bd53c5 100644 --- a/README.md +++ b/README.md @@ -46,3 +46,8 @@ running on the HPC where it resides. CBRAIN is extensively documented in its [Wiki](https://github.com/aces/cbrain/wiki). + +## Local deployment on macOS + +To run BrainPortal and a local Bourreau worker with Apple’s `container` CLI, +see [the local deployment guide](deploy/apple-container/README.md). diff --git a/deploy/apple-container/Containerfile b/deploy/apple-container/Containerfile new file mode 100644 index 000000000..ceb2fecde --- /dev/null +++ b/deploy/apple-container/Containerfile @@ -0,0 +1,18 @@ +FROM docker.io/library/ruby:4.0.2-bookworm +RUN apt-get update && apt-get install -y --no-install-recommends \ + default-libmysqlclient-dev mariadb-client nodejs rsync openssh-client openssh-server \ + python3-pip libffi-dev libsodium-dev supervisor curl procps iproute2 && \ + pip3 install --break-system-packages --no-cache-dir boutiques && rm -rf /var/lib/apt/lists/* +WORKDIR /opt/cbrain +COPY BrainPortal/Gemfile BrainPortal/Gemfile +COPY Bourreau/Gemfile Bourreau/Gemfile +RUN cd BrainPortal && bundle install --jobs 4 && \ + cd ../Bourreau && bundle install --jobs 4 + +COPY . . +RUN cd BrainPortal && bundle exec rake cbrain:plugins:install:plugins + +COPY deploy/apple-container/local.rake BrainPortal/lib/tasks/apple_container_local.rake +ENV RAILS_ENV=development +EXPOSE 3000 +ENTRYPOINT ["/opt/cbrain/deploy/apple-container/entrypoint.sh"] diff --git a/deploy/apple-container/README.md b/deploy/apple-container/README.md new file mode 100644 index 000000000..089abb1a3 --- /dev/null +++ b/deploy/apple-container/README.md @@ -0,0 +1,94 @@ +# Local CBRAIN with Apple container + +This runs BrainPortal, a local Bourreau (`ScirUnix`), and MariaDB in three +ARM64 Linux containers. It uses Apple's `container` CLI; +Docker Desktop and Docker Compose are not needed. `Containerfile` uses the OCI +build syntax accepted by Apple container; `.dockerignore` is its build-context +exclusion file. + +## Start + +Requires an Apple silicon Mac running macOS 26 or newer, Python 3, and Apple's +`container` CLI on `PATH`. Install the signed package from the +[Apple container releases](https://github.com/apple/container/releases). +The launcher checks these prerequisites before invoking container commands or +creating local state, and explains how to resolve a missing prerequisite. +The `credentials` command can still read saved credentials without the runtime. + +From the repository root: + +```sh +deploy/apple-container/apple-container.sh up +deploy/apple-container/apple-container.sh credentials +``` + +The first `up` builds the image and starts the services. Open + and sign in as `admin` using the generated initial +password. CBRAIN asks you to change it on first login. The initial password +command does not track subsequent password changes. + +The setup creates `LocalPortal`, `LocalBourreau`, `LocalStorage`, and local +Diagnostics, Parallelizer, and CbSerializer tool configurations. The worker runs +UNIX jobs inside `cbrain-bourreau`. BrainPortal starts the execution server +and its task worker over SSH. Scientific tools and their datasets must be +installed/configured separately. + +```sh +deploy/apple-container/apple-container.sh status +deploy/apple-container/apple-container.sh smoke # runs Diagnostics and verifies a saved report +deploy/apple-container/apple-container.sh logs +deploy/apple-container/apple-container.sh shell +deploy/apple-container/apple-container.sh stop +deploy/apple-container/apple-container.sh up +``` + +Only the portal's HTTP port (3000) is published, on `127.0.0.1`. All three +containers use the `cbrain-local` network. The portal starts Bourreau over SSH +and forwards its database connection through that SSH session. Bourreau +uses the forwarded portal identity to read and write `LocalStorage` on +the portal container. The launcher installs the SSH host keys it reads +from each container. + +## Persistence and rebuilds + +- `cbrain-db-data`: MariaDB database. +- `cbrain-app-data`: provider files, portal cache, SSH identity and host key, + and portal logs. +- `cbrain-bourreau-data`: task work directories, worker cache, SSH host key, + and Bourreau logs. +- `.local/apple-container/env`: generated passwords and session secret, mode 600, + excluded from Git and the image. Keep this file with database backups. + +Run the launcher from the checkout that created the profile. Its containers +and volumes are shared across checkouts, while its credentials live in that +checkout's `.local` directory. + +`stop` preserves containers and volumes. If MariaDB receives a new IP on restart, +`up` recreates the portal container with the new address and reuses its data +volume. Portal startup runs migrations, and `up` ensures the local resources exist. +The admin password is set when the database is first seeded. + +After changing the source, let active jobs finish, then rebuild and restart +the deployment. + +```sh +deploy/apple-container/apple-container.sh rebuild +``` + +`rebuild` builds the image and replaces the application containers while +keeping the database and named volumes. The `build` +command is available for building the image on its own. + +On upgrade from the combined container, run `rebuild`. +The launcher replaces the combined app container, copies its work directories +and worker cache into the new worker volume, and updates `LocalStorage` to +use SSH. The provider keeps the same record and files. Its old cache status +entries are cleared so each app can resync through SSH. + +This is a local development deployment for CBRAIN v8, using Ruby 4.0.2 +and Rails 8.1 on Debian Bookworm. Do not expose +this deployment publicly. Budget approximately 7 GB RAM for the running services +plus the image builder during builds. + +The smoke check leaves its completed task and Diagnostics report in CBRAIN so +you can inspect them in the portal. Each invocation creates one small report. diff --git a/deploy/apple-container/apple-container.sh b/deploy/apple-container/apple-container.sh new file mode 100755 index 000000000..c8d41b786 --- /dev/null +++ b/deploy/apple-container/apple-container.sh @@ -0,0 +1,233 @@ +#!/bin/bash +# Local CBRAIN deployment using Apple's container CLI (no Docker daemon). +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/../.." && pwd) +STATE="$ROOT/.local/apple-container" +# Use the canonical tag written by container build. +IMAGE=docker.io/library/cbrain-local:dev +app=cbrain-app +worker=cbrain-bourreau +db=cbrain-db +network=cbrain-local + +check_host() { + if [ "$(uname -s)" != Darwin ]; then + echo 'Error: Apple container requires macOS on an Apple silicon Mac.' >&2 + exit 1 + fi + # A shell running under Rosetta reports x86_64 even on Apple silicon. + if [ "$(uname -m)" != arm64 ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || true)" != 1 ]; then + echo 'Error: Apple container requires Apple silicon; Intel Macs are not supported.' >&2 + exit 1 + fi + local macos_version macos_major + macos_version=$(sw_vers -productVersion) + macos_major=${macos_version%%.*} + if [[ ! "$macos_major" =~ ^[0-9]+$ ]] || [ "$macos_major" -lt 26 ]; then + echo "Error: This deployment requires macOS 26 or newer (found $macos_version)." >&2 + exit 1 + fi + if ! command -v container >/dev/null 2>&1; then + echo 'Error: Apple container CLI is not installed or is not on PATH.' >&2 + echo 'Install the signed package from https://github.com/apple/container/releases, then retry.' >&2 + exit 1 + fi +} + +usage() { + echo 'Usage: deploy/apple-container/apple-container.sh {up|rebuild|build|stop|status|logs|credentials|shell|smoke}' >&2 + exit 2 +} + +# Reading saved credentials needs neither a compatible host nor the runtime. +case "${1:-up}" in + up|rebuild|build|stop|logs|status|smoke|shell) check_host ;; + credentials) ;; + *) usage ;; +esac +exists() { container inspect "$1" >/dev/null 2>&1; } +running() { container list --quiet | grep -Fx "$1" >/dev/null; } +container_ip() { + container inspect "$1" | python3 -c 'import json,sys; print(json.load(sys.stdin)[0]["status"]["networks"][0]["ipv4Address"].split("/")[0])' +} + +container_env() { + container inspect "$1" | python3 -c 'import json,sys; env=json.load(sys.stdin)[0]["configuration"]["initProcess"]["environment"]; prefix=sys.argv[1]+"="; print(next((v[len(prefix):] for v in env if v.startswith(prefix)), ""))' "$2" +} + +trust_host() { + local client=$1 address=$2 server=$3 key + key=$(container exec "$server" cat /data/ssh/host_ed25519.pub) + # Expand the arguments inside the client container. + # shellcheck disable=SC2016 + container exec "$client" sh -c ' + ssh-keygen -R "$1" >/dev/null 2>&1 || true + printf "%s %s\n" "$1" "$2" >> /root/.ssh/known_hosts + ' sh "$address" "$key" +} + +start_service() { + local service=$1 data_dir=$2 + shift 2 + if ! exists "$service"; then + container volume inspect "$service-data" >/dev/null 2>&1 || container volume create "$service-data" + container run -d --name "$service" --network "$network" -v "$service-data:$data_dir" "$@" + elif ! running "$service"; then + container start "$service" + fi +} + +stop_service() { + if running "$1"; then container stop "$1"; fi +} + +remove_service() { + if exists "$1"; then + stop_service "$1" + container delete "$1" + fi +} + +wait_for() { + local service=$1 attempts=$2 message=$3 attempt + shift 3 + for ((attempt = 0; attempt < attempts; attempt++)); do + if "$@" >/dev/null 2>&1; then return 0; fi + if ! running "$service"; then break; fi + sleep 2 + done + echo "$message" >&2 + container logs "$service" >&2 || true + if [ "$service" = "$app" ]; then + container exec "$app" tail -n 40 /data/portal-log/server.log >&2 || true + fi + return 1 +} + +build_image() { + container build --cpus 4 --memory 4G -t "$IMAGE" -f "$ROOT/deploy/apple-container/Containerfile" "$ROOT" +} + +check_start_tools() { + if ! command -v python3 >/dev/null 2>&1; then + echo 'Error: Starting the deployment requires Python 3 to read Apple container metadata.' >&2 + exit 1 + fi +} + +services=("$worker" "$app") + +prepare_state() { + # Container names are shared across checkouts, but this file lives in the checkout. + if exists "$db" || { [ ! -s "$STATE/env" ] && container volume inspect "$db-data" >/dev/null 2>&1; }; then + if [ ! -s "$STATE/env" ] || + [ "$(sed -n 's/^MARIADB_PASSWORD=//p' "$STATE/env")" != "$(container_env "$db" MARIADB_PASSWORD)" ]; then + echo "Error: $db-data needs the credentials from its original checkout. Restore $STATE/env before starting it." >&2 + return 1 + fi + fi + mkdir -p "$STATE" + chmod 700 "$STATE" + if [ ! -f "$STATE/env" ]; then + umask 077 + { + echo "MARIADB_DATABASE=cbrain" + echo "MARIADB_USER=cbrain" + echo "MARIADB_PASSWORD=$(openssl rand -hex 24)" + echo "MARIADB_ROOT_PASSWORD=$(openssl rand -hex 24)" + echo "CBRAIN_ADMIN_PASSWORD=Cb1!$(openssl rand -hex 16)" + echo "SECRET_KEY_BASE=$(openssl rand -hex 64)" + } > "$STATE/env" + fi +} + +start_profile() { + local db_ip portal_ip portal_key worker_ip + container network inspect "$network" >/dev/null 2>&1 || container network create "$network" + start_service "$db" /var/lib/mysql --memory 1G --env-file "$STATE/env" docker.io/library/mariadb:10.11 + wait_for "$db" 60 'MariaDB did not become ready' \ + container exec "$db" healthcheck.sh --connect --innodb_initialized + db_ip=$(container_ip "$db") + # Replace the legacy combined app container or refresh a changed DB address. + if exists "$app"; then + if [ "$(container_env "$app" CBRAIN_DB_HOST)" != "$db_ip" ] || + [ "$(container_env "$app" CBRAIN_SPLIT_PORTAL)" != 1 ]; then + remove_service "$app" + fi + fi + # The worker's database socket belongs to the portal's SSH session. + if ! running "$app"; then stop_service "$worker"; fi + start_service "$app" /data --cpus 4 --memory 4G \ + --env-file "$STATE/env" -e "CBRAIN_DB_HOST=$db_ip" -e CBRAIN_SPLIT_PORTAL=1 \ + -p "127.0.0.1:3000:3000" "$IMAGE" + wait_for "$app" 120 'Portal did not become ready' curl -fsS --max-time 2 "http://127.0.0.1:3000/" + portal_ip=$(container_ip "$app") + portal_key=$(container exec "$app" cat /data/ssh/id_cbrain_ed25519.pub) + if exists "$worker" && [ "$(container_env "$worker" CBRAIN_PORTAL_PUBLIC_KEY)" != "$portal_key" ]; then + remove_service "$worker" + fi + start_service "$worker" /data --cpus 2 --memory 2G \ + -e "CBRAIN_PORTAL_PUBLIC_KEY=$portal_key" "$IMAGE" worker + wait_for "$worker" 30 'Bourreau SSH host key was not created' \ + container exec "$worker" test -s /data/ssh/host_ed25519.pub + worker_ip=$(container_ip "$worker") + trust_host "$app" "$worker_ip" "$worker" + trust_host "$app" "$portal_ip" "$app" + trust_host "$worker" "$portal_ip" "$app" + + wait_for "$worker" 30 'Bourreau did not become reachable over SSH' \ + container exec "$app" ssh -i /root/.ssh/id_cbrain_ed25519 \ + -o BatchMode=yes -o ConnectTimeout=2 "root@$worker_ip" true + + # Preserve the old worker's work directories and cache on first upgrade. + # shellcheck disable=SC2016 + container exec "$app" bash -e -c ' + target="root@$1" + ssh_options=(-i /root/.ssh/id_cbrain_ed25519 -o BatchMode=yes -o ConnectTimeout=5) + if ! ssh "${ssh_options[@]}" "$target" test -f /data/.legacy-worker-imported; then + for dir in /data/work /data/worker-cache; do + if [ -d "$dir" ]; then + rsync -a -e "ssh ${ssh_options[*]}" "$dir/" "$target:$dir/" + fi + done + ssh "${ssh_options[@]}" "$target" touch /data/.legacy-worker-imported + fi + ' bash "$worker_ip" + + container exec -w /opt/cbrain/BrainPortal -e "CBRAIN_WORKER_HOST=$worker_ip" \ + -e "CBRAIN_STORAGE_HOST=$portal_ip" "$app" bundle exec rake db:local:worker + echo "CBRAIN: http://localhost:3000 — login: admin" + echo "Initial password: deploy/apple-container/apple-container.sh credentials (change on first login)" +} + +case "${1:-up}" in + build) + container system start + build_image + ;; + up|rebuild) + check_start_tools + container system start + prepare_state + if [ "${1:-up}" = rebuild ]; then + build_image + for service in "${services[@]}"; do remove_service "$service"; done + elif ! container image inspect "$IMAGE" >/dev/null 2>&1; then + build_image + fi + start_profile + ;; + stop) + for service in "${services[@]}" "$db"; do stop_service "$service"; done + ;; + logs) + container logs "$app" + container exec "$app" tail -n 80 /data/portal-log/server.log + container logs "$worker" + ;; + status) container list ;; + smoke) container exec -w /opt/cbrain/BrainPortal "$app" bundle exec rake db:local:smoke ;; + credentials) sed -n 's/^CBRAIN_ADMIN_PASSWORD=/Initial admin password: /p' "$STATE/env" ;; + shell) container exec -it -w /opt/cbrain/BrainPortal "$app" bash ;; + *) usage ;; +esac diff --git a/deploy/apple-container/entrypoint.sh b/deploy/apple-container/entrypoint.sh new file mode 100755 index 000000000..ca2104d88 --- /dev/null +++ b/deploy/apple-container/entrypoint.sh @@ -0,0 +1,62 @@ +#!/bin/bash +set -euo pipefail +umask 077 + +setup_app() { + local app=$1 + mkdir -p "/opt/cbrain/$app/tmp/pids" "/opt/cbrain/$app/tmp/sockets" "/data/logs/$app" + if [ ! -L "/opt/cbrain/$app/log" ]; then + cp -a "/opt/cbrain/$app/log/." "/data/logs/$app/" 2>/dev/null || true + rm -rf "/opt/cbrain/$app/log" + ln -s "/data/logs/$app" "/opt/cbrain/$app/log" + fi + rm -f "/opt/cbrain/$app/tmp/pids/server.pid" "/opt/cbrain/$app/tmp/sockets/"*.sock +} + +mkdir -p /data/ssh /run/sshd /root/.ssh +if [ ! -f /data/ssh/host_ed25519 ]; then + ssh-keygen -q -t ed25519 -N '' -f /data/ssh/host_ed25519 +fi +sshd_options=(-h /data/ssh/host_ed25519 -o PermitRootLogin=prohibit-password -o PasswordAuthentication=no -o KbdInteractiveAuthentication=no) + +if [ "${1:-portal}" = worker ]; then + setup_app Bourreau + mkdir -p /data/work /data/worker-cache + # The portal supplies database.yml through the reverse SSH tunnel. + rm -f /opt/cbrain/Bourreau/config/database.yml + printf 'class CBRAIN\n CBRAIN_RAILS_APP_NAME = "LocalBourreau"\nend\n' > /opt/cbrain/Bourreau/config/initializers/config_bourreau.rb + printf '%s\n' "${CBRAIN_PORTAL_PUBLIC_KEY:?Missing portal public key}" > /root/.ssh/authorized_keys + # SSH-launched shells need the image's Ruby and Bundler on PATH. + # shellcheck disable=SC2016 + printf 'export PATH=/usr/local/bundle/bin:/usr/local/bin:$PATH\nexport GEM_HOME=/usr/local/bundle\n' > /root/.bashrc + exec /usr/sbin/sshd -D -e "${sshd_options[@]}" +fi + +setup_app BrainPortal +mkdir -p /data/files /data/portal-cache /data/portal-log +cat > /opt/cbrain/BrainPortal/config/database.yml <<'YAML' +development: + adapter: mysql2 + encoding: utf8 + host: <%= ENV.fetch('CBRAIN_DB_HOST') %> + database: cbrain + username: cbrain + password: <%= ENV.fetch('MARIADB_PASSWORD').inspect %> + pool: 20 +YAML +cat > /opt/cbrain/BrainPortal/config/secrets.yml < /opt/cbrain/BrainPortal/config/initializers/config_portal.rb + +if [ ! -f /data/ssh/id_cbrain_ed25519 ]; then + ssh-keygen -q -t ed25519 -N '' -f /data/ssh/id_cbrain_ed25519 +fi +cp /data/ssh/id_cbrain_ed25519* /root/.ssh/ +cp /data/ssh/id_cbrain_ed25519.pub /root/.ssh/authorized_keys +# Serve LocalStorage to the Bourreau via SSH using the forwarded portal identity. +/usr/sbin/sshd "${sshd_options[@]}" +cd /opt/cbrain/BrainPortal +bundle exec rake db:local:prepare db:sanity:check +exec bundle exec puma -b tcp://0.0.0.0:3000 > /data/portal-log/server.log 2>&1 diff --git a/deploy/apple-container/local.rake b/deploy/apple-container/local.rake new file mode 100644 index 000000000..c5813ee39 --- /dev/null +++ b/deploy/apple-container/local.rake @@ -0,0 +1,106 @@ +namespace :db do + namespace :local do + task :prepare => :environment do + unless ActiveRecord::Base.connection.table_exists?(:users) + Rake::Task['db:schema:load'].invoke + end + Rake::Task['db:migrate'].invoke + unless User.exists?(:login => 'admin') + # Upstream seeds print a temporary password; keep that output private. + File.open('/data/seed.log', 'w', 0600) do |log| + original = $stdout + begin + $stdout = log + load Rails.root.join('db/seeds.rb') + ensure + $stdout = original + end + end + admin = User.find_by_login!('admin') + password = ENV.fetch('CBRAIN_ADMIN_PASSWORD') + admin.update!(:password => password, :password_confirmation => password) + end + CbrainSystemChecks.check([:a002_ensure_Rails_can_find_itself]) + RemoteResource.current_resource.update!(:dp_cache_dir => '/data/portal-cache', + :ssh_control_host => '127.0.0.1', :ssh_control_user => 'root', + :ssh_control_rails_dir => '/opt/cbrain/BrainPortal') + end + + task :worker => :environment do + worker_host = ENV.fetch('CBRAIN_WORKER_HOST') + storage_host = ENV.fetch('CBRAIN_STORAGE_HOST') + CbrainSystemChecks.check([:a002_ensure_Rails_can_find_itself]) + PortalSystemChecks.check([:z000_ensure_we_have_a_local_ssh_agent]) + admin = User.admin + group = Group.everyone + worker = Bourreau.find_or_initialize_by(:name => 'LocalBourreau') + if worker.persisted? && (worker.ssh_control_host != worker_host || !worker.is_alive?(:ping, true)) + worker.stop_tunnels + end + worker.assign_attributes(:user_id => admin.id, :group_id => group.id, + :description => 'Local Apple container UNIX worker', :online => true, :read_only => false, + :ssh_control_host => worker_host, :ssh_control_user => 'root', :ssh_control_port => 22, + :ssh_control_rails_dir => '/opt/cbrain/Bourreau', :cms_class => 'ScirUnix', + :cms_shared_dir => '/data/work', :dp_cache_dir => '/data/worker-cache', + :workers_instances => 1, :workers_chk_time => 5, :workers_log_to => 'combined', :workers_verbose => 1) + worker.save! + provider = DataProvider.find_by(:name => 'LocalStorage') || EnCbrainSshDataProvider.new(:name => 'LocalStorage') + DataProvider.transaction do + if provider.is_a?(EnCbrainLocalDataProvider) && provider.remote_dir.to_s == '/data/files' + # The enhanced providers use the same file layout. Old cache states + # refer to direct filesystem access and must be refreshed. + SyncStatus.where(:userfile_id => provider.userfiles.select(:id)).delete_all + provider = provider.becomes!(EnCbrainSshDataProvider) + end + abort('LocalStorage is not a compatible data provider') unless provider.is_a?(EnCbrainSshDataProvider) + provider.update!(:user_id => admin.id, :group_id => group.id, :remote_dir => '/data/files', + :remote_host => storage_host, :remote_user => 'root', :remote_port => 22, + :online => true, :read_only => false, :not_syncable => false) + end + %w[Diagnostics Parallelizer CbSerializer].each do |name| + tool = Tool.find_or_initialize_by(:cbrain_task_class_name => "CbrainTask::#{name}") + tool.assign_attributes(:name => name, :user_id => admin.id, :group_id => group.id, + :category => name == 'Diagnostics' ? 'scientific tool' : 'background', + :select_menu_text => "Launch #{name}") + tool.save! + config = ToolConfig.find_or_initialize_by(:tool_id => tool.id, :bourreau_id => worker.id, :version_name => 'local') + config.assign_attributes(:group_id => group.id, :ncpus => 1) + config.save! + end + abort(worker.operation_messages) unless worker.start + abort('Bourreau did not respond to ping') unless worker.is_alive?(:ping, true) + worker.send_command_start_workers + puts 'Local Bourreau is responding; processing worker started.' + end + task :smoke => :environment do + CbrainSystemChecks.check([:a002_ensure_Rails_can_find_itself]) + PortalSystemChecks.check([:a000_ensure_models_are_preloaded, :z000_ensure_we_have_a_local_ssh_agent]) + worker = Bourreau.find_by_name!('LocalBourreau') + abort('Bourreau is not responding') unless worker.is_alive?(:ping, true) + provider = DataProvider.find_by_name!('LocalStorage') + tool = Tool.find_by_name!('Diagnostics') + config = ToolConfig.find_by!(:tool_id => tool.id, :bourreau_id => worker.id, :version_name => 'local') + params = CbrainTask::Diagnostics.default_launch_args.transform_values { |v| v.is_a?(Numeric) ? v.to_s : v } + params[:interface_userfile_ids] = [] + task = CbrainTask::Diagnostics.create!(:user_id => User.admin.id, + :group_id => User.admin.own_group.id, :bourreau_id => worker.id, + :tool_config_id => config.id, :results_data_provider_id => provider.id, + :description => 'Apple container deployment smoke test', :status => 'New', :params => params) + puts "Created Diagnostics task #{task.id}" + worker.send_command_wakeup_workers + 90.times do + task.reload + if task.status == 'Completed' + report = Userfile.find(task.params[:report_id]) + report.sync_to_cache + abort('Diagnostics report was not saved') unless File.size?(report.cache_full_path) + puts "PASS: task #{task.id} completed and saved report #{report.id} (#{report.name})" + break + end + abort("Task #{task.id}: #{task.status}") if task.status =~ /Failed|Terminated/ + sleep 2 + end + abort("Task #{task.id} timed out in #{task.status}") unless task.status == 'Completed' + end + end +end From fa5bcd3f8e3427db5c76656cac1e923f47f34a50 Mon Sep 17 00:00:00 2001 From: Darcy Quesnel Date: Wed, 2 Dec 2026 13:27:08 -0500 Subject: [PATCH 2/2] Add local Slurm and ARM64 Apptainer profile --- deploy/apple-container/Containerfile | 22 +++++ deploy/apple-container/README.md | 50 ++++++++++- deploy/apple-container/apple-container.sh | 92 +++++++++++++++------ deploy/apple-container/entrypoint.sh | 11 +++ deploy/apple-container/local.rake | 9 +- deploy/apple-container/slurm/entrypoint.sh | 78 +++++++++++++++++ deploy/apple-container/slurm/start-munge.sh | 5 ++ 7 files changed, 236 insertions(+), 31 deletions(-) create mode 100755 deploy/apple-container/slurm/entrypoint.sh create mode 100644 deploy/apple-container/slurm/start-munge.sh diff --git a/deploy/apple-container/Containerfile b/deploy/apple-container/Containerfile index ceb2fecde..444dff875 100644 --- a/deploy/apple-container/Containerfile +++ b/deploy/apple-container/Containerfile @@ -9,6 +9,28 @@ COPY Bourreau/Gemfile Bourreau/Gemfile RUN cd BrainPortal && bundle install --jobs 4 && \ cd ../Bourreau && bundle install --jobs 4 +# Bourreau builds SIF images and the compute node executes them. +# Keep Slurm 20.11 for the existing local accounting database and cgroup-free node. +ARG CBRAIN_SLURM=0 +RUN if [ "$CBRAIN_SLURM" = 1 ]; then \ + printf 'deb https://archive.debian.org/debian bullseye main\n' > /etc/apt/sources.list.d/slurm-bullseye.list && \ + apt-get -o Acquire::Check-Valid-Until=false update && \ + apt-get install -y --no-install-recommends \ + munge slurm-client/bullseye slurmctld/bullseye slurmd/bullseye slurmdbd/bullseye cpio rpm2cpio && \ + rpm=apptainer-1.5.5-1.el8.aarch64.rpm && \ + curl -fsSL --retry 3 -o /tmp/install-unprivileged.sh \ + https://raw.githubusercontent.com/apptainer/apptainer/v1.5.5/tools/install-unprivileged.sh && \ + curl -fsSL --retry 3 -o "/tmp/$rpm" \ + "https://download.fedoraproject.org/pub/epel/8/Everything/aarch64/Packages/a/$rpm" && \ + printf '%s %s\n' \ + a097956eafa6ab3dd843ee429d0b774ed029753bfadf013b8046556228fac6f2 /tmp/install-unprivileged.sh \ + 113d396128088cec904f0f06a5f225deac00f40b40f10e20bdc138de25085f3d "/tmp/$rpm" | sha256sum -c - && \ + bash /tmp/install-unprivileged.sh -e -d el8 -a aarch64 -v "/tmp/$rpm" /opt/apptainer && \ + ln -s /opt/apptainer/bin/apptainer /usr/local/bin/apptainer && \ + apptainer --version && \ + rm -rf /var/lib/apt/lists/* /tmp/install-unprivileged.sh "/tmp/$rpm"; \ + fi + COPY . . RUN cd BrainPortal && bundle exec rake cbrain:plugins:install:plugins diff --git a/deploy/apple-container/README.md b/deploy/apple-container/README.md index 089abb1a3..05ef9a5a9 100644 --- a/deploy/apple-container/README.md +++ b/deploy/apple-container/README.md @@ -69,14 +69,14 @@ volume. Portal startup runs migrations, and `up` ensures the local resources exi The admin password is set when the database is first seeded. After changing the source, let active jobs finish, then rebuild and restart -the deployment. +the selected profile. ```sh deploy/apple-container/apple-container.sh rebuild ``` `rebuild` builds the image and replaces the application containers while -keeping the database and named volumes. The `build` +keeping the database, named volumes, and shared work directory. The `build` command is available for building the image on its own. On upgrade from the combined container, run `rebuild`. @@ -86,9 +86,51 @@ use SSH. The provider keeps the same record and files. Its old cache status entries are cleared so each app can resync through SSH. This is a local development deployment for CBRAIN v8, using Ruby 4.0.2 -and Rails 8.1 on Debian Bookworm. Do not expose -this deployment publicly. Budget approximately 7 GB RAM for the running services +and Rails 8.1 on Debian Bookworm. The Slurm profile retains Slurm 20.11 +from Debian Bullseye for compatibility with its existing accounting data and +process-based job tracking. Do not expose this deployment publicly. Budget approximately 7 GB RAM for the running services plus the image builder during builds. The smoke check leaves its completed task and Diagnostics report in CBRAIN so you can inspect them in the portal. Each invocation creates one small report. + +## Optional Slurm profile + +Select the Slurm profile in a separate shell: + +```sh +export CBRAIN_LOCAL_PROFILE=slurm +deploy/apple-container/apple-container.sh up +deploy/apple-container/apple-container.sh smoke +``` + +Open . Use the same launcher commands (`credentials`, +`status`, `logs`, and `stop`) with the profile selected. The profile uses its +own containers, volumes, credentials, and database under the `cbrain-slurm` +prefix and `.local/apple-container/slurm` state directory. + +Bourreau uses `ScirSlurm` and submits jobs to the separate +`cbrain-slurm-node` container. That container runs the Slurm controller, +compute daemon, and accounting daemon. Accounting uses a dedicated schema +in the profile's MariaDB. Bourreau and the compute node mount the same +`/cluster` directory for job work, cache, and Slurm configuration. Keep +the profile's state directory with its volumes to preserve that data and +the Munge key. + +The Slurm image includes ARM64 Apptainer 1.5.5. For a containerized tool, set +the Tool Config's container engine to **Singularity** and select an ARM64 +image. For an OCI source, use `docker://` as the index location. Bourreau +builds and caches a SIF under `/cluster/cache`, then stages it for the Slurm +job to run on the compute node. The default Diagnostics smoke test uses the +plain tool configuration. + +Inspect scheduler state and job history: + +```sh +container exec -e SLURM_CONF=/cluster/slurm.conf cbrain-slurm-bourreau sinfo +container exec -e SLURM_CONF=/cluster/slurm.conf cbrain-slurm-bourreau sacct -X +``` + +The node has two CPUs and a one-hour job limit. It uses Slurm's process-based +tracking with cgroup enforcement disabled. Allow about 9 GB of memory for +the running services. diff --git a/deploy/apple-container/apple-container.sh b/deploy/apple-container/apple-container.sh index c8d41b786..b567891f4 100755 --- a/deploy/apple-container/apple-container.sh +++ b/deploy/apple-container/apple-container.sh @@ -3,12 +3,19 @@ set -euo pipefail ROOT=$(cd "$(dirname "$0")/../.." && pwd) STATE="$ROOT/.local/apple-container" +profile=${CBRAIN_LOCAL_PROFILE:-unix} +case "$profile" in + unix) prefix=cbrain; portal_port=3000; slurm=0 ;; + slurm) prefix=cbrain-slurm; portal_port=3003; slurm=1; STATE="$STATE/slurm" ;; + *) echo 'CBRAIN_LOCAL_PROFILE must be unix or slurm' >&2; exit 1 ;; +esac # Use the canonical tag written by container build. -IMAGE=docker.io/library/cbrain-local:dev -app=cbrain-app -worker=cbrain-bourreau -db=cbrain-db -network=cbrain-local +IMAGE="docker.io/library/$prefix-local:dev" +app="$prefix-app" +worker="$prefix-bourreau" +db="$prefix-db" +network="$prefix-local" +node="$prefix-node" check_host() { if [ "$(uname -s)" != Darwin ]; then @@ -104,8 +111,13 @@ wait_for() { return 1 } +slurm_ready() { + container exec -e SLURM_CONF=/cluster/slurm.conf "$node" sinfo -N -h -o '%t' | + grep -Ex 'idle|mix|alloc' +} + build_image() { - container build --cpus 4 --memory 4G -t "$IMAGE" -f "$ROOT/deploy/apple-container/Containerfile" "$ROOT" + container build --cpus 4 --memory 4G --build-arg "CBRAIN_SLURM=$slurm" -t "$IMAGE" -f "$ROOT/deploy/apple-container/Containerfile" "$ROOT" } check_start_tools() { @@ -116,6 +128,7 @@ check_start_tools() { } services=("$worker" "$app") +if [ "$slurm" = 1 ]; then services+=("$node"); fi prepare_state() { # Container names are shared across checkouts, but this file lives in the checkout. @@ -137,17 +150,44 @@ prepare_state() { echo "MARIADB_ROOT_PASSWORD=$(openssl rand -hex 24)" echo "CBRAIN_ADMIN_PASSWORD=Cb1!$(openssl rand -hex 16)" echo "SECRET_KEY_BASE=$(openssl rand -hex 64)" + if [ "$slurm" = 1 ]; then + echo "SLURM_DB_PASSWORD=$(openssl rand -hex 24)" + fi } > "$STATE/env" fi } start_profile() { - local db_ip portal_ip portal_key worker_ip + local db_ip portal_ip portal_key worker_ip slurm_db_password + local worker_options=(-e "CBRAIN_LOCAL_PROFILE=$profile") container network inspect "$network" >/dev/null 2>&1 || container network create "$network" start_service "$db" /var/lib/mysql --memory 1G --env-file "$STATE/env" docker.io/library/mariadb:10.11 wait_for "$db" 60 'MariaDB did not become ready' \ container exec "$db" healthcheck.sh --connect --innodb_initialized db_ip=$(container_ip "$db") + if [ "$slurm" = 1 ]; then + mkdir -p "$STATE/cluster" + if [ ! -s "$STATE/cluster/munge.key" ]; then + (umask 077; openssl rand -out "$STATE/cluster/munge.key" 32) + fi + slurm_db_password=$(sed -n 's/^SLURM_DB_PASSWORD=//p' "$STATE/env") + [[ "$slurm_db_password" =~ ^[a-f0-9]{48}$ ]] || { echo 'Invalid Slurm database password' >&2; exit 1; } + # Use a separate accounting schema and user in this profile's MariaDB. + # shellcheck disable=SC2016 + container exec -i "$db" sh -c 'MYSQL_PWD="$MARIADB_ROOT_PASSWORD" exec mariadb -uroot' < /root/.bashrc + if [ "${CBRAIN_LOCAL_PROFILE:-unix}" = slurm ]; then + mkdir -p /cluster/work /cluster/cache + cd /opt/cbrain + # shellcheck source=deploy/apple-container/slurm/start-munge.sh + source deploy/apple-container/slurm/start-munge.sh + printf 'export SLURM_CONF=/cluster/slurm.conf\n' >> /root/.bashrc + fi exec /usr/sbin/sshd -D -e "${sshd_options[@]}" fi diff --git a/deploy/apple-container/local.rake b/deploy/apple-container/local.rake index c5813ee39..14db2e1f4 100644 --- a/deploy/apple-container/local.rake +++ b/deploy/apple-container/local.rake @@ -37,12 +37,15 @@ namespace :db do if worker.persisted? && (worker.ssh_control_host != worker_host || !worker.is_alive?(:ping, true)) worker.stop_tunnels end + slurm = ENV['CBRAIN_LOCAL_PROFILE'] == 'slurm' worker.assign_attributes(:user_id => admin.id, :group_id => group.id, - :description => 'Local Apple container UNIX worker', :online => true, :read_only => false, + :description => 'Local Apple container worker', :online => true, :read_only => false, :ssh_control_host => worker_host, :ssh_control_user => 'root', :ssh_control_port => 22, - :ssh_control_rails_dir => '/opt/cbrain/Bourreau', :cms_class => 'ScirUnix', - :cms_shared_dir => '/data/work', :dp_cache_dir => '/data/worker-cache', + :ssh_control_rails_dir => '/opt/cbrain/Bourreau', :cms_class => slurm ? 'ScirSlurm' : 'ScirUnix', + :cms_shared_dir => slurm ? '/cluster/work' : '/data/work', + :dp_cache_dir => slurm ? '/cluster/cache' : '/data/worker-cache', :workers_instances => 1, :workers_chk_time => 5, :workers_log_to => 'combined', :workers_verbose => 1) + worker.singularity_executable_name = 'apptainer' if slurm worker.save! provider = DataProvider.find_by(:name => 'LocalStorage') || EnCbrainSshDataProvider.new(:name => 'LocalStorage') DataProvider.transaction do diff --git a/deploy/apple-container/slurm/entrypoint.sh b/deploy/apple-container/slurm/entrypoint.sh new file mode 100755 index 000000000..3a1fff6dc --- /dev/null +++ b/deploy/apple-container/slurm/entrypoint.sh @@ -0,0 +1,78 @@ +#!/bin/bash +set -euo pipefail +umask 077 +cd /opt/cbrain +# shellcheck source=deploy/apple-container/slurm/start-munge.sh +source deploy/apple-container/slurm/start-munge.sh + +node=$(hostname) +address=$(ip -4 -o addr show scope global | awk 'NR == 1 { sub(/\/.*/, "", $4); print $4 }') +: "${address:?Slurm node needs a network address}" +install -d -o slurm -g slurm -m 755 /data/slurmctld +mkdir -p /data/slurmd +export SLURM_CONF=/cluster/slurm.conf +cat > "$SLURM_CONF.tmp" < "$dbd_config" </dev/null || true + wait "${pids[@]}" 2>/dev/null || true + fi +} +trap stop_daemons EXIT +trap 'exit 0' TERM INT +SLURM_CONF=/etc/slurm/slurm.conf /usr/sbin/slurmdbd -D & +pids+=("$!") +ready=false +for _attempt in {1..30}; do + kill -0 "${pids[0]}" + if sacctmgr -n show cluster >/dev/null 2>&1; then ready=true; break; fi + sleep 2 +done +"$ready" || { echo 'Slurm accounting did not become ready' >&2; exit 1; } +/usr/sbin/slurmctld -D & +pids+=("$!") +/usr/sbin/slurmd -D & +pids+=("$!") +wait -n diff --git a/deploy/apple-container/slurm/start-munge.sh b/deploy/apple-container/slurm/start-munge.sh new file mode 100644 index 000000000..2b4f0dbf5 --- /dev/null +++ b/deploy/apple-container/slurm/start-munge.sh @@ -0,0 +1,5 @@ +#!/bin/bash +# Sourced by the Bourreau and scheduler entrypoints. +install -o munge -g munge -m 400 /cluster/munge.key /etc/munge/munge.key +install -d -o munge -g munge -m 755 /run/munge +runuser -u munge -- /usr/sbin/munged