顯示具有 aws 標籤的文章。 顯示所有文章
顯示具有 aws 標籤的文章。 顯示所有文章

2014/02/18

AWS VPC 設定教學

在 AWS VPC(Virtual Private Cloud) 介紹中列了四種 scenario,在此以 Scenario 2: VPC with Public and Private Subnets 為例來說明操作過程。
整個過程會建立 public, private 兩個 subnet,public subnet 用來放置對外服務的 instance 具有 public IP,如 web server。而 private subnet,只允許 VPC 內部存取,如 database。


Create VPC

1. 建立 VPC,指定 CIDR block 爲 10.0.0.0/16
Local IP 位址從 10.0.0.0 - 10.0.255.255 共 256*256 個 IP


2. 切兩個 subnet
Public subnet CIDR: 10.0.0.0/16,IP 從 10.0.0.0 - 10.0.0.255
Private subnet CIDR: 10.0.1.0/16,IP 從 10.0.1.0 - 10.0.1.255
預設所有在 VPC 底下任何 subnet 的 IP 都可以互通

2013/04/01

AWS Auto Scaling 自動擴展(二)

延續上篇:AWS Auto Scaling 自動擴展(一),auto scaling 除了可以根據 EC2 instance 狀態,或是 ELB 的健康狀況做擴展,還可以搭配 CloudWatch 使用,CloudWatch 可以 monitor 的狀態有更多了,CPU、disk I/O、network I/O。

Scale up

Create auto scaling policy
$ aws autoscaling put-scaling-policy \
--policy-name as-policy-scale-up \
--auto-scaling-group-name as-group \
--adjustment-type ChangeInCapacity \
--scaling-adjustment 1 \
--cooldown 300

{
    "ResponseMetadata": {
        "RequestId": "4411e437-9b6a-11e2-933c-010eb2f029e6"
    },
    "PolicyARN": "arn:aws:autoscaling:us-east-1:332100208493:scalingPolicy:c534dcbe-91c1-4714-907a-b4974bac7c57:autoScalingGroupName/as-group:policyName/as-policy-scale-up"
}
把 PolicyARN 記下來,下一步會用到

Create cloud watch to monitor the CPU utilization
When the average CPU usage more than 60% and keep 600 seconds, then scale up
$ aws cloudwatch put-metric-alarm \
--evaluation-periods 1 \
--namespace "AWS/EC2" \
--comparison-operator GreaterThanThreshold \
--alarm-name alarm-high-cpu \
--statistic Average \
--threshold 60 \
--period 600 \
--metric-name CPUUtilization \
--alarm-actions arn:aws:autoscaling:us-east-1:332100208493:scalingPolicy:c34f62a8-bb82-4430-9390-67468a7a65f9:autoScalingGroupName/as-group:policyName/as-policy-scale-up


可以做個實驗,用 shell script 寫個 while loop 把 CPU 拉高,果然 10 分鐘後 alarm 就發生了,也會順便執行 scale-up 的 action


Scale down

Create auto scaling policy
$ aws autoscaling put-scaling-policy \
--policy-name as-policy-scale-down \
--auto-scaling-group-name as-group \
--adjustment-type ChangeInCapacity \
--scaling-adjustment -1 \
--cooldown 300
{
    "ResponseMetadata": {
        "RequestId": "c58093f7-9b6b-11e2-82fc-2bb2a883e37c"
    },
    "PolicyARN": "arn:aws:autoscaling:us-east-1:332100238493:scalingPolicy:141d692b-9ae8-4ef8-8d98-7de605c3fe04:autoScalingGroupName/as-group:policyName/as-policy-scale-down"
}

Create cloud watch to monitor the CPU utilization
When the average CPU usage less than 40% and keep 600 seconds, then scale down
$ aws cloudwatch put-metric-alarm \
--evaluation-periods 1 \
--namespace "AWS/EC2" \
--comparison-operator LessThanThreshold \
--alarm-name alarm-low-cpu \
--statistic Average \
--threshold 40 \
--period 600 \
--metric-name CPUUtilization \
--alarm-actions arn:aws:autoscaling:us-east-1:332100238493:scalingPolicy:141d692b-9ae8-4ef8-8d98-7de605c3fe04:autoScalingGroupName/as-group:policyName/as-policy-scale-down


