Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dump resources, especially checks, for debugging #832

Merged
merged 28 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7c8f4f5
Prefer GITHUB_OUTPUT for printing debug resources
kachick Jun 3, 2024
ddcda0c
Fix typos
kachick Jun 3, 2024
df660dd
Move into lightweight job
kachick Jun 3, 2024
61cfe22
Fix missing step name
kachick Jun 3, 2024
108ea79
Print the output size
kachick Jun 3, 2024
2dc5792
Fix typo
kachick Jun 3, 2024
9777fd4
Update documents
kachick Jun 3, 2024
c235b73
Gathers into single object
kachick Jun 4, 2024
692d003
Extract outputs workflow to make rerun easy
kachick Jun 4, 2024
66bcbcd
No need to guard uploading
kachick Jun 4, 2024
23ab2fd
Fix a typo
kachick Jun 4, 2024
e9a5abd
Adjust times to make multiple pollings
kachick Jun 4, 2024
81a9573
Check the filesize
kachick Jun 4, 2024
5c98a4f
Do not early exit with set -e
kachick Jun 4, 2024
e2e86a3
Do not append excess lf
kachick Jun 4, 2024
b09e5a0
Do not depend on debug mode
kachick Jun 4, 2024
0124347
Omit middle pollings in debug report
kachick Jun 4, 2024
b421c79
Remove outdated isDebug
kachick Jun 5, 2024
586d9d4
Remove payload from dump data
kachick Jun 5, 2024
234f146
Remove outdated guard in workflow
kachick Jun 5, 2024
81ed152
Do not use single quote for multine lines
kachick Jun 5, 2024
aa42873
`pnpm install @actions/artifact`
kachick Jun 5, 2024
1da1ce2
Write dump to file and just outputs the path
kachick Jun 5, 2024
1ea10a0
`pnpm uninstall @actions/artifact`
kachick Jun 5, 2024
5a273f5
Update use of action
kachick Jun 5, 2024
b5b8e70
Remove unused code and compile
kachick Jun 5, 2024
3f9d611
Clarify outputs in action.yml
kachick Jun 5, 2024
9d768c5
Simplify message
kachick Jun 5, 2024
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
65 changes: 65 additions & 0 deletions .github/workflows/outputs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
name: Outputs
on:
push:
branches: [main]
paths:
- '.github/workflows/outputs.yml'
- 'action.yml'
- 'dist/**'
pull_request:
paths:
- '.github/workflows/outputs.yml'
- 'action.yml'
- 'dist/**'
workflow_dispatch:

# Disable all permissions in workflow global as to setup clean room
# However PRs will have read permissions because this project is on a public repository
permissions: {}

