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

2013年11月27日

mongodb on AWS EC2

Attach partition to EC2 sever cat /proc/partitions major minor #blocks name 202 1 8388608 xvda1 202 112 5242880 xvdh 202 96 5242880 xvdg 202 80 52428800 xvdf sudo vi /etc/fstab /dev/xvdf /data ext4 defaults,auto,noatime,noexec 0 0 /dev/xvdg /journal ext4 defaults,auto,noatime,noexec 0 0 /dev/xvdh /log ext4 defaults,auto,noatime,noexec 0 0 sudo mount /data sudo mount /log sudo mount /journal sudo chown mongod:mongod /data /journal /log sudo ln -s /journal /data/journal sudo vi /etc/mongod.conf
/etc/mongod.conf dbpath = /data logpath = /log/mongod.log and more!! please refer reference 1

check mongodb log tail /log/mongod.log
start mongod sudo service start mongod

reference 1
reference 2




2013年11月12日

boto get_all_instances doesn't return all instances from ec2

That's because get_all_instances() actually returns reservations.
Extract reservations to get instances.

2013年10月29日

AWS Auto Scaling with ELB 設定

設定目標

1. Auto Scaling 使用一個事先建立好的 AMI 來建構不同環境(production, staging, testing)
2. Auto Scaling 自動喚起的 instance 必須自動加入某個已經設定好的 Elastic load balancer
3. Auto Scaling 必需根據系統訊號 CloudWatch alarm 調整 instances 數量

準備工作
首先下載 Auto Scaling, Load Balancing 和 CloudWatch command line tool
並且預先準備 EC2 key pair 以及 AWS ACCESS KEY / AWS SECRET KEY
這裡要注意的是,AWS SECRET KEY 只有在建立的時候找的到,如果遺失了就要重建一個
之前別人很好心的幫我先建立了一組,我登入後找不到 SECRET
準備好要使用的 AMI,一個你已經鍛鍊很久的 AMI
準備好你的 EC2 instance 所需要的 security group
準備一組 shell script ,instances 開啟的時候你希望能夠執行的 startup script / launch script
這個 launch script 最有可能用來設定你需要的執行環境,包括設定環境變數,準備執行階段需要的 code
如果你需要的環境已經完整的設定在AMI之中,那你可能不需要 launch script
為了讓 "Why this problem doesn't appear in my environment?" 發生的機會減到最小,
並且避免每次修改系統都要建立很多的 AMI,我們決定共用一個終極的 AMI
這樣就需要 launch script 的加持,在 EC2 command line 中就是使用 user-data / user-data-file 參數來設定
ec2-run-instances ami-12345678 -k my-aws-key -g my-ec2-security-group -t ti.micro --user-data-file my-launch-script.sh 關於 user-data script 有幾點分享
第一個是這個 launch script 最好只是一個啟動器來呼叫其他 script,
因為這個 user-data script 在設定之後要變更很麻煩,並不能動態改變,
所以在 user-data script 設定環境之後,我會儘快的更新 code base 然後用新的 fabric script 做接下來的動作
這個 user-data script 是用 root 的身分來執行的,如果需要改以某種身分來執行(比如說 git pull)可以使用
su - username -c "command" 但是這個 user 沒有 session 所以不能又在其中執行 sudo command ,
會產生 sudo: sorry, you must have a tty to run sudo
這個問題原本可以藉由修改 /etc/sudoers
把 Defaults requiretty 改為 #Defaults requiretty (不建議)
但是其實遠本就有 root 身分可以用了
另外藉由修改 /etc/profile.d/ 裡面的 script 可以讓使用者登入的時候共同執行某些 script 也是不建議的方式
環境設定必須要在許多服務啟動之前,不然就是動態修改 config 再重起服務
另外也要注意估算一下從啟動到 instance ready 狀態需要多少時間,預設 EC2 會給 5 分鐘的 graceful time


設定環境變數

