Files
opensearch-pyd/opensearchpy/connection/base.py
T

326 lines
11 KiB
Python
Raw Normal View History

# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
#
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
#
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
2020-04-23 11:22:08 -05:00
2022-10-04 00:15:18 +05:30
import gzip
import io
import logging
import os
import re
import warnings
from platform import python_version
try:
import simplejson as json
except ImportError:
import json
2013-08-25 16:39:56 +02:00
2021-08-16 17:20:29 +05:30
from .. import __versionstr__
from ..exceptions import HTTP_EXCEPTIONS, OpenSearchWarning, TransportError
2013-08-25 16:39:56 +02:00
2021-08-13 15:51:50 +05:30
logger = logging.getLogger("opensearch")
2021-09-16 14:59:29 +05:30
# create the opensearchpy.trace logger, but only set propagate to False if the
# logger hasn't already been configured
2021-09-16 14:59:29 +05:30
_tracer_already_configured = "opensearchpy.trace" in logging.Logger.manager.loggerDict
tracer = logging.getLogger("opensearchpy.trace")
if not _tracer_already_configured:
tracer.propagate = False
_WARNING_RE = re.compile(r"\"([^\"]*)\"")
2013-08-25 16:39:56 +02:00
class Connection(object):
"""
2021-08-13 15:51:50 +05:30
Class responsible for maintaining a connection to an OpenSearch node. It
2013-08-25 16:39:56 +02:00
holds persistent connection pool to it and it's main interface
(`perform_request`) is thread-safe.
Also responsible for logging.
:arg host: hostname of the node (default: localhost)
:arg port: port to use (integer, default: 9200)
:arg use_ssl: use ssl for the connection if `True`
2021-08-13 15:51:50 +05:30
:arg url_prefix: optional url prefix for opensearch
:arg timeout: default timeout in seconds (float, default: 10)
:arg http_compress: Use gzip compression
2020-03-11 16:33:15 -05:00
:arg opaque_id: Send this value in the 'X-Opaque-Id' HTTP header
For tracing all requests made by this transport.
2013-08-25 16:39:56 +02:00
"""
2019-05-10 09:16:33 -06:00
def __init__(
self,
host="localhost",
port=None,
2019-05-10 09:16:33 -06:00
use_ssl=False,
url_prefix="",
timeout=10,
headers=None,
http_compress=None,
2020-05-13 13:20:15 -05:00
opaque_id=None,
2019-05-10 09:16:33 -06:00
**kwargs
):
if port is None:
port = 9200
# Work-around if the implementing class doesn't
# define the headers property before calling super().__init__()
if not hasattr(self, "headers"):
self.headers = {}
headers = headers or {}
for key in headers:
self.headers[key.lower()] = headers[key]
2020-05-13 13:20:15 -05:00
if opaque_id:
self.headers["x-opaque-id"] = opaque_id
if os.getenv("ELASTIC_CLIENT_APIVERSIONING") == "1":
self.headers.setdefault(
"accept", "application/vnd.elasticsearch+json;compatible-with=7"
)
self.headers.setdefault("content-type", "application/json")
self.headers.setdefault("user-agent", self._get_default_user_agent())
if http_compress:
self.headers["accept-encoding"] = "gzip,deflate"
2019-05-10 09:16:33 -06:00
scheme = kwargs.get("scheme", "http")
if use_ssl or scheme == "https":
scheme = "https"
2017-05-15 21:56:49 +02:00
use_ssl = True
self.use_ssl = use_ssl
self.http_compress = http_compress or False
2017-05-15 21:56:49 +02:00
2020-05-13 13:20:15 -05:00
self.scheme = scheme
self.hostname = host
self.port = port
if ":" in host: # IPv6
self.host = "%s://[%s]" % (scheme, host)
else:
self.host = "%s://%s" % (scheme, host)
if self.port is not None:
self.host += ":%s" % self.port
2013-08-25 16:39:56 +02:00
if url_prefix:
2019-05-10 09:16:33 -06:00
url_prefix = "/" + url_prefix.strip("/")
2013-08-25 16:39:56 +02:00
self.url_prefix = url_prefix
self.timeout = timeout
2013-08-25 16:39:56 +02:00
def __repr__(self):
2019-05-10 09:16:33 -06:00
return "<%s: %s>" % (self.__class__.__name__, self.host)
2013-08-25 16:39:56 +02:00
def __eq__(self, other):
if not isinstance(other, Connection):
2020-03-09 11:51:35 -05:00
raise TypeError("Unsupported equality check for %s and %s" % (self, other))
return self.__hash__() == other.__hash__()
def __hash__(self):
return id(self)
def _gzip_compress(self, body):
buf = io.BytesIO()
with gzip.GzipFile(fileobj=buf, mode="wb") as f:
f.write(body)
return buf.getvalue()
def _raise_warnings(self, warning_headers):
"""If 'headers' contains a 'Warning' header raise
the warnings to be seen by the user. Takes an iterable
of string values from any number of 'Warning' headers.
"""
if not warning_headers:
return
# Grab only the message from each header, the rest is discarded.
2021-08-13 15:51:50 +05:30
# Format is: '(number) OpenSearch-(version)-(instance) "(message)"'
warning_messages = []
for header in warning_headers:
# Because 'Requests' does it's own folding of multiple HTTP headers
# into one header delimited by commas (totally standard compliant, just
# annoying for cases like this) we need to expect there may be
# more than one message per 'Warning' header.
matches = _WARNING_RE.findall(header)
if matches:
warning_messages.extend(matches)
else:
# Don't want to throw away any warnings, even if they
# don't follow the format we have now. Use the whole header.
warning_messages.append(header)
for message in warning_messages:
2021-08-13 15:51:50 +05:30
warnings.warn(message, category=OpenSearchWarning)
def _pretty_json(self, data):
# pretty JSON in tracer curl logs
try:
2019-05-10 09:16:33 -06:00
return json.dumps(
json.loads(data), sort_keys=True, indent=2, separators=(",", ": ")
).replace("'", r"\u0027")
except (ValueError, TypeError):
# non-json data or a bulk request
return data
def _log_trace(self, method, path, body, status_code, response, duration):
if not tracer.isEnabledFor(logging.INFO) or not tracer.handlers:
return
# include pretty in trace curls
2019-05-10 09:16:33 -06:00
path = path.replace("?", "?pretty&", 1) if "?" in path else path + "?pretty"
if self.url_prefix:
2019-05-10 09:16:33 -06:00
path = path.replace(self.url_prefix, "", 1)
tracer.info(
"curl %s-X%s 'http://localhost:9200%s' -d '%s'",
"-H 'Content-Type: application/json' " if body else "",
method,
path,
self._pretty_json(body) if body else "",
)
if tracer.isEnabledFor(logging.DEBUG):
2019-05-10 09:16:33 -06:00
tracer.debug(
"#[%s] (%.3fs)\n#%s",
status_code,
duration,
self._pretty_json(response).replace("\n", "\n#") if response else "",
)
def perform_request(
self,
method,
url,
params=None,
body=None,
timeout=None,
ignore=(),
headers=None,
):
raise NotImplementedError()
2019-05-10 09:16:33 -06:00
def log_request_success(
self, method, full_url, path, body, status_code, response, duration
):
"""Log a successful API call."""
2013-08-25 16:39:56 +02:00
# TODO: optionally pass in params instead of full_url and do urlencode only when needed
# body has already been serialized to utf-8, deserialize it for logging
# TODO: find a better way to avoid (de)encoding the body back and forth
if body:
2018-12-10 17:32:54 -06:00
try:
2019-05-10 09:16:33 -06:00
body = body.decode("utf-8", "ignore")
2018-12-10 17:32:54 -06:00
except AttributeError:
pass
2013-08-25 16:39:56 +02:00
logger.info(
2019-05-10 09:16:33 -06:00
"%s %s [status:%s request:%.3fs]", method, full_url, status_code, duration
2013-08-25 16:39:56 +02:00
)
2019-05-10 09:16:33 -06:00
logger.debug("> %s", body)
logger.debug("< %s", response)
2013-08-25 16:39:56 +02:00
self._log_trace(method, path, body, status_code, response, duration)
2013-08-25 16:39:56 +02:00
2019-05-10 09:16:33 -06:00
def log_request_fail(
self,
method,
full_url,
path,
body,
duration,
status_code=None,
response=None,
exception=None,
):
"""Log an unsuccessful API call."""
2016-04-27 13:21:47 +02:00
# do not log 404s on HEAD requests
2019-05-10 09:16:33 -06:00
if method == "HEAD" and status_code == 404:
2016-04-27 13:21:47 +02:00
return
2013-08-25 16:39:56 +02:00
logger.warning(
2019-05-10 09:16:33 -06:00
"%s %s [status:%s request:%.3fs]",
method,
full_url,
status_code or "N/A",
duration,
exc_info=exception is not None,
2013-08-25 16:39:56 +02:00
)
# body has already been serialized to utf-8, deserialize it for logging
# TODO: find a better way to avoid (de)encoding the body back and forth
if body:
2018-12-10 17:32:54 -06:00
try:
2019-05-10 09:16:33 -06:00
body = body.decode("utf-8", "ignore")
2018-12-10 17:32:54 -06:00
except AttributeError:
pass
2019-05-10 09:16:33 -06:00
logger.debug("> %s", body)
2013-08-25 16:39:56 +02:00
self._log_trace(method, path, body, status_code, response, duration)
2016-01-26 18:45:52 -08:00
if response is not None:
2019-05-10 09:16:33 -06:00
logger.debug("< %s", response)
2016-01-26 18:45:52 -08:00
def _raise_error(self, status_code, raw_data, content_type=None):
"""Locate appropriate exception and raise it."""
2013-08-25 16:39:56 +02:00
error_message = raw_data
additional_info = None
try:
content_type = (
"text/plain"
if content_type is None
else content_type.split(";")[0].strip()
)
if raw_data and content_type == "application/json":
2016-06-04 14:52:53 -07:00
additional_info = json.loads(raw_data)
2019-05-10 09:16:33 -06:00
error_message = additional_info.get("error", error_message)
if isinstance(error_message, dict) and "type" in error_message:
error_message = error_message["type"]
2016-02-24 16:34:50 -05:00
except (ValueError, TypeError) as err:
2019-05-10 09:16:33 -06:00
logger.warning("Undecodable raw error response from server: %s", err)
2013-08-25 16:39:56 +02:00
2019-05-10 09:16:33 -06:00
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(
status_code, error_message, additional_info
)
def _get_default_user_agent(self):
2021-08-13 15:51:50 +05:30
return "opensearch-py/%s (Python %s)" % (__versionstr__, python_version())
@staticmethod
def default_ca_certs():
"""
Get the default CA certificate bundle, preferring those configured in
the standard OpenSSL environment variables before those provided by
certifi (if available)
"""
ca_certs = os.environ.get("SSL_CERT_FILE") or os.environ.get("SSL_CERT_DIR")
if ca_certs:
return ca_certs
try:
import certifi
except ImportError:
pass
else:
return certifi.where()