Print
Category: Technology
Hits: 43074

What is serverless computing?

Serverless allows you to build and run applications and services without thinking about servers.

Why we need serverless computing?

Serverless enables you to only focus & build an applications with increased agility without considering infra and lower total cost of ownership

What is S3 in AWS?

An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services' (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata.

 

Use Case 1: Use case for serverless computing to store the result in S3 (Simple Storage Service) bucket?

Pass a text => Encrypt using serverless computing => store the output of encrypted text into S3

Dev Environment Setup


Step 1: download and install VS 2017 community edition (default ships with .NET core and Lambda function template supports)

Step 2: In VS 2017, File => New Project => AWS Lambda => AWS Lambda Project (.NET Core)

Step 3: Install AWSSDK.S3 package to work on AWS S3 Bucket APIs (Tools => Nuget Pacakage Manager => AWSSDK.S3 by Amazon Web Services)

Create Helper & Lambda function

Step 1: Encryption helper class

public class DataEncrypter
{
public static string Encrypt(string input, string key)
{
  byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
  TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
  tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
  tripleDES.Mode = CipherMode.ECB;
  tripleDES.Padding = PaddingMode.PKCS7;
  ICryptoTransform cTransform = tripleDES.CreateEncryptor();
  byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
  tripleDES.Clear();
  return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
}


Step 2: Put the encrypted text into the S3 bucket

static async Task WritingAnObjectAsync(string strEncryptedText, string strFileName)
{
try
{
var putRequest1 = new Amazon.S3.Model.PutObjectRequest
{
BucketName = bucketName,
Key = strFileName,
ContentBody = strEncryptedText
};
PutObjectResponse response1 = await client.PutObjectAsync(putRequest1);
}
}

Step 3: Using the above 2 helper class write Lambda function and encrypt the incoming request (UserName + Text) and put it in a S3 bucket


public class Function
{

private const string bucketName = "testbucket.comapnyname.com";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.APSoutheast1;
private static IAmazonS3 client;

public string Encrypt(Param input, ILambdaContext context)
{
string strEncryptedText = "";

//this hard coded part can be changed with proper authentication
if (input.UserName == "testuser")
strEncryptedText = DataEncrypter.Encrypt(input.Text, "asdfewrewqrss323");
else
strEncryptedText = DataEncrypter.Encrypt(input.Text, "asdfewrewqrss324");

client = new AmazonS3Client(bucketRegion);

WritingAnObjectAsync(strEncryptedText,input.FileName).Wait();

return string.Format("OK");
}
}



Note:


input => customized class through which required value (user name, text to encrypted) are passed while calling this lambda function
public class Param
{
public string UserName { get; set; }
public string Text { get; set; }
public string FileName { get; set; }
}

context => ILambdaContext gives runtime details by the framework.
This object provides us memory limit, remaining execution time...

 

Publish Lambda into AWS

Step 1: In solution explorer, right click project => choose => Publish to AWS lambda

Step 2: In the popup window provide, lambda function details +
AWS account details (which would have generated in AWS console under IAM, provide appropriate rights
policy to execute ex: Lambda function, S3 access)

Step 3: Click Next, and set Memory limit and Timeout

Step 4: Click Upload




Consume Lambda function


Step 1: Create a console application

Step 2: install following nuget packages
awssdk.core
awssdk.lambda
newtonsoft

Step 3: code below to send a text to encrypt and put it in a created bucket

static void PutFile()
{
AmazonLambdaClient client = new AmazonLambdaClient("ACCESS_KEY", "SECRET_ACCESSKEY",RegionEndpoint.APSoutheast1);


InvokeRequest ir = new InvokeRequest
{
FunctionName = "Encrypter",
InvocationType = InvocationType.RequestResponse,
Payload = JsonConvert.SerializeObject(new { UserName = "raja", Text = "this is the sample text", FileName = "samplefile.txt" })
};

InvokeResponse response = client.Invoke(ir);

var sr = new StreamReader(response.Payload);
JsonReader reader = new JsonTextReader(sr);

var serilizer = new JsonSerializer();
var op = serilizer.Deserialize(reader);

Console.WriteLine(op);
Console.ReadLine();
}


step 4: code below to retrieve the encrypted file(object) from the bucket and decrypt it and send it back to the client

static void GetFile()
{
AmazonLambdaClient client = new AmazonLambdaClient("ACCESS_KEY", "SECRET_ACCESSKEY", RegionEndpoint.APSoutheast1);

InvokeRequest ir = new InvokeRequest
{
FunctionName = "DecryptAndGetObject",
InvocationType = InvocationType.RequestResponse,
Payload = JsonConvert.SerializeObject(new { UserName = "raja", FileName = "samplefile.txt" })
};

InvokeResponse response = client.Invoke(ir);

var sr = new StreamReader(response.Payload);
JsonReader reader = new JsonTextReader(sr);

var serilizer = new JsonSerializer();
var op = serilizer.Deserialize(reader);

Console.WriteLine(op);
Console.ReadLine();
}

 
Lambda function costing

Total charges = Compute charges + Request charges

where,

Compute charges => based on 1) allocated memory size for the lambda function + 2) how long it run
Request charges => no of hits

The monthly compute price is $0.00001667 per GB-s and the free tier provides 400,000 GB-s.


Example,

Compute Charges

If we allocated 128MB of memory to our function, executed it 1 million times in one month, and it ran for 2 second each time, charges would be calculated as follows:


Total compute (seconds) = 1000000 * (2sec) = 2000000 seconds

Total compute (GB-s) = 2000000 * 128MB/1024 = 250000 GB-s

Total compute – Free tier compute = Monthly billable compute GB- s

250000- 400000 free tier GB-s = -150000 GB- s

Monthly compute charges = NIL (-150000 GB- s) X $0.00001667 = ~0


Monthly request charges

The monthly request price is $0.20 per 1 million requests and the free tier provides 1M requests per month.

Total requests – Free tier requests = Monthly billable requests

1M requests – 1M free tier requests = 0M Monthly billable requests

Monthly request charges = 2M * $0.2/M = $0

Total monthly charges

Total charges = Compute charges + Request charges
= $0 + $0
= $0 per month

 

More more details:

Azure    => Azure costing
Amazon => Amazon costing