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.

266 lines
7.3 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. import uuid
  3. from django.conf import settings
  4. from django.core.exceptions import SuspiciousOperation
  5. from django.db import connection
  6. from django.http import (
  7. HttpResponse,
  8. HttpResponseForbidden,
  9. HttpResponseNotFound,
  10. JsonResponse,
  11. )
  12. from django.shortcuts import get_object_or_404
  13. from django.utils import timezone
  14. from django.views.decorators.cache import never_cache
  15. from django.views.decorators.csrf import csrf_exempt
  16. from hc.api import schemas
  17. from hc.api.decorators import authorize, authorize_read, cors, validate_json
  18. from hc.api.models import Check, Notification, Channel
  19. from hc.lib.badges import check_signature, get_badge_svg
  20. @csrf_exempt
  21. @never_cache
  22. def ping(request, code, action="success"):
  23. check = get_object_or_404(Check, code=code)
  24. headers = request.META
  25. remote_addr = headers.get("HTTP_X_FORWARDED_FOR", headers["REMOTE_ADDR"])
  26. remote_addr = remote_addr.split(",")[0]
  27. scheme = headers.get("HTTP_X_FORWARDED_PROTO", "http")
  28. method = headers["REQUEST_METHOD"]
  29. ua = headers.get("HTTP_USER_AGENT", "")
  30. body = request.body.decode()
  31. check.ping(remote_addr, scheme, method, ua, body, action)
  32. response = HttpResponse("OK")
  33. response["Access-Control-Allow-Origin"] = "*"
  34. return response
  35. def _lookup(project, spec):
  36. unique_fields = spec.get("unique", [])
  37. if unique_fields:
  38. existing_checks = Check.objects.filter(project=project)
  39. if "name" in unique_fields:
  40. existing_checks = existing_checks.filter(name=spec.get("name"))
  41. if "tags" in unique_fields:
  42. existing_checks = existing_checks.filter(tags=spec.get("tags"))
  43. if "timeout" in unique_fields:
  44. timeout = td(seconds=spec["timeout"])
  45. existing_checks = existing_checks.filter(timeout=timeout)
  46. if "grace" in unique_fields:
  47. grace = td(seconds=spec["grace"])
  48. existing_checks = existing_checks.filter(grace=grace)
  49. return existing_checks.first()
  50. def _update(check, spec):
  51. if "name" in spec:
  52. check.name = spec["name"]
  53. if "tags" in spec:
  54. check.tags = spec["tags"]
  55. if "timeout" in spec and "schedule" not in spec:
  56. check.kind = "simple"
  57. check.timeout = td(seconds=spec["timeout"])
  58. if "grace" in spec:
  59. check.grace = td(seconds=spec["grace"])
  60. if "schedule" in spec:
  61. check.kind = "cron"
  62. check.schedule = spec["schedule"]
  63. if "tz" in spec:
  64. check.tz = spec["tz"]
  65. check.save()
  66. # This needs to be done after saving the check, because of
  67. # the M2M relation between checks and channels:
  68. if "channels" in spec:
  69. if spec["channels"] == "*":
  70. check.assign_all_channels()
  71. elif spec["channels"] == "":
  72. check.channel_set.clear()
  73. else:
  74. channels = []
  75. for chunk in spec["channels"].split(","):
  76. try:
  77. chunk = uuid.UUID(chunk)
  78. except ValueError:
  79. raise SuspiciousOperation("Invalid channel identifier")
  80. try:
  81. channel = Channel.objects.get(code=chunk)
  82. channels.append(channel)
  83. except Channel.DoesNotExist:
  84. raise SuspiciousOperation("Invalid channel identifier")
  85. check.channel_set.set(channels)
  86. return check
  87. @validate_json()
  88. @authorize_read
  89. def get_checks(request):
  90. q = Check.objects.filter(project=request.project)
  91. q = q.prefetch_related("channel_set")
  92. tags = set(request.GET.getlist("tag"))
  93. for tag in tags:
  94. # approximate filtering by tags
  95. q = q.filter(tags__contains=tag)
  96. checks = []
  97. for check in q:
  98. # precise, final filtering
  99. if not tags or check.matches_tag_set(tags):
  100. checks.append(check.to_dict())
  101. return JsonResponse({"checks": checks})
  102. @validate_json(schemas.check)
  103. @authorize
  104. def create_check(request):
  105. created = False
  106. check = _lookup(request.project, request.json)
  107. if check is None:
  108. if request.project.num_checks_available() <= 0:
  109. return HttpResponseForbidden()
  110. check = Check(project=request.project)
  111. created = True
  112. _update(check, request.json)
  113. return JsonResponse(check.to_dict(), status=201 if created else 200)
  114. @csrf_exempt
  115. @cors("GET", "POST")
  116. def checks(request):
  117. if request.method == "POST":
  118. return create_check(request)
  119. return get_checks(request)
  120. @cors("GET")
  121. @validate_json()
  122. @authorize_read
  123. def channels(request):
  124. q = Channel.objects.filter(project=request.project)
  125. channels = [ch.to_dict() for ch in q]
  126. return JsonResponse({"channels": channels})
  127. @csrf_exempt
  128. @cors("POST", "DELETE")
  129. @validate_json(schemas.check)
  130. @authorize
  131. def update(request, code):
  132. check = get_object_or_404(Check, code=code)
  133. if check.project != request.project:
  134. return HttpResponseForbidden()
  135. if request.method == "POST":
  136. _update(check, request.json)
  137. return JsonResponse(check.to_dict())
  138. elif request.method == "DELETE":
  139. response = check.to_dict()
  140. check.delete()
  141. return JsonResponse(response)
  142. # Otherwise, method not allowed
  143. return HttpResponse(status=405)
  144. @cors("POST")
  145. @csrf_exempt
  146. @validate_json()
  147. @authorize
  148. def pause(request, code):
  149. check = get_object_or_404(Check, code=code)
  150. if check.project != request.project:
  151. return HttpResponseForbidden()
  152. check.status = "paused"
  153. check.last_start = None
  154. check.alert_after = None
  155. check.save()
  156. return JsonResponse(check.to_dict())
  157. @never_cache
  158. @cors("GET")
  159. def badge(request, badge_key, signature, tag, format="svg"):
  160. if not check_signature(badge_key, tag, signature):
  161. return HttpResponseNotFound()
  162. q = Check.objects.filter(project__badge_key=badge_key)
  163. if tag != "*":
  164. q = q.filter(tags__contains=tag)
  165. label = tag
  166. else:
  167. label = settings.MASTER_BADGE_LABEL
  168. status, total, grace, down = "up", 0, 0, 0
  169. for check in q:
  170. if tag != "*" and tag not in check.tags_list():
  171. continue
  172. total += 1
  173. check_status = check.get_status(with_started=False)
  174. if check_status == "down":
  175. down += 1
  176. status = "down"
  177. if format == "svg":
  178. # For SVG badges, we can leave the loop as soon as we
  179. # find the first "down"
  180. break
  181. elif check_status == "grace":
  182. grace += 1
  183. if status == "up":
  184. status = "late"
  185. if format == "json":
  186. return JsonResponse(
  187. {"status": status, "total": total, "grace": grace, "down": down}
  188. )
  189. svg = get_badge_svg(label, status)
  190. return HttpResponse(svg, content_type="image/svg+xml")
  191. @csrf_exempt
  192. def bounce(request, code):
  193. notification = get_object_or_404(Notification, code=code)
  194. # If webhook is more than 10 minutes late, don't accept it:
  195. td = timezone.now() - notification.created
  196. if td.total_seconds() > 600:
  197. return HttpResponseForbidden()
  198. notification.error = request.body.decode()[:200]
  199. notification.save()
  200. notification.channel.email_verified = False
  201. notification.channel.save()
  202. return HttpResponse()
  203. def status(request):
  204. with connection.cursor() as c:
  205. c.execute("SELECT 1")
  206. c.fetchone()
  207. return HttpResponse("OK")