Pages - Menu

Showing posts with label s3. Show all posts
Showing posts with label s3. Show all posts

nopCommerce - AWS Migration

Scope

We are moving our existing websites to AWS EC2. From a high level perspective, our plan as follow.
  • Move the websites to EC2
  • Move the database to RDS
  • Content Images upload via CMS will go to s3
  • Product Images on the websites are moved to s3
  • Move the console apps to a t2.micro instance
We are using nopCommerce 3.3.

Implementation

Websites and Console Apps

Moving sites and apps to cloud instances are pretty straight forward. There are no code changes required in nopCommerce.

Database

We used the SQL Database Migration Wizard tool, pretty straight forward.

S3

Migration to S3 required some code changes, but we are not getting much resistance because of the advantage of using OO and polymorphism.

Previously we already wrote a custom class that inherit from the PictureService.

public class TAPictureService : PictureService, ITAPictureService, IPictureService

Now, I can inherit my custom class by my new AWS class.

public class AwsPictureService : TAPictureService, ITAPictureService, IPictureService

We will then override the image read / write method to connect to AWS. This was mentioned previously in my other post Amazon SDK S3 with .Net

In our DependencyRegister, we now register our new AWS Service.

builder.RegisterType<AwsPictureService>().As<IPictureService>();

Now my system is able to support either local or S3 images by changing the register type via DI.

Amazon SDK S3 with .Net

Scope

We decided to move our images on our websites from local drive to Amazon S3. This includes all our product images from the e-commerce side; as well as any images or videos that are associated to the CMS side.

Setup and Installation

AWS Toolkit for Visual Studio

  1. Follow the Amazon Setup Guide to install the AWS Toolkit. 
  2. Download and install (or NuGet) AWS SDK for .Net.
  3. Configuring AWS Credentials
  4. Use the Amazon Endpoint List to configure the end point
  5. The Amazon SDK API documentation is pretty easy to read.

Code

Upload an object

By using the Amazon SDK, We change our file service to put files to S3 instead of saving to local folder. It divides into 2 parts. We will prepare the PutObjectRequest and call AmazonS3Client.PutObject() to upload the file.

public override HttpStatusCode UploadPicture(string targetPath, string sourcePath)
{
    // Create a PutObject request
    var request = new PutObjectRequest
    {
        BucketName = bucket,
        Key = targetPath.ToLower(),
        FilePath = sourcePath,
        CannedACL = S3CannedACL.PublicRead
    };

    try
    {
        using (var client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast2))
        {
            // Put object
            PutObjectResponse response = client.PutObject(request);

            return response.HttpStatusCode;
        }
    }
    catch (Exception ex)
    {
        // logging and exception handling....
    }

    return HttpStatusCode.NotFound;
}

S3CannedACL is a predefined Access Control List that allows access to be set on S3 objects.

Access an object

To access an object in s3 is much easier. You will just need to know the url and have the correct ACL setup.

The URL format is in a form of http://{mybucket}.s3.amazonaws.com/{mykey} 

mybucket is the bucket name and mykey is the key (file path) to the object.


The Quickest Way to Bulk Create AWS S3 Buckets

I am in a mission of creating a bunch of s3 buckets in bulk. I could just use the web interface and do it manually. I reckon I can get the job done in around 30 minutes, but I am looking for a more an IT way to do it.

Solution

After a quick look around, I think I can use the Command Line Interface.

Download and Setup


Configure


Run the aws configure command to create a default profile. Fairly straight forward.

$ aws configure
AWS Access Key ID [None]: AKIAIOSFODNN7EXAMPLE
AWS Secret Access Key [None]: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Default region name [None]: us-west-2
Default output format [None]: json

A list of region name can be found here.

Commands


http://docs.aws.amazon.com/cli/latest/reference/s3/index.html

I use the ls command to pull out a list of my buckets.

$ aws s3 ls

In order to create buckets, the command I need is mb.

$ aws s3 mb s3://mybucket

I prepared my list of commands by using Excel / Find and Replace.

$ aws s3 mb s3://sunnyw.net.dummy1
$ aws s3 mb s3://sunnyw.net.dummy2
$ aws s3 mb s3://sunnyw.net.dummy3

And I just copy and paste into the console.

PS C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell> aws s3 mb s3://sunnyw.net.dummy1
make_bucket: s3://sunnyw.net.dummy1/
PS C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell> aws s3 mb s3://sunnyw.net.dummy2
make_bucket: s3://sunnyw.net.dummy2/
PS C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell> aws s3 mb s3://sunnyw.net.dummy3
make_bucket: s3://sunnyw.net.dummy3/
PS C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell>

I didn't need any fancy API calls or build any C# console. If the requirement was more complicated, I could put those logics in PowerShell script. Simple is Good!!

Bucket name does matter on AWS S3

Scope


As some of you might know I have a second career as a photographer, and it is just natural for me to write my own website (Bootstrapped indeed!!). Currently having some issues with the existing web hosting so I began to migrate my site to be hosted in Amazon S3.

Migration Began


Went through the Web UI interface on AWS portal to upload files, set permission and enabled Static Website Hosting. All nice and sweet, had some issues to apply all public read policy to the bucket so I don't have to change permission per file basis. Once again, it wasn't difficult to find out how when we are in that era of information technology, a bit of search and I got the policy example up and running.

For those who curious here the code I have used. Version date cannot be changed or it will throw error. Why 2008???

   1: {

   2: "Version":"2008-10-17",

   3: "Id":"http referer policy example",

   4: "Statement":[

   5: {

   6: "Sid":"readonly policy",

   7: "Effect":"Allow",

   8: "Principal":"*",

   9: "Action":"s3:GetObject",

  10: "Resource":"arn:aws:s3:::mybucket/*"

  11: }

  12: ]

  13: }


What really got me and wasn't so obvious to me is that the bucket name is directly related to the domain I am going to use for CNAME redirect. What does it mean? Let's have a look.

At first I setup the bucket as "swphotography" as below.

swphotography

After I change my CNAME record in my DNS register, I get the error below.

error

With my given endpoint from s3, the site works fine without 404 error.

The error message was actually quite useful, especially the 2nd and 3rd lines helped me to resolve the problem.

The 2nd line is basically saying "bucket not found", and the 3rd line is saying BucketName: www.sunnyw.net.

Bucket Name Matters!!


Hello S3, I didn't setup the bucket name as www.sunnyw.net, it was swphotography! It had me thinking maybe the bucket name is related to the url, and maybe it uses it as a way to do bucket look up.

sunnyw.net

Copy the files over from the swphotography bucket to the www.sunnyw.net bucket, my site is up and running again!

Conclusion


It was a bit of effort but pretty happy with the result. As my usual whinging thing, perhaps they can provide a wizard tool for people who want to use CDN for static website hosting? It is not an uncommon strategy to host simple content sites and you may find articles about it on the internet easily. Extra bedside reading anyone?