SD Forum Java SIG - Running Java Applications On Amazon EC2

78
Running Java and Grails applications on Amazon EC2 applications on Amazon EC2 Chris Richardson Author of POJOs in Action Founder of Cloud Tools and Cloud Foundry Chris Richardson Consulting, Inc www.chrisrichardson.net www.chrisrichardson.net

description

The Amazon Elastic Compute Cloud (EC2) is ideally suited to running Java applications. It lets you develop using standard Java software packages such as Tomcat and MySQL and rapidly deploy applications on servers that are provisioned and managed via a web services API. However, because it is a cloud, some aspects of EC2 are very different than a traditional, physical computing environment. In this session you will learn about those differences and how they impact how you handle security, networking, storage and availability. We describe how to use EC2 and the other Amazon web services to develop and deploy Java applications. You will learn how to use EC2 availability zones to deploy highly available applications. We also discuss how to architect secure applications for Amazon EC2.

Transcript of SD Forum Java SIG - Running Java Applications On Amazon EC2

Page 1: SD Forum Java SIG - Running Java Applications On Amazon EC2

Running Java and Grails applications on Amazon EC2applications on Amazon EC2

Chris RichardsonAuthor of POJOs in Action

Founder of Cloud Tools and Cloud FoundryyChris Richardson Consulting, Inc

www.chrisrichardson.netwww.chrisrichardson.net

Page 2: SD Forum Java SIG - Running Java Applications On Amazon EC2

Overall presentation goalp g

Show how to deploy Java and Grails applications on Grails applications on

Amazon Elastic Compute Cloud

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 2

Page 3: SD Forum Java SIG - Running Java Applications On Amazon EC2

About ChrisAbout Chris• Grew up in England and live in Oakland, CA• Over 20+ years of software development

experience including 12 years of Javaexperience including 12 years of Java• Author of POJOs in Action• Speaker at JavaOne, SpringOne, NFJS,

JavaPolis, Spring Experience, etc.• Chair of the eBIG Java SIG in Oakland • Chair of the eBIG Java SIG in Oakland

(www.ebig.org)• Run the Groovy/Grails meetup

