|
| 1 | +"""Handle storage retention and usage.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from pathlib import Path |
| 5 | +import shutil |
| 6 | +import threading |
| 7 | + |
| 8 | +from peewee import fn |
| 9 | + |
| 10 | +from frigate.config import FrigateConfig |
| 11 | +from frigate.const import RECORD_DIR |
| 12 | +from frigate.models import Event, Recordings |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | +bandwidth_equation = Recordings.segment_size / ( |
| 16 | + Recordings.end_time - Recordings.start_time |
| 17 | +) |
| 18 | + |
| 19 | + |
| 20 | +class StorageMaintainer(threading.Thread): |
| 21 | + """Maintain frigates recording storage.""" |
| 22 | + |
| 23 | + def __init__(self, config: FrigateConfig, stop_event) -> None: |
| 24 | + threading.Thread.__init__(self) |
| 25 | + self.name = "storage_maintainer" |
| 26 | + self.config = config |
| 27 | + self.stop_event = stop_event |
| 28 | + self.camera_storage_stats: dict[str, dict] = {} |
| 29 | + |
| 30 | + def calculate_camera_bandwidth(self) -> None: |
| 31 | + """Calculate an average MB/hr for each camera.""" |
| 32 | + for camera in self.config.cameras.keys(): |
| 33 | + # cameras with < 50 segments should be refreshed to keep size accurate |
| 34 | + # when few segments are available |
| 35 | + if self.camera_storage_stats.get(camera, {}).get("needs_refresh", True): |
| 36 | + self.camera_storage_stats[camera] = { |
| 37 | + "needs_refresh": ( |
| 38 | + Recordings.select(fn.COUNT(Recordings.id)) |
| 39 | + .where( |
| 40 | + Recordings.camera == camera, Recordings.segment_size != 0 |
| 41 | + ) |
| 42 | + .scalar() |
| 43 | + < 50 |
| 44 | + ) |
| 45 | + } |
| 46 | + |
| 47 | + # calculate MB/hr |
| 48 | + try: |
| 49 | + bandwidth = round( |
| 50 | + Recordings.select(fn.AVG(bandwidth_equation)) |
| 51 | + .where(Recordings.camera == camera, Recordings.segment_size != 0) |
| 52 | + .limit(100) |
| 53 | + .scalar() |
| 54 | + * 3600, |
| 55 | + 2, |
| 56 | + ) |
| 57 | + except TypeError: |
| 58 | + bandwidth = 0 |
| 59 | + |
| 60 | + self.camera_storage_stats[camera]["bandwidth"] = bandwidth |
| 61 | + logger.debug(f"{camera} has a bandwidth of {bandwidth} MB/hr.") |
| 62 | + |
| 63 | + def check_storage_needs_cleanup(self) -> bool: |
| 64 | + """Return if storage needs cleanup.""" |
| 65 | + # currently runs cleanup if less than 1 hour of space is left |
| 66 | + # disk_usage should not spin up disks |
| 67 | + hourly_bandwidth = sum( |
| 68 | + [b["bandwidth"] for b in self.camera_storage_stats.values()] |
| 69 | + ) |
| 70 | + remaining_storage = round(shutil.disk_usage(RECORD_DIR).free / 1000000, 1) |
| 71 | + logger.debug( |
| 72 | + f"Storage cleanup check: {hourly_bandwidth} hourly with remaining storage: {remaining_storage}." |
| 73 | + ) |
| 74 | + return remaining_storage < hourly_bandwidth |
| 75 | + |
| 76 | + def reduce_storage_consumption(self) -> None: |
| 77 | + """Remove oldest hour of recordings.""" |
| 78 | + logger.debug("Starting storage cleanup.") |
| 79 | + deleted_segments_size = 0 |
| 80 | + hourly_bandwidth = sum( |
| 81 | + [b["bandwidth"] for b in self.camera_storage_stats.values()] |
| 82 | + ) |
| 83 | + |
| 84 | + recordings: Recordings = Recordings.select().order_by( |
| 85 | + Recordings.start_time.asc() |
| 86 | + ) |
| 87 | + retained_events: Event = ( |
| 88 | + Event.select() |
| 89 | + .where( |
| 90 | + Event.retain_indefinitely == True, |
| 91 | + Event.has_clip, |
| 92 | + ) |
| 93 | + .order_by(Event.start_time.asc()) |
| 94 | + .objects() |
| 95 | + ) |
| 96 | + |
| 97 | + event_start = 0 |
| 98 | + deleted_recordings = set() |
| 99 | + for recording in recordings.objects().iterator(): |
| 100 | + # check if 1 hour of storage has been reclaimed |
| 101 | + if deleted_segments_size > hourly_bandwidth: |
| 102 | + break |
| 103 | + |
| 104 | + keep = False |
| 105 | + |
| 106 | + # Now look for a reason to keep this recording segment |
| 107 | + for idx in range(event_start, len(retained_events)): |
| 108 | + event = retained_events[idx] |
| 109 | + |
| 110 | + # if the event starts in the future, stop checking events |
| 111 | + # and let this recording segment expire |
| 112 | + if event.start_time > recording.end_time: |
| 113 | + keep = False |
| 114 | + break |
| 115 | + |
| 116 | + # if the event is in progress or ends after the recording starts, keep it |
| 117 | + # and stop looking at events |
| 118 | + if event.end_time is None or event.end_time >= recording.start_time: |
| 119 | + keep = True |
| 120 | + break |
| 121 | + |
| 122 | + # if the event ends before this recording segment starts, skip |
| 123 | + # this event and check the next event for an overlap. |
| 124 | + # since the events and recordings are sorted, we can skip events |
| 125 | + # that end before the previous recording segment started on future segments |
| 126 | + if event.end_time < recording.start_time: |
| 127 | + event_start = idx |
| 128 | + |
| 129 | + # Delete recordings not retained indefinitely |
| 130 | + if not keep: |
| 131 | + deleted_segments_size += recording.segment_size |
| 132 | + Path(recording.path).unlink(missing_ok=True) |
| 133 | + deleted_recordings.add(recording.id) |
| 134 | + |
| 135 | + # check if need to delete retained segments |
| 136 | + if deleted_segments_size < hourly_bandwidth: |
| 137 | + logger.error( |
| 138 | + f"Could not clear {hourly_bandwidth} currently {deleted_segments_size}, retained recordings must be deleted." |
| 139 | + ) |
| 140 | + recordings = Recordings.select().order_by(Recordings.start_time.asc()) |
| 141 | + |
| 142 | + for recording in recordings.objects().iterator(): |
| 143 | + if deleted_segments_size > hourly_bandwidth: |
| 144 | + break |
| 145 | + |
| 146 | + deleted_segments_size += recording.segment_size |
| 147 | + Path(recording.path).unlink(missing_ok=True) |
| 148 | + deleted_recordings.add(recording.id) |
| 149 | + |
| 150 | + logger.debug(f"Expiring {len(deleted_recordings)} recordings") |
| 151 | + # delete up to 100,000 at a time |
| 152 | + max_deletes = 100000 |
| 153 | + deleted_recordings_list = list(deleted_recordings) |
| 154 | + for i in range(0, len(deleted_recordings_list), max_deletes): |
| 155 | + Recordings.delete().where( |
| 156 | + Recordings.id << deleted_recordings_list[i : i + max_deletes] |
| 157 | + ).execute() |
| 158 | + |
| 159 | + def run(self): |
| 160 | + """Check every 5 minutes if storage needs to be cleaned up.""" |
| 161 | + while not self.stop_event.wait(300): |
| 162 | + |
| 163 | + if not self.camera_storage_stats or True in [ |
| 164 | + r["needs_refresh"] for r in self.camera_storage_stats.values() |
| 165 | + ]: |
| 166 | + self.calculate_camera_bandwidth() |
| 167 | + logger.debug(f"Default camera bandwidths: {self.camera_storage_stats}.") |
| 168 | + |
| 169 | + if self.check_storage_needs_cleanup(): |
| 170 | + self.reduce_storage_consumption() |
| 171 | + |
| 172 | + logger.info(f"Exiting storage maintainer...") |
0 commit comments