You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. from datetime import timedelta as td
  2. from django.db.models import F
  3. from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
  4. from django.utils import timezone
  5. from django.views.decorators.cache import never_cache
  6. from django.views.decorators.csrf import csrf_exempt
  7. from hc.api import schemas
  8. from hc.api.decorators import check_api_key, uuid_or_400, validate_json
  9. from hc.api.models import Check, Ping
  10. @csrf_exempt
  11. @uuid_or_400
  12. @never_cache
  13. def ping(request, code):
  14. try:
  15. check = Check.objects.get(code=code)
  16. except Check.DoesNotExist:
  17. return HttpResponseBadRequest()
  18. check.n_pings = F("n_pings") + 1
  19. check.last_ping = timezone.now()
  20. if check.status == "new":
  21. check.status = "up"
  22. check.save()
  23. check.refresh_from_db()
  24. ping = Ping(owner=check)
  25. headers = request.META
  26. ping.n = check.n_pings
  27. remote_addr = headers.get("HTTP_X_FORWARDED_FOR", headers["REMOTE_ADDR"])
  28. ping.remote_addr = remote_addr.split(",")[0]
  29. ping.scheme = headers.get("HTTP_X_FORWARDED_PROTO", "http")
  30. ping.method = headers["REQUEST_METHOD"]
  31. # If User-Agent is longer than 200 characters, truncate it:
  32. ping.ua = headers.get("HTTP_USER_AGENT", "")[:200]
  33. ping.save()
  34. response = HttpResponse("OK")
  35. response["Access-Control-Allow-Origin"] = "*"
  36. return response
  37. @csrf_exempt
  38. @check_api_key
  39. @validate_json(schemas.check)
  40. def create_check(request):
  41. if request.method == "GET":
  42. code = 200
  43. response = {
  44. "checks": [{
  45. "name": check.name,
  46. "ping_url": check.url(),
  47. "tags": check.tags,
  48. "timeout": int(check.timeout.total_seconds()),
  49. "grace": int(check.grace.total_seconds()),
  50. # "channels": check.channels,
  51. } for check in Check.objects.filter(user=request.user)]
  52. }
  53. elif request.method == "POST":
  54. check = Check(user=request.user)
  55. check.name = str(request.json.get("name", ""))
  56. check.tags = str(request.json.get("tags", ""))
  57. if "timeout" in request.json:
  58. check.timeout = td(seconds=request.json["timeout"])
  59. if "grace" in request.json:
  60. check.grace = td(seconds=request.json["grace"])
  61. check.save()
  62. # This needs to be done after saving the check, because of
  63. # the M2M relation between checks and channels:
  64. if request.json.get("channels") == "*":
  65. check.assign_all_channels()
  66. code = 201
  67. response = {
  68. "ping_url": check.url()
  69. }
  70. else:
  71. return HttpResponse(status=405)
  72. return JsonResponse(response, status=code)