(http://java.meetup.com/161)• Run a consulting and training company that u a co su t g a d t a g co pa y t at

helps organizations reduce development costs and increase effectiveness

• Founder of Cloud Tools, an open-source project for deploying Java applications on Amazon EC2: http://code google com/p/cloudtoolshttp://code.google.com/p/cloudtools

• Founder of a startup that provides outsourced, automated, and Java-centric datacenter management on the cloud: www.cloudfoundry.comy

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 3

Page 4: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y gProgramming with AWS

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 4

Page 5: SD Forum Java SIG - Running Java Applications On Amazon EC2

Power generationgPast Present

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 5

Page 6: SD Forum Java SIG - Running Java Applications On Amazon EC2

Computing has come a long wayp g g y

Past PresentPresent

www.computermuseum.org.uk

www.dell.comde co

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 6

Page 7: SD Forum Java SIG - Running Java Applications On Amazon EC2

Yet we rarely have enough hardwarey g

Can we afford the production hardware? Can we afford the production hardware? Do we know how much to buy?How long does it take to buy and install?Can we afford a test lab?Who is going to set it up and take care

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 7

of it?

Page 8: SD Forum Java SIG - Running Java Applications On Amazon EC2

Cloud computingp g

A pool of highly scalable, abstracted A pool of highly scalable, abstracted infrastructure that hosts your application, and is billed by

consumptionpBy James Staten of Forrester Research

AND is managed via a web services API

me

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 8

Page 9: SD Forum Java SIG - Running Java Applications On Amazon EC2

Amazon-Style Cloud Computingy p g

Si l Q S i Si l DBSimple Queue Service (SQS)

Simple DB(name/attribute pairs)

Pay per Elastic Compute Cloud

(EC2)use

services d

( )

Simple Storage Service(S3) Elastic Block Store managed

by Amazon

(S3)

CloudFront

Elastic Block Store(EBS - SAN)

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 9

Amazon(content delivery)

Page 10: SD Forum Java SIG - Running Java Applications On Amazon EC2

Sign upg p

Login using your Login using your existing Amazon accountSelect the web services you want to services you want to useOnly takes a few minutesB t ti But can sometimes be confusing: various ids, keys, certificates etc

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 10

Page 11: SD Forum Java SIG - Running Java Applications On Amazon EC2

Make web service calls…<RunInstancesResponse><reservationId>r-60907709</reservationId><ownerId>556666664445</ownerId><ownerId>556666664445</ownerId>…<instancesSet>

<item><instanceId>i-4ef21327</instanceId><imageId>ami-3795705e</imageId><instanceState>

<code>0</code><name>pending</name>

</instanceState>

https://ec2.amazonaws.com?Action=RunInstances&ImageId=ami-3795705e </instanceState>

<placement><availabilityZone>us-east-1b</availabilityZone>

</placement><dnsName/>

/

&MaxCount=1&MinCount=1…

<reason/><keyName>gsg-keypair</keyName><amiLaunchIndex>0</amiLaunchIndex>

</item></instancesSet>

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 11

/</RunInstancesResponse>

Page 12: SD Forum Java SIG - Running Java Applications On Amazon EC2

… a few minutes later

cer@arrakis ~$ ssh … [email protected] login: Sun Dec 30 18:54:43 2007 from 71.131.29.181[root@domU-12-31-36-00-38-23:~]

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 12

Page 13: SD Forum Java SIG - Running Java Applications On Amazon EC2

Deploying a web application on EC2p y g pp

Tomcat Server(instance 2)

MySQLDB (Slave)

Web Browser Apache Server

HTTP(S)(instance 2)

MySQL

DB (Slave)(instance 5)

(instance 1) DB (Master)(instance 4)

Tomcat Server(instance 3)

MySQLDB (Slave)(instance 6)

EBS Volume

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 13

S3

Page 14: SD Forum Java SIG - Running Java Applications On Amazon EC2

Pay per use computingy p p gVirtual Cores

Compute Units

32/64

Memory Storage $/hr**

/core* Bit

Small 1 1 32 bit 1.7G 160G 0.10

High- 2 2 5 32 bit 1 7G 350G 0 20HighCPUMedium

2 2.5 32 bit 1.7G 350G 0.20

Large 2 2 64 bit 7.5G 850G 0.40a g 6 b 5G 850G 0 0

Extra Large

4 2 64 bit 15G 1690G 0.80

High 8 2 5 64 bit 7G 1690G 0 80High-CPU XL

8 2.5 64 bit 7G 1690G 0.80

* EC2 Compute Unit = 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 14

** Windows more expensive, external bandwidth: $0.10-0.18/Gbyte

Page 15: SD Forum Java SIG - Running Java Applications On Amazon EC2

Operating systemsp g y

Use Amazon provided Machine Image (AMI)32/64-bit Fedora Core 4/6/832/64 bit Fedora Core 4/6/8Windows Server 2003 ($0.125-$2/hour)Optional SQL Server Standard ($1.10-3.20/hour)3.20/hour)

Many 3rd parties have public AMIsVarious Linux distributionsE g Redhat RightScaleE.g. Redhat, RightScale

Sun provides OpenSolarisBuild your own AMI:

Install applications starting with existing AMI and save new AMICreate an AMI from scratch

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 15

Page 16: SD Forum Java SIG - Running Java Applications On Amazon EC2

Using AWS in your applicationg y pp

S3 - Store media etc in S3SQS - messaging between loosely coupled componentsSimpleDB – alternative to RDBMSCloudFront – to distribute contentUsing these APIs

Couples your application to AWSCouples your application to AWSBut using them is optional

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 16

Page 17: SD Forum Java SIG - Running Java Applications On Amazon EC2

Developing on EC2p g

Immediate access to many serversSimplified setupGreat for testingg

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 17

Page 18: SD Forum Java SIG - Running Java Applications On Amazon EC2

Deploying on Amazon EC2 –startups/small businessesp /

Some VCs require it Get up and running quicklyValidate your business idea without:y