vi ~/.bash_profile #ec2 Settings export EC2_HOME=~/.ec2 export PATH=$PATH:$EC2_HOME/bin export EC2_URL=https://ec2.ap-northeast-1.amazonaws.com #tokyo #ec2 project settings export EC2_KEYPAIR=my-aws-key export AWS_CREDENTIAL_FILE=~/.ec2/aws_my_credentials export ELASTICBEANSTALK_URL="https://elasticbeanstalk.ap-northeast-1.amazonaws.com" export AWS_ACCESS_KEY=$(grep '^AWSAccessKeyId' "$AWS_CREDENTIAL_FILE" | cut -d= -f2) export AWS_SECRET_KEY=$(grep '^AWSSecretKey' "$AWS_CREDENTIAL_FILE" | cut -d= -f2) export AWS_REGION='ap-northeast-1' export EC2_REGION=${AWS_REGION} export EC2_URL=ec2.${AWS_REGION}.amazonaws.com export AWS_SNS_URL=http://sns.${AWS_REGION}.amazonaws.com export AWS_ELB_URL=https://elasticloadbalancing.${AWS_REGION}.amazonaws.com #ec2 load balancing export AWS_ELB_HOME=~/EC2/ElasticLoadBalancing-1.0.17.0 PATH=${PATH}:${AWS_ELB_HOME}/bin #ec2 cloud watching export AWS_CLOUDWATCH_HOME=~/EC2/CloudWatch-1.0.13.4 PATH=${PATH}:${AWS_CLOUDWATCH_HOME}/bin #ec2 auto scaling export AWS_AUTO_SCALING_HOME=~/EC2/AutoScaling-1.0.61.3 PATH=${PATH}:${AWS_AUTO_SCALING_HOME}/bin export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home/ [[ -s /Users/sushih-wen/.nvm/nvm.sh ]] && . /Users/sushih-wen/.nvm/nvm.sh # This loads NVM export PATH
接下來開始設定 Auto Scaling Group
設定 launch config
cd $EC2_HOME as-create-launch-config staging-lc --image-id ami-12345678 --instance-type m1.large --key my-aws-key --group ec2-group --user-data-file launch-staging.sh 請注意看,在第一個階段就指定了 user-data-file
而且因為 launch config 無法修改,所以之後要修改這個 script,等於全部重做
as-create-auto-scaling-group staging-asg --launch-configuration staging-lc -z ap-northeast-1a,ap-northeast-1c --load-balancers staging --max-size 10 --min-size 2 --desired-capacity 2 --health-check-type ELB --grace-period 300 --tag "k=Stack, v=staging, p=true" 以上這裡設定了 auto scale group 在多個工作區( multiple availability zone ),但是到此為止還無法跨 side
多個工作區同時失敗的機率已經很小,但是我們還是可以設定跨 side 提供服務,晚上可以睡的比較好
另外也特別設定了 Stack tag 幫助之後辨識不同 auto scale group,也可以不用設定,預設就會有個比較醜的 aws:auto-scale tag
雖然 Name 也是一個tag,但是這個 tag 無法藉由這樣的方式設定成 Name
設定到此 EC2 istances 就會自己起床工作了,並且在 Healthy 狀態自動掛到 Load Balancer 底下
也可以觀察 Auto scaling 會盡量平均 instance 數量到不同的 availability zone
來查看設定 as-describe-auto-scaling-groups staging-asg --headers 如果要刪除 Auto Scaling 必須要先關掉底下所有的 instance as-update-auto-scaling-group staging-asg --max-size 0 --min-size 0 as-delete-auto-scaling-group staging-asg 如果要暫停下來修改的話 as-suspend-processes staging-asg 回復運作 as-resume-processes staging-asg 接下來服用橡膠果實 從簡單的開始,假設我們希望在平均 CPU > 50 的時候增加一個 instance,反之減少一個 instance as-put-scaling-policy staging-scaleup --auto-scaling-group staging-asg --adjustment=1 --type ChangeInCapacity mon-put-metric-alarm staging-scaleup-cpu --metric-name CPUUtilization --namespace "AWS/EC2" --statistic Average \ --period 60 --threshold 50 --unit Percent \ --comparison-operator GreaterThanThreshold \ --dimensions AutoScalingGroupName=staging-asg --evaluation-periods 3 \ --alarm-actions 以上這樣設定就是用平均的角度來看,每分鐘檢查一次,如果連續三次 CPU 都超過 50 ,那就會啟動這個 CloudWatch Alarm 執行相對應的動作,可以執行一個以上的動作 以下是 scale down CloudWatch Alarm with Monitor Policy 檢查 CPU utilization 20次每次1分鐘 as-put-scaling-policy staging-scaledown --auto-scaling-group staging-asg --adjustment=-1 --type ChangeInCapacity mon-put-metric-alarm staging-scaledown-cpu --metric-name CPUUtilization --namespace "AWS/EC2" --statistic Average \ --period 60 --threshold 50 --unit Percent \ --comparison-operator LessThanThreshold \ --dimensions AutoScalingGroupName=staging-asg --evaluation-periods 20 \ --alarm-actions 查看有哪些 policy as-describe-policies 刪除 policy (刪除 Auto Scaling Group 會自動刪除相關的 policy) as-delete-policy 檢查你的 CPU 數據 mon-get-stats CPUUtilization --statistics "Average" --namespace "AWS/EC2" --dimensions "AutoScalingGroupName=staging-asg" 設定完要注意的是,Alarm action 只會在狀態改變的時候被觸動,並不是一直處在 Alarm 狀態就會一直觸動 所以設定一個完整的 Auto Scaling 機制必須要建立多個 Alarm action






