LoginSignup
6
5

More than 5 years have passed since last update.

AWS LambdaでPhalconを使用できるようにする

Posted at

AWS LambdaでPhalconやその他のphpなextensionsを使用する方法のご紹介
需要があるのかどうかは不明
AWS LambdaでPHPを使う方法についてはこちらを参照

phalconのコンパイル

AWS LambdaはAmazon Linuxで動いているので、Linuxな環境でコンパイルする。
基本的に公式のマニュアル通りで良いが、installスクリプトはインストールまでするように書かれているので、ビルド用の環境にphalconをインストールしたくない場合には書き換えが必要。

build-only.patch
diff --git build/install build/install
index 60f5e29..29f4d85 100755
--- build/install
+++ build/install
@@ -61,4 +61,4 @@ if [ -f Makefile ]; then
 fi

 #Perform the compilation
-phpize && ./configure --enable-phalcon && make && make install && echo -e "\nThanks for compiling Phalcon!\nBuild succeed: Please restart your web server to complete the installation"
+phpize && ./configure --enable-phalcon && make && echo -e "\nThanks for compiling Phalcon!\nBuild succeed"

共有ライブラリファイルはbuild/64bits/modules/phalcon.soとして生成される。

ファイル構成例

file-tree
├── index.js
├── script.sh
├── app
│   └── index.php
└── php
    ├── ext
    │   └── phalcon.so #phalcon extension
    ├── php            #php cli
    └── php.ini

各ファイルについて簡単な説明

index.js
exports.handler = function(event, context) {
  var exec = require('child_process').exec;
  var uri_path = "undefined" == typeof event.uri_path
                 ? '' : event.uri_path;
  exec('sh script.sh ' + uri_path, function (error, stdout, stderr) {
    if(stdout){
      console.log('stdout: ' + stdout);
    }
    if(stderr){
      console.log('stderr: ' + stderr);
    }
    if (error !== null) {
      console.log('Exec error: ' + error);
    }
    context.succeed(stdout);
  });
};

↑index.js はAWS Lambdaが起動した時に最初に読み込まれるファイル。ここからscript.shを起動する。

script.sh
#!/bin/sh
./php/php -S localhost:8080 -t ./app &
until curl http://localhost:8080/$1
do
    :
done
kill $!

↑phpのbuilt-in serverを立ち上げ、curlコマンドでリクエストを投げる。
built-in serverが立ち上がるより先にcurlコマンドが動いてしまう場合があるため、正常にレスポンスを受け取るまでリトライするよう、untilを使用している。

app/index.php
<?php
phpinfo();

↑script.shで立ち上げたbuilt-in serverが参照するファイル。phalconが読み込まれているか確認するため、phpinfo()を出力。

php.ini
date.timezone="Asia/Tokyo"
extension_dir="/var/task/php/ext"
extension=phalcon.so

↑extentionであるphalconを読み込むための設定。

php-configure-options
./configure \\
--prefix=/var/task/php \\
--disable-all \\
&& make

↑phpのconfigureオプション。
アップロードするphp.iniを参照するよう、prefixを設定する。

AWS Lambdaへのアップロード

zip -r phalcon.zip app index.js php script.sh
でファイルをzipにまとめてアップロードする。
今回、zipファイルは3MB程度になったので、AWS LambdaのWebコンソールからアップロードできた。

他の拡張を使用する場合やPHPのアプリケーションが大きい場合など、10MBを超えるケースでは、一旦S3へアップロードする必要がある。

結果

API Gateway経由でアクセスし、phpinfoの出力を確認。
phalconがextensionとして読み込まれている。

Screen Shot 2015-12-01 at 3.27.58 PM.png

API Gateway経由でAWS LambdaにHTMLを出力させる方法についてはこちらを参照。

まとめ

php.iniを参照するようphpのconfigureオプションを設定することが重要。
同じように配置をすれば、他のextensionも使用できる。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5