Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/ci/bookworm-camera-archive.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/bin/bash
set -euo pipefail

apt-get update -o APT::Update::Error-Mode=any -qq
apt-get install -y --no-install-recommends ca-certificates curl
keyring=/usr/share/keyrings/mandeye-raspberrypi.asc
curl --fail --silent --show-error --location --retry 3 \
https://archive.raspberrypi.com/debian/raspberrypi.gpg.key --output "$keyring"
fingerprint=CF8A1AF502A2AA2D763BAE7E82B129927FA3303E
printf '%s\n' "deb [signed-by=$keyring,$fingerprint] https://archive.raspberrypi.com/debian/ bookworm main" \
> /etc/apt/sources.list.d/raspberrypi.list
cat > /etc/apt/preferences.d/raspberrypi-camera <<'PREFERENCES'
Package: libcamera* libpisp*
Pin: origin archive.raspberrypi.com
Pin-Priority: 900

Package: *
Pin: origin archive.raspberrypi.com
Pin-Priority: -1
PREFERENCES
apt-get update -o APT::Update::Error-Mode=any -qq
35 changes: 35 additions & 0 deletions .github/ci/build-deb.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/bin/bash
set -euo pipefail

bash .github/ci/bookworm-camera-archive.sh
apt-get install -y --no-install-recommends build-essential cmake file git pkg-config \
libserial-dev libgpiod-dev libzmq3-dev libboost-all-dev libpistache-dev rapidjson-dev \
nlohmann-json3-dev cppzmq-dev libcamera-dev libopencv-dev pps-tools
git config --global --add safe.directory /src
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
cmake -S . -B /tmp/build -DCMAKE_BUILD_TYPE=Release -DMANDEYE_USE_LIBCAMERA=ON
cmake --build /tmp/build --parallel "$(nproc)"
ctest --test-dir /tmp/build --output-on-failure
# Give uploads of the same Git revision distinct Debian revisions. Local
# CPack builds keep their source-derived version.
release="${GITHUB_RUN_ID:?}.${GITHUB_RUN_ATTEMPT:?}"
cpack --config /tmp/build/CPackConfig.cmake -G DEB -B /packages \
-D "CPACK_PACKAGE_FILE_NAME=${PACKAGE%.deb}" -D "CPACK_DEBIAN_PACKAGE_RELEASE=$release"
version=$(dpkg-deb -f "/packages/$PACKAGE" Version)
test "${version##*-}" = "$release"
dpkg-deb -f "/packages/$PACKAGE" Package Version Architecture Depends Recommends
test "$(dpkg-deb -f "/packages/$PACKAGE" Package)" = mandeye-multisensor
test "$(dpkg-deb -f "/packages/$PACKAGE" Architecture)" = arm64
test "$(dpkg-deb -f "/packages/$PACKAGE" Recommends)" = linuxptp

if [[ ! -s /packages/legacy.deb ]]; then
cd /src/legacy
git config --global --add safe.directory /src/legacy
test "$(git rev-parse HEAD)" = "$LEGACY_SHA"
cmake -S . -B /tmp/old-build -DCMAKE_BUILD_TYPE=Release \
-DMANDEYE_HARDWARE_HEADER=mandeye-pro-cm4-bookworm.h -DMANDEYE_USE_LIBCAMERA=ON
cmake --build /tmp/old-build --parallel "$(nproc)"
cpack --config /tmp/old-build/CPackConfig.cmake -G DEB -B /packages -D CPACK_PACKAGE_FILE_NAME=legacy \
-D CPACK_DEBIAN_PACKAGE_SHLIBDEPS=ON -D CPACK_DEBIAN_PACKAGE_DEPENDS=systemd \
-D CPACK_DEBIAN_PACKAGE_RECOMMENDS=linuxptp
fi
17 changes: 17 additions & 0 deletions .github/ci/installed-scan.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/bash
set -euo pipefail

