-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy path_connector_base.py
396 lines (333 loc) · 13.7 KB
/
_connector_base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# Copyright (c) 2024 Airbyte, Inc., all rights reserved.
"""Destination base classes."""
from __future__ import annotations
import abc
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
import jsonschema
import rich
import yaml
from rich.syntax import Syntax
from airbyte_protocol.models import (
AirbyteMessage,
ConnectorSpecification,
Status,
TraceType,
Type,
)
from airbyte import exceptions as exc
from airbyte._util.telemetry import (
EventState,
log_config_validation_result,
log_connector_check_result,
)
from airbyte._util.temp_files import as_temp_files
from airbyte.logs import new_passthrough_file_logger
if TYPE_CHECKING:
import logging
from collections.abc import Generator
from typing import IO
from airbyte._executors.base import Executor
from airbyte._message_iterators import AirbyteMessageIterator
MAX_LOG_LINES = 20
class ConnectorBase(abc.ABC):
"""A class representing a destination that can be called."""
connector_type: Literal["destination", "source"]
def __init__(
self,
executor: Executor,
name: str,
config: dict[str, Any] | None = None,
*,
validate: bool = False,
) -> None:
"""Initialize the source.
If config is provided, it will be validated against the spec if validate is True.
"""
self.executor = executor
self.name = name
self._config_dict: dict[str, Any] | None = None
self._last_log_messages: list[str] = []
self._spec: ConnectorSpecification | None = None
self._selected_stream_names: list[str] = []
self._file_logger: logging.Logger = new_passthrough_file_logger(self.name)
if config is not None:
self.set_config(config, validate=validate)
def _print_info_message(
self,
message: str,
) -> None:
"""Print a message to the logger."""
if self._file_logger:
self._file_logger.info(message)
def _print_error_message(
self,
message: str,
) -> None:
"""Print a message to the console and the logger."""
rich.print(f"ERROR: {message}")
if self._file_logger:
self._file_logger.error(message)
def set_config(
self,
config: dict[str, Any],
*,
validate: bool = True,
) -> None:
"""Set the config for the connector.
If validate is True, raise an exception if the config fails validation.
If validate is False, validation will be deferred until check() or validate_config()
is called.
"""
if validate:
self.validate_config(config)
self._config_dict = config
def get_config(self) -> dict[str, Any]:
"""Get the config for the connector."""
return self._config
@property
def _config(self) -> dict[str, Any]:
if self._config_dict is None:
raise exc.AirbyteConnectorConfigurationMissingError(
connector_name=self.name,
guidance="Provide via get_destination() or set_config()",
)
return self._config_dict
def validate_config(self, config: dict[str, Any] | None = None) -> None:
"""Validate the config against the spec.
If config is not provided, the already-set config will be validated.
"""
spec = self._get_spec(force_refresh=False)
config = self._config if config is None else config
try:
jsonschema.validate(config, spec.connectionSpecification)
log_config_validation_result(
name=self.name,
state=EventState.SUCCEEDED,
)
except jsonschema.ValidationError as ex:
validation_ex = exc.AirbyteConnectorValidationFailedError(
connector_name=self.name,
message="The provided config is not valid.",
context={
"error_message": ex.message,
"error_path": ex.path,
"error_instance": ex.instance,
"error_schema": ex.schema,
},
)
log_config_validation_result(
name=self.name,
state=EventState.FAILED,
exception=validation_ex,
)
raise validation_ex from ex
def _get_spec(self, *, force_refresh: bool = False) -> ConnectorSpecification:
"""Call spec on the connector.
This involves the following steps:
* execute the connector with spec
* Listen to the messages and return the first AirbyteCatalog that comes along.
* Make sure the subprocess is killed when the function returns.
Raises:
AirbyteConnectorSpecFailedError: If the spec operation fails.
AirbyteConnectorMissingSpecError: If the spec operation does not return a spec.
"""
if force_refresh or self._spec is None:
try:
for msg in self._execute(["spec"]):
if msg.type == Type.SPEC and msg.spec:
self._spec = msg.spec
break
except exc.AirbyteSubprocessError as ex:
raise exc.AirbyteConnectorSpecFailedError(
connector_name=self.name,
log_text=ex.log_text,
) from ex
if self._spec:
return self._spec
raise exc.AirbyteConnectorMissingSpecError(
connector_name=self.name,
log_text=self._last_log_messages,
)
@property
def config_spec(self) -> dict[str, Any]:
"""Generate a configuration spec for this connector, as a JSON Schema definition.
This function generates a JSON Schema dictionary with configuration specs for the
current connector, as a dictionary.
Returns:
dict: The JSON Schema configuration spec as a dictionary.
"""
return self._get_spec(force_refresh=True).connectionSpecification
def print_config_spec(
self,
format: Literal["yaml", "json"] = "yaml", # noqa: A002
*,
output_file: Path | str | None = None,
) -> None:
"""Print the configuration spec for this connector.
Args:
format: The format to print the spec in. Must be "yaml" or "json".
output_file: Optional. If set, the spec will be written to the given file path.
Otherwise, it will be printed to the console.
"""
if format not in {"yaml", "json"}:
raise exc.PyAirbyteInputError(
message="Invalid format. Expected 'yaml' or 'json'",
input_value=format,
)
if isinstance(output_file, str):
output_file = Path(output_file)
if format == "yaml":
content = yaml.dump(self.config_spec, indent=2)
elif format == "json":
content = json.dumps(self.config_spec, indent=2)
if output_file:
output_file.write_text(content)
return
syntax_highlighted = Syntax(content, format)
rich.print(syntax_highlighted)
@property
def _yaml_spec(self) -> str:
"""Get the spec as a yaml string.
For now, the primary use case is for writing and debugging a valid config for a source.
This is private for now because we probably want better polish before exposing this
as a stable interface. This will also get easier when we have docs links with this info
for each connector.
"""
spec_obj: ConnectorSpecification = self._get_spec()
spec_dict = spec_obj.dict(exclude_unset=True)
# convert to a yaml string
return yaml.dump(spec_dict)
@property
def docs_url(self) -> str:
"""Get the URL to the connector's documentation."""
return (
f"https://docs.airbyte.com/integrations/{self.connector_type}s/"
+ self.name.lower().replace(f"{self.connector_type}-", "")
)
@property
def connector_version(self) -> str | None:
"""Return the version of the connector as reported by the executor.
Returns None if the version cannot be determined.
"""
return self.executor.get_installed_version()
def check(self) -> None:
"""Call check on the connector.
This involves the following steps:
* Write the config to a temporary file
* execute the connector with check --config <config_file>
* Listen to the messages and return the first AirbyteCatalog that comes along.
* Make sure the subprocess is killed when the function returns.
"""
with as_temp_files([self._config]) as [config_file]:
try:
for msg in self._execute(["check", "--config", config_file]):
if msg.type == Type.CONNECTION_STATUS and msg.connectionStatus:
if msg.connectionStatus.status != Status.FAILED:
rich.print(f"Connection check succeeded for `{self.name}`.")
log_connector_check_result(
name=self.name,
state=EventState.SUCCEEDED,
)
return
log_connector_check_result(
name=self.name,
state=EventState.FAILED,
)
raise exc.AirbyteConnectorCheckFailedError(
connector_name=self.name,
help_url=self.docs_url,
context={
"failure_reason": msg.connectionStatus.message,
},
)
raise exc.AirbyteConnectorCheckFailedError(
connector_name=self.name,
message="The connector `check` operation did not return a status.",
log_text=self._last_log_messages,
)
except exc.AirbyteConnectorFailedError as ex:
raise exc.AirbyteConnectorCheckFailedError(
connector_name=self.name,
original_exception=ex,
) from None
def install(self) -> None:
"""Install the connector if it is not yet installed."""
self.executor.install()
rich.print("For configuration instructions, see: \n" f"{self.docs_url}#reference\n")
def uninstall(self) -> None:
"""Uninstall the connector if it is installed.
This only works if the use_local_install flag wasn't used and installation is managed by
PyAirbyte.
"""
self.executor.uninstall()
def _peek_airbyte_message(
self,
message: AirbyteMessage,
*,
raise_on_error: bool = True,
) -> None:
"""Process an Airbyte message.
This method handles reading Airbyte messages and taking action, if needed, based on the
message type. For instance, log messages are logged, records are tallied, and errors are
raised as exceptions if `raise_on_error` is True.
Raises:
AirbyteConnectorFailedError: If a TRACE message of type ERROR is emitted.
"""
if message.type == Type.LOG:
self._print_info_message(message.log.message)
return
if message.type == Type.TRACE and message.trace.type == TraceType.ERROR:
self._print_error_message(message.trace.error.message)
if raise_on_error:
raise exc.AirbyteConnectorFailedError(
connector_name=self.name,
message=message.trace.error.message,
log_text=self._last_log_messages,
)
return
def _execute(
self,
args: list[str],
stdin: IO[str] | AirbyteMessageIterator | None = None,
) -> Generator[AirbyteMessage, None, None]:
"""Execute the connector with the given arguments.
This involves the following steps:
* Locate the right venv. It is called ".venv-<connector_name>"
* Spawn a subprocess with .venv-<connector_name>/bin/<connector-name> <args>
* Read the output line by line of the subprocess and serialize them AirbyteMessage objects.
Drop if not valid.
Raises:
AirbyteConnectorFailedError: If the process returns a failure status (non-zero).
"""
# Fail early if the connector is not installed.
self.executor.ensure_installation(auto_fix=False)
try:
for line in self.executor.execute(args, stdin=stdin):
try:
message: AirbyteMessage = AirbyteMessage.model_validate_json(json_data=line)
self._peek_airbyte_message(message)
yield message
except Exception:
# This is likely a log message, so log it as INFO.
self._print_info_message(line)
except exc.AirbyteSubprocessFailedError as ex:
# Generic subprocess failure, so raise a connector error.
raise exc.AirbyteConnectorFailedError(
connector_name=self.name,
log_text=ex.log_text,
context={
"exit_code": ex.exit_code,
},
) from None
except Exception as e:
# This is an unexpected error, so wrap the original exception when raising.
raise exc.AirbyteConnectorFailedError(
connector_name=self.name,
log_text=self._last_log_messages,
original_exception=e,
) from None
__all__ = [
"ConnectorBase",
]