Skip to content

Commit 5a48ce3

Browse files
authored
separate logs and only reveal progress in console (#14)
* separate logs and only reveal progress in console * add details in log
1 parent f239b95 commit 5a48ce3

5 files changed

Lines changed: 162 additions & 83 deletions

File tree

build.py

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import os
22
import sys
33
import subprocess
4+
import logging
5+
from utils import run_command
46

5-
def run_command(cmd, **kwargs):
6-
print("[CMD]", " ".join(cmd))
7-
subprocess.run(cmd, check=True, **kwargs)
8-
9-
def build_sqlancer_image(force_rebuild=False):
7+
def build_sqlancer_image(script_log, docker_log, force_rebuild=False):
108
if force_rebuild:
11-
print("[INFO] Rebuilding SQLancer image due to --cache not specified...")
12-
run_command(["docker", "build", "--no-cache", "-t", "sqlancer:latest", "./sqlancer"])
9+
script_log.info("Rebuilding SQLancer image: sqlancer:latest ...")
10+
run_command(["docker", "build", "--no-cache", "-t", "sqlancer:latest", "./sqlancer"], docker_log)
11+
script_log.info("SQLancer image built: sqlancer:latest")
1312
return
1413

1514
result = subprocess.run(
@@ -18,12 +17,13 @@ def build_sqlancer_image(force_rebuild=False):
1817
)
1918
images = result.stdout.strip().splitlines()
2019
if "sqlancer:latest" in images:
21-
print("[INFO] SQLancer image already exists: sqlancer:latest")
20+
script_log.info("SQLancer image exists: sqlancer:latest")
2221
else:
23-
print("[INFO] SQLancer image not found. Building from ./sqlancer...")
24-
run_command(["docker", "build", "-t", "sqlancer:latest", "./sqlancer"])
22+
script_log.info("Building SQLancer image from cache: sqlancer:latest...")
23+
run_command(["docker", "build", "-t", "sqlancer:latest", "./sqlancer"], docker_log)
24+
script_log.info("SQLancer image built: sqlancer:latest")
2525

26-
def build_network(network_name="sqlancer-net"):
26+
def build_network(script_log, docker_log, network_name="sqlancer-net"):
2727
try:
2828
output = subprocess.check_output([
2929
"docker", "network", "ls",
@@ -32,29 +32,37 @@ def build_network(network_name="sqlancer-net"):
3232
])
3333
networks = output.decode().splitlines()
3434
if network_name not in networks:
35-
print(f"[INFO] Creating docker network: {network_name}")
36-
subprocess.run(["docker", "network", "create", network_name], check=True)
35+
script_log.info("Building network: %s ...", network_name)
36+
run_command(["docker", "network", "create", network_name], docker_log)
37+
script_log.info("Network built: %s", network_name)
3738
else:
38-
print(f"[INFO] Docker network '{network_name}' already exists.")
39+
script_log.info("Network already exists: %s", network_name)
40+
3941
except Exception as e:
40-
print(f"[ERROR] Failed to check/create Docker network: {e}")
42+
script_log.error("Network building failed: %s", network_name)
4143
sys.exit(1)
4244

43-
def build_db_image(cfg, use_cache, custom=False, dockerfile_path=""):
45+
def build_db_image(cfg, use_cache, script_log, docker_log, custom=False, dockerfile_path=""):
4446
if not use_cache and not custom:
4547
image = cfg["image"]
46-
print(f"[INFO] Pulling image {image}")
47-
run_command(["docker", "pull", image])
48-
49-
if custom:
48+
script_log.info("Pulling db image: %s ...", image)
49+
run_command(["docker", "pull", image], docker_log)
50+
script_log.info("DB image pulled: %s", image)
51+
elif custom:
5052
build_cmd = ["docker", "build", "-t", cfg["image"], os.path.dirname(dockerfile_path)]
5153
if not use_cache:
5254
build_cmd.insert(2, "--no-cache")
53-
run_command(build_cmd)
55+
script_log.info("Building db image: %s ...", cfg["image"])
56+
run_command(build_cmd, docker_log)
57+
script_log.info("DB image pulled: %s ...", cfg["image"])
58+
else:
59+
script_log.info("DB image already exists: %s", cfg["image"])
5460

55-
def build_environment(cfg, use_cache, custom=False, dockerfile_path=""):
56-
build_network()
57-
build_sqlancer_image(force_rebuild=not use_cache)
61+
def build_environment(cfg, use_cache, script_log, docker_log, custom=False, dockerfile_path=""):
62+
script_log.info("==============================Building environment==============================")
63+
build_network(script_log, docker_log)
64+
build_sqlancer_image(script_log, docker_log, force_rebuild=not use_cache)
5865
if cfg["embedded"] == "no":
59-
build_db_image(cfg, use_cache, custom, dockerfile_path)
60-
66+
build_db_image(cfg, use_cache, script_log, docker_log, custom, dockerfile_path)
67+
script_log.info("==============================Building environment==============================")
68+

sqlancer/entrypoint.sh

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ echo "Waiting for DB to become healthy..."
99

1010
cd /root/sqlancer/target || { echo "Missing target directory"; exit 1; }
1111

12-
# Wait for the DB container (identified by SQLANCER_HOST) to become healthy
12+
# Wait for the DB container to become healthy
1313
for i in {1..60}; do
1414
STATUS=$(docker inspect --format='{{.State.Health.Status}}' "$SQLANCER_HOST" 2>/dev/null || echo "unknown")
1515
if [ "$STATUS" = "healthy" ]; then
@@ -18,13 +18,12 @@ for i in {1..60}; do
1818
sleep 1
1919
done
2020

21-
# Prepare the command string
2221
CMD="java -jar sqlancer-*.jar --num-threads \"$SQLANCER_THREADS\" --timeout-seconds \"$SQLANCER_TIMEOUT\" --username \"$SQLANCER_USERNAME\" --password \"$SQLANCER_PASSWORD\" --host \"$SQLANCER_HOST\" \"$SQLANCER_DBMS\" --oracle \"$SQLANCER_ORACLE\""
2322

24-
# Print command to console and log file
23+
# Show command to console + log file
2524
echo "Running: $CMD" | tee -a "$LOG_FILE"
2625

27-
# Run the command and tee output to both console and log file
28-
eval "$CMD" 2>&1 | tee -a "$LOG_FILE"
26+
# Run command: log everything, show only stats to console
27+
eval "$CMD" 2>&1 | tee -a "$LOG_FILE" | grep --line-buffered "Executed"
2928

3029
echo "[INFO] SQLancer finished. Logs saved to $LOG_DIR"

start.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import json
66
from test import test_single, test_custom_dockerfile
77
from build import build_environment, build_sqlancer_image, build_db_image
8+
from utils import setup_logging
9+
import logging
810

911
def load_json(path):
1012
with open(path) as f:
@@ -32,52 +34,54 @@ def main():
3234
global_cfg = load_json("config.json")
3335
dbms_list = global_cfg.get("dbms_list", [])
3436

37+
script_log, docker_log, sqlancer_log, run_dir = setup_logging()
38+
script_log.info("Log output directory: %s", run_dir)
39+
3540
if args.command == "test":
3641
if args.dockerfile:
3742
if not args.config:
3843
parser.error("Custom DBMS test requires --config")
3944
cfg = load_json(args.config)
40-
build_environment(cfg, use_cache, True, args.dockerfile)
41-
test_custom_dockerfile(args.dockerfile, cfg, use_cache)
45+
build_environment(cfg, use_cache, script_log, docker_log, True, args.dockerfile)
46+
test_custom_dockerfile(args.dockerfile, cfg, script_log, docker_log, sqlancer_log, run_dir, use_cache)
4247

4348
elif args.dbms == "all":
4449
for dbms in dbms_list:
4550
config_path = os.path.join(dbms, "config.json")
4651
if not os.path.exists(config_path):
47-
print(f"[WARNING] Skipping {dbms}, missing config file.")
52+
# print(f"[WARNING] Skipping {dbms}, missing config file.")
4853
continue
4954
cfg = load_json(config_path)
50-
build_environment(cfg, use_cache)
51-
test_single(cfg, use_cache)
55+
build_environment(cfg, use_cache, script_log, docker_log)
56+
test_single(cfg, script_log, docker_log, sqlancer_log, run_dir, use_cache)
5257

5358
elif args.dbms:
5459
if not args.config:
5560
parser.error("Single DBMS test requires --config")
5661
cfg = load_json(args.config)
57-
build_environment(cfg, use_cache)
58-
test_single(cfg, use_cache)
59-
62+
build_environment(cfg, use_cache, script_log, docker_log)
63+
test_single(cfg, script_log, docker_log, sqlancer_log, run_dir, use_cache)
6064
else:
6165
parser.error("Must specify either --dbms or --dockerfile")
6266
elif args.command == "build":
6367
if args.sqlancer:
64-
build_sqlancer_image(not use_cache)
68+
build_sqlancer_image(script_log, docker_log, not use_cache)
6569

6670
elif args.dbms == "all":
6771
for dbms in dbms_list:
6872
config_path = os.path.join(dbms, "config.json")
6973
if not os.path.exists(config_path):
70-
print(f"[WARNING] Skipping {dbms}, missing config file.")
74+
# print(f"[WARNING] Skipping {dbms}, missing config file.")
7175
continue
7276
cfg = load_json(config_path)
73-
build_db_image(cfg, use_cache)
77+
build_db_image(cfg, use_cache, script_log, docker_log)
7478
elif args.dbms:
7579
config_path = os.path.join(args.dbms, "config.json")
7680
if not os.path.exists(config_path):
77-
print(f"[ERROR] Config file not found for DBMS: {args.dbms}")
81+
# print(f"[ERROR] Config file not found for DBMS: {args.dbms}")
7882
sys.exit(1)
7983
cfg = load_json(config_path)
80-
build_db_image(cfg, use_cache)
84+
build_db_image(cfg, use_cache, script_log, docker_log)
8185

8286
else:
8387
parser.error("Must specify --dbms or --sqlancer for build command")

test.py

Lines changed: 51 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@
55
import time
66
import shlex
77
from datetime import datetime
8-
9-
def run_command(cmd, **kwargs):
10-
print("[CMD]", " ".join(cmd))
11-
subprocess.run(cmd, check=True, **kwargs)
8+
from utils import run_command
129

1310
def container_exists(name):
1411
result = subprocess.run(
@@ -17,18 +14,18 @@ def container_exists(name):
1714
)
1815
return name in result.stdout.strip().splitlines()
1916

20-
def start_db_container(dbms, cfg):
17+
def start_db_container(dbms, cfg, script_log, docker_log):
2118
image = cfg.get("image")
2219
container_name = cfg.get("container_name", f"{dbms}-sqlancer")
2320
env_dict = cfg.get("env", {})
2421

2522
if not image:
26-
print("[ERROR] Missing 'image' field in config.json")
23+
script_log.error( "Missing 'image' field in config.json")
2724
sys.exit(1)
2825

2926
if container_exists(container_name):
30-
print(f"[INFO] Container '{container_name}' already exists. Remove the old container and restart.")
31-
remove_container(container_name)
27+
script_log.info( "Container %s already exists, remove the old container and restart", container_name)
28+
remove_container(container_name, script_log, docker_log)
3229

3330
env_vars = []
3431
for k, v in env_dict.items():
@@ -40,13 +37,12 @@ def start_db_container(dbms, cfg):
4037
"--network", "sqlancer-net",
4138
*env_vars,
4239
image
43-
])
44-
40+
], docker_log)
4541

