spark-supervisor
Process supervisor and health monitor for sovereign daemons
Brought by drakestapleton
spark-supervisor / tests / wait.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Test-only inotify oracle: watch before examining a path; never poll on a clock. |
| 3 | wait.py PATH exists|gone|contains [TEXT], exits 1 after 15 seconds. |
| 4 | """ |
| 5 | import ctypes, os, pathlib, select, sys, time |
| 6 | p=pathlib.Path(sys.argv[1]); mode=sys.argv[2]; needle=sys.argv[3] if len(sys.argv)>3 else '' |
| 7 | libc=ctypes.CDLL(None,use_errno=True) |
| 8 | libc.inotify_add_watch.argtypes=[ctypes.c_int,ctypes.c_char_p,ctypes.c_uint32] |
| 9 | fd=libc.inotify_init1(os.O_NONBLOCK|os.O_CLOEXEC) |
| 10 | assert fd>=0 |
| 11 | watched=set(); deadline=time.monotonic()+15 |
| 12 | while True: |
| 13 | for parent in reversed(p.parents): |
| 14 | if parent.is_dir() and parent not in watched: |
| 15 | assert libc.inotify_add_watch(fd,os.fsencode(parent),0xfff)>=0 |
| 16 | watched.add(parent) |
| 17 | if mode=='exists': ready=p.exists() |
| 18 | elif mode=='gone': ready=not p.exists() |
| 19 | else: |
| 20 | try: ready=needle in p.read_text() |
| 21 | except FileNotFoundError: ready=False |
| 22 | if ready: break |
| 23 | remaining=deadline-time.monotonic() |
| 24 | if remaining<=0 or not select.select([fd],[],[],remaining)[0]: |
| 25 | raise SystemExit('test event deadline: '+str(p)) |
| 26 | try: os.read(fd,65536) |
| 27 | except BlockingIOError: pass |
| 28 | os.close(fd) |