1616# specific language governing permissions and limitations
1717# under the License.
1818
19- from flask import abort , Flask , request , Response
19+ from flask import abort , Flask , request
2020from elasticsearch import Elasticsearch
2121import json
2222import time
@@ -30,24 +30,33 @@ def generate_app(config=None):
3030 @app .route ('/report/<unique_id>' , methods = ['POST' ])
3131 def report (unique_id ):
3232 # 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" )
33+ if request .headers .get ('Content-Type' ) != 'application/json' :
34+ abort (417 , "No or incorrect Content-Type header was supplied" )
35+
36+ try :
37+ payload = json .loads (request .data )
38+ except json .JSONDecodeError :
39+ abort (400 , "Request body is not valid JSON" )
3640
3741 index = "cloudstack-%s" % time .strftime ("%Y.%m.%d" , time .gmtime ())
3842 timestamp = time .strftime ("%Y-%m-%dT%H:%M:%SZ" , time .gmtime ())
3943
4044 es = Elasticsearch ()
41- es .indices .create (index = index , ignore = 400 )
4245
43- report = json .loads (request .data )
44- report ["unique_id" ] = unique_id
45- report ["timestamp" ] = timestamp
46+ try :
47+ es .indices .create (index = index )
48+ except Exception :
49+ pass # Index already exists
50+
51+ payload ["unique_id" ] = unique_id
52+ payload ["timestamp" ] = timestamp
4653
47- es .index (index = index , doc_type = "usage-report" , body = json .dumps (report ), timestamp = timestamp , refresh = True )
54+ try :
55+ es .index (index = index , body = json .dumps (payload ), refresh = True )
56+ except Exception as e :
57+ abort (500 , "Failed to store report: %s" % str (e ))
4858
49- response = {}
50- return json_response (response )
59+ return json_response ({})
5160
5261 return app
5362
0 commit comments