forked from heroku/heroku-buildpack-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile
executable file
·412 lines (368 loc) · 19.5 KB
/
compile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env bash
# bin/compile <build-dir> <cache-dir> <env-dir>
install_ext () {
local ext=$1
local reason=${2:-}
local ext_ini="$BP_DIR/conf/php/conf.d/ext-$ext.ini"
local ext_so=
local ext_dir=$(php-config --extension-dir)
local ext_api=$(basename $ext_dir)
if [[ -f "$ext_ini" ]]; then
ext_so=$(php -r '$ini=parse_ini_file("'$ext_ini'"); echo $ext=$ini["zend_extension"]?:$ini["extension"]; exit((int)empty($ext));') # read .so name from .ini because e.g. opcache.so is named "zend-opcache"
if [[ ! -f "$ext_dir/$ext_so" ]]; then
if [[ -f "$BP_DIR/support/build/extensions/$ext_api/$ext" ]]; then
curl --silent --location "${S3_URL}/extensions/${ext_api}/${ext}.tar.gz" | tar xz -C $BUILD_DIR/.heroku/php
echo "- ${ext} (${reason}; downloaded)" | indent
cp "${ext_ini}" "${BUILD_DIR}/.heroku/php/etc/php/conf.d"
else
warning_inline "Unknown extension ${ext} (${reason}), install may fail!"
fi
else
echo "- ${ext} (${reason}; bundled)" | indent
cp "${ext_ini}" "${BUILD_DIR}/.heroku/php/etc/php/conf.d"
fi
elif [[ -f "${ext_dir}/${ext}.so" ]]; then
echo "extension = ${ext}.so" > "${BUILD_DIR}/.heroku/php/etc/php/conf.d/ext-${ext}.ini"
echo "- ${ext} (${reason}; bundled)" | indent
elif echo -n ${ext} | php -r 'exit((int)!extension_loaded(file_get_contents("php://stdin")));'; then
: # echo "- ${ext} (${reason}; enabled by default)" | indent
else
warning_inline "Unknown extension ${ext} (${reason}), install may fail!"
fi
}
# fail hard
set -o pipefail
# fail harder
set -eu
# move hidden files too, just in case
shopt -s dotglob
STACK=${STACK:-cedar} # Anvil has none
BUILD_DIR=$1
CACHE_DIR=$2/php
mkdir -p "$CACHE_DIR"
ENV_DIR=${3:-} # Anvil has none
BP_DIR=$(cd $(dirname $0); cd ..; pwd)
# convenience functions
source $BP_DIR/bin/util/common.sh
# for extensions that need special treatment
source $BP_DIR/bin/util/newrelic.sh
source $BP_DIR/bin/util/blackfire.sh
# if this is set it prevents Git clones (e.g. for Composer installs from source) during the build in some circumstances, and it is set in SSH Git deploys to Heroku
unset GIT_DIR
export_env_dir "$ENV_DIR" '^[A-Z_][A-Z0-9_]*$' '^(HOME|PATH|GIT_DIR|CPATH|CPPATH|LD_PRELOAD|LIBRARY_PATH|LD_LIBRARY_PATH|STACK|S3_URL|RTVS_URL|REQUEST_ID)$'
BUILDPACK_URL=${BUILDPACK_URL:-} # Anvil has none
BUILDPACK_BRANCH=$(expr "$BUILDPACK_URL" : '^.*/heroku-buildpack-php#\(..*\)$' || expr "$BUILDPACK_URL" : '^.*/heroku-buildpack-php\.git#\(..*\)$' || true) # POSIX expr doesn't understand ".+" or "(\.git)?"
BUILDPACK_BRANCH=${BUILDPACK_BRANCH:-master}
if [[ "$BUILDPACK_BRANCH" != v* && "$BUILDPACK_BRANCH" != "master" ]]; then
S3_URL="develop"
fi
S3_URL="https://lang-php.s3.amazonaws.com/dist-${STACK}-${S3_URL:-"master"}"
RTVS_URL="https://php-runtime-version-selector.herokuapp.com"
cd $BUILD_DIR
if [[ -n ${COMPOSER:-} ]]; then
status "Using '$COMPOSER' (from "'$COMPOSER env var) for installation.'
else
export COMPOSER="composer.json"
fi
COMPOSER_LOCK=$(basename "$COMPOSER" ".json")".lock" # replace .json with .lock if it exists, append .lock otherwise
if [[ -s "$COMPOSER" ]]; then
cat "$COMPOSER" | python -mjson.tool &> /dev/null || error "Could not parse '$COMPOSER'; make sure it's valid!"
else
if [[ ! -f "$COMPOSER" ]]; then
warning "No '$COMPOSER' found.
Using 'index.php' to declare PHP applications is considered legacy
functionality and may lead to unexpected behavior."
else
notice "Your '$COMPOSER' is completely empty.
Please change its contents to at least '{}' so it is valid JSON."
fi
echo "{}" > $COMPOSER
fi
mkdir -p .heroku/php
export COMPOSER_HOME=$CACHE_DIR/.composer
mkdir -p $COMPOSER_HOME
PHP_VERSION=
HHVM_VERSION=
if [[ "$STACK" == "cedar" ]]; then
runtimes=$(cd $BP_DIR/support/build; ls {php-5*,hhvm-3.2.0}) # cedar only has HHVM 3.2 and no PHP 7
else
runtimes=$(cd $BP_DIR/support/build; ls {php,hhvm}-*)
fi
engine="php"
engine_r="php -r"
if [[ -f "$COMPOSER" ]]; then
if [[ ! -f "$COMPOSER_LOCK" ]]; then
cat composer.json | python -c 'import sys, json; sys.exit(bool(json.load(sys.stdin).get("require", {})))' 2> /dev/null || error "Your '$COMPOSER' lists dependencies inside 'require',
but no '$COMPOSER_LOCK' was found. Please run 'composer update' to
re-generate '$COMPOSER_LOCK' if necessary, and commit it into your
repository. For more information, please refer to the docs at
https://devcenter.heroku.com/articles/php-support#activation"
fi
solver_payload=$(echo -n "$runtimes" | python -c '
import sys, json
ret = {}
ret["packages"] = sys.stdin.read().splitlines()
try:
c_lock = json.load(open(sys.argv[1]))
ret["lock"] = {k: c_lock.get(k, None) for k in ["minimum-stability", "prefer-stable", "stability-flags"]}
ret["lock"]["platform"] = {k: dict(c_lock.get("platform", {})).get(k, None) for k in ["php", "hhvm"]} # wrap in dict() to prevent simple errors with {} vs []
except IOError:
ret["lock"] = None
print json.dumps(ret)
' "$COMPOSER_LOCK" 2> /dev/null) || error "Couldn't parse '$COMPOSER_LOCK'; it must be valid JSON.
Run 'composer update' to have it re-generated by Composer."
# warn if minimum-stability is set to non-stable (regardless of whether prefer-stable is used)
if echo -n "$solver_payload" | python -c 'import sys, json; p = json.load(sys.stdin); sys.exit(p["lock"] == None or p["lock"]["minimum-stability"] == "stable");' 2> /dev/null; then
warning "Your 'composer.json' contains a non-'stable' setting
for 'minimum-stability'. This may cause the installation of
unstable versions of runtimes and extensions during this deploy.
It is recommended that you always use stability flags instead,
even if you have 'prefer-stable' enabled. For more information,
see https://getcomposer.org/doc/01-basic-usage.md#stability"
fi
solver_result=$(echo -n "$solver_payload" | curl --silent --location --fail -H'Content-Type: application/json' -H"X-Build-Request-Id: ${REQUEST_ID:-}" -d @- "${RTVS_URL}/resolve?default_runtime=php") || error "Failed to resolve runtime requirements.
If the issue persists, please contact support."
while IFS="|" read runtime_name runtime_source runtime_constraint runtime_result; do
# make sure we use the correct names for "composer.json" and "composer.lock"
case "$runtime_source" in
"composer.json")
runtime_source="$COMPOSER"
;;
"composer.lock")
runtime_source="$COMPOSER_LOCK"
;;
esac
if [[ $runtime_result ]]; then
if [[ $runtime_source == "default" ]]; then
status "No runtime required in '$COMPOSER', defaulting to ${runtime_name^^} $runtime_result."
else
status "Resolved '$runtime_source' requirement for ${runtime_name^^} to version ${runtime_result}."
if [[ "$runtime_constraint" == "$runtime_result" || "$runtime_constraint" == "=$runtime_result" ]]; then
recommended_selector="~$runtime_result"
if [[ $runtime_name == "hhvm" ]]; then
recommended_selector="${recommended_selector%.*}" # strip "3.2.0" to just "3.2"; HHVM has different versioning
fi
warning "Your '$COMPOSER' requirement for runtime '$runtime_name'
specifies an exact-match constraint of '$runtime_constraint'.
This means you will not automatically get more recent compatible
versions of ${runtime_name^^} on push once they are available. As any such
new version may contain security updates, we strongly suggest
you use a more lenient selector like '$recommended_selector' instead.
See https://devcenter.heroku.com/articles/php-support for info."
fi
fi
if [[ $runtime_name == "php" ]]; then
PHP_VERSION="$runtime_result"
elif [[ $runtime_name == "hhvm" ]]; then
HHVM_VERSION="$runtime_result"
engine="hhvm"
engine_r="hhvm --php -r"
if [[ "$STACK" == "cedar" ]]; then
warning_inline "Support for HHVM on the cedar stack is deprecated and
will be removed soon. Please upgrade to cedar-14 to continue to
use HHVM and get access to new releases. For more information,
see https://devcenter.heroku.com/articles/cedar-14-migration"
fi
fi
else
error "Could not resolve '$runtime_source' requirement for ${runtime_name^^} $runtime_constraint,
please adjust the selector. The following runtimes are available:
$(echo $runtimes | fold -s -w 65)"
fi
done <<<"$solver_result"
fi
status "Installing system packages..."
# we need to run things in here, set it up!
mkdir -p /app/.heroku
ln -s $BUILD_DIR/.heroku/php /app/.heroku/php
export PATH=/app/.heroku/php/bin:$PATH
if [[ "${PHP_VERSION}" ]]; then
PHP_DIST_URL="$S3_URL/php-$PHP_VERSION.tar.gz"
echo "- PHP $PHP_VERSION" | indent
curl --silent --location "$PHP_DIST_URL" | tar xz -C $BUILD_DIR/.heroku/php
# update config files
mkdir -p $BUILD_DIR/.heroku/php/etc/php
cp $BP_DIR/conf/php/php.ini $BUILD_DIR/.heroku/php/etc/php
cp $BP_DIR/conf/php/php-fpm.conf $BUILD_DIR/.heroku/php/etc/php
mkdir -p $BUILD_DIR/.heroku/php/etc/php/conf.d
# store PHP version in the slug for possible later evaluation
mkdir -p $BUILD_DIR/.heroku/php/.versions/php
echo $PHP_VERSION > $BUILD_DIR/.heroku/php/.versions/php/php
fi
if [[ "${HHVM_VERSION}" ]]; then
HHVM_DIST_URL="$S3_URL/hhvm-$HHVM_VERSION.tar.gz"
echo "- HHVM $HHVM_VERSION" | indent
curl --silent --location "$HHVM_DIST_URL" | tar xz -C $BUILD_DIR/.heroku/php
# store HHVM version in the slug for possible later evaluation
mkdir -p $BUILD_DIR/.heroku/php/.versions/hhvm
echo $HHVM_VERSION > $BUILD_DIR/.heroku/php/.versions/hhvm/hhvm
# make HHVM accessible
export PATH=$PATH:/app/.heroku/php/usr/bin
# so it'll start. remember to use the full path to the binary, or we'll get an infinite loop
hhvm() { LD_LIBRARY_PATH=/app/.heroku/php/usr/lib/x86_64-linux-gnu:/app/.heroku/php/usr/lib/hhvm:/app/.heroku/php/usr/lib `which hhvm` "$@"; }
export -f hhvm
fi
APACHE_VERSION="2.4.16"
APACHE_DIST_URL="$S3_URL/apache-$APACHE_VERSION.tar.gz"
echo "- Apache $APACHE_VERSION" | indent
curl --silent --location "$APACHE_DIST_URL" | tar xz -C $BUILD_DIR/.heroku/php
# Apache; copy in our config
cp $BP_DIR/conf/apache2/httpd.conf.default $BUILD_DIR/.heroku/php/etc/apache2/httpd.conf
# store Apache version in the slug for possible later evaluation
mkdir -p $BUILD_DIR/.heroku/php/.versions/apache2
echo $APACHE_VERSION > $BUILD_DIR/.heroku/php/.versions/apache2/apache2
NGINX_VERSION="1.8.0"
NGINX_DIST_URL="$S3_URL/nginx-$NGINX_VERSION.tar.gz"
echo "- Nginx $NGINX_VERSION" | indent
curl --silent --location "$NGINX_DIST_URL" | tar xz -C $BUILD_DIR/.heroku/php
# nginx; copy in our config
cp $BP_DIR/conf/nginx/nginx.conf.default $BUILD_DIR/.heroku/php/etc/nginx/nginx.conf
# store Nginx version in the slug for possible later evaluation
mkdir -p $BUILD_DIR/.heroku/php/.versions/nginx
echo $NGINX_VERSION > $BUILD_DIR/.heroku/php/.versions/nginx/nginx
# handle extensions for PHP
if [[ "${PHP_VERSION}" ]]; then
status "Installing PHP extensions..."
php() {
# the newrelic extension logs to stderr which pollutes our build output on each invocation of PHP, the daemon it launches will prevent the build from finishing, and each call to PHP would be logged to NR as non-web traffic, so we disable it for the duration of this build
`which php` -dnewrelic.enabled=0 -dnewrelic.loglevel=error -dnewrelic.daemon.dont_launch=3 -dnewrelic.daemon.loglevel=error "$@"
}
exts=()
if [[ -f "$COMPOSER_LOCK" ]]; then
exts=($(cat "$COMPOSER_LOCK" | python -c 'import sys, json, itertools; l=json.load(sys.stdin); print "\n".join(list(set(itertools.chain([plat[4:].lower() for plat in l.get("platform", []) if plat.startswith("ext-")], *[ [ pkg[4:].lower() for pkg in p.get("require", []) if pkg.startswith("ext-") ] for p in l.get("packages", []) ]))))' 2> /dev/null || true)) # convert to array
ext_source="$COMPOSER_LOCK"
else
exts=($(cat "$COMPOSER" | python -c 'from __future__ import print_function; import sys, json; { print(key[4:].lower()) for key in json.load(sys.stdin)["require"] if key.startswith("ext-")}' 2> /dev/null || true)) # convert to array
ext_source="$COMPOSER"
fi
for ext in "${!exts[@]}"; do # loop over keys in case the array is empty or else it'll error out
install_ext "${exts[$ext]}" $ext_source
done
# special treatment for New Relic; we enable it if we detect a license key for it
install_newrelic_ext
# special treatment for Blackfire; we enable it if we detect a server id and a server token for it
install_blackfire_ext
if [[ ${#exts[@]} -eq 0 || ! ${exts[*]} =~ "zend-opcache" ]]; then
install_ext "zend-opcache" "automatic"
exts+=("zend-opcache")
fi
fi
status "Installing dependencies..."
# check if we should use a composer.phar version bundled with the project
if [[ -f "composer.phar" ]]; then
[[ -x "composer.phar" ]] || error "File '/composer.phar' isn't executable; please 'chmod +x'!"
$engine_r 'new Phar("composer.phar");' &> /dev/null || error "File '/composer.phar' is not a valid PHAR archive!"
composer() {
$engine composer.phar "$@"
}
export -f composer
composer --version 2>&1 | grep "^Composer version" > /dev/null || error "File '/composer.phar' is not a Composer executable!"
notice_inline "Using '/composer.phar' to install dependencies."
else
curl --silent --location "$S3_URL/composer.tar.gz" | tar xz -C $BUILD_DIR/.heroku/php
composer() {
$engine `which composer` "$@"
}
export -f composer
fi
# echo composer version for info purposes
# tail to get rid of outdated version warnings (Composer sends those to STDOUT instead of STDERR)
composer --version 2> /dev/null | tail -n 1 | indent
# throw a notice if people have added their vendor dir to Git; that's bad practice and makes everything slow and cluttered
if [[ -e "$(composer config vendor-dir 2> /dev/null | tail -n 1)" ]]; then # tail, as composer echos outdated version warnings to STDOUT
warning "Your Composer vendor dir is part of your Git repository.
That directory should not be under version control; only your
'$COMPOSER' and '$COMPOSER_LOCK' files should be added, which
will let Composer handle installation of dependencies on deploy.
To suppress this notice, first remove the folder from your index
by running 'git rm --cached $(composer config vendor-dir 2> /dev/null | tail -n 1)/'.
Next, edit your project's '.gitignore' file and add the folder
'/$(composer config vendor-dir 2> /dev/null | tail -n 1)/' to the list.
For more info, refer to the Composer FAQ: http://bit.ly/1rlCSZU"
fi
# handle custom oauth keys
COMPOSER_GITHUB_OAUTH_TOKEN=${COMPOSER_GITHUB_OAUTH_TOKEN:-}
if [[ -n "$COMPOSER_GITHUB_OAUTH_TOKEN" ]]; then
if curl --fail --silent -H "Authorization: token $COMPOSER_GITHUB_OAUTH_TOKEN" https://api.github.com/rate_limit > /dev/null; then
composer config -g github-oauth.github.com "$COMPOSER_GITHUB_OAUTH_TOKEN" &> /dev/null # redirect outdated version warnings (Composer sends those to STDOUT instead of STDERR)
notice_inline 'Using $COMPOSER_GITHUB_OAUTH_TOKEN for GitHub OAuth.'
else
error 'Invalid $COMPOSER_GITHUB_OAUTH_TOKEN for GitHub OAuth!'
fi
else
# don't forget to remove any stored key if it's gone from the env
composer config -g --unset github-oauth.github.com &> /dev/null # redirect outdated version warnings (Composer sends those to STDOUT instead of STDERR)
if curl --silent https://api.github.com/rate_limit | python -c 'import sys, json; sys.exit((json.load(sys.stdin)["resources"]["core"]["remaining"] > 0))'; then # yes, check > 0, not < 1 - exit status of 0 will trigger the if
notice "You've reached the GitHub API's request rate limit.
Composer will try and fall back to slower downloads from source.
It's strongly recommended you use a custom OAuth token; see
http://devcenter.heroku.com/articles/php-support#custom-github-oauth-tokens"
fi
fi
# no need for the token to stay around in the env
unset COMPOSER_GITHUB_OAUTH_TOKEN
# install dependencies unless composer.json is completely empty (in which case it'd talk to packagist.org which may be slow and is unnecessary)
cat "$COMPOSER" | python -c 'import sys,json; sys.exit(not json.load(sys.stdin));' && composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction 2>&1 | indent
composer show --installed heroku/heroku-buildpack-php &> /dev/null && error "Your '$COMPOSER' requires 'heroku/heroku-buildpack-php'.
This package may only be used as a dependency in 'require-dev'!"
if cat "$COMPOSER" | python -c 'import sys,json; sys.exit("compile" not in json.load(sys.stdin).get("scripts", {}));'; then
status "Running 'composer compile'..."
composer run-script --no-dev --no-interaction compile 2>&1 | indent
fi
status "Preparing runtime environment..."
# install this buildpack like a composer package
# it will contain the apache/nginx/php configs and the boot script
# TODO: warn if require-dev has the package using a different branch
shopt -u dotglob # we don't want .git, .gitignore et al
composer_vendordir=$(composer config vendor-dir 2> /dev/null | tail -n 1) # tail, as composer echos outdated version warnings to STDOUT
composer_bindir=$(composer config bin-dir 2> /dev/null | tail -n 1) # tail, as composer echos outdated version warnings to STDOUT
# figure out the package dir name to write to and copy to it
hbpdir="$composer_vendordir/$(cat $BP_DIR/composer.json | python -c 'import sys, json; print json.load(sys.stdin)["name"]')"
mkdir -p "$BUILD_DIR/$hbpdir"
cp -r "$BP_DIR"/* "$BUILD_DIR/$hbpdir/"
# make bin dir, just in case
mkdir -p "$BUILD_DIR/$composer_bindir"
# figure out shortest relative path from vendor/heroku/heroku-buildpack-php to vendor/bin (or whatever the bin dir is)
relbin=$(python -c "import os.path; print os.path.relpath('$hbpdir', '$composer_bindir')")
# collect bin names from composer.json
relbins=$(cat $BP_DIR/composer.json | python -c 'from __future__ import print_function; import sys, json; { print(sys.argv[1]+"/"+bin) for bin in json.load(sys.stdin)["bin"] }' $relbin)
# link to bins
cd $BUILD_DIR/$composer_bindir
ln -s $relbins .
cd $BUILD_DIR
# Update the PATH
mkdir -p $BUILD_DIR/.profile.d
cat > $BUILD_DIR/.profile.d/php.sh <<"EOF"
export PATH="$HOME/.heroku/php/bin:$HOME/.heroku/php/sbin:$PATH"
EOF
if [[ $engine == "hhvm" ]]; then
cat > $BUILD_DIR/.profile.d/hhvm.sh <<"EOF"
export PATH="$PATH:$HOME/.heroku/php/usr/bin"
hhvm() { LD_LIBRARY_PATH=$HOME/.heroku/php/usr/lib/x86_64-linux-gnu:$HOME/.heroku/php/usr/lib/hhvm:$HOME/.heroku/php/usr/lib `which hhvm` "$@"; }
export -f hhvm
EOF
fi
# Alias composer if needed
if [[ -f "composer.phar" ]]; then
cat > $BUILD_DIR/.profile.d/composer.sh <<EOF
composer() {
$engine composer.phar "\$@"
}
export -f composer
EOF
else
cat > $BUILD_DIR/.profile.d/composer.sh <<EOF
composer() {
$engine \`which composer\` "\$@"
}
export -f composer
EOF
fi
install_newrelic_daemon
install_newrelic_userini
install_blackfire_agent
if [[ ! -f "Procfile" ]]; then
bindir=$(composer config bin-dir 2> /dev/null | tail -n 1) # tail, as composer echos outdated version warnings to STDOUT
echo "web: $bindir/heroku-$engine-apache2" > Procfile
notice_inline "No Procfile, using 'web: $bindir/heroku-$engine-apache2'."
fi