-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathlocalstack-chaos-injector.ts
More file actions
350 lines (294 loc) · 10.5 KB
/
localstack-chaos-injector.ts
File metadata and controls
350 lines (294 loc) · 10.5 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
import { z } from "zod";
import { type ToolMetadata, type InferSchema } from "xmcp";
import { ProFeature } from "../lib/localstack/license-checker";
import { ChaosApiClient } from "../lib/localstack/localstack.client";
import { ResponseBuilder } from "../core/response-builder";
import {
runPreflights,
requireAuthToken,
requireLocalStackRunning,
requireProFeature,
} from "../core/preflight";
import { withToolAnalytics } from "../core/analytics";
// Define the fault rule schema
const faultRuleSchema = z
.object({
service: z
.string()
.optional()
.describe("Name of the AWS service to affect (e.g., 's3', 'lambda')."),
region: z.string().optional().describe("Name of the AWS region to affect (e.g., 'us-east-1')."),
operation: z
.string()
.optional()
.describe("Name of the specific service operation to affect (e.g., 'CreateBucket')."),
probability: z
.number()
.min(0)
.max(1)
.optional()
.describe("The probability (0.0 to 1.0) of the fault occurring."),
error: z
.object({
statusCode: z
.number()
.int()
.optional()
.describe("The HTTP status code to return (e.g., 503)."),
code: z
.string()
.optional()
.describe("The AWS error code to return (e.g., 'ServiceUnavailable')."),
})
.optional()
.describe("The custom error to return."),
})
.describe("A single rule defining a chaos fault.");
// Define the schema for tool parameters
export const schema = {
action: z
.enum([
"inject-faults",
"add-fault-rule",
"remove-fault-rule",
"get-faults",
"clear-all-faults",
"inject-latency",
"get-latency",
"clear-latency",
])
.describe("The specific chaos engineering action to perform."),
rules: z
.array(faultRuleSchema)
.optional()
.describe(
"An array of fault rules. Required for 'inject-faults', 'add-fault-rule', and 'remove-fault-rule' actions."
),
latency_ms: z
.number()
.int()
.min(0)
.optional()
.describe("Network latency in milliseconds. Required for the 'inject-latency' action."),
};
// Define tool metadata
export const metadata: ToolMetadata = {
name: "localstack-chaos-injector",
description:
"Injects, manages, and clears chaos faults and network effects in LocalStack to test system resilience.",
annotations: {
title: "LocalStack Chaos Injector",
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
},
};
// Check if two fault rules match exactly
function rulesMatch(rule1: any, rule2: any): boolean {
const keys1 = Object.keys(rule1).sort();
const keys2 = Object.keys(rule2).sort();
if (keys1.length !== keys2.length) return false;
if (keys1.join(",") !== keys2.join(",")) return false;
for (const key of keys1) {
if (typeof rule1[key] === "object" && typeof rule2[key] === "object") {
if (!rulesMatch(rule1[key], rule2[key])) return false;
} else if (rule1[key] !== rule2[key]) {
return false;
}
}
return true;
}
// Format fault rules for display
function formatFaultRules(rules: any[]): string {
if (!rules || rules.length === 0) {
return "✅ No chaos faults are currently active.";
}
return `\`\`\`json\n${JSON.stringify(rules, null, 2)}\n\`\`\``;
}
// Create workflow guidance for injection actions
function addWorkflowGuidance(message: string): string {
return `${message}
**Next Step:** Now, run your application or tests to observe the system's behavior under these conditions.
Once you are done, ask me to "**analyze the logs for errors**" to see the impact of this chaos experiment.`;
}
export default async function localstackChaosInjector({
action,
rules,
latency_ms,
}: InferSchema<typeof schema>) {
return withToolAnalytics(
"localstack-chaos-injector",
{ action, rules_count: rules?.length, latency_ms },
async () => {
const preflightError = await runPreflights([
requireAuthToken(),
requireLocalStackRunning(),
requireProFeature(ProFeature.CHAOS_ENGINEERING),
]);
if (preflightError) return preflightError;
const client = new ChaosApiClient();
switch (action) {
case "get-faults": {
const result = await client.getFaults();
if (!result.success) {
return { content: [{ type: "text", text: result.message }] };
}
const formattedRules = formatFaultRules(result.data);
return { content: [{ type: "text", text: formattedRules }] };
}
case "clear-all-faults": {
const result = await client.setFaults([]);
if (!result.success) {
return ResponseBuilder.error("Chaos API Error", result.message);
}
return ResponseBuilder.success(
"All chaos faults have been cleared. The system is now operating normally."
);
}
case "inject-faults": {
if (!rules || rules.length === 0) {
return {
content: [
{
type: "text",
text: "❌ **Error:** The `inject-faults` action requires the `rules` parameter to be specified.",
},
],
};
}
const setResult = await client.setFaults(rules);
if (!setResult.success) {
return ResponseBuilder.error("Chaos API Error", setResult.message);
}
// Get current state to confirm
const getCurrentResult = await client.getFaults();
if (!getCurrentResult.success) {
return ResponseBuilder.error("Chaos API Error", getCurrentResult.message);
}
const message = `✅ New chaos faults have been injected (overwriting any previous rules). The current active faults are:
${formatFaultRules(getCurrentResult.data)}`;
return ResponseBuilder.markdown(addWorkflowGuidance(message));
}
case "add-fault-rule": {
if (!rules || rules.length === 0) {
return {
content: [
{
type: "text",
text: "❌ **Error:** The `add-fault-rule` action requires the `rules` parameter to be specified.",
},
],
};
}
const addResult = await client.addFaultRules(rules);
if (!addResult.success) {
return ResponseBuilder.error("Chaos API Error", addResult.message);
}
// Get current state to confirm
const getCurrentResult = await client.getFaults();
if (!getCurrentResult.success) {
return ResponseBuilder.error("Chaos API Error", getCurrentResult.message);
}
const message = `✅ New fault rule(s) have been added. The current active faults are:
${formatFaultRules(getCurrentResult.data)}`;
return ResponseBuilder.markdown(addWorkflowGuidance(message));
}
case "remove-fault-rule": {
if (!rules || rules.length === 0) {
return {
content: [
{
type: "text",
text: "❌ **Error:** The `remove-fault-rule` action requires the `rules` parameter to be specified.",
},
],
};
}
// First get current rules to check if the rule exists
const getCurrentResult = await client.getFaults();
if (!getCurrentResult.success) {
return ResponseBuilder.error("Chaos API Error", getCurrentResult.message);
}
// Check if all rules to remove exist in current configuration
const currentRules = getCurrentResult.data || [];
const rulesToRemove = rules;
for (const ruleToRemove of rulesToRemove) {
const ruleExists = currentRules.some((currentRule: any) =>
rulesMatch(currentRule, ruleToRemove)
);
if (!ruleExists) {
return ResponseBuilder.markdown(`⚠️ The specified rule was not found in the current configuration. No changes were made.
Current configuration:
${formatFaultRules(currentRules)}`);
}
}
// Rule exists, proceed with removal
const removeResult = await client.removeFaultRules(rulesToRemove);
if (!removeResult.success) {
return ResponseBuilder.error("Chaos API Error", removeResult.message);
}
// Get current state after removal to confirm
const getUpdatedResult = await client.getFaults();
if (!getUpdatedResult.success) {
return ResponseBuilder.error("Chaos API Error", getUpdatedResult.message);
}
const message = `✅ The specified fault rule(s) have been removed. The current active faults are:
${formatFaultRules(getUpdatedResult.data)}`;
return ResponseBuilder.markdown(message);
}
case "get-latency": {
const result = await client.getEffects();
if (!result.success) {
return ResponseBuilder.error("Chaos API Error", result.message);
}
const latency = (result.data as any)?.latency || 0;
return ResponseBuilder.markdown(`The current network latency is ${latency}ms.`);
}
case "clear-latency": {
const result = await client.setEffects({ latency: 0 });
if (!result.success) {
return ResponseBuilder.error("Chaos API Error", result.message);
}
// Get current state to confirm
const getCurrentResult = await client.getEffects();
if (!getCurrentResult.success) {
return ResponseBuilder.error("Chaos API Error", getCurrentResult.message);
}
const message = `✅ Network latency has been cleared. The current effects are:
\`\`\`json
${JSON.stringify(getCurrentResult.data, null, 2)}
\`\`\``;
return ResponseBuilder.markdown(message);
}
case "inject-latency": {
if (latency_ms === undefined || latency_ms === null) {
return {
content: [
{
type: "text",
text: "❌ **Error:** The `inject-latency` action requires the `latency_ms` parameter to be specified.",
},
],
};
}
const result = await client.setEffects({ latency: latency_ms });
if (!result.success) {
return ResponseBuilder.error("Chaos API Error", result.message);
}
// Get current state to confirm
const getCurrentResult = await client.getEffects();
if (!getCurrentResult.success) {
return ResponseBuilder.error("Chaos API Error", getCurrentResult.message);
}
const message = `✅ Latency of ${latency_ms}ms has been injected. The current network effects are:
\`\`\`json
${JSON.stringify(getCurrentResult.data, null, 2)}
\`\`\``;
return ResponseBuilder.markdown(addWorkflowGuidance(message));
}
default:
return ResponseBuilder.error("Unknown action", `Unsupported action: ${action}`);
}
}
);
}