Skip to content

Commit f28bf8a

Browse files
Add SMASH service support for testing
1 parent 8b0442e commit f28bf8a

File tree

7 files changed

+370
-1
lines changed

7 files changed

+370
-1
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/usr/bin/env bash
2+
3+
set -uo pipefail
4+
5+
SOCKET_PATH="$(readlink -m "$CARDANO_NODE_SOCKET_PATH")"
6+
STATE_CLUSTER="${SOCKET_PATH%/*}"
7+
STATE_CLUSTER_NAME="${STATE_CLUSTER##*/}"
8+
9+
export PGPASSFILE="$STATE_CLUSTER/pgpass"
10+
export SMASH_ADMIN="${SMASH_ADMIN:-admin}"
11+
export SMASH_PASSWORD="${SMASH_PASSWORD:-password}"
12+
export SMASH_ADMINS_FILE="$STATE_CLUSTER/admins.txt"
13+
14+
echo "${SMASH_ADMIN}, ${SMASH_PASSWORD}" > "$SMASH_ADMINS_FILE"
15+
16+
exec "$DBSYNC_REPO/smash-server/bin/cardano-smash-server" --config "./$STATE_CLUSTER_NAME/dbsync-config.yaml" --port %%SMASH_PORT%% --admins "$SMASH_ADMINS_FILE"

cardano_node_tests/cluster_scripts/conway_fast/start-cluster

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
# controlling environment variables:
44
# DBSYNC_REPO - will start and configure db-sync if the value is path to db-sync repository
5+
# SMASH - if set, will start and configure smash
56
# ENABLE_LEGACY - if set, local cluster will use legacy networking
67
# MIXED_P2P - if set, local cluster will use P2P for some nodes and legacy topology for others
78
# UTXO_BACKEND - 'mem' or 'disk', default is 'mem' (or legacy) if unset
@@ -206,6 +207,23 @@ startsecs=5
206207
EoF
207208
fi
208209

210+
# enable smash service
211+
if [ -n "${DBSYNC_REPO:-""}" ] && [ -n "${SMASH:-""}" ]; then
212+
[ -e "${DBSYNC_REPO}/smash-server/bin/cardano-smash-server" ] || \
213+
{ echo "The \`${DBSYNC_REPO}/smash-server/bin/cardano-smash-server\` not found, line $LINENO" >&2; exit 1; } # assert
214+
215+
cat >> "${STATE_CLUSTER}/supervisor.conf" <<EoF
216+
217+
[program:smash]
218+
command=${SCRIPT_DIR}/run-cardano-smash
219+
stderr_logfile=./${STATE_CLUSTER_NAME}/smash.stderr
220+
stdout_logfile=./${STATE_CLUSTER_NAME}/smash.stdout
221+
autostart=false
222+
autorestart=false
223+
startsecs=5
224+
EoF
225+
fi
226+
209227
# enable cardano-submit-api service
210228
if [ "$ENABLE_SUBMIT_API" -eq 1 ]; then
211229
cat >> "${STATE_CLUSTER}/supervisor.conf" <<EoF
@@ -625,6 +643,12 @@ if [ -n "${DBSYNC_REPO:-""}" ]; then
625643
supervisorctl -s "unix:///${SUPERVISORD_SOCKET_PATH}" start dbsync
626644
fi
627645

