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.

221 lines
6.1 KiB

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