Skip to content

Commit 2b09ce9

Browse files
committed
test: restore test to version from develop branch
1 parent 064fbf0 commit 2b09ce9

File tree

1 file changed

+8
-172
lines changed

1 file changed

+8
-172
lines changed

testinfra/test_ami_nix.py

Lines changed: 8 additions & 172 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,6 @@
162162
"init_database_only": false
163163
}}
164164
"""
165-
pg_cron_json = '{"pg_cron": "1.3.1"}'
166165

167166
logger = logging.getLogger("ami-tests")
168167
handler = logging.StreamHandler()
@@ -273,11 +272,10 @@ def gzip_then_base64_encode(s: str) -> str:
273272
- {{path: /etc/gotrue.env, content: {gzip_then_base64_encode(gotrue_env_content)}, permissions: '0664', encoding: gz+b64}}
274273
- {{path: /etc/wal-g/config.json, content: {gzip_then_base64_encode(walg_config_json_content)}, permissions: '0664', owner: 'wal-g:wal-g', encoding: gz+b64}}
275274
- {{path: /tmp/init.json, content: {gzip_then_base64_encode(init_json_content)}, permissions: '0600', encoding: gz+b64}}
276-
- {{path: /root/pg_extensions.json, content: {gzip_then_base64_encode('{"pg_cron": "1.3.1"}')}, permissions: '0644', encoding: gz+b64}}
277275
runcmd:
278276
- 'sudo echo \"pgbouncer\" \"postgres\" >> /etc/pgbouncer/userlist.txt'
279-
- 'cd /tmp && aws s3 cp --region ap-southeast-1 s3://init-scripts-staging/project/init.sh . 2>&1 | tee /var/log/init-download.log'
280-
- 'bash init.sh "staging" 2>&1 | tee /var/log/init-script.log'
277+
- 'cd /tmp && aws s3 cp --region ap-southeast-1 s3://init-scripts-staging/project/init.sh .'
278+
- 'bash init.sh "staging"'
281279
- 'touch /var/lib/init-complete'
282280
- 'rm -rf /tmp/*'
283281
""",
@@ -344,25 +342,6 @@ def gzip_then_base64_encode(s: str) -> str:
344342

345343
if attempt >= max_attempts:
346344
logger.error("init.sh failed to complete within the timeout period")
347-
348-
# Check init script logs before terminating
349-
try:
350-
download_log = run_ssh_command(ssh, "sudo cat /var/log/init-download.log")
351-
if download_log['succeeded']:
352-
logger.error("Init script download log:")
353-
logger.error(download_log['stdout'])
354-
else:
355-
logger.error(f"Failed to read download log: {download_log['stderr']}")
356-
357-
init_log = run_ssh_command(ssh, "sudo cat /var/log/init-script.log")
358-
if init_log['succeeded']:
359-
logger.error("Init script execution log:")
360-
logger.error(init_log['stdout'])
361-
else:
362-
logger.error(f"Failed to read init script log: {init_log['stderr']}")
363-
except Exception as e:
364-
logger.error(f"Error reading logs: {str(e)}")
365-
366345
instance.terminate()
367346
raise TimeoutError("init.sh failed to complete within the timeout period")
368347

@@ -376,65 +355,22 @@ def is_healthy(ssh) -> bool:
376355
("fail2ban", "sudo fail2ban-client status"),
377356
]
378357

