init.sh
Overview
`init.sh` is a shell script designed to initialize and run a service component named `midgard`. Its primary functions are to:
Ensure that the required genesis configuration file (
/blockstore/genesis.json) is present. If missing, the script downloads necessary tools and fetches this file from a remote RPC endpoint.Start the
midgardprocess with a specified configuration file (config.json) in the background.Handle graceful shutdowns by catching termination signals (
TERM,INT), forwarding them to themidgardprocess, and waiting for it to exit cleanly.
This script is typically part of a containerized or system service environment where it acts as the entry point to launch and manage the lifecycle of the `midgard` daemon.
Detailed Explanation
Script Initialization
#!/bin/sh
set -e
The script uses
/bin/shas the interpreter for portability.set -eensures the script exits immediately if any command returns a non-zero status, preventing silent failures.
Genesis File Check and Setup
if [ ! -f "/blockstore/genesis.json" ]; then
wget -O jq https://github.com/jqlang/jq/releases/download/jq-1.7.1/jq-linux64
chmod +x jq
mv jq /usr/bin
wget -q -O- https://rpc-v1.ninerealms.com/genesis | jq -r .result.genesis > /blockstore/genesis.json
fi
Checks if the genesis file
/blockstore/genesis.jsonexists.If not present:
Downloads
jq(a lightweight JSON processor) binary from GitHub.Makes it executable and moves it to
/usr/binso it can be used globally.Fetches the genesis JSON data from the remote RPC endpoint
https://rpc-v1.ninerealms.com/genesis.Parses the JSON response using
jqto extract.result.genesisand saves it to/blockstore/genesis.json.
**Important Details:**
This step ensures that
midgardhas the correct blockchain genesis configuration before starting.The script downloads a specific version of
jq(v1.7.1) for compatibility.The genesis file is stored in a persistent volume or designated directory
/blockstore.
Functions
start()
start() {
./midgard config.json &
PID="$!"
}
Launches the
midgardexecutable withconfig.jsonas its argument.Runs the process in the background (
&).Stores the background process ID in variable
PIDfor later management.
**Usage:**
This function is called once during script execution to start the daemon.
stop()
stop() {
echo "Catching signal and sending to PID: $PID"
kill $PID
while $(kill -0 $PID 2>/dev/null); do
sleep 1
done
}
Prints a message indicating it is forwarding termination signals to the
midgardprocess.Sends the
SIGTERMsignal to the process identified byPIDusingkill.Enters a loop to check if the process is still running (
kill -0tests for process existence without sending a signal).Sleeps 1 second between checks until the process exits.
**Usage:**
This function is triggered by signal traps to gracefully stop `midgard` before the script exits.
Signal Trapping
trap 'stop' TERM INT
Sets traps for
SIGTERMandSIGINTsignals.When these signals are received (e.g., container stop, Ctrl+C), the
stopfunction is executed to ensure clean shutdown.
Script Execution Flow
start
wait $PID
Calls
startto launchmidgard.Uses
waiton themidgardprocess ID to keep the script running and monitor the daemon.The script remains active until
midgardexits or a termination signal is caught.
Usage Example
Assuming this script has execute permission (`chmod +x init.sh`), it can be run as:
./init.sh
If
/blockstore/genesis.jsondoes not exist, it downloads dependencies and the genesis file.Starts
midgardin the background.Waits for
midgardto run.On termination signals, it shuts down
midgardgracefully.
This makes it ideal for container entrypoints or system service scripts.
Interaction with Other System Components
midgardexecutable: The core daemon/service this script manages.midgardpresumably processes blockchain data or runs a related service, configured byconfig.json./blockstore/genesis.json: A critical configuration file containing blockchain genesis state. This script ensures it is present before startingmidgard.Remote RPC Endpoint:
https://rpc-v1.ninerealms.com/genesisprovides the JSON genesis configuration if missing locally.jqJSON Processor: Used to parse the downloaded JSON to extract the correct genesis data.System Signals: The script handles system termination signals to allow
midgardto shutdown cleanly.
Implementation Details and Algorithms
Idempotent Initialization: The script only downloads
jqand the genesis file if the genesis file is missing. This prevents redundant downloads and setup on subsequent runs.Graceful Shutdown Loop: The
stopfunction uses a loop withkill -0to poll for process termination, ensuring the service fully stops before the script exits. This avoids orphan processes.Signal Handling: By trapping
TERMandINT, the script integrates well with container orchestration or system service managers that send these signals for stopping services.Background Process Management: Capturing the PID of the background process allows precise control over the child process lifecycle.
Mermaid Flowchart Diagram
flowchart TD
A[Start init.sh script] --> B{Is /blockstore/genesis.json present?}
B -- No --> C[Download jq binary]
C --> D[Make jq executable and move to /usr/bin]
D --> E[Fetch genesis JSON from RPC endpoint]
E --> F[Extract .result.genesis using jq]
F --> G[Save genesis.json to /blockstore/genesis.json]
B -- Yes --> G
G --> H[Start midgard with config.json in background]
H --> I[Store midgard PID]
I --> J[Wait for midgard process]
J --> K{Receive TERM or INT signal?}
K -- Yes --> L[Call stop function]
L --> M[Send SIGTERM to midgard PID]
M --> N[Poll until midgard process exits]
N --> O[Exit script]
K -- No --> J
Summary
`init.sh` is a robust service initializer and manager script that ensures essential environment setup, launches the `midgard` daemon, and gracefully handles shutdowns. It integrates remote configuration fetching, process management, and signal handling, making it suitable for automated deployments and containerized environments within the broader system architecture.