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/03/27

memcached 常用指令

Telnet command

> set foo 0 60 3
bar
STORED


> get foo
VALUE foo 0 3
bar
END
add, replace 與 set 的用法一樣,只是 add 遇到 key 已經存在則 return error,replace 遇到 key 不存在則 return error。


> delete foo
DELETED


> flush_all
OK


> stats
STAT pid 30845
STAT uptime 427550
STAT time 1363069077
STAT version 1.4.6
STAT libevent 2.0.7-rc
STAT pointer_size 64
STAT rusage_user 0.068989
STAT rusage_system 0.086986
STAT curr_connections 5
STAT total_connections 506
STAT connection_structures 7
STAT cmd_get 10
STAT cmd_set 19
STAT cmd_flush 1
STAT get_hits 8
STAT get_misses 2
STAT delete_misses 1
STAT delete_hits 1
STAT incr_misses 0
STAT incr_hits 0


> stats slabs
STAT 1:chunk_size 96
STAT 1:chunks_per_page 10922
STAT 1:total_pages 1
STAT 1:total_chunks 10922
STAT 1:used_chunks 9442
STAT 1:free_chunks 490
STAT 1:free_chunks_end 990
STAT 1:mem_requested 875108
STAT 1:get_hits 5987916
STAT 1:cmd_set 182569
STAT 1:delete_hits 16
STAT 1:incr_hits 0
STAT 1:decr_hits 0
STAT 1:cas_hits 0
STAT 1:cas_badval 0
STAT 2:chunk_size 120
STAT 2:chunks_per_page 8738
STAT 2:total_pages 2


> stats cachedump 1 1000
ITEM test1 [133 b; 1352958262 s]
ITEM test2 [10 b; 1352958262 s]
ITEM test3 [10 b; 1352958262 s]
ITEM test4 [15 b; 1352958262 s]
ITEM test5 [11 b; 1352958262 s]



內建的 tool

Show states
$ memstat --servers=localhost
         pid: 7848
         uptime: 11912375
         time: 1364870637
         version: 1.4.6
         libevent: 2.0.7-rc
         pointer_size: 64
         rusage_user: 1193.212604
         rusage_system: 4398.974254
         curr_connections: 184
         total_connections: 930825
         connection_structures: 249
         cmd_get: 168874575
         cmd_set: 6459571
         cmd_flush: 0
         get_hits: 158956302
         get_misses: 9918273
         delete_misses: 1
         delete_hits: 401
         ...

Dump all keys
$ memdump --servers='localhost'
KEY1
KEY2
...

Cat a set of key values
$ memcat --servers='localhost' TEST --verbose
key: TEST
flags: 0
length: 3
value: 123

How to dump memcache key/value pairs fast - dump the key values in parallel mode


Copy a set of files to a memcached.
The key names will be the names of the files, without any directory path.
$ ls
test.1   test.2   test.3
$ memcp --servers='localhost' test.*
$ memdump --servers='localhost'
test.1
test.2
test.3

2013/03/26

談 Coding Style 與 Naming Convention

工作三年,回頭再來看看一些寫程式的基本 guideline,深深覺得小時候沒學好...

一個程式的週期不只有 key in 程式碼而已,包含了requirement、design、implementation、testing、maintenance。有一些好習慣從平常就要養成,習慣不好,程式寫得再快都沒有用,日後有可能在 maintenance 時就賠上了大半時間。

為了讓自己可以安穩的睡一覺,還是趁早把基礎打好吧。在網路上已經有很多現成的 rule 可以依循,不需要自己發明,除非用了以後發現有更適合自己的地方。



Coding Style

有句話是這麼說的:任何人都可以寫得出電腦看得懂的程式,但要讓『人』看得懂,不是一件容易的事情!
Run 比較久公司,可能內部自己就有一套 coding style,也可以在 google 搜尋一些 keyword: coding style, coding standard, programing guideline

自己就看得順眼的先找一套來使用吧,我自己寫 C 語言比較多,follow 的 style 比較偏向 K&R。

比較強的 IDE 都有內建排版,像是 Eclipse 預設就有 K&R、BSD、GNU...等方式,也可以根據樣板再去做修改,透過軟體排版會快很多。



