-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBoltService.ts
More file actions
1651 lines (1478 loc) · 48.3 KB
/
BoltService.ts
File metadata and controls
1651 lines (1478 loc) · 48.3 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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn, type ChildProcess } from "child_process";
import {
type BoltExecutionResult,
type BoltExecutionOptions,
type BoltJsonOutput,
type Node,
type Facts,
type ExecutionResult,
type NodeResult,
type Task,
type TaskParameter,
BoltExecutionError,
BoltTimeoutError,
BoltParseError,
BoltInventoryNotFoundError,
BoltNodeUnreachableError,
BoltTaskNotFoundError,
BoltTaskParameterError,
} from "./types";
/**
* Streaming callback for real-time output
*/
export interface StreamingCallback {
onStdout?: (chunk: string) => void;
onStderr?: (chunk: string) => void;
onCommand?: (command: string) => void;
}
/**
* Cache entry with timestamp for TTL tracking
*/
interface CacheEntry<T> {
data: T;
timestamp: number;
}
/**
* Service for executing Bolt CLI commands with timeout handling,
* JSON output parsing, and error capture
*/
export class BoltService {
private readonly defaultTimeout: number;
private readonly boltProjectPath: string;
private taskListCache: Task[] | null = null;
// Cache configuration
private readonly inventoryTtl: number;
private readonly factsTtl: number;
// Cache storage
private inventoryCache: CacheEntry<Node[]> | null = null;
private factsCache = new Map<string, CacheEntry<Facts>>();
constructor(
boltProjectPath: string,
defaultTimeout = 300000,
cacheConfig?: { inventoryTtl?: number; factsTtl?: number },
) {
this.boltProjectPath = boltProjectPath;
this.defaultTimeout = defaultTimeout;
this.inventoryTtl = cacheConfig?.inventoryTtl ?? 30000; // 30 seconds default
this.factsTtl = cacheConfig?.factsTtl ?? 300000; // 5 minutes default
}
/**
* Build a Bolt CLI command string from arguments
*
* @param args - Command line arguments for Bolt CLI
* @returns Full command string
*/
private buildCommandString(args: string[]): string {
// Escape arguments that contain spaces or special characters
const escapedArgs = args.map((arg) => {
if (arg.includes(" ") || arg.includes('"') || arg.includes("'")) {
// Escape double quotes and wrap in double quotes
return `"${arg.replace(/"/g, '\\"')}"`;
}
return arg;
});
return `bolt ${escapedArgs.join(" ")}`;
}
/**
* Execute a Bolt CLI command with timeout handling and optional streaming
*
* @param args - Command line arguments for Bolt CLI
* @param options - Execution options including timeout and working directory
* @param streamingCallback - Optional callback for real-time output streaming
* @returns Promise resolving to execution result
* @throws BoltTimeoutError if execution exceeds timeout
* @throws BoltExecutionError if Bolt returns non-zero exit code
*/
public async executeCommand(
args: string[],
options: BoltExecutionOptions = {},
streamingCallback?: StreamingCallback,
): Promise<BoltExecutionResult> {
const timeout = options.timeout ?? this.defaultTimeout;
const cwd = options.cwd ?? this.boltProjectPath;
// Emit command string if callback provided
if (streamingCallback?.onCommand) {
const commandString = this.buildCommandString(args);
streamingCallback.onCommand(commandString);
}
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
let timedOut = false;
let childProcess: ChildProcess | null = null;
// Set up timeout
const timeoutId = setTimeout(() => {
timedOut = true;
if (childProcess) {
childProcess.kill("SIGTERM");
// Force kill after 5 seconds if SIGTERM doesn't work
setTimeout(() => {
if (childProcess && !childProcess.killed) {
childProcess.kill("SIGKILL");
}
}, 5000);
}
}, timeout);
try {
// Spawn Bolt process
childProcess = spawn("bolt", args, {
cwd,
env: process.env,
shell: false,
});
// Capture stdout with streaming support
if (childProcess.stdout) {
childProcess.stdout.on("data", (data: Buffer) => {
const chunk = data.toString();
stdout += chunk;
// Stream stdout chunk if callback provided
if (streamingCallback?.onStdout) {
streamingCallback.onStdout(chunk);
}
});
}
// Capture stderr with streaming support
if (childProcess.stderr) {
childProcess.stderr.on("data", (data: Buffer) => {
const chunk = data.toString();
stderr += chunk;
// Stream stderr chunk if callback provided
if (streamingCallback?.onStderr) {
streamingCallback.onStderr(chunk);
}
});
}
// Handle process completion
childProcess.on("close", (exitCode: number | null) => {
clearTimeout(timeoutId);
if (timedOut) {
reject(
new BoltTimeoutError(
`Bolt command execution exceeded timeout of ${String(timeout)}ms`,
timeout,
),
);
return;
}
const result: BoltExecutionResult = {
success: exitCode === 0,
stdout: stdout.trim(),
stderr: stderr.trim(),
exitCode,
};
if (exitCode !== 0) {
result.error =
stderr.trim() !== ""
? stderr.trim()
: `Bolt command failed with exit code ${String(exitCode)}`;
}
resolve(result);
});
// Handle process errors
childProcess.on("error", (error: Error) => {
clearTimeout(timeoutId);
reject(
new BoltExecutionError(
`Failed to execute Bolt command: ${error.message}`,
null,
stderr.trim(),
stdout.trim(),
),
);
});
} catch (error) {
clearTimeout(timeoutId);
reject(error instanceof Error ? error : new Error(String(error)));
}
});
}
/**
* Execute a Bolt CLI command and parse JSON output
*
* @param args - Command line arguments for Bolt CLI (should include --format json)
* @param options - Execution options
* @param streamingCallback - Optional callback for real-time output streaming
* @returns Promise resolving to parsed JSON output
* @throws BoltParseError if JSON parsing fails
* @throws BoltExecutionError if Bolt returns non-zero exit code
* @throws BoltTimeoutError if execution exceeds timeout
*/
public async executeCommandWithJsonOutput(
args: string[],
options: BoltExecutionOptions = {},
streamingCallback?: StreamingCallback,
): Promise<BoltJsonOutput> {
// Ensure --format json is included in args
const argsToUse =
!args.includes("--format") && !args.includes("json")
? [...args, "--format", "json"]
: args;
const result = await this.executeCommand(
argsToUse,
options,
streamingCallback,
);
if (!result.success) {
throw new BoltExecutionError(
result.error ?? "Bolt command failed",
result.exitCode,
result.stderr,
result.stdout,
);
}
return this.parseJsonOutput(result.stdout);
}
/**
* Parse JSON output from Bolt CLI
*
* @param output - Raw stdout from Bolt CLI
* @returns Parsed JSON object
* @throws BoltParseError if parsing fails
*/
public parseJsonOutput(output: string): BoltJsonOutput {
if (!output || output.trim().length === 0) {
throw new BoltParseError(
"Bolt command returned empty output",
output,
new Error("Empty output"),
);
}
try {
return JSON.parse(output) as BoltJsonOutput;
} catch (error) {
throw new BoltParseError(
"Failed to parse Bolt JSON output",
output,
error instanceof Error ? error : new Error(String(error)),
);
}
}
/**
* Get the Bolt project path
*/
public getBoltProjectPath(): string {
return this.boltProjectPath;
}
/**
* Get the default timeout
*/
public getDefaultTimeout(): number {
return this.defaultTimeout;
}
/**
* Check if a cache entry is still valid based on TTL
*
* @param entry - Cache entry to check
* @param ttl - Time-to-live in milliseconds
* @returns true if cache entry is still valid, false otherwise
*/
private isCacheValid<T>(entry: CacheEntry<T> | null, ttl: number): boolean {
if (!entry) {
return false;
}
const now = Date.now();
return now - entry.timestamp < ttl;
}
/**
* Invalidate the inventory cache
*/
public invalidateInventoryCache(): void {
this.inventoryCache = null;
}
/**
* Invalidate facts cache for a specific node or all nodes
*
* @param nodeId - Optional node ID to invalidate. If not provided, clears all facts cache
*/
public invalidateFactsCache(nodeId?: string): void {
if (nodeId) {
this.factsCache.delete(nodeId);
} else {
this.factsCache.clear();
}
}
/**
* Invalidate all caches
*/
public invalidateAllCaches(): void {
this.invalidateInventoryCache();
this.invalidateFactsCache();
this.taskListCache = null;
}
/**
* Retrieve inventory from Bolt
*
* Executes `bolt inventory show --format json` and transforms the output
* into an array of Node objects. Results are cached based on inventoryTtl.
*
* @returns Promise resolving to array of nodes
* @throws BoltInventoryNotFoundError if inventory file is not found
* @throws BoltExecutionError if Bolt command fails
* @throws BoltParseError if JSON parsing fails
*/
public async getInventory(): Promise<Node[]> {
// Check cache first
if (this.isCacheValid(this.inventoryCache, this.inventoryTtl)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.inventoryCache!.data;
}
try {
const jsonOutput = await this.executeCommandWithJsonOutput([
"inventory",
"show",
"--format",
"json",
"--detail",
]);
const nodes = this.transformInventoryToNodes(jsonOutput);
// Update cache
this.inventoryCache = {
data: nodes,
timestamp: Date.now(),
};
return nodes;
} catch (error) {
// Check if error is due to missing inventory file
if (error instanceof BoltExecutionError && error.stderr) {
const errorMessage = error.stderr.toLowerCase();
if (
errorMessage.includes("inventory file") ||
errorMessage.includes("could not find") ||
errorMessage.includes("no such file")
) {
throw new BoltInventoryNotFoundError(
"Bolt inventory file not found. Ensure inventory.yaml exists in the Bolt project directory.",
);
}
}
throw error;
}
}
/**
* Transform Bolt inventory JSON output to Node array
*
* @param jsonOutput - Raw JSON output from Bolt inventory command
* @returns Array of Node objects
*/
private transformInventoryToNodes(jsonOutput: BoltJsonOutput): Node[] {
const nodes: Node[] = [];
// Bolt inventory output with --detail flag has structure:
// { "inventory": { "targets": [...] }, "targets": [...] }
// We use inventory.targets for detailed information
// Check for inventory.targets (detailed format)
if (jsonOutput.inventory && Array.isArray(jsonOutput.inventory.targets)) {
for (const target of jsonOutput.inventory.targets) {
const node = this.parseInventoryTarget(target);
if (node) {
nodes.push(node);
}
}
return nodes;
}
// Fallback: Handle root targets array format
const targets = jsonOutput.targets;
if (Array.isArray(targets)) {
for (const target of targets) {
const node = this.parseInventoryTarget(target);
if (node) {
nodes.push(node);
}
}
return nodes;
}
// Fallback: Handle flat object format where keys are node names
for (const [nodeName, nodeData] of Object.entries(jsonOutput)) {
if (typeof nodeData === "object" && nodeData !== null) {
const node = this.parseInventoryTarget({ name: nodeName, ...nodeData });
if (node) {
nodes.push(node);
}
}
}
return nodes;
}
/**
* Parse a single inventory target into a Node object
*
* @param target - Raw target data from Bolt inventory
* @returns Node object or null if parsing fails
*/
private parseInventoryTarget(target: unknown): Node | null {
if (typeof target !== "object" || target === null) {
return null;
}
const targetObj = target as Record<string, unknown>;
// Extract node name
const name = typeof targetObj.name === "string" ? targetObj.name : null;
if (!name) {
return null;
}
// Extract URI
const uri = typeof targetObj.uri === "string" ? targetObj.uri : name;
// Extract transport (default to 'ssh' if not specified)
let transport: "ssh" | "winrm" | "docker" | "local" = "ssh";
if (typeof targetObj.transport === "string") {
const transportValue = targetObj.transport.toLowerCase();
if (
transportValue === "ssh" ||
transportValue === "winrm" ||
transportValue === "docker" ||
transportValue === "local"
) {
transport = transportValue;
}
}
// Extract config
const config: Node["config"] = {};
if (typeof targetObj.config === "object" && targetObj.config !== null) {
const configObj = targetObj.config as Record<string, unknown>;
Object.assign(config, configObj);
}
// Extract common config fields from top level if not in config object
if (typeof targetObj.user === "string" && config.user === undefined) {
config.user = targetObj.user;
}
if (typeof targetObj.port === "number" && config.port === undefined) {
config.port = targetObj.port;
}
// Generate ID from name (use name as-is for ID)
const id = name;
return {
id,
name,
uri,
transport,
config,
};
}
/**
* Gather facts from a target node
*
* Executes `bolt task run facts --targets <node> --format json` and
* structures the output as a Facts object. Results are cached per node based on factsTtl.
*
* @param nodeId - The ID/name of the target node
* @returns Promise resolving to Facts object
* @throws BoltNodeUnreachableError if the node is unreachable
* @throws BoltExecutionError if Bolt command fails
* @throws BoltParseError if JSON parsing fails
*/
public async gatherFacts(nodeId: string): Promise<Facts> {
// Check cache first
const cachedFacts = this.factsCache.get(nodeId);
if (this.isCacheValid(cachedFacts ?? null, this.factsTtl)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return cachedFacts!.data;
}
const args = [
"task",
"run",
"facts",
"--targets",
nodeId,
"--format",
"json",
];
const command = this.buildCommandString(args);
try {
const jsonOutput = await this.executeCommandWithJsonOutput(args);
const facts = this.transformFactsOutput(nodeId, jsonOutput);
facts.command = command;
// Update cache
this.factsCache.set(nodeId, {
data: facts,
timestamp: Date.now(),
});
return facts;
} catch (error) {
// Check if error is due to node being unreachable
if (error instanceof BoltExecutionError && error.stderr) {
const errorMessage = error.stderr.toLowerCase();
if (
errorMessage.includes("unreachable") ||
errorMessage.includes("connection") ||
errorMessage.includes("could not connect") ||
errorMessage.includes("timed out") ||
errorMessage.includes("connection refused") ||
errorMessage.includes("no route to host")
) {
throw new BoltNodeUnreachableError(
`Node ${nodeId} is unreachable`,
nodeId,
error.stderr,
);
}
}
throw error;
}
}
/**
* Transform Bolt facts output to Facts object
*
* @param nodeId - The ID of the node
* @param jsonOutput - Raw JSON output from Bolt facts command
* @returns Facts object
*/
private transformFactsOutput(
nodeId: string,
jsonOutput: BoltJsonOutput,
): Facts {
// Bolt task output structure typically has items array with results per node
// Format: { "items": [{ "target": "node1", "status": "success", "value": {...} }] }
let factsData: Record<string, unknown> = {};
// Handle items array format
const items = jsonOutput.items;
if (Array.isArray(items) && items.length > 0) {
const item = items[0] as Record<string, unknown>;
if (
item.status === "success" &&
typeof item.value === "object" &&
item.value !== null
) {
factsData = item.value as Record<string, unknown>;
}
} else {
// Handle direct facts format
factsData = jsonOutput;
}
// Extract and structure facts according to the Facts interface
const facts: Facts["facts"] = {
os: this.extractOsFacts(factsData),
processors: this.extractProcessorFacts(factsData),
memory: this.extractMemoryFacts(factsData),
networking: this.extractNetworkingFacts(factsData),
};
// Include any additional facts
for (const [key, value] of Object.entries(factsData)) {
if (!["os", "processors", "memory", "networking"].includes(key)) {
facts[key] = value;
}
}
return {
nodeId,
gatheredAt: new Date().toISOString(),
facts,
};
}
/**
* Extract OS facts from raw facts data
*/
private extractOsFacts(
factsData: Record<string, unknown>,
): Facts["facts"]["os"] {
const os = factsData.os as Record<string, unknown> | undefined;
const release = os?.release as Record<string, unknown> | undefined;
return {
family: typeof os?.family === "string" ? os.family : "unknown",
name: typeof os?.name === "string" ? os.name : "unknown",
release: {
full: typeof release?.full === "string" ? release.full : "unknown",
major: typeof release?.major === "string" ? release.major : "unknown",
},
};
}
/**
* Extract processor facts from raw facts data
*/
private extractProcessorFacts(
factsData: Record<string, unknown>,
): Facts["facts"]["processors"] {
const processors = factsData.processors as
| Record<string, unknown>
| undefined;
return {
count: typeof processors?.count === "number" ? processors.count : 0,
models: Array.isArray(processors?.models)
? processors.models.filter((m): m is string => typeof m === "string")
: [],
};
}
/**
* Extract memory facts from raw facts data
*/
private extractMemoryFacts(
factsData: Record<string, unknown>,
): Facts["facts"]["memory"] {
const memory = factsData.memory as Record<string, unknown> | undefined;
const system = memory?.system as Record<string, unknown> | undefined;
return {
system: {
total: typeof system?.total === "string" ? system.total : "0",
available:
typeof system?.available === "string" ? system.available : "0",
},
};
}
/**
* Extract networking facts from raw facts data
*/
private extractNetworkingFacts(
factsData: Record<string, unknown>,
): Facts["facts"]["networking"] {
const networking = factsData.networking as
| Record<string, unknown>
| undefined;
const hostname =
networking !== undefined && typeof networking.hostname === "string"
? networking.hostname
: "unknown";
const interfaces =
networking !== undefined &&
typeof networking.interfaces === "object" &&
networking.interfaces !== null
? (networking.interfaces as Record<string, unknown>)
: {};
return {
hostname,
interfaces,
};
}
/**
* Execute a command on a target node
*
* Executes `bolt command run <cmd> --targets <node> --format json` and
* returns structured execution results including stdout, stderr, and exit code
*
* @param nodeId - The ID/name of the target node
* @param command - The command string to execute
* @param streamingCallback - Optional callback for real-time output streaming
* @returns Promise resolving to ExecutionResult object
* @throws BoltNodeUnreachableError if the node is unreachable
* @throws BoltExecutionError if Bolt command fails
* @throws BoltParseError if JSON parsing fails
* @throws BoltTimeoutError if execution exceeds timeout
*/
public async runCommand(
nodeId: string,
command: string,
streamingCallback?: StreamingCallback,
): Promise<ExecutionResult> {
const startTime = Date.now();
const executionId = this.generateExecutionId();
const args = [
"command",
"run",
command,
"--targets",
nodeId,
"--format",
"json",
];
const commandString = this.buildCommandString(args);
try {
const jsonOutput = await this.executeCommandWithJsonOutput(
args,
{},
streamingCallback,
);
const endTime = Date.now();
const result = this.transformCommandOutput(
executionId,
nodeId,
command,
jsonOutput,
startTime,
endTime,
);
result.command = commandString;
return result;
} catch (error) {
const endTime = Date.now();
// Check if error is due to node being unreachable
if (error instanceof BoltExecutionError && error.stderr) {
const errorMessage = error.stderr.toLowerCase();
if (
errorMessage.includes("unreachable") ||
errorMessage.includes("connection") ||
errorMessage.includes("could not connect") ||
errorMessage.includes("timed out") ||
errorMessage.includes("connection refused") ||
errorMessage.includes("no route to host")
) {
throw new BoltNodeUnreachableError(
`Node ${nodeId} is unreachable`,
nodeId,
error.stderr,
);
}
}
// Return failed execution result for other errors
if (error instanceof BoltExecutionError) {
return {
id: executionId,
type: "command",
targetNodes: [nodeId],
action: command,
status: "failed",
startedAt: new Date(startTime).toISOString(),
completedAt: new Date(endTime).toISOString(),
results: [
{
nodeId,
status: "failed",
error: error.message,
duration: endTime - startTime,
},
],
error: error.message,
command: commandString,
};
}
throw error;
}
}
/**
* Transform Bolt command output to ExecutionResult object
*
* @param executionId - Unique execution identifier
* @param nodeId - The ID of the target node
* @param command - The command that was executed
* @param jsonOutput - Raw JSON output from Bolt command
* @param startTime - Execution start timestamp
* @param endTime - Execution end timestamp
* @returns ExecutionResult object
*/
private transformCommandOutput(
executionId: string,
nodeId: string,
command: string,
jsonOutput: BoltJsonOutput,
startTime: number,
endTime: number,
): ExecutionResult {
// Bolt command output structure: { "items": [{ "target": "node1", "status": "success", "value": {...} }] }
const items = jsonOutput.items;
const results: NodeResult[] = [];
let overallStatus: ExecutionResult["status"] = "success";
if (Array.isArray(items)) {
for (const item of items) {
const itemObj = item as Record<string, unknown>;
const target =
typeof itemObj.target === "string" ? itemObj.target : nodeId;
const status = itemObj.status === "success" ? "success" : "failed";
if (status === "failed") {
overallStatus = "failed";
}
const nodeResult: NodeResult = {
nodeId: target,
status,
duration: endTime - startTime,
};
// Extract output from value object
if (typeof itemObj.value === "object" && itemObj.value !== null) {
const value = itemObj.value as Record<string, unknown>;
nodeResult.output = {
stdout: typeof value.stdout === "string" ? value.stdout : "",
stderr: typeof value.stderr === "string" ? value.stderr : "",
exitCode:
typeof value.exit_code === "number" ? value.exit_code : undefined,
};
}
// Extract error message if present
if (typeof itemObj.error === "object" && itemObj.error !== null) {
const errorObj = itemObj.error as Record<string, unknown>;
nodeResult.error =
typeof errorObj.msg === "string"
? errorObj.msg
: typeof errorObj.message === "string"
? errorObj.message
: "Command execution failed";
}
results.push(nodeResult);
}
}
return {
id: executionId,
type: "command",
targetNodes: [nodeId],
action: command,
status: overallStatus,
startedAt: new Date(startTime).toISOString(),
completedAt: new Date(endTime).toISOString(),
results,
};
}
/**
* Generate a unique execution ID
*
* @returns Unique execution identifier
*/
private generateExecutionId(): string {
return `exec_${String(Date.now())}_${Math.random().toString(36).substring(2, 11)}`;
}
/**
* Execute a task on a target node
*
* Executes `bolt task run <task> --targets <node> --params <json> --format json`
* and returns structured execution results
*
* @param nodeId - The ID/name of the target node
* @param taskName - The name of the task to execute
* @param parameters - Task parameters as key-value pairs
* @param streamingCallback - Optional callback for real-time output streaming
* @returns Promise resolving to ExecutionResult object
* @throws BoltTaskNotFoundError if the task does not exist
* @throws BoltTaskParameterError if parameters are invalid
* @throws BoltNodeUnreachableError if the node is unreachable
* @throws BoltExecutionError if Bolt command fails
* @throws BoltParseError if JSON parsing fails
* @throws BoltTimeoutError if execution exceeds timeout
*/
public async runTask(
nodeId: string,
taskName: string,
parameters?: Record<string, unknown>,
streamingCallback?: StreamingCallback,
): Promise<ExecutionResult> {
const startTime = Date.now();
const executionId = this.generateExecutionId();
// Build command arguments
const args = [
"task",
"run",
taskName,
"--targets",
nodeId,
"--format",
"json",
];
// Add parameters if provided
if (parameters && Object.keys(parameters).length > 0) {
args.push("--params", JSON.stringify(parameters));
}
const commandString = this.buildCommandString(args);
try {
const jsonOutput = await this.executeCommandWithJsonOutput(
args,
{},
streamingCallback,
);
const endTime = Date.now();
const result = this.transformTaskOutput(
executionId,
nodeId,
taskName,
parameters,
jsonOutput,
startTime,
endTime,
);
result.command = commandString;
return result;
} catch (error) {
const endTime = Date.now();
// Check if error is due to task not found
if (error instanceof BoltExecutionError && error.stderr) {
const errorMessage = error.stderr.toLowerCase();
if (
errorMessage.includes("could not find") ||
errorMessage.includes("task not found") ||
errorMessage.includes("no such task") ||
errorMessage.includes("unknown task")
) {
throw new BoltTaskNotFoundError(
`Task '${taskName}' not found in Bolt modules`,
taskName,
);
}
// Check for parameter validation errors
if (
errorMessage.includes("parameter") ||
errorMessage.includes("invalid") ||
errorMessage.includes("required") ||
errorMessage.includes("missing")
) {
const paramErrors = this.extractParameterErrors(error.stderr);
throw new BoltTaskParameterError(
`Invalid parameters for task '${taskName}'`,
taskName,
paramErrors,
);
}
// Check if error is due to node being unreachable
if (
errorMessage.includes("unreachable") ||
errorMessage.includes("connection") ||
errorMessage.includes("could not connect") ||
errorMessage.includes("timed out") ||
errorMessage.includes("connection refused") ||
errorMessage.includes("no route to host")