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.

253 lines
7.0 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 (HttpResponse, HttpResponseForbidden,
  7. HttpResponseNotFound, JsonResponse)
  8. from django.shortcuts import get_object_or_404
  9. from django.utils import timezone
  10. from django.views.decorators.cache import never_cache
  11. from django.views.decorators.csrf import csrf_exempt
  12. from hc.api import schemas
  13. from hc.api.decorators import authorize, authorize_read, cors, validate_json
  14. from hc.api.models import Check, Notification, Channel
  15. from hc.lib.badges import check_signature, get_badge_svg
  16. @csrf_exempt
  17. @never_cache
  18. def ping(request, code, action="success"):
  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.decode()
  27. check.ping(remote_addr, scheme, method, ua, body, action)
  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. else:
  70. channels = []
  71. for chunk in spec["channels"].split(","):
  72. try:
  73. chunk = uuid.UUID(chunk)
  74. except ValueError:
  75. raise SuspiciousOperation("Invalid channel identifier")
  76. try:
  77. channel = Channel.objects.get(code=chunk)
  78. channels.append(channel)
  79. except Channel.DoesNotExist:
  80. raise SuspiciousOperation("Invalid channel identifier")
  81. check.channel_set.set(channels)
  82. return check
  83. @validate_json()
  84. @authorize_read
  85. def get_checks(request):
  86. q = Check.objects.filter(user=request.user)
  87. tags = set(request.GET.getlist("tag"))
  88. for tag in tags:
  89. # approximate filtering by tags
  90. q = q.filter(tags__contains=tag)
  91. checks = []
  92. for check in q:
  93. # precise, final filtering
  94. if not tags or check.matches_tag_set(tags):
  95. checks.append(check.to_dict())
  96. return JsonResponse({"checks": checks})
  97. @validate_json(schemas.check)
  98. @authorize
  99. def create_check(request):
  100. created = False
  101. check = _lookup(request.user, request.json)
  102. if check is None:
  103. num_checks = Check.objects.filter(user=request.user).count()
  104. if num_checks >= request.user.profile.check_limit:
  105. return HttpResponseForbidden()
  106. check = Check(user=request.user)
  107. created = True
  108. _update(check, request.json)
  109. return JsonResponse(check.to_dict(), status=201 if created else 200)
  110. @csrf_exempt
  111. @cors("GET", "POST")
  112. def checks(request):
  113. if request.method == "POST":
  114. return create_check(request)
  115. return get_checks(request)
  116. @cors("GET")
  117. @validate_json()
  118. @authorize_read
  119. def channels(request):
  120. q = Channel.objects.filter(user=request.user)
  121. channels = [ch.to_dict() for ch in q]
  122. return JsonResponse({"channels": channels})
  123. @csrf_exempt
  124. @cors("POST", "DELETE")
  125. @validate_json(schemas.check)
  126. @authorize
  127. def update(request, code):
  128. check = get_object_or_404(Check, code=code)
  129. if check.user != request.user:
  130. return HttpResponseForbidden()
  131. if request.method == "POST":
  132. _update(check, request.json)
  133. return JsonResponse(check.to_dict())
  134. elif request.method == "DELETE":
  135. response = check.to_dict()
  136. check.delete()
  137. return JsonResponse(response)
  138. # Otherwise, method not allowed
  139. return HttpResponse(status=405)
  140. @cors("POST")
  141. @csrf_exempt
  142. @validate_json()
  143. @authorize
  144. def pause(request, code):
  145. check = get_object_or_404(Check, code=code)
  146. if check.user != request.user:
  147. return HttpResponseForbidden()
  148. check.status = "paused"
  149. check.last_start = None
  150. check.alert_after = None
  151. check.save()
  152. return JsonResponse(check.to_dict())
  153. @never_cache
  154. @cors("GET")
  155. def badge(request, username, signature, tag, format="svg"):
  156. if not check_signature(username, tag, signature):
  157. return HttpResponseNotFound()
  158. status = "up"
  159. q = Check.objects.filter(user__username=username)
  160. if tag != "*":
  161. q = q.filter(tags__contains=tag)
  162. label = tag
  163. else:
  164. label = settings.MASTER_BADGE_LABEL
  165. for check in q:
  166. if tag != "*" and tag not in check.tags_list():
  167. continue
  168. check_status = check.get_status(with_started=False)
  169. if status == "up" and check_status == "grace":
  170. status = "late"
  171. if check_status == "down":
  172. status = "down"
  173. break
  174. if format == "json":
  175. return JsonResponse({"status": status})
  176. svg = get_badge_svg(label, status)
  177. return HttpResponse(svg, content_type="image/svg+xml")
  178. @csrf_exempt
  179. def bounce(request, code):
  180. notification = get_object_or_404(Notification, code=code)
  181. # If webhook is more than 10 minutes late, don't accept it:
  182. td = timezone.now() - notification.created
  183. if td.total_seconds() > 600:
  184. return HttpResponseForbidden()
  185. notification.error = request.body.decode()[:200]
  186. notification.save()
  187. notification.channel.email_verified = False
  188. notification.channel.save()
  189. return HttpResponse()
  190. def status(request):
  191. with connection.cursor() as c:
  192. c.execute("SELECT 1")
  193. c.fetchone()
  194. return HttpResponse("OK")