最近又頭腦發熱,想用Kong來做一個proxy的管理工具。
本來是想用Varnish或是Squid來做的,但是在看到api-umbrella的分析之後,覺得lua+nginx真是效能神器呀。可惜api-umbrella還沒完成ruby -> lua的改版。看了他們的競爭對手名單之後,發現Kong一開始就是用lua來做的。
那就用Kong就好啦。
折騰開始
Kong是使用cassandra來存放plugin的資料和其它開發人員的設定參數,所以一開始要先安裝cassandra。
參考這一篇的教學,把cassandra裝在OS X上。
一開始要先安裝java 7:brew install java
再來就是從source code 自己build cassandra。
mkdir -p ~/opt/packages && cd $_
curl -O http://ftp.mirror.tw/pub/apache/cassandra/2.2.4/apache-cassandra-2.2.4-bin.tar.gz
gzip -dc apache-cassandra-2.2.4-bin.tar.gz | tar xf -
ln -s ~/opt/packages/apache-cassandra-2.2.4 ~/opt/cassandra
mkdir -p ~/opt/cassandra/data/data
mkdir -p ~/opt/cassandra/data/commitlog
mkdir -p ~/opt/cassandra/data/saved_caches
mkdir -p ~/opt/cassandra/logs
不能用brew install cassandra
,因為brew的cassandra版本只有2.0和3.0版,但是Kong一定要用2.1版以上、3.0版未滿。
執行 cassandra
~/opt/packages/apache-cassandra-2.2.4/bin/cassandra -f
用cqlsh測試安裝是否成功(在~/opt/packages/apache-cassandra-2.2.4/bin)。
注意memory要有1G以上,不然cassandra在執行的時候會因為out of memory直接關閉。
可以看log file (在~/opt/cassandra/logs)
不用另外安裝cqlsh (已經在bin/資料夾內) 或cassandra driver (用不到)。
如果cassandra安裝失敗的話,KongDB有提供一個免費的cassandra db可以使用
安裝Kong
Kong (金剛)是個菜市場名,放在google只會得到Hong Kong。所以要用GetKong來Google。
經過Google幫忙,發現OS X安裝指南。
如果不想折騰,可以用pkg installer快速安裝。
只是我們的目的是盡量折騰(為了能夠取得kong_DEVELOPMENT.yml),所以只能
git clone https://github.com/Mashape/kong
sudo make dev
執行Kong
切換到Kong的下載目錄
執行 (要先確定cassandra -f已經跑起來了)
kong start -c kong_DEVELOPMENT.yml
如果要停止Kong
kong stop -c kong_DEVELOPMENT.yml
如果要重啟(改完Kong的source code或是修改plugin)
kong restart -c kong_DEVELOPMENT.yml
修改Kong
Kong是nginx的lua外卦。在Kong啟動時,會覆寫/usr/local/kong/nginx.conf
的設定,所以要修改nginx的設定,必須在kong_DEVELOPMENT.yml
裡面修改(production的設定要改kong.yml)。
Kong改爛了
Kong的錯誤訊息放在 kong/nginx_tmp/logs/error.log
另外可以用ngx.log(ngx.ERR, "Hello World!")
輸出錯誤訊息到error.log
(只能在.lua程式裡使用)
不想用hello world debug法的話
可以用ZeroBrane Studio來設breakpoints。
把ZeroBrane裝好之後,在要debug的.lua scripts上面的地方,指定mobdebug的路徑:
package.path = "/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/lualibs/?/?.lua;/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/lualibs/?.lua;" .. package.path
package.cpath = "/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/bin/clibs/?.dylib;/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/bin/clibs/?/?.dylib;" .. package.cpath
注意不要用luarocks install mobdebug
來安裝,因為luarocks的mobdebug版本比ZeroBrane內附的舊,和ZeroBrane Studio一起使用會出現
[error] 14757#0: *1 lua entry thread aborted: runtime error: attempt to yield across C-call boundary
(在kong/nginx_temp/logs/error.log可看到)
在要debug的函數裡加上require('mobdebug').start("127.0.0.1")
如下圖:
把ZeroBrane打開,選擇File->Open
,打開kong_Development.yml
然後Project->Project Directory->Set From Current File
如果沒有把Project Directory設在Kong的目錄,會出現Step in/out等debug功能無法使用的情況
啟動debug server:Project->Start Debugger Server
設置breakpoint:Project->Toggle Breakpoint
把breakpoint設在require('mobdebug').start("127.0.0.1")
的下一行
啟動Kong:
kong start -c kong_DEVELOPMENT.yml
ZeroBrane就會把Kong停在breakpoint的位置了