2013年10月22日

AWS EC2 user-data launch script for ec2 instances

Specify a start-up script when you launch an EC2 instance.
Launch instance.

ec2-run-instances ami-c96bf3c8 -k capy-aws -t t1.micro -g capy-ec2 --user-data-file launch-staging.sh

Auto scale
as-create-launch-config staging-lc --image-id ami-7b4cd77a --instance-type t1.micro --user-data-file launch-staging.sh



2012年9月27日

ElasticSearch 使用Chef-solo 安裝在ec2

參閱官方教學

可以先閱讀elasticsearch on ec2了解這次許多食譜的含意

Chef是一個automate cloud infrastructure framewrok,主要語言是Ruby,適用於AWS、Rackspace等cloud service,尤其當要建立cluster servers的時候可以減少很多重複的工作


環境:

AWS ec2 m1.large

ElasticSearch: 0.19.8

Chef-solo: 跟 Chef-server比起來少了 full text search of our server attributes, executing the same command over SSH on multiple servers at once, or using a web-based GUI

目標,主要是把環境弄好把ElasticSearch安裝起來,有Nginx接應,有Monit照料,有S3當Gateway後援:
  1. First of all, install a specific version of ElasticSearch on the node
  2. Create a elasticsearch.yml file with custom configuration
  3. Create a separate user to run ElasticSearch
  4. Register a service to start ElasticSearch automatically on server boot
  5. Increase the open files limit for the elasticsearch user
  6. Configure the memory limits and other settings for the JVM
  7. Monitor the ElasticSearch process and cluster health with Monit
  8. Install the Nginx web server and use it as a proxy for ElasticSearch
  9. Store user credentials for HTTP authentication with Nginx
步驟:

EC2 Security Group設定開TCP 22, 8080, 9200, 9300, 9500且application連的到

開一台EC2,一個S3 bucket

