Changes needed to get the kiosk to run on the rpi.
[kiosk.git] / kiosk.py
index 7ffce23d6d85a4b65eb465e231a52d87355b78cc..2c75dd09a50e76e895ba003e717600a3804ad97c 100755 (executable)
--- a/kiosk.py
+++ b/kiosk.py
@@ -1,11 +1,14 @@
 #!/usr/bin/env python3
 
 from datetime import datetime
+import gc
+import linecache
 import os
 import sys
 from threading import Thread
 import time
 import traceback
+import tracemalloc
 from typing import Optional
 
 import constants
@@ -32,6 +35,48 @@ def filter_news_during_dinnertime(page: str) -> bool:
     )
 
 
+def thread_janitor() -> None:
+    tracemalloc.start()
+    tracemalloc_target = 0.0
+    gc_target = 0.0
+    gc.enable()
+
+    while True:
+        now = time.time()
+        if now > tracemalloc_target:
+            tracemalloc_target = now + 30.0
+            snapshot = tracemalloc.take_snapshot()
+            snapshot = snapshot.filter_traces((
+                tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
+                tracemalloc.Filter(False, "<unknown>"),
+            ))
+            key_type = 'lineno'
+            limit = 10
+            top_stats = snapshot.statistics(key_type)
+            print("janitor: Top %s lines" % limit)
+            for index, stat in enumerate(top_stats[:limit], 1):
+                frame = stat.traceback[0]
+                # replace "/path/to/module/file.py" with "module/file.py"
+                filename = os.sep.join(frame.filename.split(os.sep)[-2:])
+                print("janitor: #%s: %s:%s: %.1f KiB"
+                      % (index, filename, frame.lineno, stat.size / 1024))
+                line = linecache.getline(frame.filename, frame.lineno).strip()
+                if line:
+                    print('janitor:    %s' % line)
+
+            other = top_stats[limit:]
+            if other:
+                size = sum(stat.size for stat in other)
+                print("janitor: %s other: %.1f KiB" % (len(other), size / 1024))
+            total = sum(stat.size for stat in top_stats)
+            print("janitor: Total allocated size: %.1f KiB" % (total / 1024))
+        if now > gc_target:
+            print("janitor: Running gc operation")
+            gc_target = now + 60.0
+            gc.collect()
+        time.sleep(10.0)
+
+
 def thread_change_current() -> None:
     page_chooser = chooser.weighted_random_chooser_with_triggers(
         trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
@@ -102,6 +147,13 @@ def emit_wrapped(f, filename) -> None:
         else:
             return "FFFFFF"
 
+    def get_refresh_period() -> float:
+        now = datetime.now()
+        if now.hour < 7:
+            return constants.refresh_period_night_sec * 1000
+        else:
+            return constants.refresh_period_sec * 1000
+
     age = utils.describe_age_of_file_briefly(f"pages/{filename}")
     bgcolor = pick_background_color()
     f.write(
@@ -292,7 +344,7 @@ def emit_wrapped(f, filename) -> None:
 </BODY>"""
         % (
             bgcolor,
-            constants.refresh_period_sec * 1000,
+            get_refresh_period(),
             constants.hostname,
             bgcolor,
             filename,
@@ -329,6 +381,7 @@ if __name__ == "__main__":
     logging.basicConfig()
     changer_thread: Optional[Thread] = None
     renderer_thread: Optional[Thread] = None
+    janitor_thread: Optional[Thread] = None
     while True:
         if changer_thread is None or not changer_thread.is_alive():
             print(
@@ -342,4 +395,10 @@ if __name__ == "__main__":
             )
             renderer_thread = Thread(target=thread_invoke_renderers, args=())
             renderer_thread.start()
+        if janitor_thread is None or not janitor_thread.is_alive():
+            print(
+                f"MAIN[{utils.timestamp()}] - (Re?)initializing janitor thread... (wtf?!)"
+            )
+            janitor_thread = Thread(target=thread_janitor, args=())
+            janitor_thread.start()
         time.sleep(60)