-
Notifications
You must be signed in to change notification settings - Fork 220
Add /health endpoint for comprehensive service readiness checking #701
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
26
commits into
main
Choose a base branch
from
copilot/fix-683
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 17 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
e9cf9a7
Initial plan
Copilot f7916f0
Add health endpoint service and configuration
Copilot bca84c3
Rename health endpoint to /ready to avoid conflicts with Horizon's /h…
Copilot 5a4091f
Complete working implementation of /ready endpoint
Copilot 5903542
Add documentation for new /ready endpoint
Copilot f4e78bb
Rename /ready endpoint to /health per feedback
Copilot e6f5df7
Complete renaming of endpoint to /health - task finished
Copilot 31c846f
Clean up build artifacts from git history
Copilot 0172a76
Merge branch 'main' into copilot/fix-683
sagpatil f43ffa2
Resolve merge conflicts with main branch
Copilot c77de6f
Fix typo in build-testing.yml and resolve merge conflicts
Copilot 1da0bc0
resolve merge conflict in readme file
sagpatil cac8f1f
Merge branch 'main' into copilot/fix-683
sagpatil aa5ddd0
Adding better testing
sagpatil 6165455
Add Test to CI Pipeline
sagpatil 1f0c42b
Attempt to Fix CI health endpoint test and add debugging
sagpatil eae11d3
Fix health endpoint test to use proper /health endpoint through nginx
Copilot 2483658
Update README.md
sagpatil f0e6cb5
update git ignore file
sagpatil b6aa4c1
consistency in calling the health endpoint test in CI
sagpatil 0d12bb3
Merge branch 'main' into copilot/fix-683
sagpatil d66793e
extend timeout
sagpatil 84042bc
revert timeout and better start
sagpatil 0a7c8e8
fix typo
sagpatil 553b508
make readiness service more lenient during startup and readme changes
sagpatil 759181a
remove unused script adn udpate readme file
sagpatil File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
__pycache__/ | ||
*.pyc | ||
test_health_endpoint | ||
sagpatil marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,6 +22,7 @@ EXPOSE 6060 | |
EXPOSE 6061 | ||
EXPOSE 8000 | ||
EXPOSE 8002 | ||
EXPOSE 8004 | ||
EXPOSE 8100 | ||
EXPOSE 11625 | ||
EXPOSE 11626 | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
location /health { | ||
rewrite /health / break; | ||
proxy_set_header Host $http_host; | ||
proxy_pass http://127.0.0.1:8004; | ||
proxy_redirect off; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
#!/usr/bin/env python3 | ||
|
||
import json | ||
import logging | ||
import os | ||
import sys | ||
import time | ||
from http.server import BaseHTTPRequestHandler, HTTPServer | ||
import urllib.request | ||
import urllib.error | ||
|
||
# Configure logging | ||
logging.basicConfig( | ||
level=logging.INFO, | ||
format='%(asctime)s - %(levelname)s - %(message)s' | ||
) | ||
logger = logging.getLogger(__name__) | ||
|
||
class HealthCheckHandler(BaseHTTPRequestHandler): | ||
def do_GET(self): | ||
if self.path == '/' or self.path == '/health': | ||
self.handle_readiness_check() | ||
else: | ||
self.send_error(404) | ||
|
||
def handle_readiness_check(self): | ||
"""Handle readiness check requests""" | ||
|
||
# Detect enabled services by checking if they're running | ||
# rather than relying on environment variables which may not be passed to supervisord | ||
enable_core = self.is_service_intended_to_run('stellar-core') | ||
enable_horizon = self.is_service_intended_to_run('horizon') | ||
enable_rpc = self.is_service_intended_to_run('stellar-rpc') | ||
|
||
response = { | ||
'status': 'ready', | ||
'services': {} | ||
} | ||
|
||
all_healthy = True | ||
|
||
# Check stellar-core if enabled | ||
if enable_core: | ||
if self.check_stellar_core(): | ||
response['services']['stellar-core'] = 'ready' | ||
else: | ||
response['services']['stellar-core'] = 'not ready' | ||
all_healthy = False | ||
|
||
# Check horizon if enabled | ||
if enable_horizon: | ||
horizon_status = self.check_horizon() | ||
if horizon_status['ready']: | ||
response['services']['horizon'] = 'ready' | ||
# Include Horizon's detailed health info | ||
response['services']['horizon_health'] = horizon_status['health'] | ||
else: | ||
response['services']['horizon'] = 'not ready' | ||
all_healthy = False | ||
|
||
# Check stellar-rpc if enabled | ||
if enable_rpc: | ||
if self.check_stellar_rpc(): | ||
response['services']['stellar-rpc'] = 'ready' | ||
else: | ||
response['services']['stellar-rpc'] = 'not ready' | ||
all_healthy = False | ||
|
||
if not all_healthy: | ||
response['status'] = 'not ready' | ||
status_code = 503 | ||
else: | ||
status_code = 200 | ||
|
||
# Send response | ||
self.send_response(status_code) | ||
self.send_header('Content-Type', 'application/json') | ||
self.end_headers() | ||
|
||
response_json = json.dumps(response) | ||
self.wfile.write(response_json.encode('utf-8')) | ||
|
||
logger.info(f"Readiness check - Status: {response['status']}, Services: {response['services']}") | ||
|
||
def is_service_intended_to_run(self, service_name): | ||
"""Check if a service is intended to run by testing if it's reachable""" | ||
if service_name == 'stellar-core': | ||
# Check if stellar-core is running on its default port | ||
try: | ||
with urllib.request.urlopen('http://localhost:11626/info', timeout=2) as resp: | ||
return True | ||
except: | ||
return False | ||
elif service_name == 'horizon': | ||
# Check if horizon is running on its default port | ||
try: | ||
with urllib.request.urlopen('http://localhost:8001', timeout=2) as resp: | ||
return True | ||
except: | ||
return False | ||
elif service_name == 'stellar-rpc': | ||
# Check if stellar-rpc is running by calling its health method | ||
try: | ||
request_data = { | ||
'jsonrpc': '2.0', | ||
'id': 10235, | ||
'method': 'getHealth' | ||
} | ||
|
||
req = urllib.request.Request( | ||
'http://localhost:8003', | ||
data=json.dumps(request_data).encode('utf-8'), | ||
headers={'Content-Type': 'application/json'} | ||
) | ||
|
||
with urllib.request.urlopen(req, timeout=2) as resp: | ||
return True | ||
except: | ||
return False | ||
return False | ||
|
||
def check_stellar_core(self): | ||
"""Check if stellar-core is healthy""" | ||
try: | ||
with urllib.request.urlopen('http://localhost:11626/info', timeout=5) as resp: | ||
return resp.status == 200 | ||
except Exception as e: | ||
logger.debug(f"stellar-core check failed: {e}") | ||
return False | ||
|
||
def check_horizon(self): | ||
"""Check if horizon is ready and get its health status""" | ||
try: | ||
# First check the root endpoint | ||
with urllib.request.urlopen('http://localhost:8001', timeout=5) as resp: | ||
if resp.status != 200: | ||
return {'ready': False, 'health': None} | ||
|
||
data = json.load(resp) | ||
protocol_version = data.get('supported_protocol_version', 0) | ||
core_ledger = data.get('core_latest_ledger', 0) | ||
history_ledger = data.get('history_latest_ledger', 0) | ||
|
||
# Basic readiness check | ||
basic_ready = protocol_version > 0 and core_ledger > 0 and history_ledger > 0 | ||
|
||
# Try to get Horizon's own health endpoint | ||
horizon_health = None | ||
try: | ||
with urllib.request.urlopen('http://localhost:8001/health', timeout=5) as health_resp: | ||
if health_resp.status == 200: | ||
horizon_health = json.load(health_resp) | ||
except Exception: | ||
# Health endpoint might not be available, that's ok | ||
pass | ||
|
||
return { | ||
'ready': basic_ready, | ||
'health': horizon_health | ||
} | ||
|
||
except Exception as e: | ||
logger.debug(f"horizon check failed: {e}") | ||
return {'ready': False, 'health': None} | ||
|
||
def check_stellar_rpc(self): | ||
"""Check if stellar-rpc is healthy""" | ||
try: | ||
request_data = { | ||
'jsonrpc': '2.0', | ||
'id': 10235, | ||
'method': 'getHealth' | ||
} | ||
|
||
req = urllib.request.Request( | ||
'http://localhost:8003', | ||
data=json.dumps(request_data).encode('utf-8'), | ||
headers={'Content-Type': 'application/json'} | ||
) | ||
|
||
with urllib.request.urlopen(req, timeout=5) as resp: | ||
if resp.status != 200: | ||
return False | ||
|
||
data = json.load(resp) | ||
return data.get('result', {}).get('status') == 'healthy' | ||
except Exception as e: | ||
logger.debug(f"stellar-rpc check failed: {e}") | ||
return False | ||
|
||
def log_message(self, format, *args): | ||
"""Override to use our logger""" | ||
logger.info(format % args) | ||
|
||
def main(): | ||
port = 8004 | ||
server = HTTPServer(('0.0.0.0', port), HealthCheckHandler) | ||
logger.info(f"Readiness service starting on port {port}") | ||
|
||
try: | ||
server.serve_forever() | ||
except KeyboardInterrupt: | ||
logger.info("Readiness service shutting down") | ||
server.shutdown() | ||
|
||
if __name__ == '__main__': | ||
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
#! /bin/bash | ||
|
||
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" | ||
|
||
echo "starting readiness service..." | ||
set -e | ||
|
||
# Use the Python-based readiness service | ||
exec python3 "$DIR/readiness-service.py" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
[program:readiness] | ||
user=stellar | ||
directory=/opt/stellar/readiness | ||
command=/opt/stellar/readiness/bin/start | ||
autostart=true | ||
autorestart=true | ||
priority=60 | ||
redirect_stderr=true |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.