Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ The build step (`npm run build`) also runs `npm run docs`, which regenerates the
4. Downloads or cache-hits the SQL Server installer (box+exe, standalone exe, or SSEI bootstrapper)
5. Optionally downloads cumulative updates (resolves Microsoft download-page JSON, falls back to legacy `<a href>` links if the metadata is missing or unusable, fetches the page up to three times, retrying network errors, timeouts and non-2xx responses after 5 and then 10 seconds, and if resolving or downloading the update fails, warns and installs without updates)
6. Runs the installer via `@actions/exec` (exit code 3010, "succeeded but reboot required", is logged as a warning and treated as success; any other non-zero code fails the action)
7. Waits for the database to be ready (exponential backoff); not becoming ready is a warning, or an error if setup exited 3010
7. Waits for the database to be ready with `waitForDatabase()` from `src/utils.ts` (up to 6 `sqlcmd` logins with exponential backoff); if the database is not ready, or `sqlcmd` can't run, the action warns, or fails if setup exited 3010

**Installer abstraction:** `src/installers/` contains a base `Installer` class and `MsiInstaller` subclass used by the native client and ODBC installations. SQL Server itself uses direct exe/box download logic or the SSEI bootstrapper (for 2025+) in `src/utils.ts`.

Expand Down
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ See [action.yml](./action.yml):
install-arguments: ''

# Wait for the database to respond successfully to queries before completing the
# action. A maximum of 10 attempts is made.
# action. The action tries to log in up to 6 times, with waits of 1, 2, 4, 8 and
# 16 seconds between the attempts. The check uses sqlcmd. If the database is not
# ready, or sqlcmd cannot run, for example because it is not on the PATH, the
# action warns and continues. If setup asked for a reboot (exit code 3010), the
# action fails instead.
# Default: true
wait-for-ready: true

Expand Down Expand Up @@ -123,8 +127,9 @@ newer update.

If SQL Server setup succeeds but asks for a reboot (exit code 3010), the action
logs a warning and carries on without rebooting. With `wait-for-ready` enabled,
the action then fails if the instance doesn't respond to queries, rather than
only warning as it does after a normal install.
the action then fails if the instance doesn't respond to queries, or if
`sqlcmd` can't run to check it. After a normal install, the action only warns
in both cases.

### Disks with large sectors

Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ inputs:
install-arguments:
description: 'Any custom install arguments you wish to use. These must be in the format of "/ARG=VAL".'
wait-for-ready:
description: 'Wait for the database to respond successfully to queries before completing the action. A maximum of 10 attempts is made.'
description: 'Wait for the database to respond successfully to queries before completing the action. The action tries to log in up to 6 times, with waits of 1, 2, 4, 8 and 16 seconds between the attempts. The check uses sqlcmd. If the database is not ready, or sqlcmd cannot run, for example because it is not on the PATH, the action warns and continues. If setup asked for a reboot (exit code 3010), the action fails instead.'
default: 'true'
install-updates:
description: 'Attempt to install latest cumulative updates during the installation process (not available for all versions).'
Expand Down
2 changes: 1 addition & 1 deletion lib/main/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/main/index.js.map

Large diffs are not rendered by default.