46-
print(f"[INFO] Waiting for DBMS container '{container_name}' to be ready...")
42+
script_log.info("Starting DBMS container: %s ...", container_name)
4743
time.sleep(10)
4844

49-
# Optional init SQL
45+
5046
init_sql = cfg.get("init_sql")
5147
init_cmd_template = cfg.get("init_sql_command_template")
5248
if init_sql and init_cmd_template:
@@ -57,18 +53,22 @@ def start_db_container(dbms, cfg):
5753
sql=init_sql
5854
)
5955
full_cmd = ["docker", "exec", container_name] + shlex.split(cmd_str)
60-
print(f"[INFO] Running init SQL inside container: {init_sql}")
61-
run_command(full_cmd)
56+
script_log.info("Running init SQL inside container...")
57+
run_command(full_cmd, docker_log)
6258
except Exception as e:
63-
print(f"[WARNING] Failed to run init SQL: {e}")
59+
script_log.warning("Init SQL running failed")
6460

65-
def start_sqlancer_container(dbms, host_container_name, username, password, oracle, threads, timeout):
66-
date = datetime.today().strftime("%y-%m-%d-%H-%M-%S")
67-
log_dir_host = os.path.abspath(os.path.join("logs", date))
68-
os.makedirs(log_dir_host, exist_ok=True)
61+
script_log.info("DBMS container started: %s", container_name)
62+
63+
def start_sqlancer_container(dbms, host_container_name, username, password, oracle, threads, timeout, script_log, docker_log, sqlancer_log, run_dir):
64+
cmd = f"java -jar sqlancer-*.jar --num-threads {threads} --timeout-seconds {timeout} --username {username} --password {password} --host {host_container_name} {dbms} --oracle {oracle}"
65+
script_log.info("Executing test: %s", cmd)
66+
# date = datetime.today().strftime("%y-%m-%d-%H-%M-%S")
67+
# log_dir_host = os.path.abspath(os.path.join("logs", date))
68+
# os.makedirs(log_dir_host, exist_ok=True)
6969