Upfront costs Long-term financial commitmentg

Scale up/down with loadReduces the risk of a success Reduces the risk of a success catastrophe

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 18

Page 19: SD Forum Java SIG - Running Java Applications On Amazon EC2

Deploying on Amazon EC2 –enterprisesp

No need to wait for corporate ITIn some companies it can take 2 In some companies it can take 2 months to acquire hardwareRequires a long-term financial commitment upfront costscommitment, upfront costs

Use for short-term projects, e.g.Websites for marketing campaignsg p gNew York Times style projects

Use for applications that have fluctuating loads e gfluctuating loads, e.g.

heavily used once a week, once a month

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 19

Page 20: SD Forum Java SIG - Running Java Applications On Amazon EC2

Example – beer on the cloudp

Grails applicationGrails applicationShort-term marketing marketing campaign siteFluctuating loadFluctuating load

Sat/Sun 4 serversMon-Fri 1 serverMon Fri 1 server

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 20

Page 21: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y gProgramming with AWS

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 21

Page 22: SD Forum Java SIG - Running Java Applications On Amazon EC2

EC2 API and ToolsAmazon provided CLI tools

CLI equivalents of APIsqAMI creation tools

AWS CLI tools from Tim KayCLI for S3 and EC2Alternatives to Amazon CLI tools

AWS ConsoleVery slicky

ElasticFoxAwesome Firefox pluginLaunch and manage instances

S3 OrganizerFirefox pluginManipulate S3 buckets and objects

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 22

Page 23: SD Forum Java SIG - Running Java Applications On Amazon EC2

AWS Management Consoleg

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 23

Page 24: SD Forum Java SIG - Running Java Applications On Amazon EC2

Firefox pluginsp gElasticFox

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 24

S3 Organizer

Page 25: SD Forum Java SIG - Running Java Applications On Amazon EC2

Cloud Tools

Open-source project32 and 64 bit AMIs32 and 64 bit AMIs

Cent OS 5.10Apache/Tomcat/MySQL/JMeter/JetS3t installed

EC2D l f kEC2Deploy frameworkExtensible, object-orientedLaunches instancesConfigures Tomcat, MySQL, ApacheDeploys web applicationsRuns Jmeter tests

•Quicker deployment

Written in GroovyMaven and Grails plugins

Quick and easy deployment to EC2

•More accurate configuration

Quick and easy deployment to EC2

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 25

Page 26: SD Forum Java SIG - Running Java Applications On Amazon EC2

Maven and Grails pluginsp g

mvn cloudtools:deployp y

grails cloud-tools-deploy OROR

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 26

Page 27: SD Forum Java SIG - Running Java Applications On Amazon EC2

Extensible provisioning and management platformg p

Built using Domain Driven DesignMain extension points:

New IaaS clouds N i f t t t /New infrastructure components/servers

Implement interfaces or define subclassessubclasses

Define methods for deploy, start, stop, …Write the scripts Write the scripts

Recently added support for Spring dm server and eXo Portal Server

4/6/2009 Copyright (c) 2009. Chris Richardson Consulting Inc. Confidential 27

Page 28: SD Forum Java SIG - Running Java Applications On Amazon EC2

Cloud Foundryy

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 28

Page 29: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y g

The basicsRunning the web tiergDeploying a databaseHandling securityHigh availability

Programming with AWSg g

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 29

Page 30: SD Forum Java SIG - Running Java Applications On Amazon EC2

Issues with AWS

Security:

Cloud Computing Survey: IT Leaders See Big Promise, Have Big Security Questions

Security:Runs HIPAA compliant apps BUTLack of PCI complianceDiscomfort with sending gcustomer data to a 3rd party

Technology:Not yet suitable for extremely large relational databaseslarge relational databasesLack of very large machines, e.g. 64G memoryLack of multicast and multiple IP addressesaddresses

Financials:Cost of bandwidthSteady state costs > your own h dhardware

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 30

www.cio.com/article/455832/Cloud_Computing_Survey_IT_Leaders_See_Big_Promise_Have_Big_Security_Questions

