aws api gate way

aws 2017. 3. 18. 01:14

삽질

- 허용된 request만 받고 싶을때 -> api key 이용 (Resources -> GET-> Method Request를 누르면 설정하는게 나온다)

https://www.gellock.com/2015/12/10/using-api-keys-with-aws-api-gateway/

그럼 여기나온데로 request 날릴때 해더에 x-api-key: apikey 를 보내야 허용된다.

'aws' 카테고리의 다른 글

AWS lambda 삽질 일기  (0) 2017.03.17
kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

AWS lambda 삽질 일기

aws 2017. 3. 17. 21:08

#aws lambda python test


1. Lambda 에 올릴 zip 패키지 만들기

패키지를 모두 zip으로 해야하므로

로컬에서 directory를 하나만들고

directory/main.py python 파일을 만든다.

그리고 패키지는 이런식으로 폴더 아래 설치 되도록 한다.

"pip install module-name -t /absolute/path/to/directory"

그다음 lambda_handler function을 만들고 람다가 할일을 코딩한다. 그리고 나서 directory폴더 안에 있는 파일들을 모두 선택한다음 zip으로 만들고 lambda에 업로드한다.


2. main.py연결

Lambda configuration에 보면 Handler가 있는데 이부분을 main.lambda_handler 라고 써주면된다. "파일명.함수명" 이다.

3. Test

만들어진 람다 function을 보면 테스트 시그널을 줘서 실행해볼수 있는데 실행하면 끝날줄 모른다. 알고보면 이미 끝나있을거니 그 실행로그는 cloudWatch에가서 보면된다. 

4. 삽질

- 람다에서 커넥션 안되면 에러를 튕기기보다 설정된 타임아웃시간까지 hang이 걸린다. 따라서 스텝이 안넘어가면 뭔가 네트웤 이슈가 있구나 라고 생각하면된다.

- 일단 람다란 녀석은 만들어진 vpc내의 통신만 되기 때문에 외부 DB나 s3의 서비스 연결은 기본적으로 불가하다 -ㅅ-ㅋ 그래서 s3같은경우는 VPC -> endpoints 를 하나 만들어줘야 접근이 가능하다. 그리고 다른 vpc에 있는 DB같은경우는 Peering을 만들어서 하면되는데 그냥 peering만 만들면 접근이 안되고, 람다가 속한 vpc의 route table에 peering 접근설정을 해줘야한다.
예) destination: 10.0.0.0/28, target: pcx-c37bdsfsa(peering)(http://docs.aws.amazon.com/AmazonVPC/latest/PeeringGuide/vpc-peering-routing.html)

람다가 속한 vpc내 resource만 사용할경우 vpc만 설정해주면되고
람다가 그냥 퍼블릭 주소에 접근하는 경우만 있을경우는 vpc를 설정 안해주면된다.

하지만 이 둘을 모두 사용할땐 NAT gateway가 필요하다.. 이건 또 따로 돈나가고.. 이 두가지 모두 해당되면 람다는 좀 아닌것 같다.


*참고

http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html

http://blog.hde.co.jp/entry/2016/05/19/102706


'aws' 카테고리의 다른 글

aws api gate way  (0) 2017.03.18
kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

kinesis firehose 삽질일기

aws 2017. 3. 16. 20:09

kinesis 에 보면

streams랑 firehose가 있는데 

stream은 그냥 진짜 stream만 받는것이고

firehose는 stream을 받아서 s3나 elastic search(es)로 보내는 역할을 하는녀석이다.

차이 설명: DemystifyingAmazonKinesis_infographic.pdf

목적지가 s3와 es, redshift정도라면 firehose만 쓰면된다.


시작하기전에 한가지 알아두어야할 사실은 "그림에 속았다" 이다.

kinesis를 보면 마치 firehose하나로 s3, redshift, es에 동시에 보낼수 있을것 같이 보인다. 

하지만 설정에 들어가보면 3개중 하나를 고르라고한다.. 잉? 그리고는 백업용으로 s3를 선택할수는 있다. 그럼 redshift랑 es에는 동시에 못하나?

https://stackoverflow.com/questions/44595655/multiple-destinations-for-kinesis

같은 생각을 갖고있는 사람들이 역시 있다. 좀 가시나무들이 있지만 방법은 있단다.. firehose에 람다 트리거를 붙여서 람다가 es에 쓰도록 하는것..


아무튼, file tailing을 이용한 firehose에 로그보내기를 

aws-kinesis-agent를 설치하고 테스트해보았다.


1. config

-> /etc/aws-kinesis/agent.json

이렇게 테스트함.

{

  "cloudwatch.emitMetrics": false,

  "firehose.endpoint": "",

  "log.level": "DEBUG", 

  "flows": [

    {

      "filePattern": "/test/debug2.log",

      "deliveryStream": "test",

      "maxBufferAgeMillis": 1000,

      "minTimeBetweenFilePollsMillis": 1,

      "dataProcessingOptions": [

                {

                    "optionName": "LOGTOJSON",

                    "logFormat": "SYSLOG",

                    "customFieldNames": ["@timestamp", "host", "filename", "lineno", "msg"]

                }

            ]

    }

  ]

}


2. kinesis log

-> /var/log/aws-kinesis-agent/aws-kinesis-agent.log

먼가 안뜨거나 모니터링 할때 용이함.


3. 삽질

- firehose는 deliveryStream으로 써야한다는것

- aws key는 json파일말고 /etc/sysconfig/aws-kinesis-agent 여기에 설정해줘야 한다는것 (IAM role에서 AmazonKinesisFirehoseFullAccess 권한을 준 계정을 만들어 사용한다.)

- 로그가 오해의 소지가 있을수있다는 것. 로그는 파일 append에 상관없이 일정시간동안 찍는데 나오는 값은 agent가 실행된순간부터 지금까지의 토탈이다.

- 저 위에 dataProcessingOptions는 그야말로 옵션인데, 기본 파일에 남는 로그가 json string이 아니면 es에서 먹지 않고 에러만 남는다. (s3엔 상관없이 잘써짐) 그런데 여기서 가능한 logFormat이 4개가 있는데 이중에서 젤 만만한 녀석이 SYSLOG라 이거로 골랐다. 어떻게든 

Mar 16 10:46:49 앞에 이 타임 형식만 잘 찍어주면 뒤에는 없는 부분은 - 로 써서 넘기면 된다.

예) Mar 16 10:46:49 - main.py[123]: message

