-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathwordpress-server-manager.ts
More file actions
523 lines (451 loc) · 14.4 KB
/
wordpress-server-manager.ts
File metadata and controls
523 lines (451 loc) · 14.4 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/**
* WordPress Server Manager for Studio CLI
*
* Manages WordPress server processes via process manager daemon. Each site runs in a separate
* process that spawns Playground CLI.
*/
import path from 'path';
import {
PLAYGROUND_CLI_ACTIVITY_CHECK_INTERVAL,
PLAYGROUND_CLI_INACTIVITY_TIMEOUT,
PLAYGROUND_CLI_MAX_TIMEOUT,
} from '@studio/common/constants';
import { z } from 'zod';
import { SiteData } from 'cli/lib/cli-config/core';
import {
isProcessRunning,
startProcess,
stopProcess,
getDaemonBus,
type DaemonBusEventMap,
sendMessageToProcess,
} from 'cli/lib/daemon-client';
import { ProcessDescription } from 'cli/lib/types/process-manager-ipc';
import { ServerConfig, ManagerMessagePayload } from 'cli/lib/types/wordpress-server-ipc';
import { Logger } from 'cli/logger';
export const SITE_PROCESS_PREFIX = 'studio-site-';
// Get an abort signal that's triggered on SIGINT/SIGTERM. This is useful for aborting and cleaning
// up async operations.
const abortController = new AbortController();
process.on( 'SIGINT', () => abortController.abort() );
process.on( 'SIGTERM', () => abortController.abort() );
export function getProcessName( siteId: string ): string {
return `${ SITE_PROCESS_PREFIX }${ siteId }`;
}
export async function isServerRunning( siteId: string ): Promise< ProcessDescription | undefined > {
const processName = getProcessName( siteId );
return isProcessRunning( processName );
}
/**
* Start a WordPress server for a site via process manager daemon
* 1. Start the process (via the process manager daemon)
* 2. Wait for 'ready' message
* 3. Send 'start-server' message with config
* 4. Wait for response before resolving
*/
export interface StartServerOptions {
wpVersion?: string;
blueprint?: unknown;
blueprintUri?: string;
}
export async function startWordPressServer(
site: SiteData,
logger: Logger< string >,
options?: StartServerOptions
): Promise< ProcessDescription > {
const wordPressServerChildPath = path.resolve(
import.meta.dirname,
'wordpress-server-child.mjs'
);
const processName = getProcessName( site.id );
const serverConfig: ServerConfig = {
siteId: site.id,
sitePath: site.path,
port: site.port,
phpVersion: site.phpVersion,
siteTitle: site.name,
};
if ( site.customDomain ) {
const protocol = site.enableHttps ? 'https' : 'http';
serverConfig.absoluteUrl = `${ protocol }://${ site.customDomain }`;
}
if ( site.adminUsername ) {
serverConfig.adminUsername = site.adminUsername;
}
if ( site.adminPassword ) {
serverConfig.adminPassword = site.adminPassword;
}
if ( site.adminEmail ) {
serverConfig.adminEmail = site.adminEmail;
}
if ( site.isWpAutoUpdating !== undefined ) {
serverConfig.isWpAutoUpdating = site.isWpAutoUpdating;
}
if ( options?.wpVersion ) {
serverConfig.wpVersion = options.wpVersion;
}
if ( options?.blueprint && options.blueprintUri ) {
serverConfig.blueprint = {
contents: options.blueprint,
uri: options.blueprintUri,
};
}
if ( site.enableXdebug ) {
serverConfig.enableXdebug = true;
}
if ( site.enableDebugLog ) {
serverConfig.enableDebugLog = true;
}
if ( site.enableDebugDisplay ) {
serverConfig.enableDebugDisplay = true;
}
const readyOrExit = await subscribeForReadyOrExit( processName );
try {
const processDesc = await startProcess( processName, wordPressServerChildPath );
await readyOrExit.waitFor( processDesc.pmId );
await sendMessage(
processDesc.pmId,
processName,
{
topic: 'start-server',
data: { config: serverConfig },
},
{ logger }
);
return processDesc;
} finally {
readyOrExit.dispose();
}
}
function buildChildExitedError( processName: string, stderrTail?: string ): Error {
let message = `WordPress server child process "${ processName }" exited before becoming ready.`;
if ( stderrTail?.trim() ) {
message += `\n${ stderrTail.trimEnd() }`;
}
return new Error( message );
}
/**
* Attaches listeners to the daemon bus *before* the child process is started so we cannot miss
* an early `ready` or `exit` event. Events that arrive before the caller knows the pmId are
* buffered (filtered by processName) and replayed once `waitFor(pmId)` is called.
* Must be disposed via `dispose()` when done.
*/
async function subscribeForReadyOrExit( processName: string ): Promise< {
waitFor: ( pmId: number ) => Promise< void >;
dispose: () => void;
} > {
const bus = await getDaemonBus();
const pendingReady: Array< DaemonBusEventMap[ 'process-message' ] > = [];
const pendingExits: Array< DaemonBusEventMap[ 'process-event' ] > = [];
let onReady: () => void = () => {};
let onExit: ( stderrTail?: string ) => void = () => {};
let waiting = false;
const messageHandler = ( packet: DaemonBusEventMap[ 'process-message' ] ) => {
if ( packet.process.name !== processName || packet.raw.topic !== 'ready' ) {
return;
}
if ( waiting ) {
onReady();
} else {
pendingReady.push( packet );
}
};
const eventHandler = ( event: DaemonBusEventMap[ 'process-event' ] ) => {
if ( event.process.name !== processName || event.event !== 'exit' ) {
return;
}
if ( waiting ) {
onExit( event.stderrTail );
} else {
pendingExits.push( event );
}
};
bus.on( 'process-message', messageHandler );
bus.on( 'process-event', eventHandler );
const waitFor = ( pmId: number ): Promise< void > => {
waiting = true;
let timeoutId: NodeJS.Timeout;
let abortListener: () => void;
return new Promise< void >( ( resolve, reject ) => {
timeoutId = setTimeout( () => {
reject( new Error( 'Timeout waiting for ready message from WordPress server child' ) );
}, PLAYGROUND_CLI_INACTIVITY_TIMEOUT );
abortListener = () => {
reject( new Error( 'Operation aborted' ) );
};
onReady = () => resolve();
onExit = ( stderrTail ) => reject( buildChildExitedError( processName, stderrTail ) );
abortController.signal.addEventListener( 'abort', abortListener );
// Replay any events we buffered before pmId was known.
const bufferedExit = pendingExits.find( ( event ) => event.process.pm_id === pmId );
if ( bufferedExit ) {
onExit( bufferedExit.stderrTail );
return;
}
const bufferedReady = pendingReady.find( ( packet ) => packet.process.pm_id === pmId );
if ( bufferedReady ) {
onReady();
}
} ).finally( () => {
clearTimeout( timeoutId );
abortController.signal.removeEventListener( 'abort', abortListener );
// Release per-call handlers; the bus listeners stay until dispose().
onReady = () => {};
onExit = () => {};
waiting = false;
} );
};
const dispose = () => {
bus.off( 'process-message', messageHandler );
bus.off( 'process-event', eventHandler );
};
return { waitFor, dispose };
}
const messageActivityTrackers = new Map<
string,
{
activityCheckIntervalId: NodeJS.Timeout;
}
>();
export interface SendMessageOptions {
maxTotalElapsedTime?: number;
logger?: Logger< string >;
}
/**
* Send message to process (via the process manager daemon) and wait for response with
* activity-based timeout.
* - Tracks last activity timestamp
* - Checks periodically for inactivity
* - Has both inactivity timeout and max total timeout
*/
export async function sendMessage(
pmId: number,
processName: string,
message: ManagerMessagePayload,
options: SendMessageOptions = {}
): Promise< unknown > {
const { maxTotalElapsedTime = PLAYGROUND_CLI_MAX_TIMEOUT, logger } = options;
const bus = await getDaemonBus();
const messageId = crypto.randomUUID();
let responseHandler: ( packet: DaemonBusEventMap[ 'process-message' ] ) => void;
let processEventHandler: ( event: DaemonBusEventMap[ 'process-event' ] ) => void;
let abortListener: () => void;
return new Promise( ( resolve, reject ) => {
const startTime = Date.now();
let lastActivityTimestamp = Date.now();
const activityCheckIntervalId = setInterval( () => {
const now = Date.now();
const timeSinceLastActivity = now - lastActivityTimestamp;
const totalElapsedTime = now - startTime;
if (
timeSinceLastActivity > PLAYGROUND_CLI_INACTIVITY_TIMEOUT ||
totalElapsedTime > maxTotalElapsedTime
) {
const timeoutReason =
totalElapsedTime > maxTotalElapsedTime
? `Maximum timeout of ${ maxTotalElapsedTime / 1000 }s exceeded`
: `No activity for ${ PLAYGROUND_CLI_INACTIVITY_TIMEOUT / 1000 }s`;
reject(
new Error(
`Timeout waiting for response to message ${ message.topic }: ${ timeoutReason }`
)
);
}
}, PLAYGROUND_CLI_ACTIVITY_CHECK_INTERVAL );
messageActivityTrackers.set( messageId, {
activityCheckIntervalId,
} );
processEventHandler = ( event ) => {
if ( event.process.name === processName && event.event === 'exit' ) {
reject( new Error( 'WordPress server process exited unexpectedly' ) );
}
};
responseHandler = ( packet ) => {
if ( packet.process.pm_id !== pmId ) {
return;
}
if ( packet.raw.topic === 'activity' ) {
lastActivityTimestamp = Date.now();
} else if ( packet.raw.topic === 'console-message' ) {
lastActivityTimestamp = Date.now();
logger?.reportProgress( packet.raw.message );
} else if ( packet.raw.topic === 'error' && packet.raw.originalMessageId === messageId ) {
const error = new Error( packet.raw.errorMessage ) as Error & {
cliArgs?: Record< string, unknown >;
};
if ( packet.raw.errorStack ) {
error.stack = packet.raw.errorStack;
}
if ( packet.raw.cliArgs ) {
error.cliArgs = packet.raw.cliArgs;
}
reject( error );
} else if ( packet.raw.topic === 'result' && packet.raw.originalMessageId === messageId ) {
resolve( packet.raw.result );
}
};
abortListener = () => {
void sendMessageToProcess( pmId, { messageId, topic: 'abort', data: {} } );
reject( new Error( 'Operation aborted' ) );
};
abortController.signal.addEventListener( 'abort', abortListener );
bus.on( 'process-event', processEventHandler );
bus.on( 'process-message', responseHandler );
sendMessageToProcess( pmId, { ...message, messageId } ).catch( reject );
} ).finally( () => {
abortController.signal.removeEventListener( 'abort', abortListener );
bus.off( 'process-event', processEventHandler );
bus.off( 'process-message', responseHandler );
const tracker = messageActivityTrackers.get( messageId );
if ( tracker ) {
clearInterval( tracker.activityCheckIntervalId );
messageActivityTrackers.delete( messageId );
}
} );
}
const GRACEFUL_STOP_TIMEOUT = 5000;
export async function stopWordPressServer( siteId: string ): Promise< void > {
const processName = getProcessName( siteId );
const runningProcess = await isProcessRunning( processName );
if ( ! runningProcess ) {
return;
}
try {
const bus = await getDaemonBus();
let busExitEventListener: ( event: DaemonBusEventMap[ 'process-event' ] ) => void;
const exitPromise = new Promise< void >( ( resolve ) => {
busExitEventListener = ( event: DaemonBusEventMap[ 'process-event' ] ) => {
if ( event.process.name === processName && event.event === 'exit' ) {
resolve();
}
};
bus.on( 'process-event', busExitEventListener );
} ).finally( () => {
bus.off( 'process-event', busExitEventListener );
} );
await sendMessage(
runningProcess.pmId,
processName,
{ topic: 'stop-server', data: {} },
{ maxTotalElapsedTime: GRACEFUL_STOP_TIMEOUT }
);
// Allow 5 seconds (arbitrary number) of cleanup time for the child process before throwing an
// exception and telling the process manager to send a SIGKILL signal.
await Promise.race( [
exitPromise,
new Promise( ( resolve, reject ) => setTimeout( reject, 5000 ) ),
] );
} catch {
return stopProcess( processName );
}
}
export interface RunBlueprintOptions {
wpVersion?: string;
blueprint: unknown;
blueprintUri: string;
}
/**
* Run a blueprint on a site without starting a server
* 1. Start the process (via the process manager daemon)
* 2. Wait for 'ready' message
* 3. Send 'run-blueprint' message with config
* 4. Wait for completion
* 5. Stop the process
*/
export async function runBlueprint(
site: SiteData,
logger: Logger< string >,
options: RunBlueprintOptions
): Promise< void > {
const wordPressServerChildPath = path.resolve(
import.meta.dirname,
'wordpress-server-child.mjs'
);
const processName = getProcessName( site.id );
const serverConfig: ServerConfig = {
siteId: site.id,
sitePath: site.path,
port: site.port,
phpVersion: site.phpVersion,
siteTitle: site.name,
blueprint: {
contents: options.blueprint,
uri: options.blueprintUri,
},
};
if ( site.customDomain ) {
const protocol = site.enableHttps ? 'https' : 'http';
serverConfig.absoluteUrl = `${ protocol }://${ site.customDomain }`;
}
if ( site.adminUsername ) {
serverConfig.adminUsername = site.adminUsername;
}
if ( site.adminPassword ) {
serverConfig.adminPassword = site.adminPassword;
}
if ( site.adminEmail ) {
serverConfig.adminEmail = site.adminEmail;
}
if ( site.isWpAutoUpdating !== undefined ) {
serverConfig.isWpAutoUpdating = site.isWpAutoUpdating;
}
if ( options.wpVersion ) {
serverConfig.wpVersion = options.wpVersion;
}
if ( site.enableXdebug ) {
serverConfig.enableXdebug = true;
}
if ( site.enableDebugLog ) {
serverConfig.enableDebugLog = true;
}
if ( site.enableDebugDisplay ) {
serverConfig.enableDebugDisplay = true;
}
const readyOrExit = await subscribeForReadyOrExit( processName );
try {
const processDesc = await startProcess( processName, wordPressServerChildPath );
try {
await readyOrExit.waitFor( processDesc.pmId );
await sendMessage(
processDesc.pmId,
processName,
{
topic: 'run-blueprint',
data: { config: serverConfig },
},
{ logger }
);
} finally {
// Always stop the process after blueprint is applied
await stopProcess( processName );
}
} finally {
readyOrExit.dispose();
}
}
const wpCliResultSchema = z.object( {
stdout: z.string(),
stderr: z.string(),
exitCode: z.number(),
} );
export async function sendWpCliCommand(
siteId: string,
args: string[],
stdin?: Buffer
): Promise< z.infer< typeof wpCliResultSchema > > {
const processName = getProcessName( siteId );
const runningProcess = await isProcessRunning( processName );
if ( ! runningProcess ) {
throw new Error( `WordPress server is not running` );
}
const result = await sendMessage( runningProcess.pmId, processName, {
topic: 'wp-cli-command',
data: {
args,
...( stdin && stdin.length > 0
? { stdinBase64: stdin.toString( 'base64' ) }
: {} ),
},
} );
return wpCliResultSchema.parse( result );
}