#!/usr/bin/env python3 """DBMS_PIPE isolation between two PostgreSQL databases in one postmaster.""" import os from pathlib import Path import shutil import subprocess import tempfile import time tool_bin=os.environ.get("PIPE_TEST_BINDIR") if tool_bin is None: initdb=shutil.which("initdb") if initdb is None: raise RuntimeError("provide PIPE_TEST_BINDIR with initdb/psql/pg_ctl/createdb") tool_bin=str(Path(initdb).parent) bindir=Path(tool_bin) root=Path(tempfile.mkdtemp(prefix="dbms_pipe_namespace_",dir="/tmp")) evidence=Path(os.environ.get("PIPE_NAMESPACE_EVIDENCE_DIR",str(root/"evidence"))) evidence.mkdir(parents=True,exist_ok=True) sock=root/"socket" sock.mkdir() data=root/"data" port=os.environ.get("PIPE_NAMESPACE_PORT","56467") name="PIPE_R04_TWO_DATABASES" db_b="pipe_r04_other" started=False children=[] def record(message): print(message,flush=True) with (evidence/"status.txt").open("a") as f: f.write(message+"\n") def process(cmd,tag,input=None,check=True): p=subprocess.run([str(x) for x in cmd],input=input,text=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,check=False) (evidence/(tag+".txt")).write_text(p.stdout) if check and p.returncode!=0: raise RuntimeError(f"{tag}: rc={p.returncode}, tail={p.stdout[-1200:]}") return p.stdout def sql(db,text,tag): return process([bindir/"psql","-XAtq","-v","ON_ERROR_STOP=1", "-h",sock,"-p",port,"-U","postgres","-d",db,"-c",text],tag).strip() def check(received,expected,tag): if received!=str(expected): raise RuntimeError(f"{tag}: got {received!r}, expected {expected!r}") record("PASS "+tag) def receive(db,tag): return sql(db,f""" DO $$ DECLARE rc int; value text; BEGIN rc:=dbms_pipe_receive_message('{name}'::varchar2,0,NULL::varchar2); IF rc IS DISTINCT FROM 0 THEN RAISE EXCEPTION 'receive rc=%',rc; END IF; value:=dbms_pipe_unpack_message_varchar2()::text; IF value IS DISTINCT FROM '{tag}' THEN RAISE EXCEPTION 'payload %, expected {tag}',value; END IF; END $$;""","receive-"+tag) def send(db,value): sql(db,f""" DO $$ BEGIN PERFORM dbms_pipe_pack_message('{value}'::varchar2); IF dbms_pipe_send_message('{name}'::varchar2,0,65536,false,0) IS DISTINCT FROM 0 THEN RAISE EXCEPTION 'send failed'; END IF; END $$;""","send-"+value) try: record("START isolated RuDB database namespace test") process([bindir/"initdb","-D",data,"-U","postgres","-A","trust", "--no-sync","--no-instructions"],"initdb") with (data/"postgresql.conf").open("a") as f: f.write("listen_addresses = ''\n") f.write(f"unix_socket_directories = '{sock}'\nport = {port}\nfsync = off\nmax_connections = 30\n") process([bindir/"pg_ctl","-D",data,"-l",evidence/"server.log","-w","start"],"start") started=True process([bindir/"createdb","-h",sock,"-p",port,"-U","postgres",db_b],"createdb") record("PASS two PostgreSQL databases") check(sql("postgres",f"SELECT dbms_pipe_create_pipe('{name}'::varchar2,65536,false,false,0)","create-a"),"0","create A") send("postgres","A_ORIGINAL") check(sql(db_b,f"SELECT dbms_pipe_receive_message('{name}'::varchar2,0,NULL::varchar2)","b-no-a"),"1","B cannot read A (nonblocking)") send(db_b,"B_ORIGINAL") receive("postgres","A_ORIGINAL") receive(db_b,"B_ORIGINAL") record("PASS independent same-name public pipe queues") send("postgres","A_UNPURGED") send(db_b,"B_PURGED") sql(db_b,f"SELECT dbms_pipe_purge('{name}'::varchar2)","purge-b") check(sql(db_b,f"SELECT dbms_pipe_receive_message('{name}'::varchar2,0,NULL::varchar2)","b-empty"),"1","B purge") receive("postgres","A_UNPURGED") record("PASS PURGE is database-local") send("postgres","A_UNREMOVED") check(sql(db_b,f"SELECT dbms_pipe_remove_pipe('{name}'::varchar2)","remove-b"),"0","B remove") receive("postgres","A_UNREMOVED") record("PASS REMOVE is database-local") sql("postgres",f""" DO $$ DECLARE value text; BEGIN PERFORM dbms_pipe_pack_message('CASE_FOLDED'::varchar2); IF dbms_pipe_send_message('{name}'::varchar2,0,65536,false,0) IS DISTINCT FROM 0 THEN RAISE EXCEPTION 'send'; END IF; IF dbms_pipe_receive_message(lower('{name}')::varchar2,0,NULL::varchar2) IS DISTINCT FROM 0 THEN RAISE EXCEPTION 'receive'; END IF; value:=dbms_pipe_unpack_message_varchar2()::text; IF value IS DISTINCT FROM 'CASE_FOLDED' THEN RAISE EXCEPTION 'wrong value %',value; END IF; END $$;""","case-folded") record("PASS case-insensitive name inside database") # Waiters in A and B use the same name but belong to different databases. # A SEND must wake/deliver only to A; B times out without a message. for db,tag in (("postgres","A"),(db_b,"B")): query=f""" DO $$ DECLARE rc int; value text := ''; BEGIN rc:=dbms_pipe_receive_message('{name}'::varchar2,3,NULL::varchar2); IF rc=0 THEN value:=dbms_pipe_unpack_message_varchar2()::text; END IF; RAISE NOTICE 'R04_{tag}_RESULT=%:%',rc,value; END $$;""" env=os.environ.copy() env["PGAPPNAME"]=f"r04_waiter_{tag}" args=[str(bindir/"psql"),"-XAtq","-v","ON_ERROR_STOP=1", "-h",str(sock),"-p",port,"-U","postgres","-d",db,"-c",query] children.append((tag,subprocess.Popen(args,env=env,text=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT))) ready=False for attempt in range(100): count=sql("postgres","SELECT count(*) FROM pg_stat_activity " "WHERE application_name LIKE 'r04_waiter_%' " "AND wait_event_type='Extension'","waiter-count") if count=="2": ready=True break time.sleep(.03) if not ready: raise RuntimeError("two database-specific waiters did not register") send("postgres","A_WAKE") for tag,proc in children: output,_=proc.communicate(timeout=10) (evidence/f"waiter-{tag}.txt").write_text(output) if proc.returncode!=0: raise RuntimeError(f"waiter {tag} exited {proc.returncode}: {output}") expected="R04_A_RESULT=0:A_WAKE" if tag=="A" else "R04_B_RESULT=1:" if expected not in output: raise RuntimeError(f"waiter {tag} wrong outcome: {output}") record("PASS concurrent same-name waiters isolated across databases") check(sql("postgres",f"SELECT dbms_pipe_remove_pipe('{name}'::varchar2)","remove-a"),"0","A remove") record("PASS_ALL_R04") finally: for tag,proc in children: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=3) except subprocess.TimeoutExpired: proc.kill() proc.wait() if started: process([bindir/"pg_ctl","-D",data,"-m","immediate","-w","stop"],"stop",check=False) record("CLEAN temporary PostgreSQL cluster") shutil.rmtree(root)