646+
# start smash
647+
if [ -n "${DBSYNC_REPO:-""}" ] && [ -n "${SMASH:-""}" ]; then
648+
echo "Starting smash"
649+
supervisorctl -s "unix:///${SUPERVISORD_SOCKET_PATH}" start smash
650+
fi
651+
628652
echo "Sleeping for initial Tx submission delay of $TX_SUBMISSION_DELAY seconds"
629653
sleep "$TX_SUBMISSION_DELAY"
630654

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
"""Tests for basic SMASH operations."""
2+
3+
4+
import logging
5+
from http import HTTPStatus
6+
import pytest
7+
from cardano_clusterlib import clusterlib
8+
9+
from cardano_node_tests.utils import logfiles
10+
from cardano_node_tests.utils import configuration
11+
from cardano_node_tests.utils import dbsync_utils
12+
from cardano_node_tests.utils import dbsync_queries
13+
from cardano_node_tests.utils import smash_utils
14+
15+
LOGGER = logging.getLogger(__name__)
16+
17+
18+
@pytest.fixture(autouse=True)
19+
def check_smash_availability():
20+
"""Fixture to check SMASH availability before each test."""
21+
if not configuration.HAS_SMASH:
22+
pytest.skip("Skipping test because SMASH service is not available.")
23+
24+
25+
class TestBasicSmash:
26+
"""Basic tests for SMASH service."""
27+
28+
@pytest.fixture()
29+
def locked_pool(
30+
self,
31+
cluster_lock_pool: clusterlib.ClusterLib,
32+
) -> dbsync_queries.PoolDataDBRow:
33+
"""Get pool id from cluster with locked pool."""
34+
cluster_obj, pool_name = cluster_lock_pool
35+
pools_ids = cluster_obj.g_query.get_stake_pools()
36+
locked_pool_number = int(pool_name.replace("node-pool", ""))
37+
pools = [next(dbsync_queries.query_pool_data(p)) for p in pools_ids]
38+
locked_pool_data = next((item for item in pools if 'pool' + locked_pool_number in item.metadata_url), None)
39+
return locked_pool_data
40+
41+
@pytest.fixture(scope="session")
42+
def smash(
43+
self,
44+
) -> smash_utils.SmashClient:
45+
"""Create SMASH client."""
46+
smash = smash_utils.get_client()
47+
return smash
48+
49+
def test_fetch_pool_metadata(
50+
self,
51+
locked_pool: dbsync_queries.PoolDataDBRow,
52+
smash: smash_utils.SmashClient
53+
):
54+
pool_id = locked_pool.view
55+
56+
# Offchain metadata is inserted into database few minutes after start of a cluster
57+
def _query_func():
58+
pool_metadata = next(iter(dbsync_queries.query_off_chain_pool_data(pool_id)), None)
59+
assert pool_metadata != None, dbsync_utils.NO_RESPONSE_STR
60+
return pool_metadata
61+
metadata_dbsync = dbsync_utils.retry_query(query_func=_query_func, timeout=360)
62+
63+
expected_metadata = smash_utils.PoolMetadata(
64+
name=metadata_dbsync.json["name"],
65+
description=metadata_dbsync.json["description"],
66+
ticker=metadata_dbsync.ticker_name,
67+
homepage=metadata_dbsync.json["homepage"]
68+
)
69+
actual_metadata = smash.get_pool_metadata(pool_id, metadata_dbsync.hash.hex())
70+
assert expected_metadata == actual_metadata
71+
72+
def test_delist_pool(
73+
self,
74+
locked_pool: dbsync_queries.PoolDataDBRow,
75+
smash: smash_utils.SmashClient,
76+
request: pytest.FixtureRequest,
77+
worker_id: str,
78+
):
79+
pool_id = locked_pool.view
80+
81+
# Define and register function that ensures pool is re-enlisted after test
82+
def pool_cleanup():
83+
smash.enlist_pool(pool_id)
84+
request.addfinalizer(pool_cleanup)
85+
86+
# Delist the pool
87+
pool_data = dbsync_utils.get_pool_data(pool_id)
88+
expected_delisted_pool = smash_utils.PoolData(pool_id=pool_data.hash)
89+
actual_delisted_pool = smash.delist_pool(pool_id)
90+
assert expected_delisted_pool == actual_delisted_pool
91+
92+
# Check if fetching metadata for a delisted pool returns an error
93+
res_metadata = smash.get_pool_metadata(pool_id, pool_data.metadata_hash)
94+
assert isinstance(res_metadata, smash_utils.SmashError)
95+
assert HTTPStatus.FORBIDDEN == res_metadata.status_code
96+
assert f"Pool {pool_data.hash} is delisted" == res_metadata.message
97+
98+
# Ignore expected errors in logs that would fail test in teardown phase
99+
err_msg = 'Delisted pool already exists!'
100+
expected_err_regexes = [err_msg]
101+
logfiles.add_ignore_rule(
102+
files_glob="smash.stdout",
103+
regex="|".join(expected_err_regexes),
104+
ignore_file_id=worker_id,
105+
)
106+
# Ensure re-delisting an already delisted pool returns an error
107+
res_delist = smash.delist_pool(pool_id)
108+
assert isinstance(res_delist, smash_utils.SmashError)
109+
assert HTTPStatus.BAD_REQUEST == res_delist.status_code
110+
assert 'DbInsertError' == res_delist.message.get("code")
111+
assert err_msg == res_delist.message.get("description")
112+
113+
def test_enlist_pool(
114+
self,
115+
locked_pool: dbsync_queries.PoolDataDBRow,
116+
smash: smash_utils.SmashClient,
117+
):
118+
pool_id = locked_pool.view
119+
120+
# Ensure enlisting an already enlisted pool returns an error
121+
res_enlist = smash.enlist_pool(pool_id)
122+
assert isinstance(res_enlist, smash_utils.SmashError)
123+
assert HTTPStatus.NOT_FOUND == res_enlist.status_code
124+
assert 'RecordDoesNotExist' == res_enlist.message.get("code")
125+
assert 'The requested record does not exist.' == res_enlist.message.get("description")
126+
127+
# Delist the pool
128+
smash.delist_pool(pool_id)
129+
pool_data = dbsync_utils.get_pool_data(pool_id)
130+
res_metadata = smash.get_pool_metadata(pool_id, pool_data.metadata_hash)
131+
assert f"Pool {pool_data.hash} is delisted" == res_metadata.message
132+
133+
# Enlist pool
134+
actual_res_enlist = smash.enlist_pool(pool_id)
135+
expected_res_enlist = smash_utils.PoolData(pool_id=pool_data.hash)
136+
assert expected_res_enlist == actual_res_enlist

