prometheus_api.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env python
  2. # -- coding: utf-8 --
  3. # Licensed to Cloudera, Inc. under one
  4. # or more contributor license agreements. See the NOTICE file
  5. # distributed with this work for additional information
  6. # regarding copyright ownership. Cloudera, Inc. licenses this file
  7. # to you under the Apache License, Version 2.0 (the
  8. # "License"); you may not use this file except in compliance
  9. # with the License. You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import json
  19. import logging
  20. from django.utils.html import escape
  21. from django.utils.translation import ugettext as _
  22. from django.views.decorators.http import require_POST
  23. from desktop.lib.django_util import JsonResponse
  24. from desktop.lib.i18n import force_unicode
  25. from metadata.prometheus_client import PrometheusApi
  26. LOG = logging.getLogger(__name__)
  27. def error_handler(view_fn):
  28. def decorator(*args, **kwargs):
  29. try:
  30. return view_fn(*args, **kwargs)
  31. except Exception, e:
  32. LOG.exception(e)
  33. response = {
  34. 'status': -1,
  35. 'message': force_unicode(str(e))
  36. }
  37. return JsonResponse(response, status=500)
  38. return decorator
  39. @error_handler
  40. @require_POST
  41. def query(request):
  42. response = {
  43. 'status': 0
  44. }
  45. api = PrometheusApi(request.user)
  46. query = json.loads(request.POST.get('query', '{}'))
  47. if request.POST.get('start'):
  48. response['data'] = api.range_query(query, start=request.POST.get('start'), end=request.POST.get('end'), step=request.POST.get('step'))
  49. else:
  50. response['data'] = api.query(query)
  51. return JsonResponse(response)