下載所需腳本
curl -# -L -k https://gist.github.com/gists/2050769/download | tar xz --strip 1 -C .
node-example.json設定好之後存為node.json,另外把local端參數設定一下
HOST=EC2主機位置 SSH_OPTIONS="-o User=ec2-user -o IdentityFile=ec2要用的key.pem -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
腳本和食譜上傳到ec2
scp $SSH_OPTIONS ./bootstrap.sh ./patches.sh ./node.json ./solo.rb $HOST:/tmp
開始安裝,這裡官網的作法是傳指令給遠端
time ssh -t $SSH_OPTIONS $HOST "sudo bash /tmp/bootstrap.sh" time ssh -t $SSH_OPTIONS $HOST "sudo bash /tmp/patches.sh" time ssh -t $SSH_OPTIONS $HOST "sudo chef-solo --node-name es-1 -j /tmp/node.json" #es-1是node名稱,cluster第二台就是es-2,可任意
這樣就裝好了,來檢查一下
ssh -t $SSH_OPTIONS $HOST "curl http://localhost:9200" ssh -t $SSH_OPTIONS $HOST "sudo service elasticsearch status -v" #從外部透過nginx curl http://{NGINX-USERNAME}:{NGINX-PASSWORD}@$HOST:8080 #第二台之後檢查cluster設置是否成功 ssh -t $SSH_OPTIONS $HOST "curl localhost:9200/_cluster/health?pretty"




2012年6月20日

在Ubuntu 建立Git server with Gitolite

Ubuntu 12.04
Git package: gitolite 2.x

Admin local machine準備工作
建立SSH Key
ssh-keygen -t rsa -f my_account
或是使用之前建立的~/.ssh/id_rsa.pub
把public key丟到server
rsync -uva --rsh='ssh -i mykey.pem' ~/.ssh/id_rsa.pub ubuntu@server:/tmp #mykey.pem is an example for amazon ec2

登入server開始安裝gitolite
sudo apt-get install git-core sudo apt-get install gitolite mv /tmp/id_rsa.pub /tmp/my_account.pub
建立使用者 "git" 就是我們的git admin user
sudo adduser \ --system \ --shell /bin/bash \ --gecos 'git version control' \ --group \ --disabled-password \ --home /home/git \ git
設定新使用者path
sudo su git echo "PATH=$HOME/bin:$PATH" >> ~/.bashrc
跑gitolite setup command

gl-setup /tmp/my_account.pub

如果需要gitweb 此時可以把$REPO_UMASK 設定為0027
安裝完成,調整server config和add user
回local machine
git clone git@server:gitolite-admin.git
這裡如果有permission問題就是ssh key沒有設定好
抓回來的gitolite-admin就是git server設定資料夾
新增使用者就是把使用者產生的public key丟到gitolite-admin/keydir/後上傳
cd gitolite-admin cp /tmp/john.pub keydir/john.pub git add keydir/john.pub git commit -m 'add user john' git push

建立repo
cd gitolite-admin vim conf/gitolite.conf 把testing改成要的repo名稱後上傳

如果想要進一步學習Git 操作可以閱讀版本控制使用Git



參考資料
http://blog.longwin.com.tw/2011/03/linux-gitolite-git-server-2011/
http://www.countableset.ch/blog/blog/2012/04/29/ubuntu-12-dot-04-installing-gitolite-and-gitweb/
http://blog.crboy.net/

使用 AWS 筆記 (三) 各種database及建立mongodb

首先我們發現到AWS已經提供了三類型database可以使用
http://aws.amazon.com/running_databases/

1. RDS可以連結不同relational database,如MySQL、Oracle等,這還有分你要不要自行管理。

2. SimpleDB(NoSQL),easy to start with,好處是query方便彈性(因為全做index),也因此performance, scale比較差,有類似table的"domain"儲存上限10GB。

3. DynamoDB,可能源自於2007年amazon dynamo論文,SSD固態硬碟儲存,distributed data store,只有primary key index,fast and scalable,但是由於他不能對其他value做index,文件也不夠多,我們先靜觀其變。

不管,早就想用mongodb了,文件非常豐富

先看Amazon的這篇
http://d36cz9buwru1tt.cloudfront.net/AWS_NoSQL_MongoDB.pdf
再看MongoDB的這篇
http://www.mongodb.org/display/DOCS/Amazon+EC2

我們決定先玩玩看,先建security group,一般來說分兩種,app server access/operational access

Default Port(TCP):


