service-ue2.py 1.19 KB
Newer Older
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
1
2
3
4
5
6
7
8
9
10
from flask import Flask, redirect, request
import requests, os, logging, json
import elasticapm
from elasticapm.contrib.flask import ElasticAPM

# A very boring and basic hip-hop-service to demonstrate 
# observability via tracing across multiple services.

logging.basicConfig(level=logging.INFO)

Nane Kratzke's avatar
Nane Kratzke committed
11
service = os.environ.get('BASE', 'hiphop-svc')
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
12
tier = int(os.environ.get('TIER', '1'))
Nane Kratzke's avatar
Nane Kratzke committed
13
id = os.environ.get('NS', 'unknown')
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
14
app = Flask(__name__)
Nane Kratzke's avatar
Nane Kratzke committed
15
apm = ElasticAPM(app, service_name=f"{id}-{service}-{tier}")
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
16
17
18

@app.route('/')
def index():
Nane Kratzke's avatar
Nane Kratzke committed
19
    return redirect('/hip')
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
20
21
22
23
24
25
26

@app.route('/hip')
def hip():
    logging.info(f"Request from { request.remote_addr } with headers { json.dumps(dict(request.headers)) }")
    r = ""
    url = f"http://{ service }-{ tier + 1 }/hip"
    try:
Nane Kratzke's avatar
Nane Kratzke committed
27
        r = requests.get(url).content.decode('utf-8')
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
28
29
30
31
32
33
34
35
36
37
38
    except Exception as ex:
        logging.error(f"Fetching { url } failed ({ ex })") 
        r = "END"
    
    hip = "hip " if tier == 1 else ""

    return f"{hip} hop-{ tier } -> { r }".strip()

# This is just to demonstrate the power and pitfalls of centralized
# consolidated logging.
if tier <= 1:
Nane Kratzke's avatar
Nane Kratzke committed
39
    print(f"pwd: { ' '.join(id.split('-')[::-1]) }")
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
40
41

app.run(host="0.0.0.0", port=80)