forked from bazel-contrib/setup-bazel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stickydisk.js
211 lines (191 loc) · 8.22 KB
/
stickydisk.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
const core = require('@actions/core');
const { promisify } = require('util');
const { exec } = require('child_process');
const { createStickyDiskClient } = require('./util');
const execAsync = promisify(exec);
/**
* Gets a sticky disk from the service
* @param {string} stickyDiskKey - Key to identify the sticky disk
* @param {Object} options - Optional parameters
* @param {AbortSignal} [options.signal] - AbortSignal for cancellation
* @returns {Promise<{expose_id: string, device: string}>}
*/
async function getStickyDisk(stickyDiskKey, options = {}) {
const client = createStickyDiskClient();
core.debug(`Getting sticky disk for ${stickyDiskKey}`);
const response = await client.getStickyDisk({
stickyDiskKey: stickyDiskKey,
region: process.env.BLACKSMITH_REGION || 'eu-central',
installationModelId: process.env.BLACKSMITH_INSTALLATION_MODEL_ID || '',
vmId: process.env.VM_ID || '',
stickyDiskType: 'stickydisk',
stickyDiskToken: process.env.BLACKSMITH_STICKYDISK_TOKEN,
repoName: process.env.GITHUB_REPO_NAME || ''
}, {
signal: options?.signal,
});
return {
expose_id: response.exposeId,
device: response.diskIdentifier
};
}
/**
* Formats a block device with ext4 if needed
* @param {string} device - Path to the block device
* @returns {Promise<string>} - Returns the device path
*/
async function maybeFormatBlockDevice(device) {
try {
// Check if device is formatted with ext4
try {
// Need sudo for blkid as it requires root to read block device metadata
const { stdout } = await execAsync(`sudo blkid -o value -s TYPE ${device}`);
if (stdout.trim() === 'ext4') {
core.debug(`Device ${device} is already formatted with ext4`);
try {
// Need sudo for resize2fs as it requires root to modify block device
// This operation preserves existing filesystem ownership and permissions
await execAsync(`sudo resize2fs -f ${device}`);
core.debug(`Resized ext4 filesystem on ${device}`);
} catch (error) {
core.warning(`Error resizing ext4 filesystem on ${device}: ${error}`);
}
return device;
}
} catch {
// blkid returns non-zero if no filesystem found, which is fine
core.debug(`No filesystem found on ${device}, will format it`);
}
// Format device with ext4, setting default ownership to current user
core.debug(`Formatting device ${device} with ext4`);
// Need sudo for mkfs.ext4 as it requires root to format block device
// -m0: Disable reserved blocks (all space available to non-root users)
// root_owner=$(id -u):$(id -g): Sets filesystem root directory owner to current (runner) user
// This ensures the filesystem is owned by runner user from the start
await execAsync(`sudo mkfs.ext4 -m0 -E root_owner=$(id -u):$(id -g) -Enodiscard,lazy_itable_init=1,lazy_journal_init=1 -F ${device}`);
core.debug(`Successfully formatted ${device} with ext4`);
return device;
} catch (error) {
core.error(`Failed to format device ${device}: ${error}`);
throw error;
}
}
/**
* Mounts a sticky disk at the specified path
* @param {string} stickyDiskKey - Key to identify the sticky disk
* @param {string} stickyDiskPath - Path where the disk should be mounted
* @param {AbortSignal} signal - Signal for operation cancellation
* @param {AbortController} controller - Controller for timeout management
* @returns {Promise<{device: string, exposeId: string}>}
*/
async function mountStickyDisk(stickyDiskKey, stickyDiskPath, signal, controller) {
const timeoutId = setTimeout(() => controller.abort(), 15000);
const stickyDiskResponse = await getStickyDisk(stickyDiskKey, { signal });
const device = stickyDiskResponse.device;
const exposeId = stickyDiskResponse.expose_id;
clearTimeout(timeoutId);
await maybeFormatBlockDevice(device);
// Create mount point WITHOUT sudo so the directory is owned by runner user
// This is important because the mount point ownership affects access when nothing is mounted.
await execAsync(`mkdir -p ${stickyDiskPath}`);
// Mount the device with default options
await execAsync(`sudo mount ${device} ${stickyDiskPath}`);
// After mounting, set the ownership of the mount point
await execAsync(`sudo chown $(id -u):$(id -g) ${stickyDiskPath}`);
core.debug(`${device} has been mounted to ${stickyDiskPath} with expose ID ${exposeId}`);
return { device, exposeId };
}
async function commitStickydisk(exposeId, stickyDiskKey) {
core.info(`Committing sticky disk ${stickyDiskKey} with expose ID ${exposeId}`);
if (!exposeId || !stickyDiskKey) {
core.warning('No expose ID or sticky disk key found, cannot report sticky disk to Blacksmith');
return;
}
try {
const client = createStickyDiskClient();
await client.commitStickyDisk({
exposeId,
stickyDiskKey,
vmId: process.env.VM_ID || '',
shouldCommit: true,
repoName: process.env.GITHUB_REPO_NAME || '',
stickyDiskToken: process.env.BLACKSMITH_STICKYDISK_TOKEN || ''
}, {
timeoutMs: 30000
});
core.info(`Successfully committed sticky disk ${stickyDiskKey} with expose ID ${exposeId}`);
} catch (error) {
core.warning(`Error committing sticky disk: ${error instanceof Error ? error.message : String(error)}`);
}
}
async function cleanupStickyDiskWithoutCommit(exposeId, stickyDiskKey) {
core.info(`Cleaning up sticky disk ${stickyDiskKey} with expose ID ${exposeId}`);
if (!exposeId || !stickyDiskKey) {
core.warning('No expose ID or sticky disk key found, cannot report sticky disk to Blacksmith');
return;
}
try {
const client = createStickyDiskClient();
await client.commitStickyDisk({
exposeId,
stickyDiskKey,
vmId: process.env.VM_ID || '',
shouldCommit: false,
repoName: process.env.GITHUB_REPO_NAME || '',
stickyDiskToken: process.env.BLACKSMITH_STICKYDISK_TOKEN || ''
}, {
timeoutMs: 30000
});
} catch (error) {
core.warning(`Error reporting build failed: ${error instanceof Error ? error.message : String(error)}`);
// We don't want to fail the build if this fails so we swallow the error.
}
}
async function unmountAndCommitStickyDisk(path, { device, exposeId }, stickyDiskKey) {
try {
// Check if path is mounted
try {
const { stdout: mountOutput } = await execAsync(`mount | grep ${path}`);
if (!mountOutput) {
core.debug(`${path} is not mounted, skipping unmount`);
return;
}
} catch {
// grep returns non-zero if no match found
core.debug(`${path} is not mounted, skipping unmount`);
return;
}
// First try to unmount with retries
for (let attempt = 1; attempt <= 10; attempt++) {
try {
await execAsync(`sudo umount ${path}`);
core.info(`Successfully unmounted ${path}`);
break;
} catch (error) {
if (attempt === 10) {
throw error;
}
core.warning(`Unmount failed, retrying (${attempt}/10)...`);
await new Promise(resolve => setTimeout(resolve, 300));
}
}
const actionFailed = core.getState('action-failed') === 'true';
if (!actionFailed) {
await commitStickydisk(exposeId, stickyDiskKey);
} else {
await cleanupStickyDiskWithoutCommit(exposeId, stickyDiskKey);
}
} catch (error) {
if (error instanceof Error) {
core.error(`Failed to cleanup and commit sticky disk at ${path}: ${error}`);
}
}
}
module.exports = {
getStickyDisk,
maybeFormatBlockDevice,
mountStickyDisk,
unmountAndCommitStickyDisk,
commitStickydisk,
cleanupStickyDiskWithoutCommit
};