bash .github/ci/bookworm-camera-archive.sh
apt-get install -y --no-install-recommends "/packages/$PACKAGE" python3-venv
for path in /opt/mandeye/{control_program,extras/mandeye_libcamera,led_demo,button_demo}; do
test -x "$path"
done
for unit in mandeye_libcamera_cam{0,1}.service; do
test -f "/usr/lib/systemd/system/$unit"
done
test -z "$(getent passwd pi)"
python3 tests/package/test-device-config.py
python3 tests/package/test-picamera-config.py
python3 -m venv /tmp/scan-venv
/tmp/scan-venv/bin/pip install --disable-pip-version-check 'laspy[lazrs]==2.6.1'
/tmp/scan-venv/bin/python tests/installed-scan.py
188 changes: 188 additions & 0 deletions .github/ci/package-comment.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
'use strict';

const marker = '<!-- mandeye-arm64-packages -->';
const sha = /^[a-f0-9]{40}$/;
const path = '.github/workflows/build-deb.yml';

function currentRun(runs, pr) {
// run_number (unlike updated_at) cannot promote a rerun of an older build.
return runs.filter(run =>
run.path === path && run.event === 'pull_request' &&
run.display_title === `Bookworm ARM64 PR ${pr.number} ${pr.merge_commit_sha}` &&
run.head_sha === pr.head.sha && run.head_branch === pr.head.ref &&
run.head_repository?.id === pr.head.repo?.id &&
(!run.pull_requests?.length || run.pull_requests.some(link =>
link.number === pr.number && link.base.repo.id === pr.base.repo.id &&
link.base.ref === pr.base.ref)))
.sort((a, b) => b.run_number - a.run_number || b.run_attempt - a.run_attempt)[0];
}

function uploadAttempt(run, jobs) {
// GitHub retains jobs from successful earlier attempts on a partial rerun.
// Require evidence of the current attempt; a stale job listing cannot certify it.
if (!jobs.some(j => j.run_attempt === run.run_attempt) || jobs.some(j =>
j.run_id !== run.id || j.head_sha !== run.head_sha || !Number.isSafeInteger(j.run_attempt) ||
j.run_attempt < 1 || j.run_attempt > run.run_attempt)) return null;
const builds = jobs.filter(j => j.name === 'Build and test .deb');
const attempt = Math.max(...builds.map(j => j.run_attempt));
const latest = builds.filter(j => j.run_attempt === attempt);
if (latest.length !== 1 || latest[0].status !== 'completed' || latest[0].conclusion !== 'success') return null;
const build = latest[0];
// On publisher-only retries GitHub may copy a successful build to a new
// job ID and run_attempt while preserving its runner and execution interval.
const sameExecution = j => j === build || (j.name === build.name &&
j.status === 'completed' && j.conclusion === 'success' &&
Number.isSafeInteger(build.runner_id) && build.runner_id > 0 && j.runner_id === build.runner_id &&
Number.isFinite(Date.parse(build.started_at)) && Date.parse(build.completed_at) > Date.parse(build.started_at) &&
j.started_at === build.started_at && j.completed_at === build.completed_at);
const uploaded = Math.min(...builds.filter(sameExecution).map(j => j.run_attempt));
if (builds.filter(j => j.run_attempt === uploaded).length !== 1) return null;
// Only a rerun of the comment jobs can inherit a package. A failed, skipped
// or incomplete newer build must never fall back to an older artifact.
if (jobs.some(j => j.run_attempt > uploaded && !sameExecution(j) &&
!['result / comment', 'building / comment'].includes(j.name))) return null;
return uploaded;
}

function availability(run, artifacts, directResult, merge, now, artifactAttempt) {
if (!run) return {state: 'waiting'};
const outcome = run.status === 'completed' ? run.conclusion : directResult;
if (!outcome) return {state: 'building'};
if (outcome !== 'success') return {state: outcome === 'cancelled' ? 'cancelled' : 'failed'};

// Artifact listings span all attempts of the same run. A raw file carries
// its attempt in its basename, including when two uploads arrive out of order.
if (!artifactAttempt) return {state: 'unavailable'};
const prefix = `mandeye-multisensor-bookworm-arm64-${merge}-a`;
const name = `${prefix}${artifactAttempt}.deb`;
const runArtifacts = artifacts.filter(a => a.workflow_run?.id === run.id);
const attemptName = new RegExp(`^${prefix}(\\d+)\\.deb$`);
if (runArtifacts.some(a => Number(a.name.match(attemptName)?.[1]) > artifactAttempt)) return {state: 'unavailable'};
const matching = runArtifacts.filter(a => a.name === name);
if (matching.length !== 1) return {state: 'unavailable'};
const [a] = matching;
const expires = Date.parse(a.expires_at);
if (a.expired || expires <= now) return {state: 'expired'};
if (!Number.isFinite(expires) || !Number.isSafeInteger(a.id) ||
!/^sha256:[a-f0-9]{64}$/.test(a.digest)) return {state: 'unavailable'};
return {state: 'ready', name, id: a.id, digest: a.digest.slice(7), expiry: new Date(expires).toISOString()};
}