33 changes: 9 additions & 24 deletions src/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,33 +188,18 @@ export default async function install() {
core.setOutput('sa-password', password);
core.setOutput('instance-name', instanceName);
if (wait) {
core.startGroup('Waiting for database');
let res = await waitForDatabase(password);
let count = 0;
while (res !== 0 && count < 5) {
const waitTime = Math.pow(2, count);
core.debug(`Database not ready, waiting ${waitTime} second${waitTime === 1 ? '' : 's'}`);
await new Promise((resolve) => setTimeout(resolve, waitTime * 1000));
count++;
core.debug(`Checking database, attempt ${count}`);
res = await waitForDatabase(password);
if (res === 0) {
break;
const readiness = await core.group('Waiting for database', () => waitForDatabase(password));
if (readiness.status === 'unavailable') {
if (rebootRequired) {
throw new Error(`Unable to check that the database is ready after setup requested a reboot (exit code 3010) that could not be performed, because sqlcmd could not run: ${readiness.reason}`);
}
}
if (res === 0) {
if (count) {
core.info(`Database ready after ${count} attempts`);
} else {
core.info(`Database ready`);
core.warning(`Skipping the readiness check because sqlcmd could not run: ${readiness.reason}`);
} else if (readiness.status === 'not-ready') {
if (rebootRequired) {
throw new Error(`Database not ready after ${readiness.attempts} attempts; setup requested a reboot (exit code 3010) that could not be performed`);
}
} else if (rebootRequired) {
core.endGroup();
throw new Error(`Database not ready after ${count} attempts; setup requested a reboot (exit code 3010) that could not be performed`);
} else {
core.warning(`Database not ready after ${count} attempts, moving on`);
core.warning(`Database not ready after ${readiness.attempts} attempts, moving on`);
}
core.endGroup();
}
core.info(`SQL Server ${version} installed`);
} catch (e) {
Expand Down
52 changes: 49 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,58 @@ export function downloadTool(url: string, extName?: string) {
}

/**
* Helper function that uses sqlcmd to check if the SQL server is running.
* The outcome of the readiness check. It is `unavailable` when sqlcmd can't run, for example because it isn't on
* the PATH.
*/
export type DatabaseReadiness =
| { status: 'ready' | 'not-ready', attempts: number }
| { status: 'unavailable', reason: string };

/**
* The number of times that the readiness check tries to log in. If you change it, also change the
* `wait-for-ready` description in `action.yml`.
*/
const READINESS_ATTEMPTS = 6;

/**
* Try up to READINESS_ATTEMPTS times to log in to the SQL Server instance. Before each new attempt, wait twice
* as long as before, starting at 1 second. If sqlcmd can't run, stop and return `unavailable` instead of
* rejecting.
*
* @param {string} password
* @returns {Promise<DatabaseReadiness>}
*/
export async function waitForDatabase(password: string): Promise<DatabaseReadiness> {
try {
let attempts = 1;
let res = await queryDatabase(password);
while (res !== 0 && attempts < READINESS_ATTEMPTS) {
const waitTime = 2 ** (attempts - 1);
core.debug(`Database not ready, waiting ${waitTime} second${waitTime === 1 ? '' : 's'}`);
await delay(waitTime * 1000);
attempts++;
core.debug(`Checking database, attempt ${attempts} of ${READINESS_ATTEMPTS}`);
res = await queryDatabase(password);
}
if (res !== 0) {
return { status: 'not-ready', attempts };
}
core.info(attempts === 1 ? 'Database ready' : `Database ready after ${attempts} attempts`);
return { status: 'ready', attempts };
} catch (error) {
// exec rejects when it can't find sqlcmd on the PATH, or when Node reports a spawn error event, for
// example EACCES
return { status: 'unavailable', reason: error instanceof Error ? error.message : String(error) };
}
}

/**
* Use sqlcmd to check once if the SQL Server instance accepts logins.
*
* @param {string} password
* @returns {number} Status code
* @returns {Promise<number>} The sqlcmd exit code
*/
export function waitForDatabase(password: string) {
function queryDatabase(password: string) {
return exec.exec('sqlcmd', [
'-S',
'(local)',
Expand Down
97 changes: 56 additions & 41 deletions test/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const utils = {
downloadSseiInstaller: mock.fn(async () => 'C:\\tmp\\ssei\\setup.exe'),
downloadUpdateInstaller: mock.fn(async () => 'C:\\tmp\\exe\\sqlupdate.exe'),
findInstanceDirArgs: mock.fn(async () => [] as string[]),
waitForDatabase: mock.fn(async () => 0),
waitForDatabase: mock.fn(async () => ({ status: 'ready', attempts: 1 })),
downloadTool: mock.fn(async () => ''),
};

Expand Down Expand Up @@ -99,7 +99,7 @@ describe('install', () => {
utils.downloadSseiInstaller.mock.mockImplementation(async () => 'C:\\tmp\\ssei\\setup.exe');
utils.downloadUpdateInstaller.mock.mockImplementation(async () => 'C:\\tmp\\exe\\sqlupdate.exe');
utils.findInstanceDirArgs.mock.mockImplementation(async () => []);
utils.waitForDatabase.mock.mockImplementation(async () => 0);
utils.waitForDatabase.mock.mockImplementation(async () => ({ status: 'ready', attempts: 1 }));

VERSIONS.clear();
VERSIONS.set('box', {
Expand Down Expand Up @@ -238,19 +238,20 @@ describe('install', () => {
assert.deepEqual(core.setOutput.mock.calls.map((c) => c.arguments), [['sa-password', 'secret password'], ['instance-name', 'MSSQLSERVER']]);
});
it('fails if the database is not ready after setup requests a reboot', async () => {
const original = globalThis.setTimeout;
(globalThis as any).setTimeout = (cb: () => void) => { cb(); return 0 as any; };
try {
exec.exec.mock.mockImplementation(async () => 3010);
utils.waitForDatabase.mock.mockImplementation(async () => 1);
await assert.rejects(() => install(), {
message: 'Database not ready after 5 attempts; setup requested a reboot (exit code 3010) that could not be performed',
});
} finally {
globalThis.setTimeout = original;
}
assert.equal(utils.waitForDatabase.mock.callCount(), 6);
assert.equal(core.endGroup.mock.callCount(), core.startGroup.mock.callCount());
exec.exec.mock.mockImplementation(async () => 3010);
utils.waitForDatabase.mock.mockImplementation(async () => ({ status: 'not-ready', attempts: 6 }));
await assert.rejects(() => install(), {
message: 'Database not ready after 6 attempts; setup requested a reboot (exit code 3010) that could not be performed',
});
assert.equal(utils.waitForDatabase.mock.callCount(), 1);
assert.equal(utils.gatherSummaryFiles.mock.calls[0].arguments[0], true);
});
it('fails if sqlcmd cannot run after setup requests a reboot', async () => {
exec.exec.mock.mockImplementation(async () => 3010);
utils.waitForDatabase.mock.mockImplementation(async () => ({ status: 'unavailable', reason: 'Unable to locate executable file: sqlcmd.' }));
await assert.rejects(() => install(), {
message: 'Unable to check that the database is ready after setup requested a reboot (exit code 3010) that could not be performed, because sqlcmd could not run: Unable to locate executable file: sqlcmd.',
});
assert.equal(utils.gatherSummaryFiles.mock.calls[0].arguments[0], true);
});
it('fails if setup exits with any other non-zero code', async () => {
Expand Down Expand Up @@ -375,32 +376,46 @@ describe('install', () => {
assert.equal(exec.exec.mock.callCount(), 1);
assert.equal(exec.exec.mock.calls[0].arguments[0], '"C:\\tmp\\exe\\setup.exe"');
});
it('waits for max of 10 attempts', async () => {
const original = globalThis.setTimeout;
(globalThis as any).setTimeout = (cb: () => void) => { cb(); return 0 as any; };
try {
utils.waitForDatabase.mock.mockImplementation(async () => 1);
await install();
} finally {
globalThis.setTimeout = original;
}
assert.equal(utils.waitForDatabase.mock.callCount(), 6);
assert.deepEqual(core.warning.mock.calls.map((c) => c.arguments[0]), ['Database not ready after 5 attempts, moving on']);
});
it('waits until db is ready', async () => {
const original = globalThis.setTimeout;
(globalThis as any).setTimeout = (cb: () => void) => { cb(); return 0 as any; };
try {
let call = 0;
utils.waitForDatabase.mock.mockImplementation(async () => {
call++;
return call >= 3 ? 0 : 1;
});
await install();
} finally {
globalThis.setTimeout = original;
}
assert.equal(utils.waitForDatabase.mock.callCount(), 3);
it('warns and carries on if the database is not ready', async () => {
utils.waitForDatabase.mock.mockImplementation(async () => ({ status: 'not-ready', attempts: 6 }));
await install();
assert.equal(utils.waitForDatabase.mock.callCount(), 1);
assert.deepEqual(core.warning.mock.calls.map((c) => c.arguments[0]), ['Database not ready after 6 attempts, moving on']);
assert.equal(utils.gatherSummaryFiles.mock.calls[0].arguments[0], false);
});
it('warns and skips the readiness check if sqlcmd cannot run', async () => {
utils.waitForDatabase.mock.mockImplementation(async () => ({ status: 'unavailable', reason: 'Unable to locate executable file: sqlcmd.' }));
await install();
assert.deepEqual(core.warning.mock.calls.map((c) => c.arguments[0]), ['Skipping the readiness check because sqlcmd could not run: Unable to locate executable file: sqlcmd.']);
assert.deepEqual(core.setOutput.mock.calls.map((c) => c.arguments), [['sa-password', 'secret password'], ['instance-name', 'MSSQLSERVER']]);
assert.ok(core.info.mock.calls.some((c) => c.arguments[0] === 'SQL Server box installed'));
assert.equal(utils.gatherSummaryFiles.mock.calls[0].arguments[0], false);
});
it('checks the database in its own log group', async () => {
let group: string | undefined;
core.group.mock.mockImplementation(async (name: string, cb: () => unknown) => {
group = name;
try {
return await cb();
} finally {
group = undefined;
}
});
let checkedIn: string | undefined;
utils.waitForDatabase.mock.mockImplementation(async () => {
checkedIn = group;
return { status: 'ready', attempts: 1 };
});
await install();
assert.equal(checkedIn, 'Waiting for database');
assert.deepEqual(utils.waitForDatabase.mock.calls[0].arguments, ['secret password']);
});
it('does not check the database if wait-for-ready is false', async () => {
utils.gatherInputs.mock.mockImplementation(() => defaultInputs({ wait: false }));
await install();
assert.equal(utils.waitForDatabase.mock.callCount(), 0);
assert.ok(!core.group.mock.calls.some((c) => c.arguments[0] === 'Waiting for database'));
assert.equal(core.warning.mock.callCount(), 0);
});
it('fetches summary files', async () => {
utils.gatherInputs.mock.mockImplementation(() => defaultInputs({ wait: false }));
Expand Down
Loading
Loading