Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix startstop lambda has no effect on desire count #35

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18
15 changes: 7 additions & 8 deletions resources/serverstatus.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*

This code was created from sample code provided for the AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
Expand Down Expand Up @@ -35,7 +35,7 @@ const ec2Client = new EC2Client({ region: REGION });
/**
* Everything here has the assumption there is only one task.
*/
const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent, context: Context) => {
export const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent, context: Context) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

console.log(`New getServerStatus request: ${JSON.stringify(event)}`);
console.log(`With context: ${JSON.stringify(context)}`);

Expand All @@ -50,7 +50,6 @@ const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent, context:
};
};

export default handler;

async function getIPFunction() {

Expand All @@ -62,15 +61,15 @@ async function getIPFunction() {

try {

const listTasksCommandInput: ListTasksCommandInput = {
const listTasksCommandInput: ListTasksCommandInput = {
serviceName: SERVICE_ARN,
cluster: CLUSTER_ARN,
desiredStatus: "RUNNING"
}
const listTasksCommandResult = await ecsClient.send(new ListTasksCommand(listTasksCommandInput));
console.log(listTasksCommandResult);
console.log("ECS List Tasks Command Result: " + listTasksCommandResult);

if (!listTasksCommandResult.taskArns || listTasksCommandResult.taskArns.length <= 0) return;
if (!listTasksCommandResult.taskArns || listTasksCommandResult.taskArns.length <= 0) return statusResults;

const networkInterfaceId = await getNetworkInterfaceId(CLUSTER_ARN, listTasksCommandResult.taskArns);

Expand All @@ -79,7 +78,7 @@ async function getIPFunction() {
}
const describeNetworkInterfacesResult = await ec2Client.send(new DescribeNetworkInterfacesCommand(describeNetworkInterfacesInput));

if (!describeNetworkInterfacesResult.NetworkInterfaces || describeNetworkInterfacesResult.NetworkInterfaces.length <= 0) return;
if (!describeNetworkInterfacesResult.NetworkInterfaces || describeNetworkInterfacesResult.NetworkInterfaces.length <= 0) return statusResults;
const publicIp = describeNetworkInterfacesResult.NetworkInterfaces.find(x => x.Association != undefined)?.Association?.PublicIp;

console.log("found public IP " + publicIp);
Expand Down Expand Up @@ -111,7 +110,7 @@ const getNetworkInterfaceId = async (cluster: string, tasks: string[]): Promise<

const networkInterfaceId = firstAttachment.details?.find(d => d.name === 'networkInterfaceId')?.value;
if (!networkInterfaceId) throw new Error(`Could not find a network interface on given attachment: ${JSON.stringify(firstAttachment)}`);

console.debug(`Found interface "${networkInterfaceId}"`);
return networkInterfaceId;
} catch (err) {
Expand Down
99 changes: 50 additions & 49 deletions resources/startstopserver.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*
/*

ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
Expand All @@ -20,63 +20,64 @@ import { ECSClient, UpdateServiceCommand } from '@aws-sdk/client-ecs';
import { APIGatewayEvent, APIGatewayProxyHandler, Context } from 'aws-lambda';

//Set the AWS Region
const REGION = process.env.REGION;
const REGION = process.env.REGION;

const SERVICE_NAME = process.env.SERVICE_NAME;
const CLUSTER_ARN = process.env.CLUSTER_ARN;
const SERVICE_NAME = process.env.SERVICE_NAME;
const CLUSTER_ARN = process.env.CLUSTER_ARN;
const PASSWORD = process.env.PASSWORD;

const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent, context: Context) => {
console.log("request: " + JSON.stringify(event));
let responseCode = 400;
let message = "authentication failed";
export const handler: APIGatewayProxyHandler = async (event: APIGatewayEvent, context: Context) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

console.log("request: " + JSON.stringify(event));
let responseCode = 400;
let message = "authentication failed";

const params = {
desiredCount: 1,
service: SERVICE_NAME,
cluster: CLUSTER_ARN
}

if (event.queryStringParameters && event.queryStringParameters.desiredCount !== undefined) {
let count = Math.min(Math.max(+event.queryStringParameters.desiredCount, 0), 1);
params.desiredCount = count;
console.log("changing desiredCount to " + count);
}
const params = {
desiredCount: 1,
service: SERVICE_NAME,
cluster: CLUSTER_ARN
}

if (event.queryStringParameters && event.queryStringParameters.key) {
let key = event.queryStringParameters.key;
if (key == PASSWORD) {
const client = new ECSClient({ region: REGION });
console.log("starting service " + JSON.stringify(params));
message = "authentication success";
responseCode = 200;
if (event.queryStringParameters && event.queryStringParameters.desiredCount !== undefined) {
let count = Math.min(Math.max(+event.queryStringParameters.desiredCount, 0), 1);
params.desiredCount = count;
console.log("changing desiredCount to " + count);
}

if (event.queryStringParameters && event.queryStringParameters.key) {
let key = event.queryStringParameters.key;
if (key == PASSWORD) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const client = new ECSClient({region: REGION});
console.log("starting service " + JSON.stringify(params));
message = "authentication success";
responseCode = 200;

const updateCommand = new UpdateServiceCommand(params);

client.send(updateCommand).then(
(data) => {console.log(data);},
(err) => { console.log(err);}
);
const updateCommand = new UpdateServiceCommand(params);

await client.send(updateCommand).then(
(data) => {
console.log(`OK! ${JSON.stringify(data, null, 2)}`);
},
(err) => {
console.log(`Error! ${JSON.stringify(err, null, 2)}`);
Comment on lines +57 to +62
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would refactor this to be pure async/await:

      try {
        const result = await client.send(updateCommand);
        console.log(`OK! ${JSON.stringify(result, null, 2)}`);
      } catch (error) {
        console.log(`Error! ${JSON.stringify(error, null, 2)}`);
      }

}
);
}
}

let responseBody = {
message: message,
};

// The output from a Lambda proxy integration must be
// in the following JSON object. The 'headers' property
// is for custom response headers in addition to standard
// ones. The 'body' property must be a JSON string. For
// base64-encoded payload, you must also set the 'isBase64Encoded'
// property to 'true'.
return {
statusCode: responseCode,
headers: {
},
body: JSON.stringify(responseBody)
};
};
let responseBody = {
message: message,
};

export default handler;
// The output from a Lambda proxy integration must be
// in the following JSON object. The 'headers' property
// is for custom response headers in addition to standard
// ones. The 'body' property must be a JSON string. For
// base64-encoded payload, you must also set the 'isBase64Encoded'
// property to 'true'.
return {
statusCode: responseCode,
headers: {},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed, and the comment above is redundant if the handler response is strongly typed

body: JSON.stringify(responseBody)
};
};