Page 31: SD Forum Java SIG - Running Java Applications On Amazon EC2

Cost issuesRunning larger servers 24 x 7 looks expensive (e.g. $0.80/hr, $560/month)( g $ / , $ / )

BUT when owning your own hardware

Lack of elasticityLong procurement timeMust buy for the estimated peak loadMust buy for the estimated peak loadMust buy redundant hardwareRisk of a success catastrophe

CostElectricity ($0.07-$0.30 / kWh), cooling, spaceSystem administration costsManagement overhead

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 31

Page 32: SD Forum Java SIG - Running Java Applications On Amazon EC2

Starter website - $$

w w w .acm e.com

EC 2 Instance

E lastic IP A Low cost - $72/month

Elastic - load increases ⇒d i f i tApache

T om cat

expand in a few minutes

Available –instance crashes ⇒replace in a few minutes

M ySQ L

p

EB S V olum e

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 32

Page 33: SD Forum Java SIG - Running Java Applications On Amazon EC2

Higher capacity website - $$g p y $$

www acme com

Elastic IP

www.acme.com

Low cost - > ~$216/month (1 or more Tomcats, 0 or more Slaves)

Apache

Elastic - load changes ⇒ quickly expand/subtract Tomcats with no downtime

Tomcat Tomcat

Available –instance crashes ⇒replace in a few minutes

MySQL(Master)

EBS Volume

MySql (slave)

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 33

Page 34: SD Forum Java SIG - Running Java Applications On Amazon EC2

Batch processing architecturep g

e g media transcodinge.g. media transcoding

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 34

Page 35: SD Forum Java SIG - Running Java Applications On Amazon EC2

Easy upgradesy pg

Clone production environmentMake read-only or turn offSnapshot EBS volumes and create new

lvolumes

Apply upgrades to cloneTest cloneMove elastic IP addresses to cloneTerminate old instances once you are sure that everything works

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 35

Page 36: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y g

The basicsRunning the web tiergDeploying a databaseHandling securityHigh availability

Programming with AWSg g

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 36

Page 37: SD Forum Java SIG - Running Java Applications On Amazon EC2

No hardware load balancingg

Coming in 2009Use software load balancer

ApacheHAProxy…

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 37

Page 38: SD Forum Java SIG - Running Java Applications On Amazon EC2

Elastic IP addresses

Instance IP addresses are dynamically allocated on start-upallocated on start up

Does not work well for publicly accessible services, e.g. a website