A standalone mongod process: 27017
mongos : 27017
shard server (mongod --shardsvr) : 27018
config server (mongod --configsvr) : 27019
web statistics page for mongod : add 1000 to port number (28017, by default).

當然也要讓我們的ssh( port 22)可以連上
ec2-create-group amongo --description "security group for mongodb"
ec2-authorize amongo -p 22
ec2-authorize amongo -o amongo -u [user_account_number]
ec2-authorize amongo -o application -u [user_account_number]
可開一個web-based status interface
ec2-authorize amongo -p 28017

然後我們直接選AMI from Amazon Marketplace裝好的mongodb,看到10gen有出兩個image, MongoDB/MOngoDB with EBS RAID,如果有錢可以選100GB共四個volume做RAID 10又做replica, shard當然是很爽啦,窮人跟我一樣選MongoDB安裝成single node(可能已經是RAID 10),3月8號才更新的,版本是2.0.4 for production,裝上去就完成了

測試一下
$sudo chkconfig mongod on $sudo /etc/init.d/mongod start
進mongodb
$mongo >use testdb
沒問題

因為很怕掛掉(一年有0.1%~0.5%的機會會掛掉),來測試一下ec2的detach, attach, take snapshot等功能

要修改EBS volume (容量大小或其他設定)必須關機>detach>take snapshot>Create Volume from snapshot>attach to ec2 instance>開機,不能熱操作

因為是從AMI產生的volume,attach的時候必須要用/dev/sda1喔!


想要進一步了解AWS操作可以看看AWS雲端企業實戰聖經






2012年6月11日

使用 AWS 筆記 (二) 建立EC2 instance




建立帳號/信用卡認證/手機認證應/下載金鑰應該沒什麼問題

接下來進入amazon service console
選擇EC2
選擇東京機房
建立Security Group(主要是增加SSH 從工作區可以連過去)
建立Instance
使用Ubuntu 12.04 LTS(Long Term Support) 64-bit AMI(Amazon Machine Image)
選擇 t1.micro (新帳戶第一年免費)

上面影片是使用windows gui + putty 來建立 instance
linux使用者參考這邊https://help.ubuntu.com/community/EC2StartersGuide
mac使用者參考這邊http://www.robertsosinski.com/2008/01/26/starting-amazon-ec2-with-mac-os-x/

如果是使用Ubuntu AMI 一般來說使用ubuntu登入
使用BitNami 一般來說就是bitnami登入



下一篇 使用 AWS 筆記 (三) 各種database及建立mongodb

想要進一步了解AWS操作可以看看AWS雲端企業實戰聖經



2012年6月10日

使用 AWS 筆記 (一) 選擇Amazon EC2


Amazon EC2還沒用之前感覺非常困難,一直沒有機會使用(逃避)

背景是這樣:

GAE (python) 我使用了一年多,漲價之後就沒有太大優勢,具有環境的特殊性限制,以及環境綁定的寫作方式,我目前把他定位成一個運算工具,而不是一個適合放完整大型網站的地方,但是用來做crawler, simple task worker, cron jobs等工作仍然是我的首選,開發時間短,而且免費quota足夠做非常多事情。

Heroku 簡單容易上手,而且支援算是完整,預設git版本控制簡直美妙,add-ons生態系經營的相當好,目前缺點就是貴以及不夠快(亞洲),網站每慢0.1秒就會損失1%的使用者,還有看log的速度我無法接受,花錢也無法解決的問題是個難題,但是如果要做mvp,或是專案時間緊迫要上線,Heroku是首選。

Linode 有考慮過但還是不能滿足這次的需求,我們的目標是百萬使用者,也達到過這樣的目標(not slashdotted),所以scalability是一個實際會發生的問題,加上我們規劃將來後端分散式處理資料的可擴充性,VPS在這方面是比較不足的,或許AWS一年優惠用完,又生不出使用者的時候我們可以考慮躲進來。

