257 lines
9.8 KiB
Python
257 lines
9.8 KiB
Python
import datetime
|
|
import multiprocessing
|
|
import os
|
|
import traceback
|
|
|
|
from tblib import pickling_support
|
|
|
|
from process_helper import stop_processing
|
|
|
|
pickling_support.install()
|
|
import pickle, sys
|
|
import time
|
|
from multiprocessing import Process
|
|
|
|
import diskcache
|
|
import requests
|
|
|
|
from camera import CaliforniaCamera, NevadaCamera
|
|
from recorder import Recorder
|
|
|
|
MAX_PROCESSES = 16
|
|
SKIP_TIME_CHECKS = True
|
|
DEBUG_MODE = False
|
|
MAX_RECORDING_TIME = 60 # 1200
|
|
|
|
CACHE = diskcache.Cache('cache')
|
|
|
|
|
|
def log(msg):
|
|
print(f"{datetime.datetime.now()} - Process {os.getpid()}: {msg}")
|
|
|
|
|
|
def parse_cameras_nevada(data):
|
|
cameras = []
|
|
data = data["data"]
|
|
for camera in data:
|
|
cam = NevadaCamera(camera)
|
|
log(f"Parsed camera: {cam}")
|
|
cameras.append(cam)
|
|
return cameras
|
|
|
|
|
|
def parse_cameras_california(data):
|
|
cameras = []
|
|
data = data['data']
|
|
for camera in data:
|
|
cctv = camera['cctv']
|
|
cam = CaliforniaCamera(cctv)
|
|
log("Parsed camera: " + str(cam))
|
|
cameras.append(cam)
|
|
return cameras
|
|
|
|
|
|
def request_camera_api(api_url, parse):
|
|
try:
|
|
log(f"Requesting camera API at {api_url}")
|
|
CACHE["requesting camera api"] = True
|
|
response = requests.get(api_url)
|
|
if response.status_code != 200:
|
|
raise RuntimeError(f"Request to {api_url} failed with status code {response.status_code}")
|
|
data = response.json()
|
|
cameras_for_url = parse(data)# parse_cameras(data)
|
|
cameras = sorted([c for c in cameras_for_url if c.stream_url], key=lambda c: c.index)
|
|
CACHE.add(api_url, cameras, expire=7200)
|
|
CACHE.pop("requesting camera api")
|
|
return cameras
|
|
except Exception as e:
|
|
log(f"camera api request failed with exception: {str(e)}\n{traceback.format_exc()}")
|
|
CACHE["exception"] = pickle.dumps(sys.exc_info())
|
|
return []
|
|
|
|
|
|
def load_cameras_nevada():
|
|
print("Loading nevada cameras...")
|
|
base_url = "https://www.nvroads.com/List/GetData/Cameras"
|
|
|
|
response = requests.get(base_url)
|
|
if response.status_code != 200:
|
|
raise RuntimeError(f"Request to {base_url} failed with status code {response.status_code}")
|
|
data = response.json()
|
|
total = int(data["recordsTotal"])
|
|
cameras = []
|
|
length = 50
|
|
for start in range(0, total, length):
|
|
query_params = ('{"columns":[{"data":null,"name":""},'
|
|
'{"name":"sortOrder","s":true},'
|
|
'{"name":"region","s":true},'
|
|
'{"name":"roadway","s":true},'
|
|
'{"data":4,"name":""}],'
|
|
f'"start":{start},"length":{length}}}')
|
|
query = f"query={query_params}"
|
|
url = f"{base_url}?{query}"
|
|
while "requesting camera api" in CACHE:
|
|
log("another process is requesting camera api")
|
|
time.sleep(30)
|
|
if url in CACHE:
|
|
cameras_for_url = CACHE[url]
|
|
else:
|
|
cameras_for_url = request_camera_api(url, parse_cameras_nevada)
|
|
cameras.extend(cameras_for_url)
|
|
names = set()
|
|
filtered_cameras = []
|
|
for camera in cameras:
|
|
name = " ".join(str(''.join([c for c in str(camera.name) if c.isalnum() or c.isspace()])).split())
|
|
if name not in names:
|
|
filtered_cameras.append(camera)
|
|
names.add(name)
|
|
return cameras
|
|
|
|
|
|
def load_cameras_california():
|
|
api_urls = [f"https://cwwp2.dot.ca.gov/data/d{i}/cctv/cctvStatusD{f'0{i}' if i < 10 else f'{i}'}.json"
|
|
for i in range(1, 13)]
|
|
cameras = []
|
|
# CACHE.clear()
|
|
for api_url in api_urls:
|
|
# log(f"loading cameras from {api_url}")
|
|
while "requesting camera api" in CACHE:
|
|
log("another process is requesting camera api")
|
|
time.sleep(30)
|
|
if api_url in CACHE:
|
|
cameras_for_url = CACHE[api_url]
|
|
else:
|
|
cameras_for_url = request_camera_api(api_url, parse_cameras_california)
|
|
cameras.extend(cameras_for_url)
|
|
names = set()
|
|
for camera in cameras:
|
|
name = " ".join(str(''.join([c for c in str(camera.name) if c.isalnum() or c.isspace()])).split())
|
|
if name in names:
|
|
raise ValueError(f"found duplicate camera name {camera.name}")
|
|
names.add(name)
|
|
return cameras
|
|
|
|
|
|
def record_cameras(location, distance, load_cameras):
|
|
try:
|
|
cameras = load_cameras()
|
|
cameras = sorted([c for c in cameras if c.stream_url], key=lambda c: c.index)
|
|
recorder = Recorder(cameras, location, distance, MAX_RECORDING_TIME)
|
|
recorder.start_recording(SKIP_TIME_CHECKS, DEBUG_MODE)
|
|
except Exception as e:
|
|
log(f"recording failed with exception: {str(e)}\n{traceback.format_exc()}")
|
|
CACHE["exception"] = pickle.dumps(sys.exc_info())
|
|
|
|
|
|
class ProcessSupervisor:
|
|
def __init__(self, location, distance, load_cameras):
|
|
self.location = location
|
|
self.distance = distance
|
|
|
|
self.next_start = 0
|
|
self.sleep_time = 30
|
|
self.failed_start = 0
|
|
self.next_log = 0
|
|
self.requesting_cameras_since = 0
|
|
self.load_cameras = load_cameras
|
|
self.processes: list[tuple[multiprocessing.Process, float]] = []
|
|
log("ProcessSupervisor created")
|
|
|
|
def start(self):
|
|
while True:
|
|
self.sleep_time = 10
|
|
self.check_cache()
|
|
self.monitor_running_processes()
|
|
self.start_new_process()
|
|
time.sleep(self.sleep_time)
|
|
|
|
def monitor_running_processes(self):
|
|
running_processes = [(p, start_time) for p, start_time in self.processes if p.is_alive()]
|
|
stopped_processes = [(p, start_time) for p, start_time in self.processes if not p.is_alive()]
|
|
now = time.time()
|
|
avg_running = 0.0 if len(running_processes) == 0 else sum([now - start_time for p, start_time in running_processes]) / len(running_processes)
|
|
avg_stopped = 0.0 if len(stopped_processes) == 0 else sum([now - start_time for p, start_time in stopped_processes]) / len(stopped_processes)
|
|
running_msg = f"{len(running_processes)} process{"es" if len(running_processes) != 1 else ""} running"
|
|
avg_runtime_msg = f", {"average " if len(running_processes) != 1 else ""}runtime: {datetime.timedelta(seconds=int(avg_running))}" if avg_running > 0 else ""
|
|
stopped_msg = f"{len(stopped_processes)} process{"es" if len(stopped_processes) != 1 else ""} stopped"
|
|
avg_runtime_stopped_msg = f", {"average " if len(stopped_processes) != 1 else ""}runtime: {datetime.timedelta(seconds=int(avg_stopped))}"
|
|
log(f"{running_msg}{avg_runtime_msg}")
|
|
if len(stopped_processes) > 0:
|
|
log(f"{stopped_msg}{avg_runtime_stopped_msg}")
|
|
|
|
unstopped_processes = [(p, start_time) for p, start_time in running_processes if now - start_time > MAX_RECORDING_TIME + 600]
|
|
if len(unstopped_processes) > 0:
|
|
try:
|
|
raise ValueError(f"{len(unstopped_processes)} processes did not terminate correctly")
|
|
except Exception:
|
|
CACHE["exception"] = pickle.dumps(sys.exc_info())
|
|
|
|
if len(CACHE["active_cameras"]) > len(running_processes):
|
|
try:
|
|
raise ValueError("there are more cameras active than processes running")
|
|
except Exception:
|
|
CACHE["exception"] = pickle.dumps(sys.exc_info())
|
|
|
|
if time.time() > self.next_log:
|
|
active_cameras = CACHE["active_cameras"]
|
|
for camera, start_time in active_cameras:
|
|
log(f"Camera {camera} recording for {datetime.timedelta(seconds=int(time.time()-start_time))}")
|
|
self.next_log = time.time() + 60
|
|
|
|
if len(running_processes) == 0:
|
|
if self.failed_start == 0:
|
|
self.failed_start = now
|
|
if self.failed_start < now - 600:
|
|
log("Recording processes failed, increasing wait time")
|
|
self.sleep_time = 3600
|
|
self.next_start = now + 3600
|
|
self.failed_start = 0
|
|
else:
|
|
self.failed_start = 0
|
|
|
|
self.processes = running_processes
|
|
|
|
def start_new_process(self):
|
|
if self.next_start < time.time() and len(self.processes) < MAX_PROCESSES:
|
|
if "requesting camera api" in CACHE:
|
|
if self.requesting_cameras_since == 0:
|
|
self.requesting_cameras_since = time.time()
|
|
elif self.requesting_cameras_since + 1800 < time.time():
|
|
try:
|
|
raise TimeoutError("requesting cameras appears to be blocked")
|
|
except Exception:
|
|
CACHE["exception"] = pickle.dumps(sys.exc_info())
|
|
return
|
|
log("starting new process")
|
|
p = Process(target=record_cameras, args=(self.location,self.distance, self.load_cameras))
|
|
p.start()
|
|
self.processes.append((p, time.time()))
|
|
self.next_start = time.time() + 10
|
|
self.requesting_cameras_since = 0
|
|
|
|
def check_cache(self):
|
|
if "exception" in CACHE:
|
|
for p, t in self.processes:
|
|
if p.is_alive():
|
|
stop_processing(p, None)
|
|
_, exc, tb = pickle.loads(CACHE["exception"])
|
|
raise ValueError(f"An Exception was raised: {str(exc)}").with_traceback(tb)
|
|
if "cameras_available" in CACHE and CACHE["cameras_available"] == 0:
|
|
log("no cameras available, stopping new processes for 30 minutes")
|
|
self.next_start = time.time() + 1800
|
|
CACHE.pop("cameras_available")
|
|
|
|
|
|
def main_recording():
|
|
CACHE.clear()
|
|
# CACHE.pop("requesting camera api")
|
|
# CACHE.pop("exception")
|
|
# CACHE.pop("cameras_available")
|
|
# record_cameras("Los Angeles", 0)
|
|
# load_cameras()
|
|
# CACHE.clear()
|
|
CACHE["active_cameras"] = set()
|
|
# record_cameras("Las Vegas", 0, load_cameras_nevada)
|
|
p = ProcessSupervisor("Las Vegas", 0, load_cameras_nevada)
|
|
p.start()
|