Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use redis #2

Merged
merged 2 commits into from
Jan 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
11 changes: 2 additions & 9 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,9 +1,2 @@
# Created by .ignore support plugin (hsz.mobi)
.project
*/.project
/*.iml
.idea
.vagrant
*.rpm
/vagrant/*.vdi
*.DS_Store
__pycache__
venv
6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

28 changes: 28 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": [
"run",
"--port",
"5000"
],
"env": {
"FLASK_APP": "app.app",
"REDIS_HOST":"127.0.0.1",
"FLASK_PORT": "8080"
},
"pythonPath": "${config:python.pythonPath}",
"cwd": "${workspaceFolder}",
"module": "flask"
}
]
}
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"python.pythonPath": "venv/bin/python3"
}
15 changes: 15 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM python:3.7-alpine

LABEL \
app="docker-cursantX" \
layer="frontend" \
git-url="https://github.com/hlesey/phippy.git"

WORKDIR /app
COPY app/ .
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

ENV FLASK_APP=app

CMD ["python", "-m", "flask", "run", "--host", "0.0.0.0"]
18 changes: 18 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

DOCKER_HUB_USER=hlesey
REPO_NAME=phippy
VERSION=$$(cat app/__version__.py | cut -d '=' -f2 | tr -d '"')

build:
docker build -t ${DOCKER_HUB_USER}/${REPO_NAME}:${VERSION} .

push:
docker push ${DOCKER_HUB_USER}/${REPO_NAME}:${VERSION}

run:
docker-compose up

dev_setup:
[ -d venv ] || mkdir venv
[ -f venv/bin/activate ] || python3 -m venv venv
./venv/bin/pip install -r requirements.txt
26 changes: 9 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# phippy
# Phippy
Simple tutorial to build and deploy a simple Python app in Kubernetes.


Expand All @@ -11,29 +11,19 @@ docker push <DOCKER_HUB_USER>/phippy
```

## Launch the app using Docker
```
docker network create phippy
docker run -d -p 2379:2379 --net phippy --name etcd quay.io/coreos/etcd:3.3.4
docker run -d -p 31380:80 --net phippy --name phippy <DOCKER_HUB_USER>/phippy
```

Or you can use the existing scripts to build/push/run/cleanup the app:
You can use the existing commands to build/push/run the app:

```
./docker_build.sh
./docker_push.sh
./docker_run.sh
./docker_cleanup.sh
make build
make push
make run
```

## Test the app
```
curl localhost:31380
```

## Launch the app with Docker Compose
```
docker-compose up -d
make run
curl localhost:5000
```

## Scale up the app with Docker Compose
Expand Down Expand Up @@ -63,13 +53,15 @@ kubectl describe svc phippy
kubectl get nodes
curl <NODE_IP>:<NODEPORT>
```

## Optional - deploy app via ingress

```
kubectl apply -f kubernetes/ingress
```

## Test the app by accessing the ingress name and port

```
kubectl get ingress
kubectl describe ingress phippy
Expand Down
Empty file added app/__init__.py
Empty file.
1 change: 1 addition & 0 deletions app/__version__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__="1.0"
55 changes: 55 additions & 0 deletions app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import os
import platform
from prometheus_client import generate_latest, CONTENT_TYPE_LATEST, REGISTRY
from flask import Flask, Response, render_template
from redis import Redis
from app.__version__ import __version__
from app.monitoring import register_metrics

app = Flask(__name__)
redis = Redis(host=os.environ.get('REDIS_HOST', 'redis'), port=int(os.environ.get('REDIS_PORT', 6379)))
redis.set('hits', 0)
register_metrics(app, app_version=__version__)

@app.route('/', methods=['POST'])
def hits_post():
redis.incr('hits')
hits = int(redis.get('hits'))

if hits % 5 == 0:
return render_template("index.html", picture="/static/images/not_ok.png", message="You can do better!")
return render_template("index.html", picture="/static/images/ok.jpg", message="You hit me %s times." % hits)


@app.route('/', methods=['GET'])
def hits_get():
hits = int(redis.get('hits'))
return render_template("index.html", picture="/static/images/ok.jpg", message="You hit me %s times." % hits)


@app.route('/version')
def version():
return "version=" + __version__


@app.route('/healthz')
def healthz():
if redis.ping():
return "healthy"
else:
return "unheathy"


@app.route('/node')
def node():
return platform.node()


@app.route('/metrics')
def metrics():
return Response(generate_latest(), mimetype=CONTENT_TYPE_LATEST)


@app.errorhandler(500)
def handle_500(error):
return str(error), 500
71 changes: 71 additions & 0 deletions app/monitoring.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import logging
from flask import request
from prometheus_client import Counter, Histogram, Info
from timeit import default_timer

logger = logging.getLogger(__name__)

APP_NAME = "phippy"
APP_INFO = Info("app_version", "Aplication Version")

ERROROS_COUNT = Counter(
"errors_total",
"Number of errors",
["app", "verb", "endpont", "status"]
)
REQUESTS_COUNT = Counter(
"request_total",
"Request duration in seconds",
["app", "verb", "endpoint", "status"]
)
REQUEST_DURATION_HISTOGRAM = Histogram(
"request_duration_seconds",
"Request duration in seconds",
["app", "verb", "endpoint", "status"]
)



def before_request():
"""
Get start time of a request
"""
request._prometheus_metrics_request_start_time = default_timer()


def after_request(response):
"""
Register Prometheus metrics after each request
"""
if hasattr(request, "_prometheus_metrics_request_start_time"):
request_latency = max(
default_timer() - request._prometheus_metrics_request_start_time, 0
)
REQUEST_DURATION_HISTOGRAM.labels(
APP_NAME,
request.method,
request.endpoint,
response.status_code,
).observe(request_latency)
REQUESTS_COUNT.labels(
APP_NAME,
request.method,
request.endpoint,
response.status_code,
).inc()
return response


def register_metrics(app, app_version=None, app_config=None):
"""
Register metrics middlewares
Flask application can register more than one before_request/after_request.
Beware! Before/after request callback stored internally in a dictionary.
Before CPython 3.6 dictionaries didn't guarantee keys order, so callbacks
could be executed in arbitrary order.
"""

app.before_request(before_request)
app.after_request(after_request)
# APP_INFO.info({"version": app_version, "config": app_config})

File renamed without changes
File renamed without changes
7 changes: 7 additions & 0 deletions app/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{% block content %}
<body>
<h1>{{ message }}</h1>

<img src="{{picture}}" alt="Smiley face" height="300" width="350">
</body>
{% endblock %}
36 changes: 0 additions & 36 deletions dcos/app.json

This file was deleted.

30 changes: 0 additions & 30 deletions dcos/db.json

This file was deleted.

24 changes: 24 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: "3.7"

services:
web:
image: hlesey/phippy:1.0
environment:
REDIS_HOST: redis
REDIS_PORT: 6379
FLASK_ENV: development
ports:
- "5000:5000"
networks:
- phippy
depends_on:
- redis
redis:
image: hlesey/redis:4
ports:
- "6379:6379"
networks:
- phippy
networks:
phippy:
name: phippy
Loading