forked from better/segment2datadog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
54 lines (49 loc) · 1.6 KB
/
app.py
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
45
46
47
48
49
50
51
52
53
54
import hmac
import hashlib
import logging
import os
from flask import Flask, jsonify, request, abort
from datadog import initialize, api, statsd
# get keys from enfironment variables
SEGMENT_SHARED_SECRET = os.environ['SEGMENT_SHARED_SECRET']
DATADOG_API_KEY = os.environ['DD_API_KEY']
DATADOG_APP_KEY = os.environ['DD_APP_KEY']
# initialize datadog
options = {
'api_key': DATADOG_API_KEY,
'app_key': DATADOG_APP_KEY
}
initialize(**options)
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
@app.route('/')
def index():
app.logger.debug('viewed root route')
return "Segment2Datadog is up and running!"
@app.route('/api/<string:source>', methods=['POST'])
def segment2datadog(source):
# check signature
signature = request.headers['x-signature']
digest = hmac.new(SEGMENT_SHARED_SECRET.encode(), msg=request.data, digestmod=hashlib.sha1).hexdigest()
if digest != signature:
abort(403, 'Signature not valid.')
if not source:
abort(404, 'Source parameter not present.')
content = request.get_json(silent=True)
# increment event counter in datadog
if content['type'] == 'track':
app.logger.debug(
'{ event: "%s", userId: "%s" }',
'-'.join(content['event'].split()),
content['userId']
)
statsd.increment(
'segment.event',
tags = [
'source:' + source,
'event:' + '-'.join(content['event'].split()),
'type:' + content['type'],
'user-id:' + content['userId'].replace('|','_')
]
)
return jsonify({'source': source, 'data': content})