70-
run_log_container_dir = "/logs"
71-
sqlancer_logs_container_dir = "/root/sqlancer/target/logs"
70+
log_dir_host = os.path.abspath(run_dir)
71+
os.makedirs(log_dir_host, exist_ok=True)
7272

7373
run_command([
7474
"docker", "run", "--rm",
@@ -81,15 +81,17 @@ def start_sqlancer_container(dbms, host_container_name, username, password, orac
8181
"-e", f"SQLANCER_ORACLE={oracle}",
8282
"-e", f"SQLANCER_THREADS={threads}",
8383
"-e", f"SQLANCER_TIMEOUT={timeout}",
84-
"-v", f"{log_dir_host}:{run_log_container_dir}",
85-
"-v", f"{log_dir_host}:{sqlancer_logs_container_dir}",
84+
# "-v", f"{log_dir_host}:/logs",
85+
"-v", f"{log_dir_host}:/root/sqlancer/target/logs",
8686
"sqlancer:latest"
87-
])
87+
], sqlancer_log)
88+
script_log.info("Test executed")
8889

8990

90-
def test_single(cfg, use_cache=False):
91+
def test_single(cfg, script_log, docker_log, sqlancer_log, run_dir, use_cache=False):
92+
script_log.info("==============================Executing test==============================")
9193
if cfg["embedded"] == "no":
92-
start_db_container(cfg["dbms"], cfg)
94+
start_db_container(cfg["dbms"], cfg, script_log, docker_log)
9395

