Initial commit

This commit is contained in:
Honza Horak 2017-08-21 00:28:57 +02:00
commit a3e6c67270
35 changed files with 1152 additions and 0 deletions

View file

@ -0,0 +1 @@
APP_HOME=project

View file

@ -0,0 +1,3 @@
def application(environ, start_response):
start_response('200 OK', [('Content-Type','text/plain')])
return [b"Hello World from app-home WSGI application!"]

View file

@ -0,0 +1 @@
gunicorn

61
test/django-test-app/.gitignore vendored Normal file
View file

@ -0,0 +1,61 @@
# Django
db.sqlite3
staticfiles/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/

10
test/django-test-app/manage.py Executable file
View file

@ -0,0 +1,10 @@
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)

View file

View file

@ -0,0 +1,103 @@
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y*b^6p#z&cm2)8rzgbp2i4k*+rg2h%60l*bmf6hg&ro!z0-ael'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

View file

@ -0,0 +1,21 @@
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]

View file

@ -0,0 +1,16 @@
"""
WSGI config for project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = get_wsgi_application()

View file

@ -0,0 +1 @@
Django==1.8.1

View file

@ -0,0 +1,2 @@
Flask
gunicorn

View file

@ -0,0 +1,41 @@
import locale
import os
import sys
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello():
assert os.environ['PYTHONIOENCODING'] == 'UTF-8'
assert os.environ['LC_ALL'] == 'en_US.UTF-8'
assert os.environ['LANG'] == 'en_US.UTF-8'
assert locale.getdefaultlocale() == ('en_US', 'UTF-8')
assert locale.getpreferredencoding() == 'UTF-8'
print(u'\u292e')
return b'Hello World from locale test application!'
print('-- GLOBAL --')
for k,v in os.environ.items():
print('%r=%r' % (k, v))
print()
print(sys.stdout.encoding)
print(locale.getlocale())
print(locale.getdefaultlocale())
print(locale.getpreferredencoding())
try:
print(u'\u292e')
except Exception as e:
print(e)
print('------------')
if __name__ == '__main__':
application.run()

View file

@ -0,0 +1,14 @@
import os
import mod_wsgi.server
mod_wsgi.server.start(
'--log-to-terminal',
'--port', '8080',
'--trust-proxy-header', 'X-Forwarded-For',
'--trust-proxy-header', 'X-Forwarded-Port',
'--trust-proxy-header', 'X-Forwarded-Proto',
'--processes', os.environ.get('MOD_WSGI_PROCESSES', '1'),
'--threads', os.environ.get('MOD_WSGI_THREADS', '5'),
'--application-type', 'module',
'--entry-point', 'wsgi'
)

View file

@ -0,0 +1,2 @@
mod_wsgi
Flask

View file

@ -0,0 +1,9 @@
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello():
return b'Hello World from mod_wsgi hosted WSGI application!'
if __name__ == '__main__':
application.run()

View file

@ -0,0 +1,2 @@
gunicorn
numpy

View file

@ -0,0 +1,7 @@
import numpy
def application(environ, start_response):
start_response('200 OK', [('Content-Type','text/plain')])
matrix = numpy.array([[1,2,3],[6,5,4],[7,8,8]])
matrix.dot(numpy.linalg.inv(matrix))
return [b"Hello World from numpy WSGI application!"]

196
test/run Executable file
View file

@ -0,0 +1,196 @@
#!/bin/bash
#
# The 'run' performs a simple test that verifies that S2I image.
# The main focus here is to excersise the S2I scripts.
#
# IMAGE_NAME specifies a name of the candidate image used for testing.
# The image has to be available before this script is executed.
#
IMAGE_NAME=${IMAGE_NAME:-openshift/python-36-centos7-candidate}
declare -a WEB_APPS=({standalone,setup,django,numpy,app-home,virtualenv-uwsgi,locale,mod-wsgi}-test-app)
# TODO: Make command compatible for Mac users
test_dir="$(readlink -zf $(dirname "${BASH_SOURCE[0]}"))"
image_dir=$(readlink -zf ${test_dir}/..)
# TODO: This should be part of the image metadata
test_port=8080
info() {
echo -e "\n\e[1m[INFO] $@\e[0m\n"
}
image_exists() {
docker inspect $1 &>/dev/null
}
container_exists() {
image_exists $(cat $cid_file)
}
container_ip() {
docker inspect --format="{{ .NetworkSettings.IPAddress }}" $(cat $cid_file)
}
run_s2i_build() {
info "Building the ${1} application image ..."
s2i build ${s2i_args} file://${test_dir}/${1} ${IMAGE_NAME} ${IMAGE_NAME}-testapp
}
prepare() {
if ! image_exists ${IMAGE_NAME}; then
echo "ERROR: The image ${IMAGE_NAME} must exist before this script is executed."
exit 1
fi
# TODO: S2I build require the application is a valid 'GIT' repository, we
# should remove this restriction in the future when a file:// is used.
info "Preparing to test ${1} ..."
pushd ${test_dir}/${1} >/dev/null
git init
git config user.email "build@localhost" && git config user.name "builder"
git add -A && git commit -m "Sample commit"
popd >/dev/null
}
run_test_application() {
docker run --user=100001 ${CONTAINER_ARGS} --rm --cidfile=${cid_file} ${IMAGE_NAME}-testapp
}
cleanup_app() {
info "Cleaning up app container ..."
if [ -f $cid_file ]; then
if container_exists; then
docker stop $(cat $cid_file)
fi
fi
}
cleanup() {
info "Cleaning up the test application image"
if image_exists ${IMAGE_NAME}-testapp; then
docker rmi -f ${IMAGE_NAME}-testapp
fi
rm -rf ${test_dir}/${1}/.git
}
check_result() {
local result="$1"
if [[ "$result" != "0" ]]; then
info "TEST FAILED (${result})"
cleanup
exit $result
fi
}
wait_for_cid() {
local max_attempts=10
local sleep_time=1
local attempt=1
local result=1
info "Waiting for application container to start $CONTAINER_ARGS ..."
while [ $attempt -le $max_attempts ]; do
[ -f $cid_file ] && [ -s $cid_file ] && break
attempt=$(( $attempt + 1 ))
sleep $sleep_time
done
}
test_s2i_usage() {
info "Testing 's2i usage' ..."
s2i usage ${s2i_args} ${IMAGE_NAME} &>/dev/null
}
test_docker_run_usage() {
info "Testing 'docker run' usage ..."
docker run ${IMAGE_NAME} &>/dev/null
}
test_scl_usage() {
local run_cmd="$1"
local expected="$2"
local cid_file="$3"
info "Testing the image SCL enable"
out=$(docker run --rm ${IMAGE_NAME} /bin/bash -c "${run_cmd}" 2>&1)
if ! echo "${out}" | grep -q "${expected}"; then
echo "ERROR[/bin/bash -c "${run_cmd}"] Expected '${expected}', got '${out}'"
return 1
fi
out=$(docker exec $(cat ${cid_file}) /bin/bash -c "${run_cmd}" 2>&1)
if ! echo "${out}" | grep -q "${expected}"; then
echo "ERROR[exec /bin/bash -c "${run_cmd}"] Expected '${expected}', got '${out}'"
return 1
fi
out=$(docker exec $(cat ${cid_file}) /bin/sh -ic "${run_cmd}" 2>&1)
if ! echo "${out}" | grep -q "${expected}"; then
echo "ERROR[exec /bin/sh -ic "${run_cmd}"] Expected '${expected}', got '${out}'"
return 1
fi
}
test_connection() {
info "Testing the HTTP connection (http://$(container_ip):${test_port}) ${CONTAINER_ARGS} ..."
local max_attempts=30
local sleep_time=1
local attempt=1
local result=1
while [ $attempt -le $max_attempts ]; do
response_code=$(curl -s -w %{http_code} -o /dev/null http://$(container_ip):${test_port}/)
status=$?
if [ $status -eq 0 ]; then
if [ $response_code -eq 200 ]; then
result=0
fi
break
fi
attempt=$(( $attempt + 1 ))
sleep $sleep_time
done
return $result
}
test_application() {
local cid_file=$(mktemp -u --suffix=.cid)
# Verify that the HTTP connection can be established to test application container
run_test_application &
# Wait for the container to write it's CID file
wait_for_cid
test_scl_usage "python --version" "Python 3.6." "${cid_file}"
check_result $?
test_connection
check_result $?
cleanup_app
}
# Since we built the candidate image locally, we don't want S2I attempt to pull
# it from Docker hub
s2i_args="--force-pull=false"
# Verify the 'usage' script is working properly when running the base image with 's2i usage ...'
test_s2i_usage
check_result $?
# Verify the 'usage' script is working properly when running the base image with 'docker run ...'
test_docker_run_usage
check_result $?
for app in ${WEB_APPS[@]}; do
prepare ${app}
run_s2i_build ${app}
check_result $?
# test application with default user
test_application
# test application with random user
CONTAINER_ARGS="-u 12345" test_application
info "All tests for the ${app} finished successfully."
cleanup ${app}
done
info "All tests finished successfully."

57
test/setup-test-app/.gitignore vendored Normal file
View file

@ -0,0 +1,57 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/

View file

@ -0,0 +1,10 @@
from setuptools import setup, find_packages
setup (
name = "testapp",
version = "0.1",
description = "Example application to be deployed.",
packages = find_packages(),
install_requires = ["gunicorn"],
)

View file

@ -0,0 +1,4 @@
def application(environ, start_response):
start_response('200 OK', [('Content-Type','text/plain')])
return [b"Hello from gunicorn WSGI application!"]

View file

@ -0,0 +1,30 @@
import os
import time
from gunicorn.app.base import BaseApplication
from gunicorn.six import iteritems
print('LOADING MODULE %s' % __file__)
def wsgi_handler(environ, start_response):
print('HANDLE REQUEST %s' % time.time())
start_response('200 OK', [('Content-Type','text/html')])
return [b"Hello World from standalone WSGI application!"]
class StandaloneApplication(BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(StandaloneApplication, self).__init__()
def load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == '__main__':
StandaloneApplication(wsgi_handler, {'bind': ':8080'}).run()

View file

@ -0,0 +1 @@
gunicorn

View file

@ -0,0 +1 @@
UPGRADE_PIP_TO_LATEST=1

View file

@ -0,0 +1,29 @@
#!/bin/bash
# First test virtualenv environment and pip upgrade
echo "Testing that the virtual environment's Python is being used ..."
if [ "$(which python)" != "/opt/app-root/bin/python" ]; then
echo "ERROR: Initialization of the virtual environment failed."
exit 1
fi
echo "Testing UPGRADE_PIP_TO_LATEST=1 (set in .s2i/environment) ..."
pip_major_version=$(pip --version | cut -d" " -f2 | cut -d"." -f1)
if [ -z "$pip_major_version" ] || [ "$pip_major_version" -lt "9" ]; then
echo "ERROR: Failed to upgrade pip to version 9 or later."
exit 1
fi
# Now test the uwsgi server
exec uwsgi \
--http-socket :8080 \
--die-on-term \
--master \
--single-interpreter \
--enable-threads \
--threads=5 \
--thunder-lock \
--module wsgi

View file

@ -0,0 +1,2 @@
uWSGI
Flask

View file

@ -0,0 +1,9 @@
from flask import Flask
application = Flask(__name__)
@application.route('/')
def hello():
return b'Hello World from uWSGI hosted WSGI application!'
if __name__ == '__main__':
application.run()