- 진짜 최강삽질은 es에 기록이 된다음부터인데, 키바나에서 일단 시작하려면 index pattern에서 add New를 해줘야하는데 이때 Time-field name이 뜨질 않는다. Advanced Settings에 가면, dateFormat:scaled라고 해서 타입을 정해줄수있는데 IOS8601 기준밖에 안된다. 그러나 Mar 16 10:46:49 이 타임형식은 rfc3164라는것!! 그래서 여기서 막혔다....


참고:

http://docs.aws.amazon.com/firehose/latest/dev/writing-with-agents.html

https://www.sumologic.com/aws/demystifying-kinesis-streams-firehose-infographic/

'aws' 카테고리의 다른 글

aws api gate way  (0) 2017.03.18
AWS lambda 삽질 일기  (0) 2017.03.17
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

Approach1. Using awscli (you don't have to make codes)

1. before collecting some metrics from your instance, your instance must be lauched with CloudWatchFullAccess IAM role.

ref: http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/UsingIAM.html

Amazon CloudWatch integrates with AWS Identity and Access Management (IAM) so that you can specify which CloudWatch actions a user in your AWS Account can perform. For example, you could create an IAM policy that gives only certain users in your organization permission to use GetMetricStatistics. They could then use the action to retrieve data about your cloud resources. 

* in my  case, I made new role(named cloudwatch_test) on IAM service with CloudWatchFullAccess, CloudWatchLogsFullAccess policies. and launch ec2 instance with this IAM role. 


2. follow this. to install cloudwatch tool stuffs

http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/mon-scripts-perl.html


3. After installing perl stuffs and finishing role settings, you can use perl command like this.

$ sudo mv aws-scripts-mon /usr/local/bin/aws-scripts-mon

$ echo "* * * * * ubuntu /usr/local/bin/aws-scripts-mon/mon-put-instance-data.pl --mem-used --mem-avail --disk-path=/dev/xvda1 --disk-space-used --dis-space-avail --from-cron" | sudo tee /etc/cron.d/aws-monitor-mem-disk-usage

* "ubuntu" is user name 

now you can check your custom metric in Ec2 monitoring->View all CloudWatch metrics->Metrics-> Linux System Metrics

if you want to monitor your existing ec2 instance, unfortunately there is no way. I tried below, but it was not working.

(you should install awscli tool first, just type $sudo apt-get install awscli, $aws configure)

1. aws iam create-instance-profile --instance-profile-name CloudWatchProfile

2. aws iam add-role-to-instance-profile --instance-profile-name CloudWatchProfile --role-name cloudwatch_test


Approach2. Using Boto (you have to do some works, but could be more flexible)

http://arr.gr/blog/2013/08/monitoring-ec2-instance-memory-usage-with-cloudwatch/

followed record.

1. make t2 micro ec2 instance (ubuntu)

2. install prerequisites

$sudo apt-get update

$sudo apt-get install python-pip

$sudo pip install boto

3. setup boto config file

$sudo vim /etc/boto.cfg

[Credentials]
aws_access_key_id = <your_access_key_here>
aws_secret_access_key = <your_secret_key_here>

4. get source code and set to cron job

$ curl https://gist.githubusercontent.com/shevron/6204349/raw/cw-monitor-memusage.py | sudo tee /usr/local/bin/cw-monitor-memusage.py

$ sudo chmod +x /usr/local/bin/cw-monitor-memusage.py

$ echo "***** ubuntu /usr/local/bin/cw-monitor-memusage.py" | sudo tee /etc/cron.d/cw-monitor-memusage

* "ubuntu" is user name 

5. check it in AWS management console

Ec2 monitoring->View all CloudWatch metrics->Metrics-> Custom Metrics (it will take a time, wait until this menu created)




'aws' 카테고리의 다른 글

AWS lambda 삽질 일기  (0) 2017.03.17
kinesis firehose 삽질일기  (0) 2017.03.16
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
HTTP 505: HTTP Version Not Supported  (0) 2014.07.09
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

elasticache dump to file

aws 2015. 3. 23. 21:48

elasticache는 save명령어가 disable되어있다. 

replica set으로 구성되어있어서 불필요한 disk 저장이 필요없기도 하거니와 save명령어는 synchronous 하기때문에 redis block을 초래하기 떄문일지도 모르겠다.

암튼, 혹 redis를 아마존 서비스를 이용해서가 아닌 그냥 ec2에 띄워서 쓰고 싶다면, 어쨌거나 data를 백업해서 가져와야하는데 save가 없으니 어떻게 하냐

redis-cli -h hostname sync > dump.rdb

명령어를 이용. (로컬에서 해봤더니 자체 sync만 동작하고 파일엔 데이터가 안써짐. 아무래도 remote host에 있는걸 여기로 sync한다는 것으로 remote에 있는 redis host를 써야하나봄)

아무튼 elasticache host는 위 명령어로 data를 backup할 수 있고 

redis.conf 파일에 셋팅된 dir 패스에 dump.rdb를 넣어놓고 redis를 다시 시작하면 쭉~ 들어간다.

'aws' 카테고리의 다른 글

kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
[ubuntu server instance] mytoon setting  (0) 2014.10.24
HTTP 505: HTTP Version Not Supported  (0) 2014.07.09
boto s3 Broken pipe error  (0) 2014.04.25
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

ubuntu t2.micro magnatic 8GB


$ sudo apt-get update

* LC_ALL 설정

/home/ubuntu/.bashrc 에 다음 추가

export LC_ALL="en_US.UTF-8"

* shell update

source .bash_profile



* mongoDB 설치

(http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/)


* mongoDB Setting

Now configure the following MongoDB parameters by editing the configuration file /etc/mongod.conf:

dbpath = /data
logpath = /log/mongod.log

* db path에 db폴더 만들고 권한 바꿔주기

$ sudo mkdir /data/db

$ sudo chown ubuntu /data/db


* 몽고 서비스 시작

$ sudo service mongod start


* For deployment

$ sudo apt-get install git

$ sudo apt-get install libxml2-dev libxslt1-dev python-dev

# $ sudo apt-get install python-pip

wget http://peak.telecommunity.com/dist/ez_setup.py

sudo python ez_setup.py

$ sudo easy_install requests==2.3.0

$ sudo easy_install -U pip


nginx

1
2
3
4
sudo aptitude install software-properties-common;
sudo add-apt-repository ppa:nginx/development;
sudo apt-get update;
sudo apt-get install nginx;

* 몇몇 mac과 별도로 설치한 module들

$ sudo pip install --no-use-wheel --upgrade distribute

$ sudo pip install cssselect

$ sudo apt-get install python-lxml

$ sudo pip install w3lib

$ sudo pip install tzlocal

$ sudo apt-get install nodejs (for javascript runtime)

$ sudo pip install futures


* server / job log file 생성

$ mkdir server/log

$ touch server/log/log.txt

$ touch server/log/job.txt

$sudo chown -R mongodb:mongodb /data /log /journal
* mongod 띄울때 기본적으로 localhost 만 붙을 수 있도록

bind_ip = 127.0.0.1

설정이 되어있다. remote에서 붙게 하려면 이걸 빼줄것!


'aws' 카테고리의 다른 글

kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
HTTP 505: HTTP Version Not Supported  (0) 2014.07.09
boto s3 Broken pipe error  (0) 2014.04.25
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

s3 upload 하다가 발생한 에런데 문제는 파일이름에 특문이 들어가 있어서 였다.

'aws' 카테고리의 다른 글

kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
boto s3 Broken pipe error  (0) 2014.04.25
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,

boto s3 Broken pipe error

aws 2014. 4. 25. 21:44

Problematic Code

1
2
conn = S3Connection(settings.AWS_ACCESS_KEY,
                    settings.AWS_ACCESS_SECRET)

Code with no problem

1
2
3
conn = S3Connection(settings.AWS_ACCESS_KEY,
                    settings.AWS_ACCESS_SECRET,
                    host="s3-ap-southeast-1.amazonaws.com") # Specify


'aws' 카테고리의 다른 글

kinesis firehose 삽질일기  (0) 2017.03.16
How to EC2 disk and memory usage monitoring  (0) 2015.03.27
elasticache dump to file  (1) 2015.03.23
[ubuntu server instance] mytoon setting  (0) 2014.10.24
HTTP 505: HTTP Version Not Supported  (0) 2014.07.09
블로그 이미지

시간을 거스르는자

ytkang86@gmail.com

,