|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import os |
| 5 | +import base64 |
| 6 | +import json |
| 7 | +from datetime import datetime |
| 8 | +from datetime import timezone |
| 9 | +from urllib.parse import urlparse |
| 10 | +import requests |
| 11 | +from requests.adapters import HTTPAdapter |
| 12 | + |
| 13 | + |
| 14 | +def get_timestamp(): |
| 15 | + """Get formatted timestamp based on SE_LOG_TIMESTAMP_FORMAT.""" |
| 16 | + ts_format = os.environ.get('SE_LOG_TIMESTAMP_FORMAT', '%Y-%m-%d %H:%M:%S,%f') |
| 17 | + # Convert bash format to Python format |
| 18 | + if '%3N' in ts_format: |
| 19 | + # Replace %3N (bash milliseconds) with %f (Python microseconds) and trim later |
| 20 | + ts_format_python = ts_format.replace('%3N', '%f') |
| 21 | + timestamp = datetime.now(timezone.utc).strftime(ts_format_python) |
| 22 | + # Convert microseconds to milliseconds (trim last 3 digits) |
| 23 | + if '%f' in ts_format_python: |
| 24 | + # Find the microseconds part and trim to milliseconds |
| 25 | + parts = timestamp.rsplit(',', 1) |
| 26 | + if len(parts) == 2 and len(parts[1]) == 6: |
| 27 | + timestamp = parts[0] + ',' + parts[1][:3] |
| 28 | + else: |
| 29 | + timestamp = datetime.now(timezone.utc).strftime(ts_format) |
| 30 | + return timestamp |
| 31 | + |
| 32 | + |
| 33 | +def create_session(): |
| 34 | + """Create requests session with timeout configuration.""" |
| 35 | + session = requests.Session() |
| 36 | + return session |
| 37 | + |
| 38 | + |
| 39 | +def get_basic_auth(): |
| 40 | + """Get basic authentication header if credentials are provided.""" |
| 41 | + username = os.environ.get('SE_ROUTER_USERNAME') |
| 42 | + password = os.environ.get('SE_ROUTER_PASSWORD') |
| 43 | + |
| 44 | + if username and password: |
| 45 | + credentials = f"{username}:{password}" |
| 46 | + encoded_credentials = base64.b64encode(credentials.encode()).decode() |
| 47 | + return {"Authorization": f"Basic {encoded_credentials}"} |
| 48 | + |
| 49 | + return {} |
| 50 | + |
| 51 | + |
| 52 | +def validate_endpoint(endpoint, graphql_endpoint=False, max_time=1): |
| 53 | + """ |
| 54 | + Validate an endpoint by making HTTP request and checking status code. |
| 55 | +
|
| 56 | + Args: |
| 57 | + endpoint (str): The endpoint URL to validate |
| 58 | + graphql_endpoint (bool): Whether this is a GraphQL endpoint |
| 59 | + max_time (int): Maximum time for request in seconds |
| 60 | + """ |
| 61 | + process_name = "endpoint.checks" |
| 62 | + session = create_session() |
| 63 | + |
| 64 | + # Set up headers |
| 65 | + headers = {} |
| 66 | + headers.update(get_basic_auth()) |
| 67 | + |
| 68 | + try: |
| 69 | + if graphql_endpoint: |
| 70 | + # GraphQL endpoint check |
| 71 | + headers['Content-Type'] = 'application/json' |
| 72 | + data = {"query": "{ grid { sessionCount } }"} |
| 73 | + |
| 74 | + response = session.post( |
| 75 | + endpoint, |
| 76 | + headers=headers, |
| 77 | + json=data, |
| 78 | + timeout=max_time, |
| 79 | + verify=False # Equivalent to curl's -k flag |
| 80 | + ) |
| 81 | + else: |
| 82 | + # Regular endpoint check |
| 83 | + response = session.get( |
| 84 | + endpoint, |
| 85 | + headers=headers, |
| 86 | + timeout=max_time, |
| 87 | + verify=False # Equivalent to curl's -k flag |
| 88 | + ) |
| 89 | + |
| 90 | + status_code = response.status_code |
| 91 | + |
| 92 | + except requests.exceptions.Timeout: |
| 93 | + print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} timed out after {max_time} seconds") |
| 94 | + return False |
| 95 | + except requests.exceptions.ConnectionError: |
| 96 | + print(f"{get_timestamp()} [{process_name}] - Failed to connect to endpoint {endpoint}") |
| 97 | + return False |
| 98 | + except requests.exceptions.RequestException as e: |
| 99 | + print(f"{get_timestamp()} [{process_name}] - Error connecting to endpoint {endpoint}: {str(e)}") |
| 100 | + return False |
| 101 | + |
| 102 | + # Handle different status codes |
| 103 | + if status_code == 404: |
| 104 | + print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} is not found - status code: {status_code}") |
| 105 | + return False |
| 106 | + elif status_code == 401: |
| 107 | + print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} requires authentication - status code: {status_code}. Please provide valid credentials via SE_ROUTER_USERNAME and SE_ROUTER_PASSWORD environment variables.") |
| 108 | + return False |
| 109 | + elif status_code != 200: |
| 110 | + print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} is not available - status code: {status_code}") |
| 111 | + return False |
| 112 | + |
| 113 | + return True |
| 114 | + |
| 115 | + |
| 116 | +def main(): |
| 117 | + """Main function to handle command line arguments and execute validation.""" |
| 118 | + if len(sys.argv) < 2: |
| 119 | + print("Usage: python3 validate_endpoint.py <endpoint> [graphql_endpoint]") |
| 120 | + print(" endpoint: The URL endpoint to validate") |
| 121 | + print(" graphql_endpoint: 'true' if this is a GraphQL endpoint (default: false)") |
| 122 | + sys.exit(1) |
| 123 | + |
| 124 | + endpoint = sys.argv[1] |
| 125 | + graphql_endpoint = len(sys.argv) > 2 and sys.argv[2].lower() == 'true' |
| 126 | + max_time = int(os.environ.get('SE_ENDPOINT_CHECK_TIMEOUT', 1)) |
| 127 | + |
| 128 | + # Validate the endpoint |
| 129 | + success = validate_endpoint(endpoint, graphql_endpoint, max_time) |
| 130 | + |
| 131 | + # Exit with appropriate code |
| 132 | + sys.exit(0 if success else 1) |
| 133 | + |
| 134 | + |
| 135 | +if __name__ == "__main__": |
| 136 | + main() |
0 commit comments