|
| 1 | +#!/usr/bin/env python |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | + |
| 19 | +from flask import abort, Flask, request, Response |
| 20 | +from elasticsearch import Elasticsearch |
| 21 | +import json |
| 22 | +import time |
| 23 | + |
| 24 | +def json_response(response): |
| 25 | + return json.dumps(response, indent=2) + "\n", 200, {'Content-Type': 'application/json; charset=utf-8'} |
| 26 | + |
| 27 | +def generate_app(config=None): |
| 28 | + app = Flask(__name__) |
| 29 | + |
| 30 | + @app.route('/report/<unique_id>', methods=['POST']) |
| 31 | + def report(unique_id): |
| 32 | + # We expect JSON data, so if the Content-Type doesn't match JSON data we throw an error |
| 33 | + if 'Content-Type' in request.headers: |
| 34 | + if request.headers['Content-Type'] != 'application/json': |
| 35 | + abort(417, "No or incorrect Content-Type header was supplied") |
| 36 | + |
| 37 | + index = "cloudstack-%s" % time.strftime("%Y.%m.%d", time.gmtime()) |
| 38 | + timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) |
| 39 | + |
| 40 | + es = Elasticsearch() |
| 41 | + es.indices.create(index=index, ignore=400) |
| 42 | + |
| 43 | + report = json.loads(request.data) |
| 44 | + report["unique_id"] = unique_id |
| 45 | + report["timestamp"] = timestamp |
| 46 | + |
| 47 | + es.index(index=index, doc_type="usage-report", body=json.dumps(report), timestamp=timestamp, refresh=True) |
| 48 | + |
| 49 | + response = {} |
| 50 | + return json_response(response) |
| 51 | + |
| 52 | + return app |
| 53 | + |
| 54 | + |
| 55 | +app = generate_app() |
| 56 | + |
| 57 | +# Only run the App if this script is invoked from a Shell |
| 58 | +if __name__ == '__main__': |
| 59 | + app.debug = True |
| 60 | + app.run(host='0.0.0.0', port=8088) |
| 61 | + |
| 62 | +# Otherwise provide a variable called 'application' for mod_wsgi |
| 63 | +else: |
| 64 | + application = app |
0 commit comments