Naming Convention (Naming Rule)

好的命名法對於程式可讀性是會大大加分的,其範疇包含了程式內部變數、檔案名稱、外部參數,其實命名法也沒有一個制式規定,但有一些約定成俗的法則。
最常聽到的應該是『匈牙利命名法』,有很清楚的規範,但如果完全照著走就會發現變數變得很冗長...
另外還有『駝峰式命名法』也是常見的


根據不同的語言、平台,都有自己的一套命名法,這些『約定成俗』的名稱,我還沒辦法整理出可以遵循的 rule,真的得靠臨摹別人的程式來習得,多看一些 open source project 吧。



Documentation

Programer 好像都蠻討厭寫文件的,但很抱歉,你可能需要開 API 給別人,日後需要轉交給同事,或是自己因為時間久了也會忘記,所以寫文件真的蠻必要的。
Software design document (SDD) 算是我有認為比較常用的一種,裡面包含了 data design、architecture design、interface design、procedural design。但真正常用的還是只有 data structure 與 API,這時候就要介紹一下 doxygen,也就是把文件跟 code 結合在一起,方便維護。按照 doxygen 的格式去寫註解,最後可以產生 html 或 pdf 的文件。
c - Tools to get a pictorial function call graph of code - Stack Overflow
另外,在這篇有提到蠻多工具可以把 function call 畫成圖片,也就是流程圖,這對於 trace code 有些幫助!但 function call 應該是在 design 階段就劃分好,否則輸出的流程太雜亂幫助也不大。



小結

Vgod曾說過:好的程式設計師跟普通的程式設計師,效率可以差上幾十倍甚至幾百倍。除了上述的 coding 習慣、使用工具、開發環境...種種細節都會影響到,在拼專案之餘,也花些時間注重這些東西吧,一起往神人的境界努力!如果還有其他關於基礎學習,我再更新上來。

2013/03/24

在 Mac OS X 建置 python 開發環境

Install gcc for command line

Open XCode, click menu Preferences -> Downloads
check Command-Line Tools


Install Python-2.7.3

$ tar zxvf Python-2.7.3.tgz
$ cd Python-2.7.3
$ ./configure --prefix=/opt/Python-2.7.3
$ make && make install
$ export PATH=/opt/Python-2.7.3/bin:$PATH


Install distribute-0.6.35

$ tar zxvf distribute-0.6.27.tar.gz
$ cd distribute-0.6.27
$ python setup.py build
$ python setup.py install


Install pip-1.3.1

$ tar zxvf pip-1.1.tar.gz
$ cd pip-1.1
$ python setup.py build
$ python setup.py install


Install virtual environment

$ pip install virtualenv
$ virtualenv --no-site-packages /opt/pyenv
$ export PATH=/opt/pyenv/bin:$PATH



Install eclipse IDE

Download Eclipse Classic 4.2.2

Install PyDev plug-in for eclipse

Click menu Help -> Install New Software
Add repository with location: http://pydev.org/updates, then check the PyDev


Configure the interpreter

Click menu Preferences -> PyDev -> Interpreter - Python
Add new...
 

Add a new project and run it.
The debug mode is powerful.

2013/03/16

極致工藝 MacBook Air

昨天把我吃飯的傢伙給升級了 - MacBook Air


從 2009 MacBook Pro (Core 2 Duo) 升級到 2012 MacBook Air (i7 + SSD) 真的超有感覺
我已經忘了什麼是等待

由於 CPU 跟 Ram 都是不能更換的 就一次升到頂規啦
CPU i5 跟 i7 只差 3000 多
Ram 的話由於要跑 VM 升到 8G 也是必要的
SSD 我用 256GB 倒是沒有更大的需求 (SSD可以自行更換)


港版的 MBA 鍵帽上沒有注音符號 相當乾淨
符合我的風格 真的超愛

這個薄度令人驚嘆
重量從 MBP 的 2.06kg 降到 MBA 的1.35kg
天天要帶來帶去 以後身體負擔也減少些

疊疊樂
我的 MBP 可以退役了
MBA 正式上線