service.py 1.17 KB
Newer Older
Nane Kratzke's avatar
Nane Kratzke committed
1
from flask import Flask, redirect, request
Nane Kratzke's avatar
Nane Kratzke committed
2
import requests, os, logging, json
Nane Kratzke's avatar
Nane Kratzke committed
3
import elasticapm
Nane Kratzke's avatar
Nane Kratzke committed
4
from elasticapm.contrib.flask import ElasticAPM
5

Nane Kratzke's avatar
Nane Kratzke committed
6
# A very boring and basic hip-hop-service to demonstrate 
Nane Kratzke's avatar
Nane Kratzke committed
7
# observability via tracing across multiple services.
Nane Kratzke's avatar
Nane Kratzke committed
8

Nane Kratzke's avatar
Nane Kratzke committed
9
10
logging.basicConfig(level=logging.INFO)

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

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

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

Nane Kratzke's avatar
Nane Kratzke committed
34
    return f"{hip} hop-{ tier } -> { r }".strip()
Nane Kratzke's avatar
Nane Kratzke committed
35

Nane Kratzke's avatar
Hiphop    
Nane Kratzke committed
36
37
38
39

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

Nane Kratzke's avatar
Nane Kratzke committed
42
app.run(host="0.0.0.0", port=80)