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.

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