import os
from http.server import BaseHTTPRequestHandler, HTTPServer
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import ConnectionError
# Fetch Elasticsearch URI from environment variables
ELASTICSEARCH_URI = os.getenv("ELASTICSEARCH_URI")
# Initialize Elasticsearch client
def connect_elasticsearch():
try:
# Create an Elasticsearch client using the URI
es = Elasticsearch([ELASTICSEARCH_URI])
# Check connection by pinging Elasticsearch
if es.ping():
return True
return False
except ConnectionError:
return False
# HTTP request handler class
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# Check if Elasticsearch is reachable
if connect_elasticsearch():
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b"Elasticsearch connection successful!")
else:
self.send_response(500)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b"Failed to connect to Elasticsearch")
# Run the server
def run(server_class=HTTPServer, handler_class=RequestHandler, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run()