Elastic IP addresses:Elastic IP addresses:Statically allocated public IP addressesAssociated with your accountAttached to an instance (e g public facing web Attached to an instance (e.g. public facing web server) = it's public IP addressYou configure DNS to resolve to the elastic IP address

Pricing:Non-attached Elastic IP address - $0.01/hour$0 10 per remap (if > 100 in a month)$0.10 per remap (if > 100 in a month)

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 38

Page 39: SD Forum Java SIG - Running Java Applications On Amazon EC2

Elastic IP address operationsp

Operation Parameters XML document

DescribeAddresses PublicIp.n (optional) List of IP addresses and associated instance idinstance id

AllocateAddress - Public IP address

Release Address Public Ip address -

AssociateAddress InstanceId Public IP AssociateAddress InstanceId, Public IP Address

-

DisasssociateAddress Public IP Address -DisasssociateAddress Public IP Address

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 39

Page 40: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y g

The basicsRunning the web tiergDeploying a databaseHandling securityHigh availability

Programming with AWSg g

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 40

Page 41: SD Forum Java SIG - Running Java Applications On Amazon EC2

Elastic Block Storageg

Local storage is ephemeralM t bl t lMountable storage volumes

"On-demand SAN"Size: 1 GB to 1 TBSize: 1 GB to 1 TBMount on a single instance

Create snapshotspStored in S3Create new volumes from the snapshot

CCost:$0.10/GByte/month$0 10 per 1 million I/O requests$0.10 per 1 million I/O requests

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 41

Page 42: SD Forum Java SIG - Running Java Applications On Amazon EC2

Using EBS Volumesg

AWS:CreateVolume Size=50G

mkfs xfs /dev/sdh

CreateVolume Size=50GAttachVolume InstanceId=… Device=/dev/sdh

mkfs.xfs /dev/sdhecho "/dev/sdh /vol xfs noatime 0 0" >> /etc/fstabmkdir /volmount /volmount /volmkdir /vol/lib /vol/logmv /var/lib/mysql /vol/lib

[mysql.server]user=mysqlbasedir /vol/lib

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 42

basedir=/vol/lib

Page 43: SD Forum Java SIG - Running Java Applications On Amazon EC2

Backing up your databaseg p y

mysqldump --add-drop-database --databases foo | gzip > backup.sql.gznow=`date +%d%m%y_%H%M`aws put $bucket/${object}_${now}.sql.gz backup.sql.gzaws copy $bucket/${object}_latest $bucket/${object}_${now}.sql.gz

FLUSH TABLES WITH READ LOCKSHOW MASTER STATUS

xfs_freeze -f /vol

# AWS WS: CreateSnapshot

xfs freeze -u /volxfs_freeze u /vol

UNLOCK TABLES

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 43

Page 44: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y g

The basicsRunning the web tiergDeploying a databaseHandling securityHigh availability

Programming with AWSg g

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 44

Page 45: SD Forum Java SIG - Running Java Applications On Amazon EC2

Security benefits of cloud computingp g

Leverages the world class security techniques of amazon.comCloud infrastructure enables:

Unlimited loggingAbility to test changes on a cloneClone servers and volumes for forensic analysis

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 45

Page 46: SD Forum Java SIG - Running Java Applications On Amazon EC2

The usual security best practicesy p

Turn off unused servicesFile ownership and permissionsDisabling password based ssh loging p gStandard Linux, Apache, Tomcat and MySQL best practicesy Q p

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 46

Page 47: SD Forum Java SIG - Running Java Applications On Amazon EC2

Network securityy

Cannot sniff traffic for other instancesUse EC2 firewall – aka. security groupsConsider encrypting network trafficLimit SSH access to only your locationy y

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 47

Page 48: SD Forum Java SIG - Running Java Applications On Amazon EC2

Security Groupsy pNamed set of firewall rules associated with your accountAn instance

Belongs to one or more security groupsDefaults to “default” security groupg

Permits inbound trafficProtocol: tcp, udpRange of ports

?Action=RunInstances&SecurityGroup.1=g1&SecurityGroup.2=g2

From:Anywhere – specific port rangeAn IP address (range) – specific port rangeAnother group - all ports

Common usagePort 80 (http)/443 (https) – anywhere

When you first signup don’t forget to enable

ffPort 22 (ssh) – just from your location

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 48

SSH traffic

Page 49: SD Forum Java SIG - Running Java Applications On Amazon EC2

Using security groupsg y g p

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 49

Page 50: SD Forum Java SIG - Running Java Applications On Amazon EC2

Use a software firewall

E.g. iptablesIn addition to security groups

Security Group: Tomcat Servers are only accessible from Apache Serveriptables: Tomcat servers only allow port 22 and po t 8009 (AJP)22 and port 8009 (AJP)

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 50

Page 51: SD Forum Java SIG - Running Java Applications On Amazon EC2

Storage securityg y

Amazon wipes disks so one customer cannot see another’s dataBut

You don’t know where it isAmazon could be subpoena’d

Consider encrypting dataEncrypted file systemsEncrypting sensitive data in DBEncrypting backups in S3

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 51

Page 52: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y g

The basicsRunning the web tiergDeploying a databaseHandling securityHigh availability

Programming with AWSg g

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 52

Page 53: SD Forum Java SIG - Running Java Applications On Amazon EC2

Deploying highly available applicationspp

AWS has had very well publicized outages

BUT…Is internal IT really any better?In reality: AWS is (more) reliabley ( )Don’t forget:

You are not responsible for the hardwareYou are not responsible for the hardwareInstance fails ⇒ Launch a new one in a few minutes

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 53

Page 54: SD Forum Java SIG - Running Java Applications On Amazon EC2

But once in a blue moonFrom: Amazon EC2 Notification [email protected]: Notice: Degraded Amazon EC2 InstanceTo: XXXXX@yahoo comTo: [email protected]: Friday, January 23, 2009, 5:54 AMHello,

We have noticed that one or more of your instances are running on a hostdegraded due to hardware failuredegraded due to hardware failure.

i-5e0b8b34

The risk of your instances failing is increased at this point. We cannotdetermine the health of any applications running on the instances. We recommendthat you launch replacement instances and start migrating to them.

Feel free to terminate the instances with the ec2-terminate-instance API whenyou are done with them.

Let us know if you have any questionsLet us know if you have any questions.

Sincerely,

The Amazon EC2 Team

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 54

Page 55: SD Forum Java SIG - Running Java Applications On Amazon EC2

Can't migrate internal IP addressesg

Instance has one fixed, internal IP addressaddressUsing Elastic IP = $

ThereforeThereforeHandling active/standby failover is difficult:

E.g. Cannot migrate IP address of failed database to standby database

Have your own host namesHave your own host namesUpdate /etc/hostsRun DNS server

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 55

Page 56: SD Forum Java SIG - Running Java Applications On Amazon EC2

No multicast for resource discoveryy

Prevents the use of standard clustered resource discovery

E.g. JGroups etc

Use a registry: DatabaseSimpleDBSecurity groups…

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 56

Page 57: SD Forum Java SIG - Running Java Applications On Amazon EC2

Regions and availability zonesg y

By default, your database By default, your database master and slave could run on the same physical host!Regions - geographically dispersed locations

us-east-1

eu-west-1p

Availability zone -engineered to be insulated from failure in other zonesSpecify availability zone

us-east-1a, eu-

west-1ap y ywhen launching instancesSLA with 99.95% availability with multiple availability zones

us-east-1b

west 1a

You pay for inter-zone network traffic us-east-

1c

eu-west-1b

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 57

Page 58: SD Forum Java SIG - Running Java Applications On Amazon EC2

Amazon EC2 SLA*

99.95% availability if you are using >1 availability zoneAvailability

Instances have external connectivityYou can launch new instances

Service credit for not meeting SLA

* Read the small print

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 58

Page 59: SD Forum Java SIG - Running Java Applications On Amazon EC2

Regions and Availability Zones APIg y

Operation Parameters XML document

DescribeRegions Region.n (optional) List of region names and urls

DescribeAvailabilityZones ZoneName n List of availability zones DescribeAvailabilityZones ZoneName.n List of availability zones and state

https://<region>.ec2.amazonaws.com?Action=RunInstances&Placement.AvailabilityZone=<availabilityZone>

https://ec2.amazonaws.com?Action=RunInstances&Placement AvailabilityZone <availabilityZone>

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 59

&Placement.AvailabilityZone=<availabilityZone>

Page 60: SD Forum Java SIG - Running Java Applications On Amazon EC2

Highly available - $$$g y $$$

www.acme.com Higher cost - > ~$

Availability Zone A Availability Zone B

Elastic IP A Elastic IP B

Higher cost > $ 360/month (2 Apaches, 2 MySqls, 1 or more Tomcats, 0 or more Slaves)

El ti l d h

Apache Apache

Elastic - load changes ⇒quickly expand/subtract Tomcats with no downtime

Available – No SPOF, instance

TomcatTomcat Tomcat

Tomcat

,crashes ⇒ replace in a few minutes

MySQL(Master 1)

MySQL(Master 2)

EBS Volume EBS Volume

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 60

EBS Volume

Page 61: SD Forum Java SIG - Running Java Applications On Amazon EC2

Agendag

Amazon-style cloud computingUsing Amazon EC2Deploying on Amazon EC2p y gProgramming with AWS

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 61

Page 62: SD Forum Java SIG - Running Java Applications On Amazon EC2

Using AWS in your applicationg y ppAccess instance meta dataSimple Storage Service (S3)Simple Storage Service (S3)

Stores blobs of dataEg. Photo sharing websiteStore mediaHand out URLs to S3 objects

Simple Queue Service (SQS)Hosted queue-based messaging systemq g g yAlternative to JMSLoosely coupling between systems

SimpleDBSchema-less non-relational databaseStore data setsExecute queries

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 62

Page 63: SD Forum Java SIG - Running Java Applications On Amazon EC2

Eventual consistencyy

AWS is distributedData is replicated among many nodesData is replicated among many nodesReplication takes timeUpdates eventually appear

Why?CAP theorem by BrewerPick two: consistency, availability, Pick two: consistency, availability, partitioning

Example:S3 a GET might not see a PUTS3 – a GET might not see a PUTSQS – reading from a queue might not retrieve recently added messages…

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 63

Page 64: SD Forum Java SIG - Running Java Applications On Amazon EC2

Instance meta data

Instance can find out:f b lfInformation about itself

User data supplied by user at launch timeEnables a generic AMI to customize itself gdynamicallyAvailable data includes:

user-datauser datasecurity-groupspublic-hostnameplacement/availability-zoneplacement/availability zone…

curl http://169.254.169.254/2008-12-01/meta-data/<<data type>>

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 64

Page 65: SD Forum Java SIG - Running Java Applications On Amazon EC2

Amazon Simple Storage Service (S3)p g ( )

Flat storage model consisting of buckets and objectsand objectsBucket

has a name e g <AccessKey> <name>has a name, e.g. <AccessKey>.<name>contains objects

Objects jHas a key, e.g. mypicture.jpgStores 1 byte - 5G

Si l ti hi hi l fil tSimulating a hierarchical file-systemObject key can look like a path ☺presentations/february09/aws pptpresentations/february09/aws.ppt

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 65

Page 66: SD Forum Java SIG - Running Java Applications On Amazon EC2

S3 REST API

PUT / HTTP/1.1Create a bucket

PUT /<ObjectName> HTTP/1 1

Host: <BucketName>.s3.amazonaws.com …

Create a bucket

PUT /<ObjectName> HTTP/1.1Host: <BucketName>.s3.amazonaws.com ……Bytes…

Create an item in a bucket

GET /<ObjectName> HTTP/1.1Host: <BucketName>.s3.amazonaws.com … Download an item

DELETE /<ObjectName> HTTP/1.1Host: <BucketName>.s3.amazonaws.com

Delete an item

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 66

… Delete an item

Page 67: SD Forum Java SIG - Running Java Applications On Amazon EC2

Amazon CloudFront

Content delivery networkOriginal content stored in S3 bucketRegister publically accessible bucket

ith Cl dF t i d i with CloudFront ⇒ unique domain name (foo1234.cloudfront.net)Content accessed through that Content accessed through that domain name is delivered by geographically distributed edge geographically distributed edge servers

http:// foo1234.cloudfront.net/i/bar.jpg k / /b⇒ <BucketName>/i/bar.jpg

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 67

Page 68: SD Forum Java SIG - Running Java Applications On Amazon EC2

SimpleDB modelp

DomainHas a nameContains items

id description color

123 jeans blue, black

Item:Has a name

456 shoes red, white

Has one or more attributes

Attribute:Has a nameHas one or more values

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 68

Page 69: SD Forum Java SIG - Running Java Applications On Amazon EC2

Simple DB modelpIt’s not a relational database

No joinsEventual consistency - updates eventually appearNo transactions – single item updateNo locking

LimitsLimits100 domains per account250,000,000 attribute name-value pairs per domain256 attribute name-value pairs per itemQueries return …

Pricing:Machine utilization: $0 14/hour after first 25 free Machine utilization: $0.14/hour after first 25 free hours/monthFees for data transfer in and out (Free for access from EC2)

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 69

Page 70: SD Forum Java SIG - Running Java Applications On Amazon EC2

SimpleDB Operationsp pSOAP and REST APIDomains: Create/List/DeleteDomains: Create/List/DeletePutAttributes

DomainNameAttributeNameAttributeNameAttribute.N.Name/Attribute.N.ValueAttribute.N.Replace – add or replace

DeleteAttributesDomainNameAttributeNameAttribute.N.Name/Attribute.N.Value

GetAttributesDomainNameAttributeName.n

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 70

Page 71: SD Forum Java SIG - Running Java Applications On Amazon EC2

SimpleDB Select queriesp q

“SQL-like” Select query languageVarious limitations

Sort by attribute must appear in where clause and select list…

select * Select operation

SelectExpression

select * from domainNamewhere SomeAttribute > 2order by SomeAttributelimit 10

NextTokenlimit 10

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 71

Page 72: SD Forum Java SIG - Running Java Applications On Amazon EC2

SimpleDB custom queriesp q

Query[‘SomeAttribute’ > 2]

DomainQueryExpresssion

[ SomeAttribute > 2] sort ‘SomeAttribute’

Pagination with: MaxNumberOfItems/NextTokenR t It NReturns ItemNames

QueryWithAttributesAdd A ib N ( i l)Adds AttributeName.n (optional)Returns values

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 72

Page 73: SD Forum Java SIG - Running Java Applications On Amazon EC2

Using SimpleDBg pReplace joins by denormalizing/duplicating data

E.g. Duplicate child data in parent in parent-child l i hirelationship

E.g. http://blog.adaptiveblue.com/?p=1145People-Interaction-Thing (1-N N-1)Store Interaction in People and in ThingStore Interaction in People and in Thing

Parallelize SimpleDB requestsAn application should/could issue multiple requests in parallel

d l l dPartition data across multiple domainsE.g. People1, People2Improves performance

Use SimpleDB when:Use SimpleDB when:You can tolerate inconsistenciesYou don’t need transactionsi.e. bad for banking but good for social network, read i t i d tintensive data

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 73

Page 74: SD Forum Java SIG - Running Java Applications On Amazon EC2

Amazon SQSQQueues:

As many as you wantUnlimited sizeMessages deleted after 4 daysAWS might delete queues that are idle for > 30 daysMessage are to 8Kb (store binary and larger messages in Message are to 8Kb (store binary and larger messages in S3 or SimpleDB)

Semantics of distributed queuingOrder is not guaranteed

lAt-least onceReceiveMessage returns messages from a subset of servers, e.g. possibly no messages

Pricing:g$0.000001 per Request$0.100 per GB – all data transfer in$0.170-0.100 per GB – data transfer out

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 74

Page 75: SD Forum Java SIG - Running Java Applications On Amazon EC2

SQS API detailsQSOAP API onlyManaging queriesManaging queries

Create/List/Delete QueuesSending a Message

SendMessageSendMessageProcessing a message

ReceiveMessageDeleteMessagee ete essageVisibility timeout: a received message that is not deleted within the timeout will reappear

Queue attributesSetQueueAttributes/GetQueueAttributesApproximateNumberOfMessagesVisibilityTimeout

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 75

Page 76: SD Forum Java SIG - Running Java Applications On Amazon EC2

Java libraries for AWS

JetS3tJetS3tRich API for accessing S3jets3t.dev.java.net/j j

TypicaAPI for SQS, EC2, SimpleDBcode.google.com/p/typica

SimpleJPASubset of JPA on Subset of JPA on Simple DBcode.google.com/p/simplejpa

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 76

Page 77: SD Forum Java SIG - Running Java Applications On Amazon EC2

Summaryy

Amazon-style cloud computing providesImmediate access to a scalable infrastructureP f t Pay as you go – no upfront investment/commitment requiredEasily scale up/downEasily scale up/downOptional AWS services

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 77

Page 78: SD Forum Java SIG - Running Java Applications On Amazon EC2

Final thoughtsg

Download or contribute to Cloud Tools today :y

www.cloudtools.org

Checkout Cloud Foundry:

www cloudfoundry comwww.cloudfoundry.com

Buy my book ☺

Send email:

[email protected]

Visit my website:

www.chrisrichardson.net

Talk to me about consulting and training

Phone: 510 904 9832

Copyright (c) 2009 Chris Richardson. All rights reserved. Slide 78