From f40afd01ba9d33d9be9765fa041fc526976c49a1 Mon Sep 17 00:00:00 2001 From: Krishan Date: Wed, 7 Oct 2026 18:31:17 +0100 Subject: [PATCH] Ignore image entrypoints, clean up containers on cancel, release from a workflow run --- .github/workflows/release.yml | 48 ++++++++++++++++++++++++++++++----- README.md | 6 ++--- package-lock.json | 4 +-- package.json | 2 +- runnable/index.js | 2 +- src/docker.ts | 2 +- src/index.ts | 19 +++++++++----- 7 files changed, 61 insertions(+), 22 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2111293..f0c43df 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,21 +1,55 @@ name: Release on: - push: - tags: ['v*.*.*'] + workflow_dispatch: +concurrency: + group: release jobs: create-release: runs-on: ubuntu-latest + # NOTE(krishan711): the release environment only allows main and holds the deploy key, which is the only thing allowed past the tag ruleset + environment: release permissions: contents: write steps: - name: Check out the repo uses: actions/checkout@v7 - - name: Create Release + with: + ssh-key: ${{ secrets.RELEASE_DEPLOY_KEY }} + - name: Push the version tag + id: version + run: | + version="v$(jq -r .version package.json)" + if [[ ! "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then + echo "::error::package.json version $version is not semver" + exit 1 + fi + existingSha="$(git ls-remote origin "refs/tags/$version" | cut -f1)" + if [[ -n "$existingSha" && "$existingSha" != "$GITHUB_SHA" ]]; then + echo "::error::$version already exists on $existingSha, bump the version in package.json" + exit 1 + fi + if [[ -z "$existingSha" ]]; then + git tag "$version" + git push origin "refs/tags/$version" + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Create the release env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: gh release create ${{ github.ref_name }} --title "Release ${{ github.ref_name }}" --generate-notes + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.version }} + run: | + if gh release view "$VERSION" >/dev/null 2>&1; then + echo "$VERSION is already released" + elif [[ "$VERSION" == *-* ]]; then + gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes --prerelease + else + gh release create "$VERSION" --verify-tag --title "Release $VERSION" --generate-notes + fi - name: Move the major version tag + if: ${{ !contains(steps.version.outputs.version, '-') }} + env: + VERSION: ${{ steps.version.outputs.version }} run: | - majorTag="${GITHUB_REF_NAME%%.*}" + majorTag="${VERSION%%.*}" git tag --force "$majorTag" - git push --force origin "$majorTag" + git push --force origin "refs/tags/$majorTag" diff --git a/README.md b/README.md index 952bee5..79ad21b 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The step fails when any check fails. Every check's full log is printed in its ow | Field | Required | Description | | --- | --- | --- | | `name` | yes | Short unique name, used for the container and the log group. | -| `command` | yes | Run with `sh -c` in the image, in the image's working directory. Quote it if it contains `: `. | +| `command` | yes | Run with `sh -c` in the image, ignoring the image's `ENTRYPOINT`, in the image's working directory. Quote it if it contains `: `. | | `check-name` | no | Report this check as its own GitHub check with this name. | | `annotations-file` | no | JSON file the command writes inside the container, in the [create-annotations](https://github.com/kibalabs/github-action-create-annotations) format, attached to the check. Needs `check-name`. Relative paths start from the image's working directory. | | `stdout-file` | no | Save the command's standard output to this file in the workspace, e.g. to compare generated files afterwards. | @@ -69,10 +69,10 @@ A check passes when its command exits with 0. Annotations are added to the check When [Skip If Passed](https://github.com/kibalabs/github-action-skip-if-passed) decides a job can be skipped, it sets `CHECKS_ALREADY_PASSED=true` and this action does nothing. Its checks set `external_id` to the workflow run's id, so Skip If Passed copies them onto the skipped commit. -If the job is cancelled or times out, a post step marks any checks that didn't finish as cancelled. +If the job is cancelled or times out, a post step marks any checks that didn't finish as cancelled and force-removes their containers. ## Development Build with `make build`, which bundles `src/` into `runnable/index.js`. GitHub runs that file directly, so commit it with every source change. Run the tests with `make test`. -To release, push a `vX.Y.Z` tag. The release workflow publishes the release and moves the `vX` tag to it, so `@v1` always points at the latest 1.x release. +To release, bump `version` in `package.json` in a PR, then run the Release workflow on `main` (Actions → Release → Run workflow). It tags `vX.Y.Z`, publishes the release and moves the `vX` tag to it, so `@v1` always points at the latest 1.x release. Versions with a pre-release suffix (e.g. `1.1.0-rc1`) are published as pre-releases and don't move `vX`. Only the release workflow can push version tags. diff --git a/package-lock.json b/package-lock.json index 58e53a0..f773399 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@kibalabs/github-action-run-docker-checks", - "version": "1.0.0", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@kibalabs/github-action-run-docker-checks", - "version": "1.0.0", + "version": "1.0.1", "license": "MIT", "dependencies": { "@actions/core": "^3.0.1", diff --git a/package.json b/package.json index 698b0f4..de9edf5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kibalabs/github-action-run-docker-checks", - "version": "1.0.0", + "version": "1.0.1", "description": "GitHub Action to run checks in parallel docker containers and report each as its own GitHub check", "license": "MIT", "private": true, diff --git a/runnable/index.js b/runnable/index.js index 29437ff..b6ea117 100644 --- a/runnable/index.js +++ b/runnable/index.js @@ -196,4 +196,4 @@ default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.l /* istanbul ignore else should not happen */ n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(` `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(` -`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Va=/* @__PURE__ */ E((e=>{var t=Na(),n=ga(),r=_a(),i=Vi(),a=$(),o=za(),s=Ba();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Ha=(/* @__PURE__ */ E((e=>{var t=Na(),n=ga(),r=ma(),i=_a(),a=Mi(),o=$(),s=Wi(),c=Ni(),l=Ki(),u=Ji();La();var d=Ra(),f=za(),p=Ba(),m=Va(),h=Ei();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();const Ua=[`name`,`command`,`check-name`,`annotations-file`,`stdout-file`],Wa=(e,t,n)=>{let r=e[t];if(r==null)return null;if(typeof r!=`string`||r.trim().length===0)throw Error(`${n}: ${t} must be a non-empty string`);return r.trim()},Ga=e=>{let t=(0,Ha.parse)(e);if(!Array.isArray(t)||t.length===0)throw Error(`checks must be a YAML list with at least one check`);let n=t.map((e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`check ${t+1}: must be a mapping with a name and a command`);let n=e,r=Wa(n,`name`,`check ${t+1}`);if(!r)throw Error(`check ${t+1}: name is required`);let i=Object.keys(n).filter(e=>!Ua.includes(e));if(i.length>0)throw Error(`${r}: unknown field(s) ${i.join(`, `)}, expected ${Ua.join(`, `)}`);let a=Wa(n,`command`,r);if(!a)throw Error(`${r}: command is required`);let o=Wa(n,`check-name`,r),s=Wa(n,`annotations-file`,r);if(s&&!o)throw Error(`${r}: annotations-file needs a check-name to attach the annotations to`);return{name:r,command:a,checkName:o,annotationsFile:s,stdoutFile:Wa(n,`stdout-file`,r)}}),r=n.map(e=>e.name).filter((e,t,n)=>n.indexOf(e)!==t);if(r.length>0)throw Error(`check names must be unique, repeated: ${[...new Set(r)].join(`, `)}`);return n},Ka=async(e,t=null,r=!1)=>{t&&await v(a.dirname(t),{recursive:!0});let i=_(`docker`,e,{stdio:[`ignore`,`pipe`,`pipe`]}),o=t?n(t):null,s=``,c=``;i.stdout.on(`data`,e=>{o?o.write(e):s+=e.toString()}),i.stderr.on(`data`,e=>{o&&r?o.write(e):c+=e.toString()});let[l]=await g(i,`close`);return o&&(o.end(),await g(o,`finish`)),{exitCode:l??1,stdout:s,stderr:c}},qa=async e=>{let t=await Ka(e);if(t.exitCode!==0)throw Error(`docker ${e[0]} failed: ${t.stderr.trim()}`);return t.stdout.trim()},Ja=async e=>{let t=[`image`,`inspect`,`--format`,`{{.Config.WorkingDir}}`,e],n=await Ka(t);return n.exitCode===0?n.stdout.trim()||`/`:(await qa([`pull`,`--quiet`,e]),await qa(t)||`/`)},Ya=async(e,t,n)=>{await qa([`run`,`--detach`,`--name`,e,t,`sh`,`-c`,n])},Xa=async e=>Number(await qa([`wait`,e])),Za=async(e,t,n)=>{await Ka([`logs`,e],t,!n)},Qa=async(e,t,n)=>{await qa([`cp`,`${e}:${t}`,n])},$a=async e=>{await Ka([`rm`,`--force`,e])},eo=[1e3,2e3,4e3];var to=class extends Error{constructor(e){super(e),this.name=`ChecksPermissionError`}};const no=e=>typeof e==`object`&&e&&`status`in e?Number(e.status):void 0,ro=e=>{let t=t=>e.annotations.filter(e=>e.annotation_level===t).length,n=[[t(`failure`),`failure(s)`],[t(`warning`),`warning(s)`],[t(`notice`),`notice(s)`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`),r=e.isSuccess?`Passed`:`Failed${e.exitCode===null?``:` (exit code ${e.exitCode})`}`,i=e.log.length>6e4,a=i?e.log.slice(-6e4):e.log;return{title:`${r} in ${e.durationSeconds}s`,summary:n.length>0?n.join(`, `):`No annotations.`,text:`${i?`Log (last part):`:`Log:`}\n\n\`\`\`\n${a.trimEnd().replace(/```/g,"`​``")}\n\`\`\``}},io=async(e,t,n)=>{try{return(await e.rest.checks.create({owner:t.owner,repo:t.repo,name:n,head_sha:t.headSha,external_id:String(t.runId),details_url:t.runUrl,status:`in_progress`})).data.id}catch(e){throw no(e)===403?new to(`The token can't create checks, give the job checks: write permission. Details: ${e}`):e}},ao=async(e,t,n,r,i)=>{try{await e.rest.checks.update({owner:t.owner,repo:t.repo,check_run_id:n,...r})}catch(a){if(no(a)===404&&i.length>0){await y(i[0]),await ao(e,t,n,r,i.slice(1));return}throw a}},oo=async(e,t,n,r)=>{let i=ro(r),a=[];for(let e=0;e{await r,await ao(e,t,n,{output:{...i,annotations:a}},eo)},Promise.resolve())},so=`checkRunIds`,co=e=>e instanceof Error?e.message:String(e),lo=()=>{let{owner:e,repo:t}=wi.repo;return{owner:e,repo:t,headSha:wi.payload.pull_request?.head.sha??wi.sha,runId:wi.runId,runUrl:`${wi.serverUrl}/${e}/${t}/actions/runs/${wi.runId}`}},uo=async(e,t,n,i,o)=>{if(!t.annotationsFile)return[];let s=a.join(o,`${e}-annotations.json`);try{return await Qa(e,a.posix.resolve(n,t.annotationsFile),s),JSON.parse(await r.readFile(s,`utf8`)).map(e=>({...e,path:a.join(i,e.path)}))}catch(e){return rn(`${t.name}: could not read ${t.annotationsFile}: ${co(e)}`),[]}},fo=async(e,n,i,o,s)=>{let c=`${e.name.replace(/[^a-zA-Z0-9_.-]/g,`-`)}-${t().slice(0,8)}`,l=a.join(s,`${c}.log`),u=Date.now(),d=null,f=[],p=``;try{await Ya(c,n,e.command),d=await Xa(c),await Za(c,l,!1),e.stdoutFile&&await Za(c,a.resolve(e.stdoutFile),!0),f=await uo(c,e,i,o,s)}catch(e){p=co(e)}finally{await $a(c)}let m=await r.readFile(l,`utf8`).catch(()=>``);return{definition:e,isSuccess:d===0&&!p,exitCode:d,durationSeconds:Math.round((Date.now()-u)/1e3),log:p?`${m}\n${p}`:m,annotations:f}},po=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=!0;return await n.reduce(async(n,a)=>{if(await n,a.checkName&&i)try{r.set(a.name,await io(e,t,a.checkName))}catch(e){if(!(e instanceof to))throw e;i=!1,rn(`Running the checks without reporting them as separate checks: ${e.message}`,{title:`Checks not reported`})}},Promise.resolve()),r},mo=async e=>{await zt.addTable([[{data:`Check`,header:!0},{data:`Result`,header:!0},{data:`Duration`,header:!0}],...e.map(e=>[e.definition.checkName??e.definition.name,e.isSuccess?`Passed`:`Failed`,`${e.durationSeconds}s`])]).write()},ho=async()=>{if(process.env.CHECKS_ALREADY_PASSED===`true`){an(`Skipping: CHECKS_ALREADY_PASSED is set, these checks already passed on an earlier run`);return}let e=$t(`image`,{required:!0}),t=Ga($t(`checks`,{required:!0})),n=$t(`annotations-path-prefix`,{required:!1}),o=Ti($t(`github-token`,{required:!0})),s=lo(),c=await Ja(e),l=await r.mkdtemp(a.join(process.env.RUNNER_TEMP||i.tmpdir(),`docker-checks-`)),u=await po(o,s,t);cn(so,JSON.stringify([...u.values()])),an(`Running ${t.length} checks in ${e}: ${t.map(e=>e.name).join(`, `)}`);let d=await Promise.all(t.map(async t=>{let r=await fo(t,e,c,n,l);an(`${r.isSuccess?`Passed`:`Failed`}: ${t.name} in ${r.durationSeconds}s`);let i=u.get(t.name);return i&&await oo(o,s,i,r).catch(e=>rn(`${t.name}: could not report the check: ${co(e)}`)),r}));d.forEach(e=>{on(`${e.isSuccess?`Passed`:`Failed`}: ${e.definition.name} (${e.durationSeconds}s)`),an(e.log),sn()}),await mo(d);let f=d.filter(e=>!e.isSuccess).map(e=>e.definition.name);en(`failed-checks`,f.join(`,`)),f.length>0&&tn(`${f.length} check(s) failed: ${f.join(`, `)}`)},go=async()=>{let e=JSON.parse(ln(so)||`[]`);if(e.length===0)return;let t=Ti($t(`github-token`,{required:!0})),n=lo();await Promise.all(e.map(async e=>{(await t.rest.checks.get({owner:n.owner,repo:n.repo,check_run_id:e})).data.status!==`completed`&&await t.rest.checks.update({owner:n.owner,repo:n.repo,check_run_id:e,status:`completed`,conclusion:`cancelled`})}))};(async()=>{let e=ln(`isPost`)===`true`;cn(`isPost`,`true`);try{await(e?go():ho())}catch(t){e?rn(`Could not cancel unfinished checks: ${co(t)}`):tn(co(t))}})();export{}; \ No newline at end of file +`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Va=/* @__PURE__ */ E((e=>{var t=Na(),n=ga(),r=_a(),i=Vi(),a=$(),o=za(),s=Ba();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Ha=(/* @__PURE__ */ E((e=>{var t=Na(),n=ga(),r=ma(),i=_a(),a=Mi(),o=$(),s=Wi(),c=Ni(),l=Ki(),u=Ji();La();var d=Ra(),f=za(),p=Ba(),m=Va(),h=Ei();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();const Ua=[`name`,`command`,`check-name`,`annotations-file`,`stdout-file`],Wa=(e,t,n)=>{let r=e[t];if(r==null)return null;if(typeof r!=`string`||r.trim().length===0)throw Error(`${n}: ${t} must be a non-empty string`);return r.trim()},Ga=e=>{let t=(0,Ha.parse)(e);if(!Array.isArray(t)||t.length===0)throw Error(`checks must be a YAML list with at least one check`);let n=t.map((e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`check ${t+1}: must be a mapping with a name and a command`);let n=e,r=Wa(n,`name`,`check ${t+1}`);if(!r)throw Error(`check ${t+1}: name is required`);let i=Object.keys(n).filter(e=>!Ua.includes(e));if(i.length>0)throw Error(`${r}: unknown field(s) ${i.join(`, `)}, expected ${Ua.join(`, `)}`);let a=Wa(n,`command`,r);if(!a)throw Error(`${r}: command is required`);let o=Wa(n,`check-name`,r),s=Wa(n,`annotations-file`,r);if(s&&!o)throw Error(`${r}: annotations-file needs a check-name to attach the annotations to`);return{name:r,command:a,checkName:o,annotationsFile:s,stdoutFile:Wa(n,`stdout-file`,r)}}),r=n.map(e=>e.name).filter((e,t,n)=>n.indexOf(e)!==t);if(r.length>0)throw Error(`check names must be unique, repeated: ${[...new Set(r)].join(`, `)}`);return n},Ka=async(e,t=null,r=!1)=>{t&&await v(a.dirname(t),{recursive:!0});let i=_(`docker`,e,{stdio:[`ignore`,`pipe`,`pipe`]}),o=t?n(t):null,s=``,c=``;i.stdout.on(`data`,e=>{o?o.write(e):s+=e.toString()}),i.stderr.on(`data`,e=>{o&&r?o.write(e):c+=e.toString()});let[l]=await g(i,`close`);return o&&(o.end(),await g(o,`finish`)),{exitCode:l??1,stdout:s,stderr:c}},qa=async e=>{let t=await Ka(e);if(t.exitCode!==0)throw Error(`docker ${e[0]} failed: ${t.stderr.trim()}`);return t.stdout.trim()},Ja=async e=>{let t=[`image`,`inspect`,`--format`,`{{.Config.WorkingDir}}`,e],n=await Ka(t);return n.exitCode===0?n.stdout.trim()||`/`:(await qa([`pull`,`--quiet`,e]),await qa(t)||`/`)},Ya=async(e,t,n)=>{await qa([`run`,`--detach`,`--name`,e,`--entrypoint`,`sh`,t,`-c`,n])},Xa=async e=>Number(await qa([`wait`,e])),Za=async(e,t,n)=>{await Ka([`logs`,e],t,!n)},Qa=async(e,t,n)=>{await qa([`cp`,`${e}:${t}`,n])},$a=async e=>{await Ka([`rm`,`--force`,e])},eo=[1e3,2e3,4e3];var to=class extends Error{constructor(e){super(e),this.name=`ChecksPermissionError`}};const no=e=>typeof e==`object`&&e&&`status`in e?Number(e.status):void 0,ro=e=>{let t=t=>e.annotations.filter(e=>e.annotation_level===t).length,n=[[t(`failure`),`failure(s)`],[t(`warning`),`warning(s)`],[t(`notice`),`notice(s)`]].filter(([e])=>Number(e)>0).map(([e,t])=>`${e} ${t}`),r=e.isSuccess?`Passed`:`Failed${e.exitCode===null?``:` (exit code ${e.exitCode})`}`,i=e.log.length>6e4,a=i?e.log.slice(-6e4):e.log;return{title:`${r} in ${e.durationSeconds}s`,summary:n.length>0?n.join(`, `):`No annotations.`,text:`${i?`Log (last part):`:`Log:`}\n\n\`\`\`\n${a.trimEnd().replace(/```/g,"`​``")}\n\`\`\``}},io=async(e,t,n)=>{try{return(await e.rest.checks.create({owner:t.owner,repo:t.repo,name:n,head_sha:t.headSha,external_id:String(t.runId),details_url:t.runUrl,status:`in_progress`})).data.id}catch(e){throw no(e)===403?new to(`The token can't create checks, give the job checks: write permission. Details: ${e}`):e}},ao=async(e,t,n,r,i)=>{try{await e.rest.checks.update({owner:t.owner,repo:t.repo,check_run_id:n,...r})}catch(a){if(no(a)===404&&i.length>0){await y(i[0]),await ao(e,t,n,r,i.slice(1));return}throw a}},oo=async(e,t,n,r)=>{let i=ro(r),a=[];for(let e=0;e{await r,await ao(e,t,n,{output:{...i,annotations:a}},eo)},Promise.resolve())},so=`checkRunIds`,co=`containerNames`,lo=e=>e instanceof Error?e.message:String(e),uo=()=>{let{owner:e,repo:t}=wi.repo;return{owner:e,repo:t,headSha:wi.payload.pull_request?.head.sha??wi.sha,runId:wi.runId,runUrl:`${wi.serverUrl}/${e}/${t}/actions/runs/${wi.runId}`}},fo=async(e,t,n,i,o)=>{if(!t.annotationsFile)return[];let s=a.join(o,`${e}-annotations.json`);try{return await Qa(e,a.posix.resolve(n,t.annotationsFile),s),JSON.parse(await r.readFile(s,`utf8`)).map(e=>({...e,path:a.join(i,e.path)}))}catch(e){return rn(`${t.name}: could not read ${t.annotationsFile}: ${lo(e)}`),[]}},po=async(e,t,n,i,o,s)=>{let c=a.join(s,`${e}.log`),l=Date.now(),u=null,d=[],f=``;try{await Ya(e,n,t.command),u=await Xa(e),await Za(e,c,!1),t.stdoutFile&&await Za(e,a.resolve(t.stdoutFile),!0),d=await fo(e,t,i,o,s)}catch(e){f=lo(e)}finally{await $a(e)}let p=await r.readFile(c,`utf8`).catch(()=>``);return{definition:t,isSuccess:u===0&&!f,exitCode:u,durationSeconds:Math.round((Date.now()-l)/1e3),log:f?`${p}\n${f}`:p,annotations:d}},mo=async(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=!0;return await n.reduce(async(n,a)=>{if(await n,a.checkName&&i)try{r.set(a.name,await io(e,t,a.checkName)),cn(so,JSON.stringify([...r.values()]))}catch(e){if(!(e instanceof to))throw e;i=!1,rn(`Running the checks without reporting them as separate checks: ${e.message}`,{title:`Checks not reported`})}},Promise.resolve()),r},ho=async e=>{await zt.addTable([[{data:`Check`,header:!0},{data:`Result`,header:!0},{data:`Duration`,header:!0}],...e.map(e=>[e.definition.checkName??e.definition.name,e.isSuccess?`Passed`:`Failed`,`${e.durationSeconds}s`])]).write()},go=async()=>{if(process.env.CHECKS_ALREADY_PASSED===`true`){an(`Skipping: CHECKS_ALREADY_PASSED is set, these checks already passed on an earlier run`);return}let e=$t(`image`,{required:!0}),n=Ga($t(`checks`,{required:!0})),o=$t(`annotations-path-prefix`,{required:!1}),s=Ti($t(`github-token`,{required:!0})),c=uo(),l=await Ja(e),u=await r.mkdtemp(a.join(process.env.RUNNER_TEMP||i.tmpdir(),`docker-checks-`)),d=await mo(s,c,n),f=n.map(e=>`${e.name.replace(/[^a-zA-Z0-9_.-]/g,`-`)}-${t().slice(0,8)}`);cn(co,JSON.stringify(f)),an(`Running ${n.length} checks in ${e}: ${n.map(e=>e.name).join(`, `)}`);let p=await Promise.all(n.map(async(t,n)=>{let r=await po(f[n],t,e,l,o,u);an(`${r.isSuccess?`Passed`:`Failed`}: ${t.name} in ${r.durationSeconds}s`);let i=d.get(t.name);return i&&await oo(s,c,i,r).catch(e=>rn(`${t.name}: could not report the check: ${lo(e)}`)),r}));p.forEach(e=>{on(`${e.isSuccess?`Passed`:`Failed`}: ${e.definition.name} (${e.durationSeconds}s)`),an(e.log),sn()}),await ho(p);let m=p.filter(e=>!e.isSuccess).map(e=>e.definition.name);en(`failed-checks`,m.join(`,`)),m.length>0&&tn(`${m.length} check(s) failed: ${m.join(`, `)}`)},_o=async()=>{let e=JSON.parse(ln(co)||`[]`);await Promise.all(e.map(e=>$a(e)));let t=JSON.parse(ln(so)||`[]`);if(t.length===0)return;let n=Ti($t(`github-token`,{required:!0})),r=uo();await Promise.all(t.map(async e=>{(await n.rest.checks.get({owner:r.owner,repo:r.repo,check_run_id:e})).data.status!==`completed`&&await n.rest.checks.update({owner:r.owner,repo:r.repo,check_run_id:e,status:`completed`,conclusion:`cancelled`})}))};(async()=>{let e=ln(`isPost`)===`true`;cn(`isPost`,`true`);try{await(e?_o():go())}catch(t){e?rn(`Could not clean up unfinished checks or containers: ${lo(t)}`):tn(lo(t))}})();export{}; \ No newline at end of file diff --git a/src/docker.ts b/src/docker.ts index e45522e..78c8239 100644 --- a/src/docker.ts +++ b/src/docker.ts @@ -61,7 +61,7 @@ export const getImageWorkingDirectory = async (image: string): Promise = }; export const startContainer = async (containerName: string, image: string, command: string): Promise => { - await runDockerOrThrow(['run', '--detach', '--name', containerName, image, 'sh', '-c', command]); + await runDockerOrThrow(['run', '--detach', '--name', containerName, '--entrypoint', 'sh', image, '-c', command]); }; export const waitForContainer = async (containerName: string): Promise => { diff --git a/src/index.ts b/src/index.ts index 0bc9847..b2aa224 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { ChecksPermissionError, completeCheck, createInProgressCheck, ICheckTarg import { IAnnotation, ICheckDefinition, ICheckResult, SKIP_ENVIRONMENT_VARIABLE } from './model'; const CHECK_RUN_IDS_STATE = 'checkRunIds'; +const CONTAINER_NAMES_STATE = 'containerNames'; const getErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error)); @@ -42,8 +43,7 @@ const readAnnotations = async (containerName: string, definition: ICheckDefiniti } }; -const runCheck = async (definition: ICheckDefinition, image: string, workingDirectory: string, pathPrefix: string, tempDirectory: string): Promise => { - const containerName = `${definition.name.replace(/[^a-zA-Z0-9_.-]/g, '-')}-${randomUUID().slice(0, 8)}`; +const runCheck = async (containerName: string, definition: ICheckDefinition, image: string, workingDirectory: string, pathPrefix: string, tempDirectory: string): Promise => { const logPath = path.join(tempDirectory, `${containerName}.log`); const startTime = Date.now(); let exitCode: number | null = null; @@ -83,6 +83,8 @@ const createChecks = async (octokit: Octokit, target: ICheckTarget, definitions: } try { checkRunIds.set(definition.name, await createInProgressCheck(octokit, target, definition.checkName)); + // NOTE(krishan711): saved after every creation so the post step can cancel the created checks even if a later creation fails + saveState(CHECK_RUN_IDS_STATE, JSON.stringify([...checkRunIds.values()])); } catch (error) { if (!(error instanceof ChecksPermissionError)) { throw error; @@ -115,10 +117,11 @@ const runChecks = async (): Promise => { const workingDirectory = await getImageWorkingDirectory(image); const tempDirectory = await fs.mkdtemp(path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'docker-checks-')); const checkRunIds = await createChecks(octokit, target, definitions); - saveState(CHECK_RUN_IDS_STATE, JSON.stringify([...checkRunIds.values()])); + const containerNames = definitions.map((definition: ICheckDefinition): string => `${definition.name.replace(/[^a-zA-Z0-9_.-]/g, '-')}-${randomUUID().slice(0, 8)}`); + saveState(CONTAINER_NAMES_STATE, JSON.stringify(containerNames)); logInfo(`Running ${definitions.length} checks in ${image}: ${definitions.map((definition: ICheckDefinition): string => definition.name).join(', ')}`); - const results = await Promise.all(definitions.map(async (definition: ICheckDefinition): Promise => { - const result = await runCheck(definition, image, workingDirectory, pathPrefix, tempDirectory); + const results = await Promise.all(definitions.map(async (definition: ICheckDefinition, index: number): Promise => { + const result = await runCheck(containerNames[index], definition, image, workingDirectory, pathPrefix, tempDirectory); logInfo(`${result.isSuccess ? 'Passed' : 'Failed'}: ${definition.name} in ${result.durationSeconds}s`); const checkRunId = checkRunIds.get(definition.name); if (checkRunId) { @@ -139,8 +142,10 @@ const runChecks = async (): Promise => { } }; -// NOTE(krishan711): runs after the job even when it is cancelled or times out, so the checks this action created don't stay in progress forever +// NOTE(krishan711): runs after the job even when cancelled or timed out, cleaning up checks and their containers const cancelUnfinishedChecks = async (): Promise => { + const containerNames = JSON.parse(getState(CONTAINER_NAMES_STATE) || '[]') as string[]; + await Promise.all(containerNames.map((containerName: string): Promise => removeContainer(containerName))); const checkRunIds = JSON.parse(getState(CHECK_RUN_IDS_STATE) || '[]') as number[]; if (checkRunIds.length === 0) { return; @@ -162,7 +167,7 @@ const run = async (): Promise => { await (isPost ? cancelUnfinishedChecks() : runChecks()); } catch (error) { if (isPost) { - warning(`Could not cancel unfinished checks: ${getErrorMessage(error)}`); + warning(`Could not clean up unfinished checks or containers: ${getErrorMessage(error)}`); } else { setFailed(getErrorMessage(error)); }