|
| 1 | +from contextlib import contextmanager |
| 2 | +from dagster import AssetExecutionContext, ConfigurableResource |
| 3 | +from dagster_shell import execute_shell_command |
| 4 | +from pydantic import Field |
| 5 | +from enum import Enum |
| 6 | +import tempfile |
| 7 | + |
| 8 | +class CloudqueryCommand(Enum): |
| 9 | + SYNC = "sync" |
| 10 | + MIGRATE = "migrate" |
| 11 | + |
| 12 | + |
| 13 | +class CloudqueryResource(ConfigurableResource): |
| 14 | + """Resource for interacting with the Cloudquery CLI.""" |
| 15 | + |
| 16 | + path_to_cloudquery_binary: str = Field( |
| 17 | + description=( |
| 18 | + "Path to the Cloudquery binary. Defaults to 'cloudquery' if not set." |
| 19 | + ), |
| 20 | + default="cloudquery", |
| 21 | + ) |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def _is_dagster_maintained(cls) -> bool: |
| 25 | + return False |
| 26 | + |
| 27 | + def migrate(self, context: AssetExecutionContext, *, spec_path: str = "", spec_blob: str = ""): |
| 28 | + self._run(CloudqueryCommand.MIGRATE, context, spec_path=spec_path, spec_blob=spec_blob) |
| 29 | + |
| 30 | + def sync(self, context: AssetExecutionContext, *, spec_path: str = "", spec_blob: str = ""): |
| 31 | + self._run(CloudqueryCommand.SYNC, context, spec_path=spec_path, spec_blob=spec_blob) |
| 32 | + |
| 33 | + def _resolve_cloudquery_path(self) -> str: |
| 34 | + return self.path_to_cloudquery_binary |
| 35 | + |
| 36 | + def _resolve_spec(self, *, spec_path: str = "", spec_blob: str = "") -> str: |
| 37 | + if spec_path and spec_blob: |
| 38 | + raise ValueError("Supply either `spec_path` or `spec_blob`, not both.") |
| 39 | + if not spec_path and not spec_blob: |
| 40 | + raise ValueError("You must supply either `spec_path` or `spec_blob`.") |
| 41 | + if spec_path: |
| 42 | + with open(spec_path, "r") as file: |
| 43 | + return file.read() |
| 44 | + if spec_blob: |
| 45 | + return spec_blob |
| 46 | + |
| 47 | + @contextmanager |
| 48 | + def _make_spec_file(self, *, spec_path: str = "", spec_blob: str = ""): |
| 49 | + spec = self._resolve_spec(spec_path=spec_path, spec_blob=spec_blob) |
| 50 | + with tempfile.NamedTemporaryFile(mode='w+t') as temp_file: |
| 51 | + temp_file.write(spec) |
| 52 | + temp_file.flush() |
| 53 | + yield temp_file.name |
| 54 | + |
| 55 | + def _run(self, command: CloudqueryCommand, context: AssetExecutionContext, *, spec_path: str = "", spec_blob: str = ""): |
| 56 | + cloudquery_path = self._resolve_cloudquery_path() |
| 57 | + |
| 58 | + with self._make_spec_file(spec_path=spec_path, spec_blob=spec_blob) as spec_file: |
| 59 | + ret = execute_shell_command(f"{cloudquery_path} {command.value} --log-console {spec_file}", output_logging="STREAM", log=context.log) |
| 60 | + if ret[1] != 0: |
| 61 | + raise Exception(f"cloudquery command failed with: {ret}") |
0 commit comments