有一些疑問
Scale-up 會增加到多少台?Scale-down 會減至多少台?
CloudWatch 不會重複 trigger,除非狀態從 alarm 回到 normal。


參考資料
Llovizna: Auto Scaling With Amazon EC2

2013/03/31

AWS Auto Scaling 自動擴展(一)

AWS Auto Scaling 是用來處理 application 擴充性問題,根據當下的忙碌狀況來增減 instance。需要搭配 ELB 或是 CloudWatch 使用。

ELB (Elastic Load Balance) 的原理類似 DNS round-robin,在同一個 domain name 上綁定多組 instance IP,讓外部的 request 可以分散到各 instance 去處理。ELB 也會定期對底下的 instance 做 healthy check,若發現 instance 有問題,則 dispatch 時就會掠過這台,而 Auto Scaling 也會根據這個結果去 launch 新的 instance 並掛載 ELB 底下。ELB 下的 instance 是沒有上限值的。




Setup Auto Scaling

Auto Scaling 目前尚未提供 web 界面,只能用 command line 的方式去設定,在開始之前,請確定已經透過 web 設定好:
  • Create Image for a instance (ImageID: ami-7061fb19) 
  • Create ELB (with/without instance) (Load Balance Name: webserver)

Create auto scaling configuration
$ aws autoscaling create-launch-configuration \
--launch-configuration-name as-config \
--image-id ami-7061fb19 --instance-type t1.micro

Show the auto scaling configuration
$ aws autoscaling describe-launch-configurations

Create auto scaling group
$ aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name as-group \
--launch-configuration-name as-config \
--availability-zones us-east-1a \
--load-balancer-names webserver \
--max-size 3 --min-size 2 \
--default-cooldown 300
這個指令一執行,auto scaling 就被啟動了。

為了避免 instance 重複被 launch,有個時間參數設定很重要:
  • --default-cooldown (integer)
    The amount of time, in seconds, after a scaling activity completes before any further trigger-related scaling activities can start.
這個時間至少要大於服務啓動的時間
服務啓動時間 = EC2 開機時間 + Web Service 啓動時間 (+ ELB check health 的時間)

Show the auto scaling group
$ aws autoscaling describe-auto-scaling-groups

照上面的設定最少會有 2 台 instance 在 list 上
            "Instances": [
                {
                    "InstanceId": "i-e0a77c8c",
                    "AvailabilityZone": "us-east-1a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "Pending",
                    "LaunchConfigurationName": "as-config"
                },
                {
                    "InstanceId": "i-e2a77c8e",
                    "AvailabilityZone": "us-east-1a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "Pending",
                    "LaunchConfigurationName": "as-config"
                }
            ],

Verify
可以試著把任一台 instance stop,auto scaling 機制偵測到後又會 launch 一台新的,並且掛到 ELB 底下。




Monitor ELB healthy

Create auto scaling group 時,預設是對每個 instance 做 healthy check,若要改為 check ELB,則要加上兩個參數:
  • --health-check-type ELB
  • --health-check-grace-period 60
$ aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name as-group \
--launch-configuration-name as-config \
--availability-zones us-east-1a \
--load-balancer-names webserver \
--max-size 3 --min-size 2 \
--health-check-type ELB --health-check-grace-period 300

Verify
可以試著讓 ELB 的狀態變成 unhealthy,在此我的 ELB 狀態是去 check 各 instance 的 web service,所以我把全部的 instance web service都停止,果真會掛 instance 上來。

但我對於這邊的行為還沒完全掌握,當沒有一台 instance 能夠服務時,那些不能服務的 instance 從 ELB list 中移除並 terminate,auto scaling 會 detect 到,並且循序 launch 一台新的 instance,直到 ELB 正常為止,但如果 service 是因為太忙碌不是掛掉,應該要加更多的 instance 上去而不是移除。



Stop Auto Scaling

Update group setting
$ aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name as-group \
--min-size 0 --max-size 0

如果不更新就直接刪除,會有 error message: You cannot delete an AutoScalingGroup while there are instances or pending Spot instance request(s) still in the group.

Detete auto scaling group
$ aws autoscaling delete-auto-scaling-group --auto-scaling-group-name as-group

要注意一點,刪除 auto scaling group 後,所有的 instance 都會被 terminate!



