Просмотр исходного кода

feat(monitors): Add duration to stats endpoint (#39651)

Adds duration as a field inside of the time series data from the monitor
stats endpoint. Field represents the average duration of the check-ins
that happened within one roll-up period.
David Wang 2 лет назад
Родитель
Сommit
8e5f34f710
1 измененных файлов с 30 добавлено и 10 удалено
  1. 30 10
      src/sentry/api/endpoints/monitor_stats.py

+ 30 - 10
src/sentry/api/endpoints/monitor_stats.py

@@ -14,24 +14,44 @@ class MonitorStatsEndpoint(MonitorEndpoint, StatsMixin):
         args = self._parse_args(request)
 
         stats = {}
+        duration_stats = {}
         current = tsdb.normalize_to_epoch(args["start"], args["rollup"])
         end = tsdb.normalize_to_epoch(args["end"], args["rollup"])
+
+        # initialize success/failure/duration stats in preparation for counting/aggregating
         while current <= end:
             stats[current] = {CheckInStatus.OK: 0, CheckInStatus.ERROR: 0}
+            duration_stats[current] = {"sum": 0, "num_checkins": 0}
             current += args["rollup"]
 
+        # retrieve the list of checkins in the time range and count success/failure/duration
         history = MonitorCheckIn.objects.filter(
             monitor=monitor,
             status__in=[CheckInStatus.OK, CheckInStatus.ERROR],
             date_added__gt=args["start"],
             date_added__lte=args["end"],
-        ).values_list("date_added", "status")
-        for datetime, status in history.iterator():
-            stats[tsdb.normalize_to_epoch(datetime, args["rollup"])][status] += 1
-
-        return Response(
-            [
-                {"ts": ts, "ok": data[CheckInStatus.OK], "error": data[CheckInStatus.ERROR]}
-                for ts, data in stats.items()
-            ]
-        )
+        ).values_list("date_added", "status", "duration")
+        for datetime, status, duration in history.iterator():
+            ts = tsdb.normalize_to_epoch(datetime, args["rollup"])
+            stats[ts][status] += 1
+            if duration:
+                duration_stats[ts]["sum"] += duration
+                duration_stats[ts]["num_checkins"] += 1
+
+        # compute average duration and construct response object
+        stats_duration_data = []
+        for ts, data in stats.items():
+            duration_sum, num_checkins = duration_stats[ts].values()
+            avg_duration = 0
+            if num_checkins > 0:
+                avg_duration = duration_sum / num_checkins
+            stats_duration_data.append(
+                {
+                    "ts": ts,
+                    "ok": data[CheckInStatus.OK],
+                    "error": data[CheckInStatus.ERROR],
+                    "duration": avg_duration,
+                }
+            )
+
+        return Response(stats_duration_data)