diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..cf87d15 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,50 @@ +name: Validate action +on: + pull_request: + schedule: + - cron: 0 0 * * * + +jobs: + default-parameters: + strategy: + matrix: + os: [ windows-2016, windows-2019 ] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: configure-pagefile-action + uses: ./ + with: + minimum-size: 8GB + + - name: validation + shell: pwsh + run: | + (Get-CimInstance Win32_PageFileUsage).AllocatedBaseSize + Invoke-Expression "wmic pagefile list /format:list" | Select-String "AllocatedBaseSize=", "Name=" + + custom-parameters: + strategy: + matrix: + os: [ windows-2016, windows-2019 ] + disk-root: [ "C:", "D:" ] + fail-fast: false + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: configure-pagefile-action + uses: ./ + with: + minimum-size: 4GB + maximum-size: 8GB + disk-root: ${{ matrix.disk-root }} + + - name: validation + shell: pwsh + run: | + (Get-CimInstance Win32_PageFileUsage).AllocatedBaseSize + Invoke-Expression "wmic pagefile list /format:list" | Select-String "AllocatedBaseSize=", "Name=" diff --git a/.github/workflows/workflow.yml b/.github/workflows/workflow.yml new file mode 100644 index 0000000..df8679d --- /dev/null +++ b/.github/workflows/workflow.yml @@ -0,0 +1,20 @@ +name: Build action +on: [pull_request] + +jobs: + Build: + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@master + + - name: Set Node.JS + uses: actions/setup-node@master + with: + node-version: 12.x + + - name: npm install + run: npm install + + - name: Build + run: npm run build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..140d803 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +lib \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2e02d83 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2020 Maxim Lobanov and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 601ddd9..0e814af 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,33 @@ # configure-pagefile-action -Set PageFileSize on GitHub Windows Hosted Agents +This action is intended to configure Pagefile size and location for Windows images in GitHub Actions. + +# Available parameters +| Argument | Description | Format | Default value | +|----------|-------------|--------|---------------| +| `minimum-size` | Set minimum size of Pagefile | `2048MB`, `4GB`, `8GB` and etc | `8GB` | +| `maximum-size` | Set maximum size of Pagefile | The same like `minimum-size` | `minimum-size` | +| `disk-root` | Set disk root where Pagefile will be located | `C:` or `D:` | `D:` | + +# Usage +``` +name: CI +on: [push] +jobs: + build: + runs-on: windows-latest + steps: + - name: configure Pagefile + uses: al-cheb/configure-pagefile-action@v1.0 + with: + minimum-size: 8 + + - name: configure Pagefile + uses: al-cheb/configure-pagefile-action@v1.0 + with: + minimum-size: 8 + maximum-size: 16 + disk-root: "D:" +``` + +# License +The scripts and documentation in this project are released under the [MIT License](LICENSE) \ No newline at end of file diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..538d7b8 --- /dev/null +++ b/action.yml @@ -0,0 +1,21 @@ +name: 'Configure Pagefile' +author: 'Aleksandr Chebotov & Maxim Lobanov' +description: 'Configure Pagefile on Windows agents in GitHub Actions' +inputs: + minimum-size: + description: 'Set minimum size of Pagefile' + required: false + default: 8GB + maximum-size: + description: 'Set maximum size of Pagefile' + required: false + disk-root: + description: 'Set disk root where pagefile.sys will be located' + required: false + default: 'D:' +runs: + using: 'node12' + main: 'dist/index.js' +branding: + icon: 'cpu' + color: 'purple' \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..80e3bb8 --- /dev/null +++ b/dist/index.js @@ -0,0 +1,454 @@ +module.exports = +/******/ (function(modules, runtime) { // webpackBootstrap +/******/ "use strict"; +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ __webpack_require__.ab = __dirname + "/"; +/******/ +/******/ // the startup function +/******/ function startup() { +/******/ // Load entry module and return exports +/******/ return __webpack_require__(465); +/******/ }; +/******/ +/******/ // run startup +/******/ return startup(); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ 87: +/***/ (function(module) { + +module.exports = require("os"); + +/***/ }), + +/***/ 129: +/***/ (function(module) { + +module.exports = require("child_process"); + +/***/ }), + +/***/ 431: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(__webpack_require__(87)); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +function escapeData(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 465: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = __importStar(__webpack_require__(622)); +const child = __importStar(__webpack_require__(129)); +const core = __importStar(__webpack_require__(470)); +const run = () => { + try { + if (process.platform !== "win32") { + throw new Error(`This task is intended only for Windows platform. It can't be run on '${process.platform}' platform`); + } + const minimumSize = core.getInput("minimum-size", { required: true }); + const maximumSize = core.getInput("maximum-size", { required: false }) || minimumSize; + const diskRoot = core.getInput("disk-root", { required: true }); + core.info("Pagefile configuration:"); + core.info(`- Minimum size: ${minimumSize}`); + core.info(`- Maximum size: ${maximumSize}`); + core.info(`- Disk root: ${diskRoot}`); + const scriptPath = path.resolve(path.join("scripts", "SetPageFileSize.ps1")); + const scriptArguments = [ + "-MinimumSize", minimumSize, + "-MaximumSize", maximumSize, + "-DiskRoot", diskRoot + ]; + core.debug("Invoke configuration script:"); + core.debug(`Script path: ${scriptPath}`); + core.debug(`Script arguments: ${scriptArguments}`); + const scriptResult = child.spawnSync("pwsh", ["-File", scriptPath, ...scriptArguments], { + timeout: 60 * 1000 + }); + if (scriptResult.stdout) { + core.info(scriptResult.stdout.toString()); + } + if (scriptResult.stderr) { + core.error(scriptResult.stderr.toString()); + } + if (scriptResult.status !== 0) { + throw new Error(`Script has finished with exit code '${scriptResult.status}'`); + } + } + catch (error) { + core.setFailed(error.message); + } +}; +run(); + + +/***/ }), + +/***/ 470: +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const command_1 = __webpack_require__(431); +const os = __importStar(__webpack_require__(87)); +const path = __importStar(__webpack_require__(622)); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = command_1.toCommandValue(val); + process.env[name] = convertedVal; + command_1.issueCommand('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + command_1.issueCommand('add-path', {}, inputPath); + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + */ +function error(message) { + command_1.issue('error', message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message. Errors will be converted to string via toString() + */ +function warning(message) { + command_1.issue('warning', message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 622: +/***/ (function(module) { + +module.exports = require("path"); + +/***/ }) + +/******/ }); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..dbf2c94 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,31 @@ +{ + "name": "configure-pagefile-action", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@actions/core": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.4.tgz", + "integrity": "sha512-YJCEq8BE3CdN8+7HPZ/4DxJjk/OkZV2FFIf+DlZTC/4iBlzYCD5yjRR6eiOS5llO11zbRltIRuKAjMKaWTE6cg==" + }, + "@types/node": { + "version": "12.12.37", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.37.tgz", + "integrity": "sha512-4mXKoDptrXAwZErQHrLzpe0FN/0Wmf5JRniSVIdwUrtDf9wnmEV1teCNLBo/TwuXhkK/bVegoEn/wmb+x0AuPg==", + "dev": true + }, + "@zeit/ncc": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@zeit/ncc/-/ncc-0.21.1.tgz", + "integrity": "sha512-M9WzgquSOt2nsjRkYM9LRylBLmmlwNCwYbm3Up3PDEshfvdmIfqpFNSK8EJvR18NwZjGHE5z2avlDtYQx2JQnw==", + "dev": true + }, + "typescript": { + "version": "3.8.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.8.3.tgz", + "integrity": "sha512-MYlEfn5VrLNsgudQTVJeNaQFUAI7DkhnOjdpAp4T+ku1TfQClewlbSuTVHiA+8skNBgaf02TL/kLOvig4y3G8w==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..ad44415 --- /dev/null +++ b/package.json @@ -0,0 +1,30 @@ +{ + "name": "configure-pagefile-action", + "version": "1.0.0", + "private": true, + "description": "Configure Pagefile on Windows agents in GitHub Actions", + "main": "lib/configure-pagefile.js", + "scripts": { + "build": "tsc && ncc build" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/al-cheb/configure-pagefile-action.git" + }, + "keywords": [ + "actions", + "pagefile", + "configure", + "windows" + ], + "author": "Aleksandr Chebotov & Maxim Lobanov", + "license": "MIT", + "dependencies": { + "@actions/core": "^1.2.3" + }, + "devDependencies": { + "@types/node": "^12.0.4", + "@zeit/ncc": "^0.21.1", + "typescript": "^3.8.3" + } +} diff --git a/scripts/SetPageFileSize.ps1 b/scripts/SetPageFileSize.ps1 new file mode 100644 index 0000000..8407efd --- /dev/null +++ b/scripts/SetPageFileSize.ps1 @@ -0,0 +1,193 @@ +<# +.SYNOPSIS + Configure Pagefile on Windows machine +.NOTES + Author: Aleksandr Chebotov +.EXAMPLE + SetPageFileSize.ps1 -MinimumSize 4GB -MaximumSize 8GB -DiskRoot "D:" +#> + +param( + [System.UInt64] $MinimumSize = 8gb , + [System.UInt64] $MaximumSize = 8gb , + [System.String] $DiskRoot = "D:" +) + +# https://referencesource.microsoft.com/#System.IdentityModel/System/IdentityModel/NativeMethods.cs,619688d876febbe1 +# https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/mm/modwrite/create.htm +# https://referencesource.microsoft.com/#mscorlib/microsoft/win32/safehandles/safefilehandle.cs,9b08210f3be75520 +# https://referencesource.microsoft.com/#mscorlib/system/security/principal/tokenaccesslevels.cs,6eda91f498a38586 +# https://www.autoitscript.com/forum/topic/117993-api-ntcreatepagingfile/ + +$source = @' +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Principal; +using System.Text; +using Microsoft.Win32; +using Microsoft.Win32.SafeHandles; + +namespace Util +{ + class NativeMethods + { + [StructLayout(LayoutKind.Sequential)] + internal struct LUID + { + internal uint LowPart; + internal uint HighPart; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct LUID_AND_ATTRIBUTES + { + internal LUID Luid; + internal uint Attributes; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct TOKEN_PRIVILEGE + { + internal uint PrivilegeCount; + internal LUID_AND_ATTRIBUTES Privilege; + + internal static readonly uint Size = (uint)Marshal.SizeOf(typeof(TOKEN_PRIVILEGE)); + } + + [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal struct UNICODE_STRING + { + internal UInt16 length; + internal UInt16 maximumLength; + internal string buffer; + } + + [DllImport("kernel32.dll", SetLastError=true)] + internal static extern IntPtr LocalFree(IntPtr handle); + + [DllImport("advapi32.dll", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)] + internal static extern bool LookupPrivilegeValueW( + [In] string lpSystemName, + [In] string lpName, + [Out] out LUID luid + ); + + [DllImport("advapi32.dll", SetLastError = true, PreserveSig = false)] + internal static extern bool AdjustTokenPrivileges( + [In] SafeCloseHandle tokenHandle, + [In] bool disableAllPrivileges, + [In] ref TOKEN_PRIVILEGE newState, + [In] uint bufferLength, + [Out] out TOKEN_PRIVILEGE previousState, + [Out] out uint returnLength + ); + + [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, PreserveSig = false)] + internal static extern bool OpenProcessToken( + [In] IntPtr processToken, + [In] int desiredAccess, + [Out] out SafeCloseHandle tokenHandle + ); + + [DllImport("ntdll.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)] + internal static extern Int32 NtCreatePagingFile( + [In] ref UNICODE_STRING pageFileName, + [In] ref Int64 minimumSize, + [In] ref Int64 maximumSize, + [In] UInt32 flags + ); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern uint QueryDosDeviceW( + string lpDeviceName, + StringBuilder lpTargetPath, + int ucchMax + ); + } + + public sealed class SafeCloseHandle: SafeHandleZeroOrMinusOneIsInvalid + { + [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] + internal extern static bool CloseHandle(IntPtr handle); + + private SafeCloseHandle() : base(true) + { + } + + public SafeCloseHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) + { + SetHandle(preexistingHandle); + } + + override protected bool ReleaseHandle() + { + return CloseHandle(handle); + } + } + + public class PageFile + { + public static void SetPageFileSize(long minimumValue, long maximumValue, string lpDeviceName) + { + SetPageFilePrivilege(); + StringBuilder lpTargetPath = new StringBuilder(260); + + UInt32 resultQueryDosDevice = NativeMethods.QueryDosDeviceW(lpDeviceName, lpTargetPath, lpTargetPath.Capacity); + if (resultQueryDosDevice == 0) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + string pageFilePath = lpTargetPath.ToString() + "\\pagefile.sys"; + + NativeMethods.UNICODE_STRING pageFileName = new NativeMethods.UNICODE_STRING + { + length = (ushort)(pageFilePath.Length * 2), + maximumLength = (ushort)(2 * (pageFilePath.Length + 1)), + buffer = pageFilePath + }; + + Int32 resultNtCreatePagingFile = NativeMethods.NtCreatePagingFile(ref pageFileName, ref minimumValue, ref maximumValue, 0); + if (resultNtCreatePagingFile != 0) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + Console.WriteLine("PageFile: {0} / {1} bytes for {2}", minimumValue, maximumValue, pageFilePath); + } + + static void SetPageFilePrivilege() + { + const int SE_PRIVILEGE_ENABLED = 0x00000002; + const int AdjustPrivileges = 0x00000020; + const int Query = 0x00000008; + + NativeMethods.LUID luid; + NativeMethods.LookupPrivilegeValueW(null, "SeCreatePagefilePrivilege", out luid); + + SafeCloseHandle hToken; + NativeMethods.OpenProcessToken( + Process.GetCurrentProcess().Handle, + AdjustPrivileges | Query, + out hToken + ); + + NativeMethods.TOKEN_PRIVILEGE previousState; + NativeMethods.TOKEN_PRIVILEGE newState; + uint previousSize = 0; + newState.PrivilegeCount = 1; + newState.Privilege.Luid = luid; + newState.Privilege.Attributes = SE_PRIVILEGE_ENABLED; + + NativeMethods.AdjustTokenPrivileges(hToken, false, ref newState, NativeMethods.TOKEN_PRIVILEGE.Size, out previousState, out previousSize); + } + } +} +'@ + +Add-Type -TypeDefinition $source + +# Set SetPageFileSize +[Util.PageFile]::SetPageFileSize($minimumSize, $maximumSize, $diskRoot) \ No newline at end of file diff --git a/src/configure-pagefile.ts b/src/configure-pagefile.ts new file mode 100644 index 0000000..0e69350 --- /dev/null +++ b/src/configure-pagefile.ts @@ -0,0 +1,41 @@ +import * as path from "path"; +import * as child from "child_process"; +import * as core from "@actions/core"; + +const run = (): void => { + try { + if (process.platform !== "win32") { + throw new Error(`This task is intended only for Windows platform. It can't be run on '${process.platform}' platform`); + } + + const minimumSize = core.getInput("minimum-size", { required: true }); + const maximumSize = core.getInput("maximum-size", { required: false }) || minimumSize; + const diskRoot = core.getInput("disk-root", { required: true }); + + core.info("Pagefile configuration:"); + core.info(`- Minimum size: ${minimumSize}`); + core.info(`- Maximum size: ${maximumSize}`); + core.info(`- Disk root: ${diskRoot}`); + + const scriptPath = path.resolve(path.join("scripts", "SetPageFileSize.ps1")); + const scriptArguments = [ + "-MinimumSize", minimumSize, + "-MaximumSize", maximumSize, + "-DiskRoot", diskRoot + ]; + core.debug("Invoke configuration script:"); + core.debug(`Script path: ${scriptPath}`); + core.debug(`Script arguments: ${scriptArguments}`); + + const scriptResult = child.spawnSync("pwsh", ["-File", scriptPath, ...scriptArguments], { + timeout: 60 * 1000 + }); + if (scriptResult.stdout) { core.info(scriptResult.stdout.toString()); } + if (scriptResult.stderr) { core.error(scriptResult.stderr.toString()); } + if (scriptResult.status !== 0) { throw new Error(`Script has finished with exit code '${scriptResult.status}'`) } + } catch (error) { + core.setFailed(error.message); + } +}; + +run(); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..f37f328 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2019", + "module": "commonjs", + "outDir": "./lib", + "rootDir": "./src", + "esModuleInterop": true, + + /* Strict Type-Checking Options */ + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + + /* Additional Checks */ + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true + }, + "include": ["./src/**/*.ts"], + "exclude": ["node_modules"] + } \ No newline at end of file