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.

218 lines
6.1 KiB

10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. from datetime import timedelta as td
  2. from django.conf import settings
  3. from django.db import connection
  4. from django.http import (HttpResponse, HttpResponseForbidden,
  5. HttpResponseNotFound, JsonResponse)
  6. from django.shortcuts import get_object_or_404
  7. from django.utils import timezone
  8. from django.views.decorators.cache import never_cache
  9. from django.views.decorators.csrf import csrf_exempt
  10. from django.views.decorators.http import require_POST
  11. from hc.api import schemas
  12. from hc.api.decorators import check_api_key, validate_json
  13. from hc.api.models import Check, Notification
  14. from hc.lib.badges import check_signature, get_badge_svg
  15. @csrf_exempt
  16. @never_cache
  17. def ping(request, code, is_fail=False):
  18. check = get_object_or_404(Check, code=code)
  19. headers = request.META
  20. remote_addr = headers.get("HTTP_X_FORWARDED_FOR", headers["REMOTE_ADDR"])
  21. remote_addr = remote_addr.split(",")[0]
  22. scheme = headers.get("HTTP_X_FORWARDED_PROTO", "http")
  23. method = headers["REQUEST_METHOD"]
  24. ua = headers.get("HTTP_USER_AGENT", "")
  25. body = request.body.decode()
  26. check.ping(remote_addr, scheme, method, ua, body, is_fail)
  27. response = HttpResponse("OK")
  28. response["Access-Control-Allow-Origin"] = "*"
  29. return response
  30. def _lookup(user, spec):
  31. unique_fields = spec.get("unique", [])
  32. if unique_fields:
  33. existing_checks = Check.objects.filter(user=user)
  34. if "name" in unique_fields:
  35. existing_checks = existing_checks.filter(name=spec.get("name"))
  36. if "tags" in unique_fields:
  37. existing_checks = existing_checks.filter(tags=spec.get("tags"))
  38. if "timeout" in unique_fields:
  39. timeout = td(seconds=spec["timeout"])
  40. existing_checks = existing_checks.filter(timeout=timeout)
  41. if "grace" in unique_fields:
  42. grace = td(seconds=spec["grace"])
  43. existing_checks = existing_checks.filter(grace=grace)
  44. return existing_checks.first()
  45. def _update(check, spec):
  46. if "name" in spec:
  47. check.name = spec["name"]
  48. if "tags" in spec:
  49. check.tags = spec["tags"]
  50. if "timeout" in spec and "schedule" not in spec:
  51. check.kind = "simple"
  52. check.timeout = td(seconds=spec["timeout"])
  53. if "grace" in spec:
  54. check.grace = td(seconds=spec["grace"])
  55. if "schedule" in spec:
  56. check.kind = "cron"
  57. check.schedule = spec["schedule"]
  58. if "tz" in spec:
  59. check.tz = spec["tz"]
  60. check.save()
  61. # This needs to be done after saving the check, because of
  62. # the M2M relation between checks and channels:
  63. if "channels" in spec:
  64. if spec["channels"] == "*":
  65. check.assign_all_channels()
  66. elif spec["channels"] == "":
  67. check.channel_set.clear()
  68. return check
  69. @csrf_exempt
  70. @check_api_key
  71. @validate_json(schemas.check)
  72. def checks(request):
  73. if request.method == "GET":
  74. q = Check.objects.filter(user=request.user)
  75. tags = set(request.GET.getlist("tag"))
  76. for tag in tags:
  77. # approximate filtering by tags
  78. q = q.filter(tags__contains=tag)
  79. checks = []
  80. for check in q:
  81. # precise, final filtering
  82. if not tags or check.matches_tag_set(tags):
  83. checks.append(check.to_dict())
  84. return JsonResponse({"checks": checks})
  85. elif request.method == "POST":
  86. created = False
  87. check = _lookup(request.user, request.json)
  88. if check is None:
  89. num_checks = Check.objects.filter(user=request.user).count()
  90. if num_checks >= request.user.profile.check_limit:
  91. return HttpResponseForbidden()
  92. check = Check(user=request.user)
  93. created = True
  94. _update(check, request.json)
  95. return JsonResponse(check.to_dict(), status=201 if created else 200)
  96. # If request is neither GET nor POST, return "405 Method not allowed"
  97. return HttpResponse(status=405)
  98. @csrf_exempt
  99. @check_api_key
  100. @validate_json(schemas.check)
  101. def update(request, code):
  102. check = get_object_or_404(Check, code=code)
  103. if check.user != request.user:
  104. return HttpResponseForbidden()
  105. if request.method == "POST":
  106. _update(check, request.json)
  107. return JsonResponse(check.to_dict())
  108. elif request.method == "DELETE":
  109. response = check.to_dict()
  110. check.delete()
  111. return JsonResponse(response)
  112. # Otherwise, method not allowed
  113. return HttpResponse(status=405)
  114. @csrf_exempt
  115. @require_POST
  116. @check_api_key
  117. def pause(request, code):
  118. check = get_object_or_404(Check, code=code)
  119. if check.user != request.user:
  120. return HttpResponseForbidden()
  121. check.status = "paused"
  122. check.save()
  123. return JsonResponse(check.to_dict())
  124. @never_cache
  125. def badge(request, username, signature, tag, format="svg"):
  126. if not check_signature(username, tag, signature):
  127. return HttpResponseNotFound()
  128. status = "up"
  129. q = Check.objects.filter(user__username=username)
  130. if tag != "*":
  131. q = q.filter(tags__contains=tag)
  132. label = tag
  133. else:
  134. label = settings.MASTER_BADGE_LABEL
  135. for check in q:
  136. if tag != "*" and tag not in check.tags_list():
  137. continue
  138. check_status = check.get_status()
  139. if status == "up" and check_status == "grace":
  140. status = "late"
  141. if check_status == "down":
  142. status = "down"
  143. break
  144. if format == "json":
  145. return JsonResponse({"status": status})
  146. svg = get_badge_svg(label, status)
  147. return HttpResponse(svg, content_type="image/svg+xml")
  148. @csrf_exempt
  149. def bounce(request, code):
  150. notification = get_object_or_404(Notification, code=code)
  151. # If webhook is more than 10 minutes late, don't accept it:
  152. td = timezone.now() - notification.created
  153. if td.total_seconds() > 600:
  154. return HttpResponseForbidden()
  155. notification.error = request.body.decode()[:200]
  156. notification.save()
  157. notification.channel.email_verified = False
  158. notification.channel.save()
  159. return HttpResponse()
  160. def status(request):
  161. with connection.cursor() as c:
  162. c.execute("SELECT 1")
  163. c.fetchone()
  164. return HttpResponse("OK")