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.

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