jobs:
echo:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- run: echo ':)'
# Wait longer than min-interval-seconds
- run: sleep 8
- run: echo '🎉'
dump:
runs-on: ubuntu-24.04
if: ${{ github.actor != 'dependabot[bot]' && github.actor != 'renovate[bot]' }}
timeout-minutes: 5
steps:
- uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
- uses: ./
id: wait
with:
retry-method: 'equal_intervals'
wait-seconds-before-first-polling: '1'
min-interval-seconds: '3'
skip-same-workflow: 'false'
wait-list: |
[
{
"workflowFile": "outputs.yml",
"jobName": "echo",
"optional": false
}
]
- name: 'Copy the output results to files'
env:
DEBUG_DUMP: '${{ steps.wait.outputs.dump }}'
run: |
mkdir outputs
echo -n "$DEBUG_DUMP" > ./outputs/dump.json
ls -alh ./outputs
set +e
if [[ -s './outputs/dump.json' ]] && [[ '${{ runner.debug }}' != '1' ]]; then
exit 2
fi
- name: Upload dumps as an artifact
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4.3.3
with:
name: 'outputs-${{ github.job }}-${{ github.run_id }}-${{ github.run_number }}-${{ github.run_attempt }}'
path: ./outputs
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ permissions:
actions: read
```

## jobs.<job_id>.outputs

(Since v3.4.0)

If used in debug mode, this action outputs the used resources into the `dump` key.\
This data is only provided for debugging purposes, so the schema is not defined.

## Examples

I'm using this action for auto-merging bot PRs and wait for deploy.\
Expand Down
49 changes: 23 additions & 26 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ var require_tunnel = __commonJS({
connectOptions.headers = connectOptions.headers || {};
connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64");
}
debug3("making CONNECT request");
debug("making CONNECT request");
var connectReq = self.request(connectOptions);
connectReq.useChunkedEncodingByDefault = false;
connectReq.once("response", onResponse);
Expand All @@ -746,7 +746,7 @@ var require_tunnel = __commonJS({
connectReq.removeAllListeners();
socket.removeAllListeners();
if (res.statusCode !== 200) {
debug3(
debug(
"tunneling socket could not be established, statusCode=%d",
res.statusCode
);
Expand All @@ -758,21 +758,21 @@ var require_tunnel = __commonJS({
return;
}
if (head.length > 0) {
debug3("got illegal response body from proxy");
debug("got illegal response body from proxy");
socket.destroy();
var error2 = new Error("got illegal response body from proxy");
error2.code = "ECONNRESET";
options.request.emit("error", error2);
self.removeSocket(placeholder);
return;
}
debug3("tunneling connection has established");
debug("tunneling connection has established");
self.sockets[self.sockets.indexOf(placeholder)] = socket;
return cb(socket);
}
function onError(cause) {
connectReq.removeAllListeners();
debug3(
debug(
"tunneling socket could not be established, cause=%s\n",
cause.message,
cause.stack
Expand Down Expand Up @@ -834,9 +834,9 @@ var require_tunnel = __commonJS({
}
return target;
}
var debug3;
var debug;
if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
debug3 = function() {
debug = function() {
var args = Array.prototype.slice.call(arguments);
if (typeof args[0] === "string") {
args[0] = "TUNNEL: " + args[0];
Expand All @@ -846,10 +846,10 @@ var require_tunnel = __commonJS({
console.error.apply(console, args);
};
} else {
debug3 = function() {
debug = function() {
};
}
exports.debug = debug3;
exports.debug = debug;
}
});

Expand Down Expand Up @@ -18878,15 +18878,15 @@ var require_core = __commonJS({
Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
}
exports.getBooleanInput = getBooleanInput2;
function setOutput(name, value) {
function setOutput2(name, value) {
const filePath = process.env["GITHUB_OUTPUT"] || "";
if (filePath) {
return file_command_1.issueFileCommand("OUTPUT", file_command_1.prepareKeyValueMessage(name, value));
}
process.stdout.write(os2.EOL);
command_1.issueCommand("set-output", { name }, utils_1.toCommandValue(value));
}
exports.setOutput = setOutput;
exports.setOutput = setOutput2;
function setCommandEcho(enabled) {
command_1.issue("echo", enabled ? "on" : "off");
}
Expand All @@ -18896,14 +18896,14 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``);
error2(message);
}
exports.setFailed = setFailed2;
function isDebug3() {
function isDebug2() {
return process.env["RUNNER_DEBUG"] === "1";
}
exports.isDebug = isDebug3;
function debug3(message) {
exports.isDebug = isDebug2;
function debug(message) {
command_1.issueCommand("debug", {}, message);
}
exports.debug = debug3;
exports.debug = debug;
function error2(message, properties = {}) {
command_1.issueCommand("error", utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message);
}
Expand Down Expand Up @@ -31125,9 +31125,6 @@ function parseInput() {
if (typeof prSha === "string") {
commitSha = prSha;
} else {
if ((0, import_core.isDebug)()) {
(0, import_core.debug)(JSON.stringify({ label: "PullRequestContext", pr: pr2 }, null, 2));
}
(0, import_core.error)("github context has unexpected format: missing context.payload.pull_request.head.sha");
}
}
Expand Down Expand Up @@ -31161,7 +31158,7 @@ function parseInput() {
const trigger = { ...repo, ref: commitSha, runId, jobName: job, eventName };
const githubToken = (0, import_core.getInput)("github-token", { required: true, trimWhitespace: false });
(0, import_core.setSecret)(githubToken);
return { trigger, options, githubToken };
return { trigger, options, githubToken, payload };
}

// node_modules/.pnpm/[email protected]/node_modules/universal-user-agent/index.js
Expand Down Expand Up @@ -32555,8 +32552,9 @@ function colorize(severity, message) {
async function run() {
const startedAt = performance.now();
(0, import_core3.startGroup)("Parameters");
const { trigger, options, githubToken } = parseInput();
const { trigger, options, githubToken, payload } = parseInput();
(0, import_core3.info)(JSON.stringify(
// Do NOT include payload
{
trigger,
startedAt,
Expand All @@ -32572,6 +32570,7 @@ async function run() {
if (options.isDryRun) {
return;
}
const dumper = { trigger, options, payload, results: [] };
for (; ; ) {
attempts += 1;
if (attempts > options.attemptLimits) {
Expand All @@ -32589,9 +32588,6 @@ async function run() {
const elapsed = mr.Duration.from({ milliseconds: Math.ceil(performance.now() - startedAt) });
(0, import_core3.startGroup)(`Polling ${attempts}: ${(/* @__PURE__ */ new Date()).toISOString()} # total elapsed ${readableDuration(elapsed)}`);
const checks = await fetchChecks(githubToken, trigger);
if ((0, import_core3.isDebug)()) {
(0, import_core3.debug)(JSON.stringify({ label: "rawdata", checks, elapsed }, null, 2));
}
const report = generateReport(
getSummaries(checks, trigger),
trigger,
Expand All @@ -32613,9 +32609,7 @@ async function run() {
`${workflowBasename}(${colorize(severity, jobName)}): [eventName: ${eventName}][runStatus: ${runStatus}][runConclusion: ${runConclusion ?? nullStr}][runURL: ${checkRunUrl}]`
);
}
if ((0, import_core3.isDebug)()) {
(0, import_core3.debug)(JSON.stringify({ label: "filtered", report }, null, 2));
}
dumper.results.push({ elapsed, checks, report });
const { ok, done, logs } = report;
for (const { severity, message, resource } of logs) {
(0, import_core3.info)(colorize(severity, message));
Expand Down Expand Up @@ -32645,6 +32639,9 @@ async function run() {
break;
}
}
if ((0, import_core3.isDebug)()) {
(0, import_core3.setOutput)("dump", JSON.stringify(dumper, null, 2));
}
}
void run();
/*! Bundled license information:
Expand Down
4 changes: 4 additions & 0 deletions snapshots/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# How to get snapshot of resources

Since v3.4.0, we can use GITHUB_OUTPUT only in debug mode\
See the section in [README](../README.md#jobsjob_idoutputs)
11 changes: 4 additions & 7 deletions src/input.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { debug, getInput, getBooleanInput, setSecret, isDebug, error } from '@actions/core';
import { getInput, getBooleanInput, setSecret, error } from '@actions/core';
import { WebhookPayload } from '@actions/github/lib/interfaces.ts';
import { context } from '@actions/github';

import { Durationable, Options, Trigger } from './schema.ts';

export function parseInput(): { trigger: Trigger; options: Options; githubToken: string } {
export function parseInput(): { trigger: Trigger; options: Options; githubToken: string; payload: WebhookPayload } {
const {
repo,
payload,
Expand All @@ -19,10 +20,6 @@ export function parseInput(): { trigger: Trigger; options: Options; githubToken:
if (typeof prSha === 'string') {
commitSha = prSha;
} else {
if (isDebug()) {
// Do not print secret even for debug code
debug(JSON.stringify({ label: 'PullRequestContext', pr }, null, 2));
}
error('github context has unexpected format: missing context.payload.pull_request.head.sha');
}
}
Expand Down Expand Up @@ -62,5 +59,5 @@ export function parseInput(): { trigger: Trigger; options: Options; githubToken:
const githubToken = getInput('github-token', { required: true, trimWhitespace: false });
setSecret(githubToken);

return { trigger, options, githubToken };
return { trigger, options, githubToken, payload };
}
37 changes: 28 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { debug, info, setFailed, isDebug, startGroup, endGroup } from '@actions/core';
import { info, setFailed, isDebug, startGroup, endGroup, setOutput } from '@actions/core';
import styles from 'ansi-styles';

function colorize(severity: Severity, message: string): string {
Expand All @@ -24,15 +24,31 @@ function colorize(severity: Severity, message: string): string {

import { parseInput } from './input.ts';
import { fetchChecks } from './github-api.ts';
import { Severity, generateReport, getSummaries, readableDuration } from './report.ts';
import { Report, Severity, generateReport, getSummaries, readableDuration } from './report.ts';
import { getInterval, wait } from './wait.ts';
import { Temporal } from 'temporal-polyfill';
import { Check, Options, Trigger } from './schema.ts';
import { WebhookPayload } from '@actions/github/lib/interfaces.ts';

interface Attempt {
elapsed: Temporal.Duration;
checks: Check[];
report: Report;
}

interface Dumper {
trigger: Trigger;
options: Options;
payload: WebhookPayload;
results: Attempt[];
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want a payload for addressing issues, such as #767.
However, the object schema scares me due to accidents. 🤔

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[github context](https://docs.github.com/en/actions/learn-github-actions/contexts#github-context)
The github context contains information about the workflow run and the event that triggered the run. You can also read most of the github context data in environment variables. For more information about environment variables, see "[Variables](https://docs.github.com/en/actions/learn-github-actions/variables)."

Warning: When using the whole github context, be mindful that it includes sensitive information such as github.token. GitHub masks secrets when they are printed to the console, but you should be cautious when exporting or printing the context.

Warning: When creating workflows and actions, you should always consider whether your code might execute untrusted input from possible attackers. Certain contexts should be treated as untrusted input, as an attacker could insert their own malicious content. For more information, see "[Security hardening for GitHub Actions](https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#understanding-the-risk-of-script-injections)."

https://docs.github.com/en/actions/learn-github-actions/contexts#github-context

In my understanding, this payload will points to github.event, not the whole of context.

The full event webhook payload. You can access individual properties of the event using this context. This object is identical to the webhook payload of the event that triggered the workflow run, and is different for each event. The webhooks for each GitHub Actions event is linked in "Events that trigger workflows." For example, for a workflow run triggered by the push event, this object contains the contents of the push webhook payload.

But...

}

async function run(): Promise<void> {
const startedAt = performance.now();
startGroup('Parameters');
const { trigger, options, githubToken } = parseInput();
const { trigger, options, githubToken, payload } = parseInput();
info(JSON.stringify(
// Do NOT include payload
{
trigger,
startedAt,
Expand All @@ -50,6 +66,9 @@ async function run(): Promise<void> {
return;
}

// Do not include secret even in debug mode
const dumper: Dumper = { trigger, options, payload, results: [] };

for (;;) {
attempts += 1;
if (attempts > options.attemptLimits) {
Expand All @@ -70,9 +89,7 @@ async function run(): Promise<void> {
const elapsed = Temporal.Duration.from({ milliseconds: Math.ceil(performance.now() - startedAt) });
startGroup(`Polling ${attempts}: ${(new Date()).toISOString()} # total elapsed ${readableDuration(elapsed)}`);
const checks = await fetchChecks(githubToken, trigger);
if (isDebug()) {
debug(JSON.stringify({ label: 'rawdata', checks, elapsed }, null, 2));
}

const report = generateReport(
getSummaries(checks, trigger),
trigger,
Expand Down Expand Up @@ -101,9 +118,7 @@ async function run(): Promise<void> {
);
}

if (isDebug()) {
debug(JSON.stringify({ label: 'filtered', report }, null, 2));
}
dumper.results.push({ elapsed, checks, report });

const { ok, done, logs } = report;

Expand Down Expand Up @@ -139,6 +154,10 @@ async function run(): Promise<void> {
break;
}
}

if (isDebug()) {
setOutput('dump', JSON.stringify(dumper, null, 2));
}
}

void run();
Loading