379-
service_status = {}
380358
for service, command in health_checks:
381359
try:
382360
result = run_ssh_command(ssh, command)
383361
if not result['succeeded']:
384362
logger.warning(f"{service} not ready")
385-
logger.error(f"{service} command failed")
386-
logger.error(f"{service} stdout: {result['stdout']}")
387-
logger.error(f"{service} stderr: {result['stderr']}")
388-
389-
# Always read and log the PostgreSQL logs
390-
logger.warning("PostgreSQL status check:")
391-
try:
392-
log_files = [
393-
"/var/log/postgresql/*.log",
394-
"/var/log/postgresql/*.csv"
395-
]
396-
397-
for log_pattern in log_files:
398-
log_result = run_ssh_command(ssh, f"sudo cat {log_pattern}")
399-
if log_result['succeeded']:
400-
logger.error(f"PostgreSQL logs from {log_pattern}:")
401-
logger.error(log_result['stdout'])
402-
if log_result['stderr']:
403-
logger.error(f"Log read errors: {log_result['stderr']}")
404-
else:
405-
logger.error(f"Failed to read PostgreSQL logs from {log_pattern}: {log_result['stderr']}")
406-
except Exception as e:
407-
logger.error(f"Error reading PostgreSQL logs: {str(e)}")
408-
409-
service_status[service] = False
410-
else:
411-
service_status[service] = True
412-
413-
except Exception as e:
414-
logger.warning(f"Connection failed during {service} check, attempting reconnect...")
415-
logger.error(f"Error details: {str(e)}")
416-
service_status[service] = False
417-
418-
# Log overall status of all services
419-
logger.info("Service health status:")
420-
for service, healthy in service_status.items():
421-
logger.info(f"{service}: {'healthy' if healthy else 'unhealthy'}")
422-
423-
# If any service is unhealthy, wait and return False with status
424-
if not all(service_status.values()):
425-
if service_status.get("postgres", False): # If postgres is healthy but others aren't
426-
sleep(5) # Only wait if postgres is up but other services aren't
427-
logger.warning("Some services are not healthy, will retry...")
428-
return False
429-
430-
logger.info("All services are healthy, proceeding to tests...")
363+
return False
364+
except Exception:
365+
logger.warning(f"Connection failed during {service} check")
366+
return False
367+
431368
return True
432369

433370
while True:
434371
if is_healthy(ssh):
435372
break
436-
logger.warning("Health check failed, retrying...")
437-
sleep(5)
373+
sleep(1)
438374