參考資料

2013/03/30

使用 Command Line Tool 建立 AWS EC2 Instance

AWS 以已經有提供 web 界面可以操作了,為何還要使用 command line 呢?答案是為了自動化的過程。Auto scaling 就是一個很好的例子。


Install AWS Command Line Interface

It run in Python environment, and installed by pip.
$ pip install awscli


Setup credential and region

Method 1
$ vim ~/.aws.conf
aws_access_key_id=AKIAIJQ7YGMRQTBIH7HJ
aws_secret_access_key=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
region=us-east-1
$ export AWS_CONFIG_FILE=~/.aws.conf

Method 2
$ export AWS_ACCESS_KEY_ID=AKIAIJQ7YGMRQTBIH7HJ
$ export AWS_SECRET_ACCESS_KEY=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
$ export AWS_DEFAULT_REGION=us-east-1

若沒有設定好,則會出現下面的 error
Unable to locate credentials
You must specify a region or set the AWS_DEFAULT_REGION environment variable.


Create Instance

$ aws ec2 run-instances --image-id ami-002bf169 --min-count 1 --max-count 1 \
--instance-type m1.small --placement '{"availability_zone":"us-east-1a"}'
{
    "OwnerId": "132130202433",
    "ReservationId": "r-ec8f2587",
    "requestId": "05125c46-dfbd-4ef4-89a8-0efe6f59ba87",
    "Groups": [
        {
            "GroupName": "default",
            "GroupId": "sg-2337df4f"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": "",
            "KernelId": "aki-825ea7eb",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-03-30T02:58:42.000Z",
            "ProductCodes": [],
            "StateTransitionReason": "",
            "InstanceId": "i-ff16069f",
            "ImageId": "ami-002bf169",
            "PrivateDnsName": "",
            "SecurityGroups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-2437df4f"
                }
            ],
            "ClientToken": "",
            "InstanceType": "m1.small",
            "NetworkInterfaces": [],
            "Placement": {
                "Tenancy": "default",
                "GroupName": "",
                "AvailabilityZone": "us-east-1a"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "VirtualizationType": "paravirtual",
            "RootDeviceType": "instance-store",
            "AmiLaunchIndex": 0
        }
    ]
}

image-id 就是 AMI 的 id,它可以是 My AMI 也可以是 Community AMI


列出目前所有的 instance
$ aws ec2 describe-instances


關於 ec2 的操作,更詳細的可以看
$ aws ec2 help
$ aws ec2 run-instances help


Reference

2013/01/28

AWS S3 Expiration 與 Lifecycle

最近在使用 Amazon S3 (Simple Storage Service) 時有個需求,就是要讓檔案放過久的檔案自動從 S3『移除』。
一開始有點搞錯方向,一直往 expiration 的方向去找,後來才知道要用 lifecycle 才對。


Expiration:

針對某個 object 產生特定的 URL 讓使用者存取,此 URL 是有期限的,期限到了就會失效,但 object 仍然會保留在伺服器上,同一個 object 可以產生多組 URL。


Lifecycle:

針對某個 prefix 下的 object 去設定其 lifecycle,期限一到這些 object 就會安排到 queue 裡面去準備刪除。
同一個 bucket 之下 Lifecycle Configuration Rules 只能設定 1000 條,所以 object 的命名就很重要了。
期限的設定有兩種,一種是絕對時間(ex: 2022-10-12T00:00:00.000Z),一種是存放時間(從上傳到S3那一刻開始算起,ex: 365 days),


Lifecycle implement 的方法

先參考:
Object Lifecycle Management - Amazon Simple Storage Service
Manage Object Lifecycle Using the REST API

基本上就是把下面格式的 XML 以 PUT 的方式送到 http://bucketname.s3.amazonaws.com/?lifecycle

  
    rule_id
    logs/
    Enabled
    
      365
      GLACIER
    
    
      3650
    
  

上例就是設定 logs 底下的 object 在 365天後轉移到 Glacier,並在3650天後自動刪除。
Glacier 是 AWS 另一個儲存的服務,可以針對不常用的大型檔案,以 archive 的方式從 S3 轉移到 Glacier,價格低廉但取回的時間較長。

2012/05/13

讓 SimpleDB 支援 paging (offset)