cardano_node_tests/utils/cluster_scripts.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ class InstancePorts:
5151
webserver: int
5252
metrics_submit_api: int
5353
submit_api: int
54+
smash: int
5455
supervisor: int
5556
relay1: int
5657
ekg_relay1: int
@@ -189,6 +190,7 @@ def _get_node_ports(num: int) -> NodePorts:
189190
webserver=last_port,
190191
metrics_submit_api=last_port - 1,
191192
submit_api=last_port - 2,
193+
smash=last_port - 3,
192194
supervisor=12001 + instance_num,
193195
# Relay1
194196
relay1=0,
@@ -266,6 +268,8 @@ def _replace_instance_files(
266268
new_content = new_content.replace(
267269
"%%METRICS_SUBMIT_API_PORT%%", str(instance_ports.metrics_submit_api)
268270
)
271+
# Reconfigure smash port
272+
new_content = new_content.replace("%%SMASH_PORT%%", str(instance_ports.smash))
269273
# Reconfigure webserver port
270274
new_content = new_content.replace("%%WEBSERVER_PORT%%", str(instance_ports.webserver))
271275
return new_content
@@ -615,6 +619,8 @@ def _reconfigure_testnet(
615619
new_content = new_content.replace(
616620
"%%METRICS_SUBMIT_API_PORT%%", str(instance_ports.metrics_submit_api)
617621
)
622+
# Reconfigure smash port
623+
new_content = new_content.replace("%%SMASH_PORT%%", str(instance_ports.smash))
618624
# Reconfigure EKG metrics port
619625
new_content = new_content.replace("%%EKG_PORT_RELAY1%%", str(instance_ports.ekg_relay1))
620626
# Reconfigure prometheus metrics port
@@ -713,3 +719,4 @@ def prepare_scripts_files(
713719
start_script_args=[configuration.BOOTSTRAP_DIR],
714720
dir=destdir,
715721
)
722+

cardano_node_tests/utils/configuration.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ def _check_cardano_node_socket_path() -> None:
3535
# See `cat /proc/sys/net/ipv4/ip_local_port_range`.
3636
PORTS_BASE = int(os.environ.get("PORTS_BASE") or 23000)
3737

38+
SMASH_ADMIN = os.environ.get("SMASH_ADMIN", "admin")
39+
SMASH_PASSWORD = os.environ.get("SMASH_PASSWORD", "password")
40+
3841
# Used also in startup scripts as `if [ -n "$VAR" ]...`
3942
ENABLE_LEGACY = (os.environ.get("ENABLE_LEGACY") or "") != ""
4043
# Used also in startup scripts as `if [ -n "$VAR" ]...`
@@ -100,6 +103,14 @@ def _check_cardano_node_socket_path() -> None:
100103
else:
101104
DBSYNC_BIN = pl.Path("/nonexistent")
102105

106+
HAS_SMASH = HAS_DBSYNC and bool(os.environ.get("SMASH"))
107+
if HAS_SMASH:
108+
SMASH_BIN = (
109+
pl.Path(os.environ["DBSYNC_REPO"]).expanduser() / "smash-server" / "bin" / "cardano-smash-server"
110+
).resolve()
111+
else:
112+
SMASH_BIN = pl.Path("/nonexistent")
113+
103114
DONT_OVERWRITE_OUTFILES = bool(os.environ.get("DONT_OVERWRITE_OUTFILES"))
104115

105116
# Cluster instances are kept running after tests finish

0 commit comments

Comments
 (0)