-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
migrate validate_endpoint to python #2868
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
KyriosGN0
wants to merge
4
commits into
SeleniumHQ:trunk
Choose a base branch
from
KyriosGN0:python2
base: trunk
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 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
#!/usr/bin/env python3 | ||
|
||
import sys | ||
import os | ||
import base64 | ||
import json | ||
from datetime import datetime | ||
from datetime import timezone | ||
from urllib.parse import urlparse | ||
import requests | ||
from requests.adapters import HTTPAdapter | ||
|
||
|
||
def get_timestamp(): | ||
"""Get formatted timestamp based on SE_LOG_TIMESTAMP_FORMAT.""" | ||
ts_format = os.environ.get('SE_LOG_TIMESTAMP_FORMAT', '%Y-%m-%d %H:%M:%S,%f') | ||
# Convert bash format to Python format | ||
if '%3N' in ts_format: | ||
# Replace %3N (bash milliseconds) with %f (Python microseconds) and trim later | ||
ts_format_python = ts_format.replace('%3N', '%f') | ||
timestamp = datetime.now(timezone.utc).strftime(ts_format_python) | ||
# Convert microseconds to milliseconds (trim last 3 digits) | ||
if '%f' in ts_format_python: | ||
# Find the microseconds part and trim to milliseconds | ||
parts = timestamp.rsplit(',', 1) | ||
if len(parts) == 2 and len(parts[1]) == 6: | ||
timestamp = parts[0] + ',' + parts[1][:3] | ||
else: | ||
timestamp = datetime.now(timezone.utc).strftime(ts_format) | ||
return timestamp | ||
|
||
|
||
def create_session(max_time=1): | ||
"""Create requests session with timeout configuration.""" | ||
session = requests.Session() | ||
return session | ||
|
||
|
||
def get_basic_auth(): | ||
"""Get basic authentication header if credentials are provided.""" | ||
username = os.environ.get('SE_ROUTER_USERNAME') | ||
password = os.environ.get('SE_ROUTER_PASSWORD') | ||
|
||
if username and password: | ||
credentials = f"{username}:{password}" | ||
encoded_credentials = base64.b64encode(credentials.encode()).decode() | ||
return {"Authorization": f"Basic {encoded_credentials}"} | ||
|
||
return {} | ||
|
||
|
||
def validate_endpoint(endpoint, graphql_endpoint=False, max_time=1): | ||
""" | ||
Validate an endpoint by making HTTP request and checking status code. | ||
|
||
Args: | ||
endpoint (str): The endpoint URL to validate | ||
graphql_endpoint (bool): Whether this is a GraphQL endpoint | ||
max_time (int): Maximum time for request in seconds | ||
""" | ||
process_name = "endpoint.checks" | ||
session = create_session(max_time) | ||
|
||
# Set up headers | ||
headers = {} | ||
headers.update(get_basic_auth()) | ||
|
||
try: | ||
if graphql_endpoint: | ||
# GraphQL endpoint check | ||
headers['Content-Type'] = 'application/json' | ||
data = {"query": "{ grid { sessionCount } }"} | ||
|
||
response = session.post( | ||
endpoint, | ||
headers=headers, | ||
json=data, | ||
timeout=max_time, | ||
verify=False # Equivalent to curl's -k flag | ||
) | ||
else: | ||
# Regular endpoint check | ||
response = session.get( | ||
endpoint, | ||
headers=headers, | ||
timeout=max_time, | ||
verify=False # Equivalent to curl's -k flag | ||
) | ||
|
||
status_code = response.status_code | ||
|
||
except requests.exceptions.Timeout: | ||
print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} timed out after {max_time} seconds") | ||
return False | ||
except requests.exceptions.ConnectionError: | ||
print(f"{get_timestamp()} [{process_name}] - Failed to connect to endpoint {endpoint}") | ||
return False | ||
except requests.exceptions.RequestException as e: | ||
print(f"{get_timestamp()} [{process_name}] - Error connecting to endpoint {endpoint}: {str(e)}") | ||
return False | ||
|
||
# Handle different status codes | ||
if status_code == 404: | ||
print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} is not found - status code: {status_code}") | ||
return False | ||
elif status_code == 401: | ||
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.") | ||
return False | ||
elif status_code != 200: | ||
print(f"{get_timestamp()} [{process_name}] - Endpoint {endpoint} is not available - status code: {status_code}") | ||
return False | ||
|
||
return True | ||
|
||
|
||
def main(): | ||
"""Main function to handle command line arguments and execute validation.""" | ||
if len(sys.argv) < 2: | ||
print("Usage: python3 validate_endpoint.py <endpoint> [graphql_endpoint]") | ||
print(" endpoint: The URL endpoint to validate") | ||
print(" graphql_endpoint: 'true' if this is a GraphQL endpoint (default: false)") | ||
sys.exit(1) | ||
|
||
endpoint = sys.argv[1] | ||
graphql_endpoint = len(sys.argv) > 2 and sys.argv[2].lower() == 'true' | ||
max_time = int(os.environ.get('SE_ENDPOINT_CHECK_TIMEOUT', 1)) | ||
|
||
# Validate the endpoint | ||
success = validate_endpoint(endpoint, graphql_endpoint, max_time) | ||
|
||
# Exit with appropriate code | ||
sys.exit(0 if success else 1) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file was deleted.
Oops, something went wrong.
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
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.