# A practice worker for the alert-on-stall task. It "processes" a job every second and serves Prometheus metrics on
# :8000/metrics. Create /tmp/pause inside its container and it stops processing but keeps serving metrics, which is
# what a stuck worker looks like from outside.
import http.server, os, threading, time

processed = 0
def work():
    global processed
    while True:
        time.sleep(1)
        if not os.path.exists('/tmp/pause'):
            processed += 1
threading.Thread(target=work, daemon=True).start()

class Metrics(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != '/metrics':
            self.send_response(404); self.end_headers(); return
        body = ('# HELP worker_jobs_processed_total Jobs finished since start.\n'
                '# TYPE worker_jobs_processed_total counter\n'
                f'worker_jobs_processed_total {processed}\n').encode()
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain; version=0.0.4')
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *args):
        pass

http.server.ThreadingHTTPServer(('0.0.0.0', 8000), Metrics).serve_forever()