439375
# Return both the SSH connection and instance IP for use in tests
440376
yield {
@@ -571,103 +507,3 @@ def test_postgrest_ending_empty_key_query_parameter_is_removed(host):
571507
},
572508
)
573509
assert res.ok
574-
575-
576-
def test_pg_cron_extension(host):
577-
# Only run this test for PostgreSQL 15
578-
postgres_version = os.environ.get("POSTGRES_MAJOR_VERSION")
579-
if postgres_version != "15":
580-
pytest.skip(f"Skipping pg_cron test for PostgreSQL version {postgres_version}")
581-
582-
# Use the SSH connection to run commands as postgres user
583-
ssh = host['ssh']
584-
585-
# Check prestart script
586-
result = run_ssh_command(ssh, 'ls -l /usr/local/bin/postgres_prestart.sh')
587-
assert result['succeeded'], f"Failed to find prestart script: {result['stderr']}"
588-
logger.info(f"Prestart script details: {result['stdout']}")
589-
590-
# Check if extensions file exists
591-
result = run_ssh_command(ssh, 'sudo cat /root/pg_extensions.json')
592-
assert result['succeeded'], f"Failed to read extensions file: {result['stderr']}"
593-
logger.info(f"Extensions file contents: {result['stdout']}")
594-
595-
# Check if version switcher exists
596-
result = run_ssh_command(ssh, 'ls -l /var/lib/postgresql/.nix-profile/bin/switch_pg_cron_version')
597-
assert result['succeeded'], f"Failed to find version switcher: {result['stderr']}"
598-
logger.info(f"Version switcher details: {result['stdout']}")
599-
600-
# Check systemd service status
601-
logger.info("Checking systemd service status...")
602-
result = run_ssh_command(ssh, 'sudo systemctl list-units --type=service | grep postgres')
603-
logger.info(f"PostgreSQL services: {result['stdout']}")
604-
result = run_ssh_command(ssh, 'sudo systemctl status postgresql')
605-
logger.info(f"PostgreSQL service status: {result['stdout']}")
606-
607-
# Restart PostgreSQL through systemd
608-
logger.info("Restarting PostgreSQL through systemd...")
609-
result = run_ssh_command(ssh, 'sudo systemctl stop postgresql')
610-
logger.info(f"Stop result: {result['stdout']}")
611-
result = run_ssh_command(ssh, 'sudo systemctl start postgresql')
612-
logger.info(f"Start result: {result['stdout']}")
613-
614-
# Wait for PostgreSQL to be ready
615-
logger.info("Waiting for PostgreSQL to be ready...")
616-
max_attempts = 30
617-
for attempt in range(max_attempts):
618-
result = run_ssh_command(ssh, 'sudo -u postgres /usr/bin/pg_isready -U postgres')
619-
if result['succeeded']:
620-
logger.info("PostgreSQL is ready")
621-
break
622-
logger.warning(f"PostgreSQL not ready yet (attempt {attempt + 1}/{max_attempts})")
623-
sleep(2)
624-
else:
625-
raise Exception("PostgreSQL failed to start through systemd")
626-
627-
# Create the extension
628-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "CREATE EXTENSION pg_cron WITH SCHEMA pg_catalog VERSION \'1.3.1\';"')
629-
assert result['succeeded'], f"Failed to create pg_cron extension: {result['stderr']}"
630-
631-
# Verify the extension version
632-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "SELECT extversion FROM pg_extension WHERE extname = \'pg_cron\';"')
633-
assert result['succeeded'], f"Failed to get pg_cron version: {result['stderr']}"
634-
assert "1.3.1" in result['stdout'], f"Expected pg_cron version 1.3.1, but got: {result['stdout']}"
635-
logger.info(f"pg_cron version: {result['stdout']}")
636-
637-
# Check the actual function definition
638-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "\sf cron.schedule"')
639-
assert result['succeeded'], f"Failed to get cron.schedule function definition: {result['stderr']}"
640-
logger.info(f"cron.schedule function definition: {result['stdout']}")
641-
642-
# Check extension details
643-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "SELECT * FROM pg_extension WHERE extname = \'pg_cron\';"')
644-
assert result['succeeded'], f"Failed to get pg_cron extension details: {result['stderr']}"
645-
logger.info(f"pg_cron extension details: {result['stdout']}")
646-
647-
# Create test table
648-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "CREATE TABLE cron_test_log (id SERIAL PRIMARY KEY, message TEXT, log_time TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP);"')
649-
assert result['succeeded'], f"Failed to create test table: {result['stderr']}"
650-
651-
# Check the schema of cron.job table
652-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "\d cron.job"')
653-
assert result['succeeded'], f"Failed to get cron.job schema: {result['stderr']}"
654-
logger.info(f"cron.job schema: {result['stdout']}")
655-
656-
# Check available cron functions
657-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "\df cron.*"')
658-
assert result['succeeded'], f"Failed to get cron functions: {result['stderr']}"
659-
logger.info(f"Available cron functions: {result['stdout']}")
660-
661-
# Schedule a job using the basic schedule function
662-
result = run_ssh_command(ssh, '''sudo -u postgres psql -d postgres -c "SELECT cron.schedule('* * * * *'::text, 'INSERT INTO cron_test_log (message) VALUES (''Hello from pg_cron!'');'::text);"''')
663-
assert result['succeeded'], f"Failed to schedule job: {result['stderr']}"
664-
assert "1" in result['stdout'], "Expected schedule ID 1"
665-
666-
# Verify job is scheduled
667-
result = run_ssh_command(ssh, 'sudo -u postgres psql -d postgres -c "SELECT * FROM cron.job;"')
668-
assert result['succeeded'], f"Failed to query cron.job: {result['stderr']}"
669-
assert "* * * * *" in result['stdout'], "Expected cron schedule pattern"
670-
assert "INSERT INTO cron_test_log" in result['stdout'], "Expected cron command"
671-
assert "postgres" in result['stdout'], "Expected postgres username"
672-
assert "postgres" in result['stdout'], "Expected postgres database"
673-

0 commit comments

Comments
 (0)