function bodyFor(repoUrl, pr, run, info) {
const merge = sha.test(pr.merge_commit_sha) ? pr.merge_commit_sha : null;
const generation = [pr.head.sha, merge || '-', run?.run_number || 0, run?.run_attempt || 0, info.state];
const body = [
marker, `<!-- field-package ${generation.join(' ')} -->`,
'### Raspberry Pi OS Bookworm ARM64 field package', '',
`PR head \`${pr.head.sha}\` · Test merge ${merge ? '\`' + merge + '\`' : 'pending'}`,
`[Installation and first scan](${repoUrl}/blob/${merge || pr.head.sha}/README.md)`, '',
];
const runUrl = run && `${repoUrl}/actions/runs/${run.id}`;
if (info.state === 'ready') {
body.push(`[Download the .deb](${runUrl}/artifacts/${info.id}) (sign in to GitHub).`, `File: \`${info.name}\``,
'', `SHA-256: \`${info.digest}\``,
'', `Expires **${info.expiry}** (UTC). After that time the package is unavailable until a new build.`);
} else {
const message = {
waiting: 'Waiting for a build of this revision. No current package is available.',
building: 'Building and testing. No current package is available. If this attempt is cancelled or fails, rerun it.',
cancelled: 'Build cancelled. No current package is available.',
failed: 'Build failed. No current package is available.',
expired: 'Package expired. Rerun the build for a new download.',
unavailable: 'Package unavailable. Rerun the build for a new download.',
};
body.push(`**${message[info.state]}**`);
}
if (run) body.push('', `[Build ${run.run_number}, attempt ${run.run_attempt}](${runUrl}/attempts/${run.run_attempt})`);
return body.join('\n');
}

function generation(body) {
return body.match(/<!-- field-package ([a-f0-9]{40}) ([a-f0-9]{40}|-) (\d+) (\d+) (\w+) -->/);
}

function canReplace(before, after) {
const prev = generation(before);
const next = generation(after);
if (!prev || prev[1] !== next[1] || prev[2] !== next[2]) return true;
if (+next[3] !== +prev[3]) return +next[3] > +prev[3];
if (+next[4] !== +prev[4]) return +next[4] > +prev[4];
return !(['waiting', 'building'].includes(next[5]) && !['waiting', 'building'].includes(prev[5]));
}

