Skip to content

Commit

Permalink
Reorg script
Browse files Browse the repository at this point in the history
  • Loading branch information
alukach committed Oct 26, 2024
1 parent 4961203 commit 45923f0
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 147 deletions.
99 changes: 99 additions & 0 deletions bin/apply-config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
import {
ECSClient,
DescribeTasksCommand,
DescribeTaskDefinitionCommand,
} from "@aws-sdk/client-ecs";
import {
CloudWatchLogsClient,
GetLogEventsCommand,
} from "@aws-sdk/client-cloudwatch-logs";

let exitCode = null;

main()
.then((logs) => {
console.log("Task output:");
logs.forEach((l) => console.log(l));
})
.catch((error) => {
console.error(`Error: ${error}`);
exitCode = 1;
})
.finally(() => process.exit(exitCode));

async function main() {
const [, , lambdaArn] = process.argv;
const { taskArn, clusterArn } = await invokeLambda(lambdaArn);
const ecs = new ECSClient({});
const task = await pollEcsTask(ecs, taskArn, clusterArn);
exitCode = task.containers[0]?.exitCode ?? null;
if (exitCode === null)
throw new Error("Could not retrieve exit code from the ECS task.");

const { logGroup, logStreamPrefix, region, containerName } =
await getLogConfig(ecs, task.taskDefinitionArn);
const taskId = taskArn.split("/").pop();
const logStreamName = `${logStreamPrefix}/${containerName}/${taskId}`;
return fetchCloudWatchLogs(logGroup, logStreamName, region);
}

async function invokeLambda(lambdaArn) {
const lambda = new LambdaClient({});
const response = await lambda.send(
new InvokeCommand({
FunctionName: lambdaArn,
InvocationType: "RequestResponse",
Payload: new TextEncoder().encode(JSON.stringify({})),
})
);
return JSON.parse(new TextDecoder().decode(response.Payload));
}

async function pollEcsTask(ecs, taskArn, clusterArn) {
while (true) {
const { tasks } = await ecs.send(
new DescribeTasksCommand({ cluster: clusterArn, tasks: [taskArn] })
);
const task = tasks?.[0];
if (!task) throw new Error(`No tasks found with taskArn: ${taskArn}`);
console.log(`Task status: ${task.lastStatus}`);
if (task.lastStatus === "STOPPED") return task;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
}

async function getLogConfig(ecs, taskDefinitionArn) {
const { taskDefinition } = await ecs.send(
new DescribeTaskDefinitionCommand({ taskDefinition: taskDefinitionArn })
);
const containerDef = taskDefinition.containerDefinitions[0];
if (containerDef.logConfiguration?.logDriver !== "awslogs")
throw new Error("Log driver is not 'awslogs'.");
return {
logGroup: containerDef.logConfiguration.options["awslogs-group"],
logStreamPrefix:
containerDef.logConfiguration.options["awslogs-stream-prefix"],
region: containerDef.logConfiguration.options["awslogs-region"],
containerName: containerDef.name,
};
}

async function fetchCloudWatchLogs(logGroup, logStreamName, region) {
const logsClient = new CloudWatchLogsClient({ region });
let nextToken,
events = [];
do {
const { events: newEvents, nextForwardToken } = await logsClient.send(
new GetLogEventsCommand({
logGroupName: logGroup,
logStreamName,
startFromHead: true,
nextToken,
})
);
events.push(...newEvents);
nextToken = nextForwardToken !== nextToken ? nextForwardToken : null;
} while (nextToken);
return events.map((event) => event.message);
}
146 changes: 0 additions & 146 deletions config/apply-config.mjs

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"build": "tsc",
"watch": "tsc -w",
"cdk": "cdk",
"apply-config": "node ./config/apply-config.mjs"
"apply-config": "node ./bin/apply-config.mjs"
},
"devDependencies": {
"@aws-sdk/client-cloudwatch-logs": "^3.680.0",
Expand Down

0 comments on commit 45923f0

Please sign in to comment.