9496
start_sqlancer_container(
9597
dbms=cfg["dbms"],
@@ -98,36 +100,46 @@ def test_single(cfg, use_cache=False):
98100
password=cfg["password"],
99101
oracle=cfg["oracle"],
100102
threads=cfg["num_threads"],
101-
timeout=cfg["timeout_seconds"]
103+
timeout=cfg["timeout_seconds"],
104+
script_log=script_log,
105+
sqlancer_log=sqlancer_log,
106+
docker_log=docker_log,
107+
run_dir=run_dir
102108
)
103109

104110
if cfg["embedded"] == "no":
105-
remove_container(cfg["container_name"])
111+
remove_container(cfg["container_name"], script_log, docker_log)
112+
script_log.info("==============================Executing test==============================")
106113

107-
def remove_container(container_name):
114+
def remove_container(container_name, script_log, docker_log):
115+
script_log.info("Removing container: %s...", container_name)
108116
try:
109-
print(f"[INFO] Removing container: {container_name}")
110-
subprocess.run(["docker", "rm", "-f", container_name], check=True)
117+
run_command(["docker", "rm", "-f", container_name], docker_log)
118+
script_log.info("Container removed: %s", container_name)
111119
except subprocess.CalledProcessError as e:
112-
print(f"[WARNING] Failed to remove container {container_name}: {e}")
113-
120+
script_log.warning("Container removing failed: %s", container_name)
114121

115122

116-
117-
def test_custom_dockerfile(dockerfile_path, cfg, use_cache=False):
123+
def test_custom_dockerfile(dockerfile_path, cfg, script_log, docker_log, sqlancer_log, run_dir, use_cache=False):
124+
script_log.info("==============================Executing test==============================")
125+
118126
dbms=cfg["dbms"]
119127

120-
start_db_container(dbms, cfg)
128+
start_db_container(dbms, cfg, script_log, docker_log)
121129
start_sqlancer_container(
122130
dbms=dbms,
123131
host_container_name=cfg["container_name"],
124132
username=cfg["username"],
125133
password=cfg["password"],
126134
oracle=cfg["oracle"],
127135
threads=cfg["num_threads"],
128-
timeout=cfg["timeout_seconds"]
136+
timeout=cfg["timeout_seconds"],
137+
script_log=script_log,
138+
sqlancer_log=sqlancer_log,
139+
docker_log=docker_log,
140+
run_dir=run_dir
129141
)
130142

131-
remove_container(cfg["container_name"])
132-
143+
remove_container(cfg["container_name"], script_log, docker_log)
144+
script_log.info("==============================Executing test==============================")
133145

0 commit comments

Comments
 (0)