|
| 1 | +# |
| 2 | +# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved. |
| 3 | +# |
| 4 | + |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import pathlib |
| 8 | +import socket |
| 9 | +import subprocess |
| 10 | +from time import sleep |
| 11 | +from typing import List, Optional, Union |
| 12 | + |
| 13 | +try: |
| 14 | + from snowflake.connector.vendored import requests |
| 15 | +except ImportError: |
| 16 | + import requests |
| 17 | + |
| 18 | +WIREMOCK_START_MAX_RETRY_COUNT = 12 |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def _get_mapping_str(mapping: Union[str, dict, pathlib.Path]) -> str: |
| 23 | + if isinstance(mapping, str): |
| 24 | + return mapping |
| 25 | + if isinstance(mapping, dict): |
| 26 | + return json.dumps(mapping) |
| 27 | + if isinstance(mapping, pathlib.Path): |
| 28 | + if mapping.is_file(): |
| 29 | + with open(mapping) as f: |
| 30 | + return f.read() |
| 31 | + else: |
| 32 | + raise RuntimeError(f"File with mapping: {mapping} does not exist") |
| 33 | + |
| 34 | + raise RuntimeError(f"Mapping {mapping} is of an invalid type") |
| 35 | + |
| 36 | + |
| 37 | +class WiremockClient: |
| 38 | + def __init__(self): |
| 39 | + self.wiremock_filename = "wiremock-standalone.jar" |
| 40 | + self.wiremock_host = "localhost" |
| 41 | + self.wiremock_http_port = None |
| 42 | + self.wiremock_https_port = None |
| 43 | + |
| 44 | + self.wiremock_dir = pathlib.Path(__file__).parent.parent.parent / ".wiremock" |
| 45 | + assert self.wiremock_dir.exists(), f"{self.wiremock_dir} does not exist" |
| 46 | + |
| 47 | + self.wiremock_jar_path = self.wiremock_dir / self.wiremock_filename |
| 48 | + assert ( |
| 49 | + self.wiremock_jar_path.exists() |
| 50 | + ), f"{self.wiremock_jar_path} does not exist" |
| 51 | + |
| 52 | + def _start_wiremock(self): |
| 53 | + self.wiremock_http_port = self._find_free_port() |
| 54 | + self.wiremock_https_port = self._find_free_port( |
| 55 | + forbidden_ports=[self.wiremock_http_port] |
| 56 | + ) |
| 57 | + self.wiremock_process = subprocess.Popen( |
| 58 | + [ |
| 59 | + "java", |
| 60 | + "-jar", |
| 61 | + self.wiremock_jar_path, |
| 62 | + "--root-dir", |
| 63 | + self.wiremock_dir, |
| 64 | + "--enable-browser-proxying", # work as forward proxy |
| 65 | + "--proxy-pass-through", |
| 66 | + "false", # pass through only matched requests |
| 67 | + "--port", |
| 68 | + str(self.wiremock_http_port), |
| 69 | + "--https-port", |
| 70 | + str(self.wiremock_https_port), |
| 71 | + "--https-keystore", |
| 72 | + self.wiremock_dir / "ca-cert.jks", |
| 73 | + "--ca-keystore", |
| 74 | + self.wiremock_dir / "ca-cert.jks", |
| 75 | + ] |
| 76 | + ) |
| 77 | + self._wait_for_wiremock() |
| 78 | + |
| 79 | + def _stop_wiremock(self): |
| 80 | + response = self._wiremock_post( |
| 81 | + f"http://{self.wiremock_host}:{self.wiremock_http_port}/__admin/shutdown" |
| 82 | + ) |
| 83 | + if response.status_code != 200: |
| 84 | + logger.info("Wiremock shutdown failed, the process will be killed") |
| 85 | + self.wiremock_process.kill() |
| 86 | + else: |
| 87 | + logger.debug("Wiremock shutdown gracefully") |
| 88 | + |
| 89 | + def _wait_for_wiremock(self): |
| 90 | + retry_count = 0 |
| 91 | + while retry_count < WIREMOCK_START_MAX_RETRY_COUNT: |
| 92 | + if self._health_check(): |
| 93 | + return |
| 94 | + retry_count += 1 |
| 95 | + sleep(1) |
| 96 | + |
| 97 | + raise TimeoutError( |
| 98 | + f"WiremockClient did not respond within {WIREMOCK_START_MAX_RETRY_COUNT} seconds" |
| 99 | + ) |
| 100 | + |
| 101 | + def _health_check(self): |
| 102 | + mappings_endpoint = ( |
| 103 | + f"http://{self.wiremock_host}:{self.wiremock_http_port}/__admin/health" |
| 104 | + ) |
| 105 | + try: |
| 106 | + response = requests.get(mappings_endpoint) |
| 107 | + except requests.exceptions.RequestException as e: |
| 108 | + logger.warning(f"Wiremock healthcheck failed with exception: {e}") |
| 109 | + return False |
| 110 | + |
| 111 | + if ( |
| 112 | + response.status_code == requests.codes.ok |
| 113 | + and response.json()["status"] != "healthy" |
| 114 | + ): |
| 115 | + logger.warning(f"Wiremock healthcheck failed with response: {response}") |
| 116 | + return False |
| 117 | + elif response.status_code != requests.codes.ok: |
| 118 | + logger.warning( |
| 119 | + f"Wiremock healthcheck failed with status code: {response.status_code}" |
| 120 | + ) |
| 121 | + return False |
| 122 | + |
| 123 | + return True |
| 124 | + |
| 125 | + def _reset_wiremock(self): |
| 126 | + reset_endpoint = ( |
| 127 | + f"http://{self.wiremock_host}:{self.wiremock_http_port}/__admin/reset" |
| 128 | + ) |
| 129 | + response = self._wiremock_post(reset_endpoint) |
| 130 | + if response.status_code != requests.codes.ok: |
| 131 | + raise RuntimeError("Failed to reset WiremockClient") |
| 132 | + |
| 133 | + def _wiremock_post( |
| 134 | + self, endpoint: str, body: Optional[str] = None |
| 135 | + ) -> requests.Response: |
| 136 | + headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 137 | + return requests.post(endpoint, data=body, headers=headers) |
| 138 | + |
| 139 | + def import_mapping(self, mapping: Union[str, dict, pathlib.Path]): |
| 140 | + self._reset_wiremock() |
| 141 | + import_mapping_endpoint = f"http://{self.wiremock_host}:{self.wiremock_http_port}/__admin/mappings/import" |
| 142 | + mapping_str = _get_mapping_str(mapping) |
| 143 | + response = self._wiremock_post(import_mapping_endpoint, mapping_str) |
| 144 | + if response.status_code != requests.codes.ok: |
| 145 | + raise RuntimeError("Failed to import mapping") |
| 146 | + |
| 147 | + def add_mapping(self, mapping: Union[str, dict, pathlib.Path]): |
| 148 | + add_mapping_endpoint = ( |
| 149 | + f"http://{self.wiremock_host}:{self.wiremock_http_port}/__admin/mappings" |
| 150 | + ) |
| 151 | + mapping_str = _get_mapping_str(mapping) |
| 152 | + response = self._wiremock_post(add_mapping_endpoint, mapping_str) |
| 153 | + if response.status_code != requests.codes.created: |
| 154 | + raise RuntimeError("Failed to add mapping") |
| 155 | + |
| 156 | + def _find_free_port(self, forbidden_ports: Union[List[int], None] = None) -> int: |
| 157 | + max_retries = 1 if forbidden_ports is None else 3 |
| 158 | + if forbidden_ports is None: |
| 159 | + forbidden_ports = [] |
| 160 | + |
| 161 | + retry_count = 0 |
| 162 | + while retry_count < max_retries: |
| 163 | + retry_count += 1 |
| 164 | + with socket.socket() as sock: |
| 165 | + sock.bind((self.wiremock_host, 0)) |
| 166 | + port = sock.getsockname()[1] |
| 167 | + if port not in forbidden_ports: |
| 168 | + return port |
| 169 | + |
| 170 | + raise RuntimeError( |
| 171 | + f"Unable to find a free port for wiremock in {max_retries} attempts" |
| 172 | + ) |
| 173 | + |
| 174 | + def __enter__(self): |
| 175 | + self._start_wiremock() |
| 176 | + logger.debug( |
| 177 | + f"Starting wiremock process, listening on {self.wiremock_host}:{self.wiremock_http_port}" |
| 178 | + ) |
| 179 | + return self |
| 180 | + |
| 181 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 182 | + logger.debug("Stopping wiremock process") |
| 183 | + self._stop_wiremock() |
0 commit comments