service.py 1.93 KB
Newer Older
Nane Kratzke's avatar
Nane Kratzke committed
1
2
3
4
5
6
7
from flask import Flask, redirect, request, jsonify
from jaeger_client import Config
import opentracing
import requests
import traceback 
import os
import json
Nane Kratzke's avatar
Nane Kratzke committed
8
from joblib import Parallel, delayed
9
10
from elasticapm.contrib.flask import ElasticAPM
apm = ElasticAPM(app)
Nane Kratzke's avatar
Nane Kratzke committed
11

Nane Kratzke's avatar
Nane Kratzke committed
12
13
14
15
16
17
# A very boring and basic space-service to demonstrate 
# observability via tracing.

service = os.environ.get('SERVICE', 'space')
app = Flask(__name__)

18
19
20
21
22
# config = Config(config = {
#    'sampler': { 'type': 'const', 'param': 1 }, 
#    'logging': True,
#    'reporter_batch_size': 1
# }, service_name=service)
Nane Kratzke's avatar
Nane Kratzke committed
23

24
# tracer = config.initialize_tracer()
Nane Kratzke's avatar
Nane Kratzke committed
25
26
27
28
29

@app.route('/')
def index():
    return redirect('/space')

Nane Kratzke's avatar
Nane Kratzke committed
30
31
32
33
34
def load_url(key, url):
    return key, json.loads(requests.get(url).content)

    #with tracer.start_span(operation_name=key, child_of=ctx) as span:
    #    return key, json.loads(requests.get(url).content)
Nane Kratzke's avatar
Nane Kratzke committed
35

Nane Kratzke's avatar
Nane Kratzke committed
36
37
@app.route('/space')
def space():
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    #with tracer.start_span(operation_name="space") as parent_span:
    try:
        lat = float(request.args.get('lat', "0.0001"))
        lon = float(request.args.get('lon', "0.0001"))
    except Exception as ex:
        print(ex)
        return "Bad request (lat/lon not numeric)", 400
    
    queries = {
        "astros": "http://api.open-notify.org/astros.json",
        "position": "http://api.open-notify.org/iss-now.json",
        "passtime": f"http://api.open-notify.org/iss-pass.json?lat={ lat }&lon={ lon }"
    }

        #with tracer.start_span(operation_name="parallel", child_of=parent_span) as span:
    results = Parallel(n_jobs=3)(delayed(load_url)(key, url) for key, url in queries.items())
    result = { key: content for key, content in results }
Nane Kratzke's avatar
n=3    
Nane Kratzke committed
55

Nane Kratzke's avatar
Nane Kratzke committed
56
57
58
        #for key, url in queries.items():
        #    with tracer.start_span(operation_name=key, child_of=parent_span) as span:
        #       result[key] = json.loads(requests.get(url).content)
Nane Kratzke's avatar
Nane Kratzke committed
59
60
61
62

    print(result)
    return jsonify(result)

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