service-ue2.py 1.2 KB
Newer Older
Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
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
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)

service = os.environ.get('HIPHOP', 'hiphop')
tier = int(os.environ.get('TIER', '1'))
app = Flask(__name__)
apm = ElasticAPM(app, 
   service_name=f"{ service }-{ tier }",
)

@app.route('/')
def index():
    with elasticapm.capture_span("redirect"):
        return redirect('/hip')

@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:
        r = requests.get(url).content
    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:
    print(f"pwd: { ' '.join(service.spit('-')[2:3]) }")

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