AWS 我逼不得已來到了 IAAS 這一層(我學網頁當初只是想寫前端javascript阿,什麼時候下到這層了! ),Amazon EC2目前無人能出其右,先花一個小時翻過一遍神人Hank Lin的AWS雲端企業實戰聖經,內容很多很詳細很值得購買,只是寫的時間比較早,如果有2012版我會更推薦,之後又大概看了Python and AWS Cookbook,裡面主要是講用boto (python)這個工具來建立和控制Amazon的許多Cloud Service,這和使用powershell來控制Vmware Virtual Machine有異曲同工之妙,先放著以後會用到。

使用AWS第一個問題就是名詞縮寫太多了,節錄wiki資料來對照使用,看起來跟vmare提供的服務差不多,但是真正使用起來我相信有非常長的路要走...

List of AWS products

  • Amazon AWS Authentication, an implicit service, the authentication infrastructure used to authenticate access to the various services.
  • Amazon CloudFront, a content delivery network (CDN) for distributing objects to so-called "edge locations" near the requester.
  • Amazon CloudWatch, provides monitoring for AWS cloud resources and applications, starting with EC2.
  • Amazon DevPay, currently in limited beta version, is a billing and account management system for applications that developers have built atop Amazon Web Services.
  • Amazon Elastic Beanstalk provides quick deployment and management of applications in the cloud.
  • Amazon Elastic Block Store (EBS) provides persistent block-level storage volumes for EC2.
  • Amazon Elastic Compute Cloud (EC2) provides scalable virtual private servers using Xen.
  • Amazon Elastic MapReduce allows businesses, researchers, data analysts, and developers to easily and cheaply process vast amounts of data. It uses a hosted Hadoop framework running on the web-scale infrastructure of EC2 and Amazon S3.
  • Amazon ElastiCache provides in-memory caching for web applications.
  • Amazon Flexible Payments Service (FPS) provides an interface for micropayments.
  • Amazon Fulfillment Web Service provides a programmatic web service for sellers to ship items to and from Amazon using Fulfillment by Amazon.
  • Amazon Historical Pricing provides access to Amazon's historical sales data from its affiliates. (It appears that this service has been discontinued.)
  • Amazon Mechanical Turk (Mturk) manages small units of work distributed among many humans.
  • Amazon Product Advertising API formerly known as Amazon Associates Web Service (A2S) and Amazon E-Commerce Service (ECS), provides access to Amazon's product data and electronic commerce functionality.
  • Amazon Relational Database Service (RDS) provides a scalable database server with MySQL and Oracle support.
  • Amazon Route 53 provides a highly available and scalable Domain Name System (DNS) web service.
  • Amazon CloudSearch, currently in limited beta version, provides basic full text search and indexing of textual content.
  • Amazon Simple Email Service (SES) provides bulk and transactional email sending.
  • Amazon Simple Storage Service (S3) provides Web Service based storage.
  • Amazon Simple Queue Service (SQS) provides a hosted message queue for web applications.
  • Amazon Simple Notification Service (SNS) provides a hosted multiprotocol "push" messaging for web applications.
  • Amazon Simple Workflow (SWF) is a workflow service for building scalable, resilient applications.
  • Amazon SimpleDB, allows developers to run queries on structured data. It operates in concert with EC2 and S3 to provide "the core functionality of a database."
  • Amazon Virtual Private Cloud (VPC) creates a logically isolated set of Amazon EC2 instances which can be connected to an existing network using a VPN connection.
  • AWS CloudFormation, create a collection of related AWS resources and provision them in an orderly and predictable fashion.
  • AWS Import/Export, accelerates moving large amounts of data into and out of AWS using portable storage devices for transport.
  • AWS Management Console (AWS Console), A web-based point and click interface to manage and monitor the Amazon infrastructure suite including EC2, EBS, Amazon Elastic MapReduce, and Amazon CloudFront.
  • AWS Storage Gateway, an iSCSI block storage appliance with cloud-based backup.




下一篇 使用 AWS 筆記 (二) 建立EC2 instance