在 implement page 的時候通常會用到 SQL 語法的"offset"
取第一頁:
SELECT * FORM `article` OFFSET LIMIT 10
取第二頁:
SELECT * FORM `article` OFFSET LIMIT 10 OFFSET 10
取第三頁:
SELECT * FORM `article` OFFSET LIMIT 10 OFFSET 20

但 AWS SimpleDB 並不支援 offset 這個與法,必須要用 next_token 方式來取
以下用python boto library做個示例:
sdb_conn = SDBConnection(...)

# Skip first 20 items
query = "SELECT COUNT(*) FORM `article` OFFSET LIMIT 20"
rs = sdb_conn.select(sdb_domain, query=query)

# Get target page
query = "SELECT * FORM `article` OFFSET LIMIT 10"
rs2 = sdb_conn.select(sdb_domain, query=query, next_token=rs.next_token)
for item in rs2:
    ...

"SELECT COUNT(*)" 是最有效率的略過方法,如果用"SELECT * "則會有 return 2500 rows 的限制!


 參考資料

2012/03/29

SimpleDB - "Too many value tests per predicate in the query expression"

當用Simple下Querey的時候,condition超過20個就會出現下面的錯誤
Too many value tests per predicate in the query expression

Client error : Too many value tests per predicate in the query expression.

像這類的語法都不行:
SELECT * FROM domain WHERE id='1' OR id='2' OR ... id='20' OR id='21'

SELECT * FROM domain WHERE id in ('1', '2', ... '20', '21')

SELECT * FROM domain WHERE id in ('1', '2', ... '20') OR id in ('21', ...)

只能考慮分批一次抓20個,然後再合併處理。



2012/05/07 發現一種可以破解20個條件限制的辦法:
SELECT * FROM `domain` WHERE 
  account in ('key1', 'key2', 'key3', 'key4', 'key5', 'key6', 'key7', 'key8', 'key9', 'key10', 
    'key11', 'key12', 'key13', 'key14', 'key15', 'key16', 'key17', 'key18', 'key19', 'key20') OR 
  dummy IS NOT NULL OR 
  account in ('key21', 'key22', 'key23', 'key24', 'key25', 'key26', 'key27', 'key28', 'key29', 'key30', 
    'key31', 'key32', 'key33', 'key34', 'key35', 'key36', 'key37', 'key38', 'key39', 'key40')
沒錯,就是加了"OR dummy IS NOT NULL"這個多餘的條件在中間就可以下達多個條件了!

不過當你有這樣的需求時,就應該想一下是不是設計面有問題,或是該用 relational database了。



參考資料
Amazon SimpleDB » Developer Guide » Amazon SimpleDB Concepts » Limits
Query 101: Building Amazon SimpleDB Queries

2011/10/26

AWS Toolkit for Eclipse

AWS Toolkit for Eclipse

安裝時出現下面錯誤訊息:
Cannot complete the install because one or more required items could not be found.
Software currently installed: Amazon SimpleDB Management 1.0.0.v201110211341 (com.amazonaws.eclipse.datatools.enablement.simpledb.feature.feature.group 1.0.0.v201110211341)
Missing requirement: Eclipse Data Tools Platform Amazon SimpleDB UI Plug-in 1.0.0.v201110211341 (com.amazonaws.eclipse.datatools.enablement.simpledb.ui 1.0.0.v201110211341) requires 'bundle org.eclipse.datatools.sqltools.sqlscrapbook 1.0.0' but it could not be found
Cannot satisfy dependency:
From: Amazon SimpleDB Management 1.0.0.v201110211341 (com.amazonaws.eclipse.datatools.enablement.simpledb.feature.feature.group 1.0.0.v201110211341)
To: com.amazonaws.eclipse.datatools.enablement.simpledb.ui [1.0.0.v201110211341]

錯誤訊息是說缺少了 Eclipse Data Tools Platform Amazon SimpleDB UI Plug-in,但我從Eclipse Data Tools Platform (DTP)下載最新的套件還是不足。

最後直接去下載Eclipse IDE for Java EE Developers,這個版本的eclipse內建的plug-in比較完整。
再次安裝aws toolkit就可以成功了!


參考資料:
AWS Developer Forums: Eclipse AWS Toolkit install error. ...
having hard time install AWS toolkit for java and eclipse - HPCS