async function publish(github, context, buildResult, attempt) {
const repo = context.repo;
const repoId = context.payload.repository.id;
const rest = github.rest;
const list = (method, options) => github.paginate(method, {...repo, per_page: 100, ...options});
const getPR = async number => (await rest.pulls.get({...repo, pull_number: number})).data;
const direct = context.eventName === 'pull_request';
let trigger = context.payload.workflow_run;
if (direct) {
if (context.payload.pull_request.head.repo?.id !== repoId) return;
trigger = (await rest.actions.getWorkflowRun({...repo, run_id: context.runId})).data;
}
if (trigger && (trigger.path !== path || trigger.event !== 'pull_request' || !trigger.head_repository)) return;

let candidates;
if (direct || context.eventName === 'pull_request_target') {
candidates = [context.payload.pull_request];
} else if (trigger?.pull_requests?.length) {
candidates = trigger.pull_requests;
} else if (trigger) {
// Fork workflow_run payloads can omit pull_requests. Bind the run to its
// GitHub head repository and branch, as well as an already-open PR.
candidates = await list(rest.pulls.list, {state: 'open', head: `${trigger.head_repository.owner.login}:${trigger.head_branch}`});
candidates = candidates.filter(pr => pr.base.repo.id === repoId &&
pr.head.repo?.id === trigger.head_repository.id && pr.head.ref === trigger.head_branch &&
pr.created_at <= trigger.created_at);
if (candidates.length !== 1) return;
} else if (context.eventName === 'schedule') {
candidates = await list(rest.pulls.list, {state: 'open'});
} else return;

for (const candidate of candidates) {
const pr = await getPR(candidate.number);
if (pr.state !== 'open' || pr.base.repo.id !== repoId || !pr.head.repo || !sha.test(pr.head.sha)) continue;
if (trigger && (trigger.head_repository.id !== pr.head.repo.id || trigger.head_branch !== pr.head.ref)) continue;

const comments = await list(rest.issues.listComments, {issue_number: pr.number});
const previous = comments.find(c => c.user?.login === 'github-actions[bot]' && c.body?.startsWith(marker));
const latestRun = async () => currentRun(await list(rest.actions.listWorkflowRuns, {
workflow_id: trigger?.workflow_id || 'build-deb.yml', head_sha: pr.head.sha, event: 'pull_request',
}), pr);
const run = await latestRun();
if (!previous && !run && context.eventName === 'schedule') continue;
const directResult = direct && run?.id === context.runId && run.run_attempt === attempt &&
context.sha === pr.merge_commit_sha ? buildResult : '';
let artifacts = [];
let artifactAttempt = null;
if (run && (run.conclusion === 'success' || directResult === 'success')) {
const [jobs, items] = await Promise.all([
list(rest.actions.listJobsForWorkflowRun, {run_id: run.id, filter: 'all'}),
list(rest.actions.listWorkflowRunArtifacts, {run_id: run.id}),
]);
artifactAttempt = uploadAttempt(run, jobs);
artifacts = items;
}
const availabilityNow = availability(run, artifacts, directResult, pr.merge_commit_sha, Date.now(), artifactAttempt);
const body = bodyFor(`${context.serverUrl}/${repo.owner}/${repo.repo}`, pr, run, availabilityNow);
// Refresh the PR after the slower artifact/comment listings. All writers
// using this workflow share one lock; late events recompute from live data.
const [live, fresh] = await Promise.all([getPR(pr.number), latestRun()]);
if (fresh?.id !== run?.id || fresh?.run_attempt !== run?.run_attempt ||
fresh?.status !== run?.status || fresh?.conclusion !== run?.conclusion) continue;
if (live.state !== 'open' || live.head.sha !== pr.head.sha ||
live.head.repo?.id !== pr.head.repo.id || live.base.ref !== pr.base.ref ||
live.merge_commit_sha !== pr.merge_commit_sha) continue;
if (!previous) await rest.issues.createComment({...repo, issue_number: pr.number, body});
else if (previous.body !== body && canReplace(previous.body, body)) {
await rest.issues.updateComment({...repo, comment_id: previous.id, body});
}
// The build job writes its own summary. Restore it only on a partial
// rerun of this run's publisher, which carries an earlier upload.
if (directResult === 'success' && availabilityNow.state === 'ready' && artifactAttempt !== attempt) return body;
}
}

module.exports = {currentRun, availability, bodyFor, canReplace, publish};
11 changes: 11 additions & 0 deletions .github/ci/package-summary.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash
set -euo pipefail

cd "$RUNNER_TEMP/packages"
digest=$(sha256sum "$PACKAGE" | cut -d' ' -f1)
test "$digest" = "${ARTIFACT_DIGEST#sha256:}"
{
printf '[Download the .deb](%s) (sign in to GitHub).\n\n' "$PACKAGE_URL"
printf 'File: `%s`\n\nSHA-256: `%s`\n\nBuilt revision: `%s`\n\n' "$PACKAGE" "$digest" "$GITHUB_SHA"
printf '[Installation and first scan](%s/%s/blob/%s/README.md)\n' "$GITHUB_SERVER_URL" "$GITHUB_REPOSITORY" "$GITHUB_SHA"
} >> "$GITHUB_STEP_SUMMARY"
Loading
Loading