diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..e6a05a7 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1 @@ +Please make sure pull requests are opened against the development branch. Pull requests opened against master will be closed automatically. Please delete this line once you have confirmed the correct branch. diff --git a/.gitignore b/.gitignore index 15cc1ca..6160051 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ php71.zip +php73.zip diff --git a/Makefile b/Makefile index e6453b0..eee5fce 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,25 @@ ROOT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) +all: php71.zip php73.zip + php71.zip: - docker run --rm -v $(ROOT_DIR):/opt/layer lambci/lambda:build-nodejs8.10 /opt/layer/build.sh + docker run --rm -e http_proxy=${http_proxy} -v $(ROOT_DIR):/opt/layer lambci/lambda:build-provided /opt/layer/build.sh + +php73.zip: + docker run --rm -e http_proxy=${http_proxy} -v $(ROOT_DIR):/opt/layer lambci/lambda:build-provided /opt/layer/build-php-remi.sh 3 + +upload71: php71.zip + ./upload.sh 7.1 -upload: php71.zip - ./upload.sh +upload73: php73.zip + ./upload.sh 7.3 -publish: php71.zip - ./publish.sh +publish71: php71.zip + ./publish.sh 7.1 + +publish73: php73.zip + ./publish.sh 7.3 clean: - rm php71.zip + rm -f php71.zip php73.zip + diff --git a/README.md b/README.md index 61b979c..f71456d 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,81 @@ # PHP Layer For AWS Lambda -Ever wanted to run PHP websites in AWS Lambda? It's your lucky day! This Lambda Runtime Layer runs the [PHP 7.1 webserver](http://php.net/manual/en/features.commandline.webserver.php) in response to [AWS API Gateway](https://aws.amazon.com/api-gateway/) requests. +Ever wanted to run PHP websites in AWS Lambda? It's your lucky day! This Lambda Runtime Layer runs the [PHP 7.3/7.1 webserver](http://php.net/manual/en/features.commandline.webserver.php) in response to [AWS API Gateway](https://aws.amazon.com/api-gateway/) or [AWS Application Load Balancer](https://aws.amazon.com/elasticloadbalancing/features/#Details_for_Elastic_Load_Balancing_Products) requests. And, if you're looking for a great way to build serverless apps of all kinds, be sure to check out [Stackery](https://stackery.io)! This is an early iteration of the PHP runtime Layer which is not yet ready for production. Please feel free to use this Layer to learn about the Lambda Layers feature and begin experimenting with PHP functions. We welcome feedback and stay tuned for the production-ready version coming soon. ## Current Layer Version ARN -When creating/updating a Lambda function you must specify a specific version of the layer. This readme will be kept up to date with the latest version available. The latest available Lambda Layer Version ARN is: +When creating/updating a Lambda function you must specify a specific version of the layer. This readme will be kept up to date with the latest version available. The latest available Lambda Layer Version ARNs for PHP 7.3 and 7.1 are: -**arn:aws:lambda:\:887080169480:layer:php71:3** +**arn:aws:lambda:\:887080169480:layer:php73:3** + +**arn:aws:lambda:\:887080169480:layer:php71:10** + +See [Releases](https://github.com/stackery/php-lambda-layer/releases) for release notes. ### Usage #### General Usage -The layer runs the PHP 7.1 [PHP webserver](http://php.net/manual/en/features.commandline.webserver.php) in /var/task, the root directory of function code packages: +The layer runs the PHP 7.* [PHP webserver](http://php.net/manual/en/features.commandline.webserver.php) in /var/task, the root directory of function code packages: ```sh $ php -S localhost:8000 '' ``` -The Lambda Function Handler property specifies the location of the the script executed in response to an incoming API Gateway request. +The Lambda Function Handler property specifies the location of the the script executed in response to an incoming API Gateway or Application Load Balancer request. + +#### Configuration Files +There are three locations where PHP configuration may be located: + +* Files in layer code packages located under /etc/php-${PHP_VERSION}.d/ +* Files in function code package located under /php-${PHP_VERSION}.d/ +* php.ini located at the root of the function code package + +Replace ${PHP_VERSION} with '7.3', or '7.1' according to your preferred runtime. ##### Extensions -Extensions can be built using the lambci/lambda:build-nodejs8.10 Docker image. It is recommended that extensions be built into a Lambda Layer in /lib/php/7.1/modules. Then, in a php.ini file in the Lambda Function root directory put: +The following extensions are built into the layer and available in /opt/lib/php/${PHP_VERSION}/modules: -```ini -extension_dir=/opt/lib/php/7.1/modules -extension=... +PHP 7.3 Layer: +``` +bz2.so +calendar.so +ctype.so +curl.so +dom.so +exif.so +fileinfo.so +ftp.so +gettext.so +iconv.so +json.so +mbstring.so +mysqli.so +mysqlnd.so +pdo_mysql.so +pdo_pgsql.so +pdo.so +pdo_sqlite.so +pgsql.so +phar.so +posix.so +shmop.so +simplexml.so +sockets.so +sqlite3.so +sysvmsg.so +sysvsem.so +sysvshm.so +tokenizer.so +wddx.so +xmlreader.so +xml.so +xmlwriter.so +xsl.so ``` -The following extensions are built into the layer and available in /opt/lib/php/7.1/modules: - +PHP 7.1 Layer: ``` bz2.so calendar.so @@ -60,7 +105,15 @@ xsl.so zip.so ``` -#### Example +These extensions are not loaded by default. You must add the extension to a php.ini file to use it: + +```ini +extension=json.so +``` + +Extensions can be built using the lambci/lambda:build-nodejs8.10 Docker image. It is recommended that custom extensions be provided by a separate Lambda Layer with the extension .so files placed in /lib/php/${PHP_VERSION}/modules/ so they can be loaded alongside the built-in extensions listed above. + +#### SAM Example Let's create an AWS SAM PHP application. We suggest using [Stackery](https://stackery.io) to make this super simple. It automates all the scaffolding shown below. But you may also choose to roll your own application from scratch. First, install [AWS SAM CLI](https://github.com/awslabs/aws-sam-cli). Make sure to create a SAM deployment bucket as shown in [Packaging your application](https://github.com/awslabs/aws-sam-cli/blob/develop/docs/deploying_serverless_applications.rst#packaging-your-application) @@ -84,14 +137,14 @@ Resources: Properties: FunctionName: !Sub ${AWS::StackName}-phpserver Description: PHP Webserver - CodeUri: src/server + CodeUri: src/php Runtime: provided Handler: index.php MemorySize: 3008 Timeout: 30 Tracing: Active Layers: - - !Sub arn:aws:lambda:${AWS::Region}:887080169480:layer:php71:3 + - !Sub arn:aws:lambda:${AWS::Region}:887080169480:layer:php73:3 Events: api: Type: Api @@ -132,12 +185,36 @@ $ sam deploy \ ``` ### Development -Build the layer by: +Build the layers by: 1. Installing a Docker environment 1. Running `make` -This will launch a Docker container that will build php71.zip. +This will launch Docker containers that will build php73.zip and php71.zip. + +If you are behind a proxy server, just set the environment variable `http_proxy` before +invoking `make`, eg.: + +```sh + $ export http_proxy=http://myproxy.acme.com:8080 + $ make php73.zip +``` + +#### Debugging Layer Builds + +Run: + +```sh + $ docker run --rm -it -v `pwd`:/opt/layer lambci/lambda:build-nodejs8.10 /bin/bash +``` + +If you are on Windows, run this instead: + +```sh + > docker run --rm -it -v %cd%:/opt/layer lambci/lambda:build-nodejs8.10 /bin/bash +``` + +then manually execute the commands in the build.sh file. ### Disclaimer diff --git a/bootstrap b/bootstrap index 5794495..5fcf610 100755 --- a/bootstrap +++ b/bootstrap @@ -5,24 +5,42 @@ error_reporting(E_ALL | E_STRICT); $AWS_LAMBDA_RUNTIME_API = getenv('AWS_LAMBDA_RUNTIME_API'); +/* https://gist.github.com/henriquemoody/6580488 */ +$http_codes = [100=>'Continue',101=>'Switching Protocols',102=>'Processing',200=>'OK',201=>'Created',202=>'Accepted',203=>'Non-Authoritative Information',204=>'No Content',205=>'Reset Content',206=>'Partial Content',207=>'Multi-Status',208=>'Already Reported',226=>'IM Used',300=>'Multiple Choices',301=>'Moved Permanently',302=>'Found',303=>'See Other',304=>'Not Modified',305=>'Use Proxy',306=>'Switch Proxy',307=>'Temporary Redirect',308=>'Permanent Redirect',400=>'Bad Request',401=>'Unauthorized',402=>'Payment Required',403=>'Forbidden',404=>'Not Found',405=>'Method Not Allowed',406=>'Not Acceptable',407=>'Proxy Authentication Required',408=>'Request Timeout',409=>'Conflict',410=>'Gone',411=>'Length Required',412=>'Precondition Failed',413=>'Request Entity Too Large',414=>'Request-URI Too Long',415=>'Unsupported Media Type',416=>'Requested Range Not Satisfiable',417=>'Expectation Failed',418=>'I\'m a teapot',419=>'Authentication Timeout',420=>'Enhance Your Calm',420=>'Method Failure',422=>'Unprocessable Entity',423=>'Locked',424=>'Failed Dependency',424=>'Method Failure',425=>'Unordered Collection',426=>'Upgrade Required',428=>'Precondition Required',429=>'Too Many Requests',431=>'Request Header Fields Too Large',444=>'No Response',449=>'Retry With',450=>'Blocked by Windows Parental Controls',451=>'Redirect',451=>'Unavailable For Legal Reasons',494=>'Request Header Too Large',495=>'Cert Error',496=>'No Cert',497=>'HTTP to HTTPS',499=>'Client Closed Request',500=>'Internal Server Error',501=>'Not Implemented',502=>'Bad Gateway',503=>'Service Unavailable',504=>'Gateway Timeout',505=>'HTTP Version Not Supported',506=>'Variant Also Negotiates',507=>'Insufficient Storage',508=>'Loop Detected',509=>'Bandwidth Limit Exceeded',510=>'Not Extended',511=>'Network Authentication Required',598=>'Network read timeout error',599=>'Network connect timeout error']; + function start_webserver() { + $SERVER_STARTUP_TIMEOUT = 1000000; // 1 second + $pid = pcntl_fork(); switch($pid) { case -1: - die('Failed to fork webserver process'); + die("Failed to fork webserver process\n"); case 0: // exec the command $HANDLER = getenv('_HANDLER'); - chdir('/var/task'); - exec("php -S localhost:8000 '$HANDLER'"); + $phpMinorVersion = PHP_MINOR_VERSION; + $handler_components = explode('/', $HANDLER); + $handler_filename = array_pop($handler_components); + $handler_path = implode('/', array_merge(['/var/task'], $handler_components)); + chdir($handler_path); + exec("PHP_INI_SCAN_DIR=/opt/etc/php-7.${phpMinorVersion}.d/:/var/task/php-7.${phpMinorVersion}.d/ php -S localhost:8000 -c /var/task/php.ini -d extension_dir=/opt/lib/php/7.${phpMinorVersion}/modules '$handler_filename'"); exit; - // return the child pid to parent default: // Wait for child server to start - sleep(1); - return $pid; + $start = microtime(true); + + do { + if (microtime(true) - $start > $SERVER_STARTUP_TIMEOUT) { + die("Webserver failed to start within one second\n"); + } + + usleep(1000); + $fp = @fsockopen('localhost', 8000, $errno, $errstr, 1); + } while ($fp == false); + + fclose($fp); } } @@ -87,7 +105,7 @@ while (true) { } if ($invocation_id == '') { - die('Failed to determine Lambda invocation ID'); + die("Failed to determine Lambda invocation ID\n"); } curl_close($ch); @@ -127,7 +145,7 @@ while (true) { $ch = curl_init("http://localhost:8000$uri"); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); if (array_key_exists('multiValueHeaders', $event)) { $headers = array(); @@ -137,7 +155,7 @@ while (true) { array_push($headers, "${name}: ${value}"); } } - + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } @@ -153,10 +171,7 @@ while (true) { } if (strlen($body) > 0) { - curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body)); - curl_setopt($ch, CURLOPT_READFUNCTION, function ($ch, $fd, $length) use ($body) { - return $body; - }); + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } $response = array(); @@ -200,25 +215,30 @@ while (true) { curl_exec($ch); curl_close($ch); - if (preg_match('/[^\x00-\x7f]/', $response['body'])) { - $response['body'] = base64_encode($response_body); - $response['isBase64Encoded'] = TRUE; - } - $ch = curl_init("http://$AWS_LAMBDA_RUNTIME_API/2018-06-01/runtime/invocation/$invocation_id/response"); + $isALB = array_key_exists("elb", $event['requestContext']); + if ($isALB) { // Add Headers For ALB + $status = $response["statusCode"]; + if (array_key_exists($status, $http_codes)) { + $response["statusDescription"] = "$status ". $http_codes[$status]; + } else { + $response["statusDescription"] = "$status Unknown"; + } + $response["isBase64Encoded"] = false; + } $response_json = json_encode($response); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $response_json); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( - 'Content-Type: application/json', - 'Content-Length: ' . strlen($response_json) - )); - + if (!$isALB){ + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + 'Content-Type: application/json', + 'Content-Length: ' . strlen($response_json) + )); + } curl_exec($ch); curl_close($ch); } -?> \ No newline at end of file +?> diff --git a/build-php-remi.sh b/build-php-remi.sh new file mode 100755 index 0000000..8d8fbef --- /dev/null +++ b/build-php-remi.sh @@ -0,0 +1,45 @@ +#!/bin/bash -e + +PHP_MINOR_VERSION=$1 + +echo "Building layer for PHP 7.$PHP_MINOR_VERSION - using Remi repository" + +yum install -y wget +yum install -y yum-utils +wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm +wget https://rpms.remirepo.net/enterprise/remi-release-6.rpm +rpm -Uvh epel-release-latest-6.noarch.rpm +rpm -Uvh remi-release-6.rpm + +yum-config-manager --enable remi-php7${PHP_MINOR_VERSION} + +yum install -y httpd +yum install -y postgresql-devel +yum install -y libargon2-devel + +yum install -y --disablerepo="*" --enablerepo="remi,remi-php7${PHP_MINOR_VERSION}" php php-mbstring php-pdo php-mysql php-pgsql php-xml php-process + + +mkdir /tmp/layer +cd /tmp/layer +cp /opt/layer/bootstrap bootstrap +sed "s/PHP_MINOR_VERSION/${PHP_MINOR_VERSION}/g" /opt/layer/php.ini >php.ini + +mkdir bin +cp /usr/bin/php bin/ + +mkdir lib +for lib in libncurses.so.5 libtinfo.so.5 libpcre.so.0; do + cp "/lib64/${lib}" lib/ +done + +cp /usr/lib64/libedit.so.0 lib/ +cp /usr/lib64/libargon2.so.0 lib/ +cp /usr/lib64/libpq.so.5 lib/ +cp /usr/lib64/libonig.so.5 lib/ + +mkdir -p lib/php/7.${PHP_MINOR_VERSION} +cp -a /usr/lib64/php/modules lib/php/7.${PHP_MINOR_VERSION}/ + +zip -r /opt/layer/php7${PHP_MINOR_VERSION}.zip . + diff --git a/build.sh b/build.sh index c646c79..7233fd8 100755 --- a/build.sh +++ b/build.sh @@ -1,11 +1,11 @@ #!/bin/bash -yum install -y php71-cli zip +yum install -y php71-mbstring.x86_64 zip php71-pgsql php71-mysqli mkdir /tmp/layer cd /tmp/layer cp /opt/layer/bootstrap . -cp /opt/layer/php.ini . +sed "s/PHP_MINOR_VERSION/1/g" /opt/layer/php.ini >php.ini mkdir bin cp /usr/bin/php bin/ @@ -16,6 +16,7 @@ for lib in libncurses.so.5 libtinfo.so.5 libpcre.so.0; do done cp /usr/lib64/libedit.so.0 lib/ +cp /usr/lib64/libpq.so.5 lib/ cp -a /usr/lib64/php lib/ diff --git a/php.ini b/php.ini index ce1c3ec..2f19388 100644 --- a/php.ini +++ b/php.ini @@ -1,4 +1,5 @@ -extension_dir=/opt/lib/php/7.1/modules +extension_dir=/opt/lib/php/7.PHP_MINOR_VERSION/modules +display_errors=On + extension=curl.so extension=json.so -display_errors=On \ No newline at end of file diff --git a/publish.sh b/publish.sh index 1f91f7d..78b3575 100755 --- a/publish.sh +++ b/publish.sh @@ -2,18 +2,21 @@ source regions.sh -MD5SUM=$(md5 -q php71.zip) -S3KEY="php71/${MD5SUM}" +PHP_VERSION="${1}" -for region in "${PHP71_REGIONS[@]}"; do +LAYER="php${PHP_VERSION//.}" +MD5SUM=$(md5 -q "${LAYER}.zip") +S3KEY="${LAYER}/${MD5SUM}" + +for region in "${PHP_REGIONS[@]}"; do bucket_name="stackery-layers-${region}" - echo "Publishing Lambda Layer php71 in region ${region}..." + echo "Publishing Lambda Layer ${LAYER} in region ${region}..." # Must use --cli-input-json so AWS CLI doesn't attempt to fetch license URL - version=$(aws --region $region lambda publish-layer-version --cli-input-json "{\"LayerName\": \"php71\",\"Description\": \"PHP 7.1 Web Server Lambda Runtime\",\"Content\": {\"S3Bucket\": \"${bucket_name}\",\"S3Key\": \"${S3KEY}\"},\"CompatibleRuntimes\": [\"provided\"],\"LicenseInfo\": \"http://www.php.net/license/3_01.txt\"}" --output text --query Version) - echo "Published Lambda Layer php71 in region ${region} version ${version}" + version=$(aws --region $region lambda publish-layer-version --cli-input-json "{\"LayerName\": \"${LAYER}\",\"Description\": \"PHP ${PHP_VERSION} Web Server Lambda Runtime\",\"Content\": {\"S3Bucket\": \"${bucket_name}\",\"S3Key\": \"${S3KEY}\"},\"CompatibleRuntimes\": [\"provided\"],\"LicenseInfo\": \"http://www.php.net/license/3_01.txt\"}" --output text --query Version) + echo "Published Lambda Layer ${LAYER} in region ${region} version ${version}" - echo "Setting public permissions on Lambda Layer php71 version ${version} in region ${region}..." - aws --region $region lambda add-layer-version-permission --layer-name php71 --version-number $version --statement-id=public --action lambda:GetLayerVersion --principal '*' > /dev/null - echo "Public permissions set on Lambda Layer php71 version ${version} in region ${region}" + echo "Setting public permissions on Lambda Layer ${LAYER} version ${version} in region ${region}..." + aws --region $region lambda add-layer-version-permission --layer-name "${LAYER}" --version-number $version --statement-id=public --action lambda:GetLayerVersion --principal '*' > /dev/null + echo "Public permissions set on Lambda Layer ${LAYER} version ${version} in region ${region}" done diff --git a/regions.sh b/regions.sh index dc2002f..d1b9e44 100644 --- a/regions.sh +++ b/regions.sh @@ -1,4 +1,4 @@ -PHP71_REGIONS=( +PHP_REGIONS=( ap-northeast-1 ap-northeast-2 ap-south-1 diff --git a/unpublish.sh b/unpublish.sh index eb2ff9d..756825f 100755 --- a/unpublish.sh +++ b/unpublish.sh @@ -1,16 +1,18 @@ #!/bin/bash -e -VERSION=$1 +PHP_VERSION="${1}" +LAYER_VERSION="${2}" source regions.sh -MD5SUM=$(md5 -q php71.zip) -S3KEY="php71/${MD5SUM}" +LAYER="php${PHP_VERSION//.}" +MD5SUM=$(md5 -q "${LAYER}.zip") +S3KEY="${LAYER}/${MD5SUM}" -for region in "${PHP71_REGIONS[@]}"; do +for region in "${PHP_REGIONS[@]}"; do bucket_name="stackery-layers-${region}" - echo "Deleting Lambda Layer php71 version ${VERSION} in region ${region}..." - aws --region $region lambda delete-layer-version --layer-name php71 --version-number $VERSION > /dev/null - echo "Deleted Lambda Layer php71 version ${VERSION} in region ${region}" + echo "Deleting Lambda Layer ${LAYER} version ${VERSION} in region ${region}..." + aws --region $region lambda delete-layer-version --layer-name ${LAYER} --version-number $VERSION > /dev/null + echo "Deleted Lambda Layer ${LAYER} version ${VERSION} in region ${region}" done diff --git a/upload.sh b/upload.sh index 89c5afb..191f734 100755 --- a/upload.sh +++ b/upload.sh @@ -2,13 +2,16 @@ source regions.sh -MD5SUM=$(md5 -q php71.zip) -S3KEY="php71/${MD5SUM}" +PHP_VERSION="${1}" -for region in "${PHP71_REGIONS[@]}"; do +LAYER="php${PHP_VERSION//.}" +MD5SUM=$(md5 -q "${LAYER}.zip") +S3KEY="${LAYER}/${MD5SUM}" + +for region in "${PHP_REGIONS[@]}"; do bucket_name="stackery-layers-${region}" - echo "Uploading php71.zip to s3://${bucket_name}/${S3KEY}" + echo "Uploading ${LAYER}.zip to s3://${bucket_name}/${S3KEY}" - aws --region $region s3 cp php71.zip "s3://${bucket_name}/${S3KEY}" + aws --region $region s3 cp ${LAYER}.zip "s3://${bucket_name}/${S3KEY}" done