From 2d833a1379e430e9b4a121e94139931c8ced5187 Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sat, 10 Feb 2024 10:35:40 -0700 Subject: [PATCH] script for instance setup, minor corrections --- .gitignore | 1 + Project-1/Part-1/instance_run | 23 +++++++ Project-1/Part-1/project1_grader.py | 75 ++++++++++++++++++++++ Project-1/Part-1/run_instances.py | 17 ++++- Project-1/Part-1/web-tier-express/index.js | 2 +- 5 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 Project-1/Part-1/instance_run create mode 100644 Project-1/Part-1/project1_grader.py diff --git a/.gitignore b/.gitignore index 1b79aa4..fe54a0a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ *.pem node_modules/ *.log +*.ps1 diff --git a/Project-1/Part-1/instance_run b/Project-1/Part-1/instance_run new file mode 100644 index 0000000..e15e3e4 --- /dev/null +++ b/Project-1/Part-1/instance_run @@ -0,0 +1,23 @@ +#!/bin/bash +# initializing instance +cd /home/ubuntu +sudo apt update +sudo apt upgrade -y + +# Project specific setup +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash +echo -e '\nexport NVM_DIR="$HOME/.nvm"\n[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm \n[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion\n' >> .bashrc +source ~/.bashrc +export NVM_DIR="$HOME/.nvm" +[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm +[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion +nvm install v20.11.0 + +npm i -g pm2 +git clone https://github.com/20kaushik02/CSE546_Cloud_Computing_Projects repo +cd repo/Project-1/Part-1/web-tier-express +npm i + +# Start +pm2 start npm --name webTier -- run prod +pm2 save diff --git a/Project-1/Part-1/project1_grader.py b/Project-1/Part-1/project1_grader.py new file mode 100644 index 0000000..e67d86d --- /dev/null +++ b/Project-1/Part-1/project1_grader.py @@ -0,0 +1,75 @@ +import os +import boto3 +import dotenv +import httpx +import pdb +import json +import argparse + +class aws_grader(): + def __init__(self, access_keyId, access_key): + + self.iam_access_keyId = access_keyId + self.iam_secret_access_key = access_key + self.iam_session = boto3.Session(aws_access_key_id = self.iam_access_keyId, + aws_secret_access_key = self.iam_secret_access_key) + self.ec2_resources = self.iam_session.resource('ec2', 'us-east-1') + + def get_tag(self, tags, key='Name'): + + if not tags: + return 'None' + for tag in tags: + if tag['Key'] == key: + return tag['Value'] + return 'None' + + + ''' + Test Case:1 + 1) Checks if there is a web EC2 instance with the name "web-instance" + 2) Checks if the state of "web-instance" is "running". + ''' + + def test_case_1(self): + message = "" + for instance in self.ec2_resources.instances.all(): + name = self.get_tag(instance.tags) + if name == "web-instance": + message += "web-tier instance found." + state = instance.state['Name'] + message += f" With state: {state}" + if state == "running": + self.web_tier_instanceId = instance.id + print(f"Test Case:1 Passed. {message}") + return + else: + print(f"Test Case:1 Failed. {message}") + return + + message += "web-tier Instance Not Found." + print("Test Case:1 Failed. {message}") + + + def main(self): + # Use the session to access resources via the role + + print("======== Welcome to CSE546 Cloud Computing Grading Console ==================") + print(f"IAM ACESS KEY ID: {self.iam_access_keyId}") + print(f"IAM SECRET ACCESS KEY: {self.iam_secret_access_key}") + + self.test_case_1() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description='Upload images') + parser.add_argument('--access_keyId', type=str, help='ACCCESS KEY ID of the grading IAM user') + parser.add_argument('--access_key', type=str, help='SECRET ACCCESS KEY of the grading IAM user') + + args = parser.parse_args() + + access_keyId = args.access_keyId + access_key = args.access_key + + aws_obj = aws_grader(access_keyId, access_key) + aws_obj.main() diff --git a/Project-1/Part-1/run_instances.py b/Project-1/Part-1/run_instances.py index de11a7a..ae329fd 100644 --- a/Project-1/Part-1/run_instances.py +++ b/Project-1/Part-1/run_instances.py @@ -13,16 +13,31 @@ reservation = dev_ec2_client.run_instances( MaxCount=1, # try to allocate max_count instances. we only need one for now InstanceType="t2.micro", TagSpecifications=[ - {"ResourceType": "instance", "Tags": [{"Key": "Name", "Value": "WebTier"}]} + {"ResourceType": "instance", "Tags": [{"Key": "Name", "Value": "web-instance"}]} ], ) print("Instances allocated successfully:", "Yes" if reservation else "No") print("Groups:", len(reservation["Groups"])) # TODO: add grp info logging print("Instances:", len(reservation["Instances"])) + +new_inst_id = '' for inst_idx, inst in enumerate(reservation["Instances"]): print("Instance", inst_idx + 1, ":-") print("\tInstance ID:", inst["InstanceId"]) + new_inst_id = inst["InstanceId"] print("\tInstance state:", inst["State"]["Name"]) print(f"\t{inst["InstanceType"]} in {inst["Placement"]["AvailabilityZone"]}") print(f"\t{inst["CpuOptions"]["CoreCount"]}vCPU, {inst["Hypervisor"]} hypervisor") + +# Allocate EIP on successful instance launch +if reservation: + print("Waiting for instance to start running...") + waiter = dev_ec2_client.get_waiter('instance_running') + waiter.wait(InstanceIds=[new_inst_id]) + assoc = dev_ec2_client.associate_address( + AllocationId='eipalloc-02dedd204aeed8c51', + InstanceId=new_inst_id + ) + if assoc["ResponseMetadata"]["HTTPStatusCode"] == 200: + print("Allocated EIP successfully") \ No newline at end of file diff --git a/Project-1/Part-1/web-tier-express/index.js b/Project-1/Part-1/web-tier-express/index.js index 604fc81..1e4372f 100644 --- a/Project-1/Part-1/web-tier-express/index.js +++ b/Project-1/Part-1/web-tier-express/index.js @@ -23,7 +23,7 @@ fs.createReadStream(path.resolve(__dirname, "data", "results.csv")) // Controllers -const imageRecognition = (req, res, next) => { +const imageRecognition = (req, res) => { try { const fileName = req.files.inputFile[0].originalname.split(".jpg")[0]; return res.status(200).send(