From b028036abf8c52454a2129c8403db5d9bf40a483 Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Fri, 20 Nov 2026 12:42:14 +0000 Subject: [PATCH 1/7] feat(export-to-core): use pigz for parallel archive compression Add multi-threaded pigz (.tar.gz) archive compression for both mysql-data (mysqldump and mydumper modes) and fs-data, with automatic OS package installation (AUTO_INSTALL_PIGZ), configurable thread limits (USE_PIGZ, PIGZ_THREADS), clean fallback to single-threaded gzip, updated README instructions, and unit/integration tests. --- export-to-core/README.md | 36 ++- export-to-core/looker_export.py | 280 +++++++++++++++++++- export-to-core/tests/test_export_to_core.py | 182 +++++++++++++ 3 files changed, 475 insertions(+), 23 deletions(-) diff --git a/export-to-core/README.md b/export-to-core/README.md index ede100b..3c5a91c 100644 --- a/export-to-core/README.md +++ b/export-to-core/README.md @@ -16,7 +16,7 @@ The export tooling consists of one unified export script and one optional pre-mi - Verifies that `LOOKER_MASTER_KEY` unwraps the active Key-Encryption-Key (KEK) in the Looker `encryption_key` database table via RFC 3394 AES Key Unwrap. - Extracts your Looker backend database in a read-only, non-locking fashion using either **single-threaded (`mysqldump`)** or high-performance **multi-threaded (`mydumper` + `zstd`)** export mode, including schema/collation normalization (`utf8mb4_general_ci` and `BIGINT(19)` compatibility), schema-only export of `oauth_user_state`, optional schedule disabling (`DISABLE_SCHEDULED_PLANS`), and selective `setting` migration (`crypt_canary_gcm` and `closed_system`). - Stages production subdirectories from your Looker file system root path (`models`, `bare_models`, `deploy_keys`, `git_hooks`, `models-self-service`, `models-user-looker`, `remote_dependencies`, and `.persistent_store`) and normalizes Git repository and SSH configurations for `/looker_data/modelshare` in Looker (Google Cloud core). - - Wraps the 32-byte Looker Master Key under Cloud KMS and stream-encrypts exported `.tar.gz` archives using Tink Streaming AEAD (`AES128_CTR_HMAC_SHA256_1MB`) with Cloud KMS Envelope AEAD handles, producing `final_artifacts/` ready for upload to Cloud Storage and import into Looker (Google Cloud core). + - Wraps the 32-byte Looker Master Key under Cloud KMS, compresses exported `.tar.gz` archives (`mysql-data` and `fs-data`) in parallel using **`pigz`** (automatically falling back to `gzip` when unavailable), and stream-encrypts them using Tink Streaming AEAD (`AES128_CTR_HMAC_SHA256_1MB`) with Cloud KMS Envelope AEAD handles, producing `final_artifacts/` ready for upload to Cloud Storage and import into Looker (Google Cloud core). 2. **`collect_looker_diagnostics.py` (Pre-Migration Diagnostics — Optional)**: A read-only standard-library diagnostic utility that inspects your Looker directory structure, disk usage, total database storage footprint (`total_db_bytes`, `total_db_mib`, `total_db_gib`, and estimated `1.5x` staging disk requirement), and per-table MySQL/MariaDB metadata (version, character sets, collations, and sizes sorted largest-first). It makes zero modifications to your instance. --- @@ -24,15 +24,18 @@ The export tooling consists of one unified export script and one optional pre-mi ## Prerequisites ### 1. System Requirements -- Linux operating system (for example, Debian, Ubuntu, RHEL, CentOS, or Rocky Linux) with `git >= 2.36`, `tar`, and `gzip`. +- Linux operating system (for example, Debian, Ubuntu, RHEL, CentOS, or Rocky Linux) with `git >= 2.36`, `tar`, and `pigz` (recommended for parallel `.tar.gz` archive compression; `gzip` is supported as an automatic fallback). - Python `3.9` or higher. - Direct network access to your Looker backend database (`MySQL >= 8.0` or `MariaDB >= 10.4`) and `mysql` client CLI. - Free storage space on the target backup volume equal to at least `1.5x` the combined size of your Looker database and LookML directories (plus 64 MB headroom). -### 2. Database Export Utilities -Install the database dump tool corresponding to your chosen export mode: -- **Standard Mode (Single-threaded, Default)**: Requires `mysqldump` (from `mysql-client` or `default-mysql-client`). -- **Parallel Mode (Multi-threaded, Recommended for databases > 75 GB)**: +### 2. Database Export & Archive Compression Utilities +Install `pigz` for parallel archive compression alongside the database dump tool corresponding to your chosen export mode: +- **Parallel Archive Compression (`pigz`, Recommended for all modes)**: + - Used automatically for both `mysqldump` and `mydumper` archive packaging (`mysql-data` and `fs-data`), utilizing all available CPU cores by default (or `PIGZ_THREADS` when set) while emitting standard `.tar.gz` archives compatible with Looker (Google Cloud core). + - If `pigz` is not already installed on `PATH` and `AUTO_INSTALL_PIGZ=true` (default), `looker_export.py` attempts to install `pigz` automatically via your OS package manager (`apt-get`, `dnf`, `yum`, `zypper`, `apk`, or `brew`) when root or passwordless `sudo` is available (or after interactive confirmation), and otherwise falls back cleanly to single-threaded `gzip`. +- **Standard Mode (Single-threaded DB dump, Default)**: Requires `mysqldump` (from `mysql-client` or `default-mysql-client`). +- **Parallel Mode (Multi-threaded DB dump, Recommended for databases > 75 GB)**: - `mydumper` version `0.16.0` or later (downloadable from [mydumper releases](https://github.com/mydumper/mydumper/releases) or your OS package manager). - `zstd` compression CLI. @@ -57,25 +60,34 @@ Install the database dump tool corresponding to your chosen export mode: ## Installation -1. Clone the `customer-scripts` repository on a host with access to your Looker data directory and database: +1. Install `pigz` via your operating system package manager so archive packaging runs across multiple CPU cores: + ```bash + # Debian / Ubuntu + sudo apt-get update && sudo apt-get install -y pigz + + # RHEL / CentOS / Rocky Linux + sudo dnf install -y pigz + ``` + +2. Clone the `customer-scripts` repository on a host with access to your Looker data directory and database: ```bash git clone https://github.com/looker-open-source/customer-scripts.git cd customer-scripts/export-to-core ``` -2. Create and activate a Python virtual environment: +3. Create and activate a Python virtual environment: ```bash python3 -m venv venv source venv/bin/activate ``` -3. Install the required Python cryptographic packages: +4. Install the required Python cryptographic packages: ```bash pip install --upgrade pip pip install -r requirements.txt ``` -4. Ensure the scripts are executable: +5. Ensure the scripts are executable: ```bash chmod +x looker_export.py collect_looker_diagnostics.py ``` @@ -145,6 +157,7 @@ export KMS_KEY_NAME="projects//locations//keyRings/ None: ) self.mydumper_threads = os.environ.get('MYDUMPER_THREADS') or '4' self.mydumper_chunk_rows = os.environ.get('MYDUMPER_CHUNK_ROWS') or '50000' + self.use_pigz = (os.environ.get('USE_PIGZ') or 'auto').strip().lower() + self.pigz_threads = (os.environ.get('PIGZ_THREADS') or '').strip() + self.auto_install_pigz = ( + (os.environ.get('AUTO_INSTALL_PIGZ') or 'true').strip().lower() + ) self.keep_intermediate_files = ( os.environ.get('KEEP_INTERMEDIATE_FILES') or 'false' ) @@ -919,6 +928,95 @@ def _stream_command_to_encrypted_artifact( if rc != 0: self.die(err_msg) + def _should_use_pigz(self) -> bool: + """Returns True when pigz parallel compression is enabled and available.""" + return self.use_pigz != 'false' and shutil.which('pigz') is not None + + @staticmethod + def _kill_and_reap(procs: Sequence[subprocess.Popen[Any] | None]) -> None: + """Terminates and reaps any still-running child processes in procs.""" + for proc in procs: + if proc is not None and proc.poll() is None: + proc.kill() + for proc in procs: + if proc is not None: + proc.wait() + + def _stream_tar_archive_to_encrypted_artifact( + self, + stage_dir: str, + archive_target: str, + out_data: str, + out_handle: str, + err_msg: str, + ) -> None: + """Archives and compresses stage_dir/archive_target into Tink AEAD output. + + Uses multi-threaded 'pigz' when enabled and available on PATH, falling back + to single-threaded 'tar -czf -' (gzip) otherwise, and verifies exit codes + of both 'tar' and 'pigz'. + """ + if not self._should_use_pigz(): + if self.use_pigz == 'true': + self.die( + f"{err_msg}: 'pigz' is not available on PATH while USE_PIGZ=true." + ) + cmd = ['tar', '-czf', '-', '-C', stage_dir, archive_target] + self._stream_command_to_encrypted_artifact( + cmd, out_data, out_handle, err_msg + ) + return + + tar_cmd = ['tar', '-cf', '-', '-C', stage_dir, archive_target] + pigz_cmd = ['pigz', '-c'] + if self.pigz_threads: + pigz_cmd.extend(['-p', str(self.pigz_threads)]) + self.log_debug( + f"Streaming archive '{archive_target}' via pigz " + f"(threads={self.pigz_threads or 'auto'}) -> '{out_data}'..." + ) + tar_proc: subprocess.Popen[Any] | None = None + pigz_proc: subprocess.Popen[Any] | None = None + tar_rc: int | None = None + pigz_rc: int | None = None + try: + tar_proc = subprocess.Popen(tar_cmd, stdout=subprocess.PIPE) + self._active_procs.append(tar_proc) + if tar_proc.stdout is None: + self.die(err_msg) + pigz_proc = subprocess.Popen( + pigz_cmd, stdin=tar_proc.stdout, stdout=subprocess.PIPE + ) + self._active_procs.append(pigz_proc) + tar_proc.stdout.close() # Ensure tar receives SIGPIPE if pigz exits. + if pigz_proc.stdout is None: + self.die(err_msg) + stream_encrypt(out_data, out_handle, input_stream=pigz_proc.stdout) + pigz_proc.stdout.close() + pigz_rc = pigz_proc.wait() + tar_rc = tar_proc.wait() + except SystemExit as err: + if self._cleaned_up: + raise + self._kill_and_reap((pigz_proc, tar_proc)) + self.die(f'{err_msg}: {err}') + except (OSError, ValueError, RuntimeError, tink.TinkError) as err: + self._kill_and_reap((pigz_proc, tar_proc)) + self.die(f'{err_msg}: {err}') + finally: + for proc, rc_val in ((pigz_proc, pigz_rc), (tar_proc, tar_rc)): + if proc is not None: + if proc.stdout is not None and not proc.stdout.closed: + proc.stdout.close() + if proc in self._active_procs: + self._active_procs.remove(proc) + if rc_val is None and proc.poll() is None: + proc.kill() + proc.wait() + + if tar_rc != 0 or pigz_rc != 0: + self.die(f'{err_msg} (tar exit={tar_rc}, pigz exit={pigz_rc}).') + def _perform_cleanup(self, exit_code: int) -> None: """Terminates child processes, scrubs secrets, and removes staging dirs.""" if self._cleaned_up: @@ -1051,6 +1149,154 @@ def validate_cli_tools(self) -> None: 'available on PATH.', ) + def _try_install_pigz(self) -> bool: + """Attempts to install 'pigz' via the OS package manager when missing.""" + if shutil.which('pigz') is not None: + return True + is_root = hasattr(os, 'geteuid') and os.geteuid() == 0 + interactive = self.auto_confirm != 'true' and sys.stdin.isatty() + apt_steps = ( + ('apt-get', 'update', '-qq'), + ('apt-get', 'install', '-y', '-qq', 'pigz'), + ) + pkg_managers: tuple[tuple[str, Sequence[Sequence[str]]], ...] = ( + ('apt-get', apt_steps), + ('dnf', (('dnf', 'install', '-y', '-q', 'pigz'),)), + ('yum', (('yum', 'install', '-y', '-q', 'pigz'),)), + ('zypper', (('zypper', '--non-interactive', 'install', 'pigz'),)), + ('apk', (('apk', 'add', '--no-cache', 'pigz'),)), + ) + mgr, steps, needs_root = next( + ((m, s, True) for m, s in pkg_managers if shutil.which(m)), + (None, (), True), + ) + if not mgr and not is_root and shutil.which('brew'): + mgr, steps, needs_root = 'brew', (('brew', 'install', 'pigz'),), False + if not mgr: + return False + + sudo_prefix: tuple[str, ...] = () + if needs_root and not is_root: + if not shutil.which('sudo'): + return False + if not interactive: + try: + probe = subprocess.run( + ['sudo', '-n', 'true'], + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5, + ) + except (OSError, subprocess.SubprocessError): + return False + if probe.returncode != 0: + return False + sudo_prefix = ('sudo', '-n') + else: + sudo_prefix = ('sudo',) + + if interactive: + sys.stderr.write( + f" [PROMPT] Install 'pigz' via '{mgr}' for parallel compression? " + '[y/N]: ' + ) + sys.stderr.flush() + if not re.fullmatch(r'[Yy]([Ee][Ss])?', sys.stdin.readline().strip()): + return False + + self.log_info(f"Installing 'pigz' via '{mgr}' for parallel compression...") + cmd_env = {**os.environ, 'DEBIAN_FRONTEND': 'noninteractive'} + for step in steps: + full_cmd = [*sudo_prefix, *step] + try: + proc = subprocess.run( + full_cmd, + check=False, + env=cmd_env if mgr == 'apt-get' else None, + stdin=None if interactive else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + timeout=120, + ) + except (OSError, subprocess.SubprocessError) as err: + self.log_warn(f"Failed executing '{' '.join(full_cmd)}': {err}") + return False + if proc.returncode != 0: + self.log_warn( + f"Command '{' '.join(full_cmd)}' failed (exit {proc.returncode})." + ) + return False + if shutil.which('pigz') is not None: + self.log_info("Successfully installed 'pigz'.") + return True + return False + + def validate_pigz(self) -> None: + """Validates USE_PIGZ/PIGZ_THREADS and installs or resolves pigz/gzip.""" + if self.use_pigz not in ('auto', 'true', 'false'): + self.preflight_fail( + 'Compression', + f"USE_PIGZ must be 'auto', 'true', or 'false' ('{self.use_pigz}').", + ) + return + if self.auto_install_pigz not in ('true', 'false'): + self.preflight_fail( + 'Compression', + "AUTO_INSTALL_PIGZ must be 'true' or 'false' " + f"('{self.auto_install_pigz}').", + ) + return + if self.pigz_threads and not re.fullmatch(r'[1-9]\d*', self.pigz_threads): + self.preflight_fail( + 'Compression', + f"PIGZ_THREADS must be an integer >= 1 ('{self.pigz_threads}').", + ) + return + if self.use_pigz == 'false': + if shutil.which('gzip'): + self.preflight_pass( + 'Compression', + "Single-threaded 'gzip' archive compression enabled " + '(USE_PIGZ=false).', + ) + else: + self.preflight_fail( + 'Compression', + "Missing required CLI binary 'gzip' on PATH when USE_PIGZ=false.", + ) + return + + if shutil.which('pigz') is None and self.auto_install_pigz == 'true': + self._try_install_pigz() + if shutil.which('pigz') is not None: + self.preflight_pass( + 'Compression', + "Parallel archive compression enabled with 'pigz' " + f"(threads={self.pigz_threads or 'auto'}).", + ) + elif self.use_pigz == 'true': + self.preflight_fail( + 'Compression', + "Missing required CLI binary 'pigz' on PATH when USE_PIGZ=true " + "(install 'pigz' or set USE_PIGZ=false).", + ) + elif shutil.which('gzip') is not None: + self.log_info( + "'pigz' not found on PATH; falling back to single-threaded 'gzip' " + "compression (install 'pigz' for faster multi-core packaging)." + ) + self.preflight_pass( + 'Compression', + "Single-threaded 'gzip' archive compression available on PATH.", + ) + else: + self.preflight_fail( + 'Compression', "Neither 'pigz' nor 'gzip' is available on PATH." + ) + def validate_mydumper(self) -> None: """Validates USE_MYDUMPER flags and mydumper >= 0.16.0 version.""" if self.use_mydumper not in ('true', 'false'): @@ -1815,6 +2061,12 @@ def print_normalized_inputs_and_confirm(self) -> None: if self.use_mydumper == 'true': self.log_info(f' MYDUMPER_THREADS : {self.mydumper_threads}') self.log_info(f' MYDUMPER_CHUNK_ROWS : {self.mydumper_chunk_rows}') + self.log_info(f' USE_PIGZ : {self.use_pigz}') + if self.use_pigz != 'false': + self.log_info( + f" PIGZ_THREADS : {self.pigz_threads or 'auto'}" + ) + self.log_info(f' AUTO_INSTALL_PIGZ : {self.auto_install_pigz}') self.log_info( f' KEEP_INTERMEDIATE_FILES : {self.keep_intermediate_files}' ) @@ -1886,6 +2138,7 @@ def run_preflight_validations(self) -> None: self.print_normalized_inputs_and_confirm() self.validate_cli_tools() + self.validate_pigz() self.validate_mydumper() self.validate_git_version() self.validate_python_environment() @@ -2191,17 +2444,17 @@ def encrypt_database_dump(self) -> None: self.log_debug( f'Packaging and encrypting MySQL database archive ({MYSQL_DATA_FILE}, ' - f'USE_MYDUMPER={self.use_mydumper})...' + f'USE_MYDUMPER={self.use_mydumper}, USE_PIGZ={self.use_pigz})...' ) if self.use_mydumper == 'true': - cmd = ['tar', '-czf', '-', '-C', self.mysql_stage_dir, '.'] + archive_target = '.' err_msg = 'Failed to package and encrypt mydumper database archive.' else: - cmd = ['tar', '-czf', '-', '-C', self.mysql_stage_dir, 'looker'] + archive_target = 'looker' err_msg = 'Failed to package and encrypt database dump.' - self._stream_command_to_encrypted_artifact( - cmd, out_data, out_handle, err_msg + self._stream_tar_archive_to_encrypted_artifact( + self.mysql_stage_dir, archive_target, out_data, out_handle, err_msg ) if self.keep_intermediate_files != 'true': @@ -2668,11 +2921,12 @@ def package_filesystem(self) -> None: out_handle = os.path.join(self.final_artifacts_dir, FS_HANDLE_FILE) self.log_debug( - f'Packaging and encrypting filesystem archive ({FS_DATA_FILE})...' + f'Packaging and encrypting filesystem archive ({FS_DATA_FILE}, ' + f'USE_PIGZ={self.use_pigz})...' ) - cmd = ['tar', '-czf', '-', '-C', self.intermediate_dir, 'modelshare'] - self._stream_command_to_encrypted_artifact( - cmd, + self._stream_tar_archive_to_encrypted_artifact( + self.intermediate_dir, + 'modelshare', out_data, out_handle, 'Failed to package and encrypt filesystem archive.', diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index b609f7e..946bf08 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -163,6 +163,7 @@ def get_aead(self, uri: str): gcpkms_mod.GcpKmsClient = _FakeGcpKmsClient integ_mod.gcpkms = gcpkms_mod + tink_mod.TinkError = type('TinkError', (Exception,), {}) tink_mod.KeysetHandle = _FakeHandle tink_mod.aead = aead_mod tink_mod.streaming_aead = saead_mod @@ -391,6 +392,123 @@ def test_append_setting_statements_uses_delete_and_insert_or_delete_only( "DELETE FROM `setting` WHERE `key` = 'closed_system';\n", ) + def test_validate_pigz_flags_threads_and_fallback(self): + with tempfile.TemporaryDirectory() as tmpdir: + for attr, bad_vals in ( + ('use_pigz', ('yes', '1', 'invalid')), + ('pigz_threads', ('0', '-4', 'abc')), + ('auto_install_pigz', ('invalid', '1')), + ): + for bad_val in bad_vals: + exp = self.exp.LookerExporter(backup_arg=tmpdir) + setattr(exp, attr, bad_val) + exp.validate_pigz() + self.assertEqual(exp.preflight_fail_count, 1) + + which_gzip_only = lambda b: '/bin/gzip' if b == 'gzip' else None + for mode, expected_fails, expected_passes in ( + ('true', 1, 0), + ('auto', 0, 1), + ): + exp = self.exp.LookerExporter(backup_arg=tmpdir) + exp.use_pigz, exp.auto_install_pigz = mode, 'false' + with mock.patch.object(shutil, 'which', side_effect=which_gzip_only): + exp.validate_pigz() + self.assertEqual(exp.preflight_fail_count, expected_fails) + self.assertEqual(exp.preflight_pass_count, expected_passes) + + def test_try_install_pigz_uses_apt_get_or_skips_without_passwordless_sudo( + self, + ): + with tempfile.TemporaryDirectory() as tmpdir: + exp = self.exp.LookerExporter(backup_arg=tmpdir) + exp.use_pigz, exp.auto_install_pigz = 'auto', 'true' + exp.auto_confirm = 'true' + installed = {'done': False} + cmds: list[list[str]] = [] + + def _which(b: str) -> str | None: + if b == 'pigz': + return '/usr/bin/pigz' if installed['done'] else None + return f'/usr/bin/{b}' if b in ('apt-get', 'sudo', 'gzip') else None + + def _run(cmd, **kw): + cmds.append(list(cmd)) + if 'install' in cmd and 'pigz' in cmd: + self.assertEqual(kw['env']['DEBIAN_FRONTEND'], 'noninteractive') + installed['done'] = True + return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') + + with ( + mock.patch.object(shutil, 'which', side_effect=_which), + mock.patch.object(os, 'geteuid', return_value=1000), + mock.patch.object(subprocess, 'run', side_effect=_run), + ): + exp.validate_pigz() + self.assertTrue(installed['done']) + self.assertEqual( + cmds, + [ + ['sudo', '-n', 'true'], + ['sudo', '-n', 'apt-get', 'update', '-qq'], + ['sudo', '-n', 'apt-get', 'install', '-y', '-qq', 'pigz'], + ], + ) + + exp2 = self.exp.LookerExporter(backup_arg=tmpdir) + exp2.use_pigz, exp2.auto_install_pigz = 'auto', 'true' + exp2.auto_confirm = 'true' + denied_cmds: list[list[str]] = [] + which_no_pigz = lambda b: ( + f'/usr/bin/{b}' if b in ('apt-get', 'sudo', 'gzip') else None + ) + run_fail = lambda c, **_: ( + denied_cmds.append(list(c)) + or subprocess.CompletedProcess(c, 1, stdout='', stderr='') + ) + with ( + mock.patch.object(shutil, 'which', side_effect=which_no_pigz), + mock.patch.object(os, 'geteuid', return_value=1000), + mock.patch.object(subprocess, 'run', side_effect=run_fail), + ): + exp2.validate_pigz() + self.assertEqual(denied_cmds, [['sudo', '-n', 'true']]) + self.assertEqual(exp2.preflight_pass_count, 1) + + def test_stream_tar_archive_with_pigz_aborts_when_tar_exits_nonzero(self): + with tempfile.TemporaryDirectory() as tmpdir: + fake_bin, stage_dir = os.path.join(tmpdir, 'b'), os.path.join(tmpdir, 's') + os.makedirs(fake_bin) + os.makedirs(stage_dir) + scripts = { + 'tar': '#!/usr/bin/env python3\nimport sys\nsys.exit(2)\n', + 'pigz': ( + '#!/usr/bin/env python3\nimport gzip, sys\n' + 'sys.stdout.buffer.write(gzip.compress(sys.stdin.buffer.read()))\n' + ), + } + for name, body in scripts.items(): + path = os.path.join(fake_bin, name) + with open(path, 'w', encoding='utf-8') as fh: + fh.write(body) + os.chmod(path, 0o700) + + exp = self.exp.LookerExporter(backup_arg=tmpdir) + exp.use_pigz, exp.pigz_threads = 'true', '2' + new_path = f"{fake_bin}:{os.environ.get('PATH', '')}" + with ( + mock.patch.dict(os.environ, {'PATH': new_path}, clear=False), + mock.patch.object(self.exp, 'get_clean_kms_key', return_value='k'), + mock.patch.object( + self.exp, '_wrap_dek_with_tink_kms', return_value=b'H' + ), + self.assertRaises(SystemExit) as ctx, + ): + exp._stream_tar_archive_to_encrypted_artifact( + stage_dir, 'missing', f'{tmpdir}/d', f'{tmpdir}/h', 'Archive error' + ) + self.assertEqual(ctx.exception.code, 1) + class CollectDiagnosticsTest(unittest.TestCase): """Tests collect_looker_diagnostics.py filesystem/report behavior.""" @@ -695,6 +813,8 @@ def _create_hermetic_fixture(self, tmpdir: str) -> dict[str, str]: ) as f: f.write( 'import types\n' + 'class TinkError(Exception):\n' + ' pass\n\n' 'class _PassThroughStream:\n' ' def __init__(self, dst):\n' ' self._dst = dst\n' @@ -1062,6 +1182,68 @@ def test_mydumper_export_uses_secure_backtick_cnf_and_post_sql(self): self.assertNotIn('utf8mb4_uca1400_ai_ci', decompressed_schema) self.assertNotIn('enable the sandbox mode', decompressed_schema) + @unittest.skipUnless(shutil.which('pigz'), 'Requires pigz binary on PATH') + def test_pigz_parallel_compression_and_use_pigz_false_override(self): + with tempfile.TemporaryDirectory() as tmpdir: + fx = self._create_hermetic_fixture(tmpdir) + base_env = { + **os.environ, + 'PATH': f"{fx['bin_dir']}:{os.environ.get('PATH', '')}", + 'PYTHONPATH': fx['pylib_dir'], + 'ON_PREM_LOOKER_DATA_DIR': fx['onprem'], + 'DB_HOST': '127.0.0.1', + 'DB_PORT': '3306', + 'DB_USER': 'looker', + 'DB_NAME': 'looker', + 'MYSQL_PWD': 's3cr3t_pw', + 'LOOKER_MASTER_KEY': base64.b64encode(b'K' * 32).decode('ascii'), + 'KMS_KEY_NAME': ( + 'projects/p1/locations/us-central1/keyRings/r1/cryptoKeys/k1' + ), + 'USE_MYDUMPER': 'false', + 'AUTO_CONFIRM': 'true', + } + + for sub, cfg, expect_str, forbid_str in ( + ( + 'pigz', + {'USE_PIGZ': 'true', 'PIGZ_THREADS': '2'}, + "Parallel archive compression enabled with 'pigz' (threads=2).", + None, + ), + ( + 'gzip', + {'USE_PIGZ': 'false'}, + "Single-threaded 'gzip' archive compression enabled" + ' (USE_PIGZ=false).', + 'via pigz', + ), + ): + bdir = os.path.join(tmpdir, f'backup_{sub}') + proc = subprocess.run( + [sys.executable, LOOKER_EXPORT_PY], + env={**base_env, 'BACKUP_DIR': bdir, **cfg}, + check=False, + capture_output=True, + text=True, + ) + self.assertEqual(proc.returncode, 0, msg=proc.stderr) + with open(os.path.join(bdir, 'looker_export.log'), encoding='utf-8') as f: + log_text = f.read() + self.assertIn(expect_str, log_text) + if forbid_str: + self.assertNotIn(forbid_str, log_text) + else: + self.assertIn("Streaming archive 'looker' via pigz (threads=2)", log_text) + self.assertIn( + "Streaming archive 'modelshare' via pigz (threads=2)", log_text + ) + fdir = os.path.join(bdir, 'final_artifacts') + with tarfile.open(os.path.join(fdir, 'mysql-data'), 'r:gz') as tf: + self.assertEqual(tf.getnames(), ['looker']) + with tarfile.open(os.path.join(fdir, 'fs-data'), 'r:gz') as tf: + self.assertTrue(any(n.startswith('modelshare') for n in tf.getnames())) + if __name__ == '__main__': unittest.main() From 17b5c25b53210444f1c3146ed86ec0c01c5bb3dc Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Tue, 24 Nov 2026 15:28:55 +0000 Subject: [PATCH 2/7] feat(export-to-core): emit exportMetrics, replicas, and instanceInfra in metadata.json --- export-to-core/README.md | 10 +- export-to-core/looker_export.py | 358 ++++++++++++++++++++ export-to-core/tests/test_export_to_core.py | 64 ++++ 3 files changed, 430 insertions(+), 2 deletions(-) diff --git a/export-to-core/README.md b/export-to-core/README.md index 3c5a91c..d14a448 100644 --- a/export-to-core/README.md +++ b/export-to-core/README.md @@ -189,6 +189,10 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a | `EXCLUDE_MARKETPLACE` | Set to `true` to exclude Looker Marketplace directories and tables from the export. | `false` | | `DISABLE_SCHEDULED_PLANS` | Set `scheduled_plan.enabled = FALSE` in the exported database artifact (leaves live source DB untouched) to prevent automatic runs immediately after import. | `true` | | `LOOKER_INSTANCE_ID` | Optional source identifier recorded as `looker_instance` in `metadata.json`. | `onprem-export` | +| `LOOKER_REPLICAS` | Optional cluster node/replica count recorded in `instanceInfra` for Looker (Google Cloud core) import sizing (auto-detected from active `node` table heartbeats when unset). | *(auto)* | +| `LOOKER_CPUS` | Optional per-node CPU count recorded in `instanceInfra` (auto-detected from host logical vCPUs when unset). | *(auto)* | +| `LOOKER_MEMORY_GB` | Optional per-node memory in GiB recorded in `instanceInfra` (auto-detected from running Looker JVM `-Xmx` or host `MemTotal` when unset). | *(auto)* | +| `LOOKER_STARTUP_ARGS` | Optional Looker startup flags recorded in `instanceInfra.commandLineArgs` with sensitive values redacted (auto-detected from running Looker JVM when unset). | *(auto)* | | `AUTO_CONFIRM` | Set to `true` to skip interactive confirmation prompts (for non-interactive automation). | `false` | | `DEBUG_LOG_ENABLED` | Write verbose `DEBUG` trace entries to `${BACKUP_DIR}/looker_export.log`. | `true` | | `KEEP_INTERMEDIATE_FILES` | Retain unencrypted staging directories under `${BACKUP_DIR}/intermediate/` after exit (debugging only). | `false` | @@ -211,13 +215,15 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a ## Output Artifacts -Upon successful completion, `looker_export.py` generates five files in `${BACKUP_DIR}/final_artifacts/`: +Upon successful completion, `looker_export.py` generates seven files in `${BACKUP_DIR}/final_artifacts/`: - `fs-data`: Tink Streaming AEAD-encrypted `.tar.gz` archive containing normalized LookML Git and Looker file system directories. - `fs-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `fs-data`. - `mysql-data`: Tink Streaming AEAD-encrypted `.tar.gz` archive containing the Looker database export (`mysqldump` SQL dump or `mydumper` + `zstd` archive). - `mysql-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `mysql-data`. -- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, and exported `file_paths`. +- `export_info.json.enc`: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) and `componentConfigs`. +- `export_info-handle.enc`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `export_info.json.enc`. +- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, `exportMetrics` (component `sizeGb` and durations for `ALL`, `DB`, and `FS`), and `instanceInfra` / `componentConfigs` for Looker (Google Cloud core) import sizing and tiering. All output artifacts are created with strict owner-only permissions (`0600`). diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index e889d18..d75d9f8 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -68,6 +68,8 @@ FS_HANDLE_FILE = 'fs-handle' MYSQL_DATA_FILE = 'mysql-data' MYSQL_HANDLE_FILE = 'mysql-handle' +EXPORT_INFO_FILE = 'export_info.json.enc' +EXPORT_INFO_HANDLE_FILE = 'export_info-handle.enc' METADATA_FILE = 'metadata.json' REQUIRED_INPUT_VARS = ( @@ -196,6 +198,10 @@ ) _ID_RSA_BAK_RE = re.compile(r'/id_rsa\.bak([\s"\']|$)', re.MULTILINE) _SCP_STYLE_REMOTE_RE = re.compile(r'^[^/]+@[^:]+:') +_XMX_RE = re.compile(r'(?:^|\s)-Xmx(\d+)([kKmMgGtT])(?=\s|$)') +_SENSITIVE_ARG_RE = re.compile( + r'(?i)(password|passwd|pwd|secret|token|master[_-]?key|credential|key)' +) _USAGE_TEXT = """\ Usage: ./looker_export.py [BACKUP_DIR] @@ -226,6 +232,10 @@ EXCLUDE_MARKETPLACE (default: false) DISABLE_SCHEDULED_PLANS (default: true) LOOKER_INSTANCE_ID (default: onprem-export) + LOOKER_REPLICAS (optional override; auto-detected from node table) + LOOKER_CPUS (optional override; auto-detected from host vCPUs) + LOOKER_MEMORY_GB (optional override; auto-detected from JVM/RAM) + LOOKER_STARTUP_ARGS (optional override; auto-detected from Looker JVM) KEEP_INTERMEDIATE_FILES (default: false) DEBUG_LOG_ENABLED (default: true) AUTO_CONFIRM (default: false) @@ -713,6 +723,62 @@ def _resolve_env_with_alias( return default_value +def _parse_jvm_xmx_gb(cmd_line: str) -> float | None: + """Extracts JVM -Xmx heap size in GiB from a command line, if present.""" + match = _XMX_RE.search(cmd_line) + if not match: + return None + amount = int(match.group(1)) + unit = match.group(2).lower() + multipliers = { + 'k': 1.0 / (1024.0 * 1024.0), + 'm': 1.0 / 1024.0, + 'g': 1.0, + 't': 1024.0, + } + return round(amount * multipliers[unit], 2) + + +def _sanitize_command_line_args(raw_args: str) -> str: + """Redacts sensitive flag values from captured Looker startup arguments.""" + tokens = raw_args.strip().split() + sanitized: list[str] = [] + redact_next = False + for tok in tokens: + if redact_next: + sanitized.append('REDACTED') + redact_next = False + continue + if '=' in tok: + flag_name, _ = tok.split('=', 1) + if _SENSITIVE_ARG_RE.search(flag_name): + sanitized.append(f'{flag_name}=REDACTED') + continue + elif tok in ('-p', '--password') or ( + tok.startswith('-') and _SENSITIVE_ARG_RE.search(tok) + ): + sanitized.append(tok) + redact_next = True + continue + sanitized.append(tok) + return ' '.join(sanitized) + + +def _format_rfc3339_utc(dt_val: datetime.datetime) -> str: + """Formats a UTC datetime as RFC 3339 with trailing Z.""" + return dt_val.astimezone(datetime.timezone.utc).strftime( + '%Y-%m-%dT%H:%M:%SZ' + ) + + +def _format_proto_duration( + start_dt: datetime.datetime, end_dt: datetime.datetime +) -> str: + """Formats elapsed duration between two timestamps as ProtoJSON 's'.""" + elapsed = max(0.0, (end_dt - start_dt).total_seconds()) + return f'{elapsed:.3f}s' + + # ============================================================================== # 3. Unified Export Orchestrator # ============================================================================== @@ -753,6 +819,16 @@ def __init__(self, backup_arg: str | None = None) -> None: self.looker_instance_id = ( os.environ.get('LOOKER_INSTANCE_ID') or 'onprem-export' ) + self.looker_replicas_override = ( + os.environ.get('LOOKER_REPLICAS') or '' + ).strip() + self.looker_cpus_override = (os.environ.get('LOOKER_CPUS') or '').strip() + self.looker_memory_gb_override = ( + os.environ.get('LOOKER_MEMORY_GB') or '' + ).strip() + self.looker_startup_args_override = ( + os.environ.get('LOOKER_STARTUP_ARGS') or '' + ).strip() self.exclude_marketplace = os.environ.get('EXCLUDE_MARKETPLACE') or 'false' self.disable_scheduled_plans = ( @@ -805,6 +881,18 @@ def __init__(self, backup_arg: str | None = None) -> None: self.db_connection_verified = False self.active_encrypted_kek = '' self.estimated_db_kb = 0 + self.detected_replicas = 1 + self.detected_cpus = float(os.cpu_count() or 1) + self.detected_memory_gb = 0.0 + self.detected_limit_memory_gb = 0.0 + self.detected_command_line_args = '' + self.export_start_dt: datetime.datetime | None = None + self.db_export_start_dt: datetime.datetime | None = None + self.db_export_end_dt: datetime.datetime | None = None + self.fs_export_start_dt: datetime.datetime | None = None + self.fs_export_end_dt: datetime.datetime | None = None + self.exported_db_bytes = 0 + self.exported_fs_bytes = 0 self.dumped_tables: list[str] = [] self.excluded_tables: list[str] = [] self.schema_only_tables_existing: list[str] = [] @@ -1980,6 +2068,142 @@ def discover_database_tables(self) -> None: f"plus filtered '{SETTING_DB_TABLE}'.", ) + def _detect_host_memory_gb(self) -> float: + """Returns total host physical RAM in GiB from /proc/meminfo or sysconf.""" + try: + if os.path.isfile('/proc/meminfo'): + with open('/proc/meminfo', encoding='utf-8') as mem_file: + for line in mem_file: + if line.startswith('MemTotal:'): + parts = line.split() + if len(parts) >= 2 and parts[1].isdigit(): + return round(int(parts[1]) / (1024.0 * 1024.0), 2) + except OSError: + pass + try: + page_size = os.sysconf('SC_PAGE_SIZE') + phys_pages = os.sysconf('SC_PHYS_PAGES') + if isinstance(page_size, int) and isinstance(phys_pages, int): + if page_size > 0 and phys_pages > 0: + return round((page_size * phys_pages) / float(1024**3), 2) + except (AttributeError, OSError, ValueError): + pass + return 0.0 + + def _detect_running_looker_jvm(self) -> tuple[float | None, str]: + """Inspects local processes for a running Looker JVM (-Xmx & args).""" + if not shutil.which('ps'): + return None, '' + try: + res = subprocess.run( + ['ps', '-eo', 'args'], + check=False, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + ) + except OSError: + return None, '' + if res.returncode != 0 or not res.stdout: + return None, '' + for raw_line in res.stdout.splitlines(): + line = raw_line.strip() + if 'java' in line and 'looker.jar' in line: + return _parse_jvm_xmx_gb(line), _sanitize_command_line_args(line) + return None, '' + + def discover_source_infra(self) -> None: + """Detects source Looker replica count, CPUs, memory, and startup flags.""" + replicas = 1 + if self.looker_replicas_override: + try: + replicas = max(1, int(self.looker_replicas_override)) + except ValueError: + self.preflight_warn( + 'Source Infrastructure', + f"Invalid LOOKER_REPLICAS='{self.looker_replicas_override}'; " + 'falling back to database node discovery.', + ) + self.looker_replicas_override = '' + + if not self.looker_replicas_override and self.db_connection_verified: + active_res = self.run_mysql_query( + 'SELECT COUNT(*) FROM `node` ' + 'WHERE `last_heartbeat` >= NOW() - INTERVAL 15 MINUTE;' + ) + parsed_count = 0 + if active_res.returncode == 0: + out_str = (active_res.stdout or '').strip() + if out_str.isdigit(): + parsed_count = int(out_str) + if parsed_count <= 0: + total_res = self.run_mysql_query('SELECT COUNT(*) FROM `node`;') + if total_res.returncode == 0: + out_str = (total_res.stdout or '').strip() + if out_str.isdigit(): + parsed_count = int(out_str) + if parsed_count > 0: + replicas = parsed_count + self.detected_replicas = max(1, replicas) + + cpus = float(os.cpu_count() or 1) + if self.looker_cpus_override: + try: + cpus = max(0.1, float(self.looker_cpus_override)) + except ValueError: + self.preflight_warn( + 'Source Infrastructure', + f"Invalid LOOKER_CPUS='{self.looker_cpus_override}'; " + f'using host vCPU count ({cpus}).', + ) + self.detected_cpus = round(cpus, 2) + + host_mem_gb = self._detect_host_memory_gb() + jvm_xmx_gb, jvm_cmd_args = self._detect_running_looker_jvm() + mem_gb = jvm_xmx_gb if jvm_xmx_gb is not None else host_mem_gb + if self.looker_memory_gb_override: + try: + mem_gb = max(0.1, float(self.looker_memory_gb_override)) + except ValueError: + self.preflight_warn( + 'Source Infrastructure', + f"Invalid LOOKER_MEMORY_GB='{self.looker_memory_gb_override}'; " + f'using detected memory ({mem_gb} GiB).', + ) + self.detected_memory_gb = round(mem_gb, 2) + self.detected_limit_memory_gb = round(max(host_mem_gb, mem_gb), 2) + + if self.looker_startup_args_override: + self.detected_command_line_args = _sanitize_command_line_args( + self.looker_startup_args_override + ) + else: + self.detected_command_line_args = jvm_cmd_args + + self.log_debug( + 'Detected source Looker infrastructure: ' + f'replicas={self.detected_replicas}, cpus={self.detected_cpus}, ' + f'memory_gb={self.detected_memory_gb}, ' + f'limit_memory_gb={self.detected_limit_memory_gb}' + ) + + @staticmethod + def _calculate_dir_size_bytes(target_dir: str) -> int: + """Computes total bytes of regular non-symlink files in target_dir.""" + if not target_dir or not os.path.isdir(target_dir): + return 0 + total = 0 + for root, _, files in os.walk(target_dir, followlinks=False): + for f_name in files: + f_full = os.path.join(root, f_name) + if os.path.islink(f_full): + continue + try: + total += os.lstat(f_full).st_size + except OSError: + pass + return total + def _calculate_fs_size_kb(self) -> int: """Computes total uncompressed size (in KB) of allowed Looker subdirs.""" if not self.on_prem_real_path: @@ -2149,6 +2373,7 @@ def run_preflight_validations(self) -> None: self.validate_looker_version() self.validate_master_key_kek() self.discover_database_tables() + self.discover_source_infra() self.validate_free_diskspace() self.print_validation_summary_and_confirm() @@ -2462,6 +2687,7 @@ def encrypt_database_dump(self) -> None: def export_database(self) -> None: """Exports and encrypts the Looker MySQL/MariaDB database.""" + self.db_export_start_dt = datetime.datetime.now(datetime.timezone.utc) os.makedirs(self.mysql_stage_dir, exist_ok=True) self.log_info( f"Exporting and encrypting database '{self.db_name}' " @@ -2471,7 +2697,10 @@ def export_database(self) -> None: self.export_database_with_mydumper() else: self.export_database_with_mysqldump() + staged_db_bytes = self._calculate_dir_size_bytes(self.mysql_stage_dir) + self.exported_db_bytes = max(staged_db_bytes, self.estimated_db_kb * 1024) self.encrypt_database_dump() + self.db_export_end_dt = datetime.datetime.now(datetime.timezone.utc) self.log_info( f'Database export completed ({MYSQL_DATA_FILE}, {MYSQL_HANDLE_FILE}).' ) @@ -2934,13 +3163,16 @@ def package_filesystem(self) -> None: def export_filesystem(self) -> None: """Stages, prunes, normalizes Git repos, and encrypts the filesystem.""" + self.fs_export_start_dt = datetime.datetime.now(datetime.timezone.utc) self.log_info( 'Exporting, normalizing, and encrypting Looker filesystem...' ) self.stage_filesystem() self.prune_staging_filesystem() self.normalize_git_repositories() + self.exported_fs_bytes = self._calculate_dir_size_bytes(self.fs_stage_dir) self.package_filesystem() + self.fs_export_end_dt = datetime.datetime.now(datetime.timezone.utc) self.log_info( f'Filesystem export completed ({FS_DATA_FILE}, {FS_HANDLE_FILE}).' ) @@ -2948,6 +3180,120 @@ def export_filesystem(self) -> None: # ============================================================================ # Metadata Generation & Main Execution # ============================================================================ + def _build_instance_infra_payload(self) -> dict[str, Any]: + """Builds InstanceInfra JSON payload matching export_info.proto.""" + deployment_cfg: dict[str, Any] = { + 'type': 'LOOKER', + 'cpus': self.detected_cpus, + 'memoryGb': self.detected_memory_gb, + 'replicas': self.detected_replicas, + 'limitCpu': self.detected_cpus, + 'limitMemoryGb': self.detected_limit_memory_gb, + } + infra_payload: dict[str, Any] = { + 'deploymentConfigs': [deployment_cfg], + } + if self.detected_command_line_args: + infra_payload['commandLineArgs'] = self.detected_command_line_args + return infra_payload + + def _build_component_configs_payload(self) -> list[dict[str, Any]]: + """Builds ComponentConfig list matching export_info.proto.""" + mysql_export_type = ( + 'MYDUMPER' if self.use_mydumper == 'true' else 'MYSQLDUMP' + ) + return [ + { + 'type': 'DB', + 'identifier': self.db_name, + 'exportType': { + 'mysqlExportType': mysql_export_type, + }, + }, + { + 'type': 'FS', + 'identifier': ( + self.on_prem_real_path or self.on_prem_looker_data_path + ), + 'exportType': { + 'filesystemExportType': 'ARCHIVE', + }, + }, + ] + + def generate_export_info(self) -> None: + """Encrypts ExportInfo (instanceInfra, replicas, componentConfigs).""" + out_data = os.path.join(self.final_artifacts_dir, EXPORT_INFO_FILE) + out_handle = os.path.join(self.final_artifacts_dir, EXPORT_INFO_HANDLE_FILE) + self.log_info( + f'Generating encrypted source infrastructure metadata ' + f'({EXPORT_INFO_FILE}, {EXPORT_INFO_HANDLE_FILE})...' + ) + export_info_payload: dict[str, Any] = { + 'sourceInstance': self.looker_instance_id or 'onprem-export', + 'instanceInfra': self._build_instance_infra_payload(), + 'componentConfigs': self._build_component_configs_payload(), + } + raw_bytes = (json.dumps(export_info_payload, indent=2) + '\n').encode( + 'utf-8' + ) + try: + stream_encrypt( + out_data, out_handle, input_stream=io.BytesIO(raw_bytes) + ) + except ( + SystemExit, + Exception, # pylint: disable=broad-exception-caught + ) as err: + self.die(f'Failed to encrypt export info metadata: {err}') + + def _build_export_metrics_payload( + self, now_dt: datetime.datetime + ) -> dict[str, Any]: + """Builds ExportMetrics JSON payload matching export_metadata.proto.""" + overall_start = self.export_start_dt or self.db_export_start_dt or now_dt + db_start = self.db_export_start_dt or overall_start + db_end = self.db_export_end_dt or now_dt + fs_start = self.fs_export_start_dt or db_end + fs_end = self.fs_export_end_dt or now_dt + + gib = float(1024**3) + db_size_gb = round(self.exported_db_bytes / gib, 6) + fs_size_gb = round(self.exported_fs_bytes / gib, 6) + all_size_gb = round( + (self.exported_db_bytes + self.exported_fs_bytes) / gib, 6 + ) + + return { + 'instanceInternalName': self.looker_instance_id or 'onprem-export', + 'componentMetrics': [ + { + 'type': 'ALL', + 'sizeGb': all_size_gb, + 'duration': _format_proto_duration(overall_start, now_dt), + 'retryCount': 0, + 'startTime': _format_rfc3339_utc(overall_start), + 'endTime': _format_rfc3339_utc(now_dt), + }, + { + 'type': 'DB', + 'sizeGb': db_size_gb, + 'duration': _format_proto_duration(db_start, db_end), + 'retryCount': 0, + 'startTime': _format_rfc3339_utc(db_start), + 'endTime': _format_rfc3339_utc(db_end), + }, + { + 'type': 'FS', + 'sizeGb': fs_size_gb, + 'duration': _format_proto_duration(fs_start, fs_end), + 'retryCount': 0, + 'startTime': _format_rfc3339_utc(fs_start), + 'endTime': _format_rfc3339_utc(fs_end), + }, + ], + } + def generate_metadata_json(self) -> None: """Writes final_artifacts/metadata.json compatible with Looker Core SLM.""" out_meta = os.path.join(self.final_artifacts_dir, METADATA_FILE) @@ -2960,6 +3306,10 @@ def generate_metadata_json(self) -> None: self.die(f'Failed to generate encryption metadata: {err}') return + now_dt = datetime.datetime.now(datetime.timezone.utc) + start_dt = self.export_start_dt or now_dt + export_time_us = str(int(start_dt.timestamp() * 1_000_000)) + metadata_payload = { 'looker_instance': self.looker_instance_id or 'onprem-export', 'looker_version': self.detected_looker_version or 'unknown', @@ -2973,7 +3323,13 @@ def generate_metadata_json(self) -> None: FS_HANDLE_FILE, MYSQL_DATA_FILE, MYSQL_HANDLE_FILE, + EXPORT_INFO_FILE, + EXPORT_INFO_HANDLE_FILE, ], + 'exportTime': export_time_us, + 'exportMetrics': self._build_export_metrics_payload(now_dt), + 'instanceInfra': self._build_instance_infra_payload(), + 'componentConfigs': self._build_component_configs_payload(), } with open(out_meta, 'w', encoding='utf-8') as mf: json.dump(metadata_payload, mf, indent=2) @@ -3012,8 +3368,10 @@ def run(self) -> None: os.chmod(self.intermediate_dir, 0o700) os.chmod(self.final_artifacts_dir, 0o700) + self.export_start_dt = datetime.datetime.now(datetime.timezone.utc) self.export_database() self.export_filesystem() + self.generate_export_info() self.generate_metadata_json() self.log_info('=== Looker Migration Export Completed Successfully ===') diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index 946bf08..138845b 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -321,6 +321,7 @@ def _worker() -> None: mock.patch.object(exporter, 'run_preflight_validations'), mock.patch.object(exporter, 'export_database'), mock.patch.object(exporter, 'export_filesystem'), + mock.patch.object(exporter, 'generate_export_info'), mock.patch.object(exporter, 'generate_metadata_json'), mock.patch.object(exporter, 'cleanup'), ): @@ -509,6 +510,40 @@ def test_stream_tar_archive_with_pigz_aborts_when_tar_exits_nonzero(self): ) self.assertEqual(ctx.exception.code, 1) + def test_discover_source_infra_and_sanitize_jvm_args(self): + with tempfile.TemporaryDirectory() as tmpdir: + exp = self.exp.LookerExporter(backup_arg=tmpdir) + exp.db_connection_verified = True + fake_ps = ( + 'java -Xmx24g -Xms12g --db-password=topsecret ' + '-p my_pwd -jar looker.jar start --clustered\n' + ) + with ( + mock.patch.object( + exp, + 'run_mysql_query', + return_value=subprocess.CompletedProcess([], 0, stdout='4\n'), + ), + mock.patch.object(exp, '_detect_host_memory_gb', return_value=64.0), + mock.patch.object( + subprocess, + 'run', + return_value=subprocess.CompletedProcess( + ['ps'], 0, stdout=fake_ps + ), + ), + ): + exp.discover_source_infra() + + self.assertEqual(exp.detected_replicas, 4) + self.assertEqual(exp.detected_memory_gb, 24.0) + self.assertEqual(exp.detected_limit_memory_gb, 64.0) + self.assertNotIn('topsecret', exp.detected_command_line_args) + self.assertNotIn('my_pwd', exp.detected_command_line_args) + self.assertIn('--db-password=REDACTED', exp.detected_command_line_args) + self.assertIn('-p REDACTED', exp.detected_command_line_args) + self.assertIn('--clustered', exp.detected_command_line_args) + class CollectDiagnosticsTest(unittest.TestCase): """Tests collect_looker_diagnostics.py filesystem/report behavior.""" @@ -868,6 +903,8 @@ def _create_hermetic_fixture(self, tmpdir: str) -> dict[str, str]: ' print("\'canary_cipher_val\'")\n' 'elif "closed_system" in query:\n' ' print("\'true\'")\n' + 'elif "`node`" in query:\n' + ' print("3")\n' ) os.chmod(fake_mysql, 0o700) @@ -995,6 +1032,8 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): 'fs-handle', 'mysql-data', 'mysql-handle', + 'export_info.json.enc', + 'export_info-handle.enc', 'metadata.json', ): artifact = os.path.join(final_dir, name) @@ -1011,6 +1050,31 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): meta['export_encryption_key']['cmek'], 'projects/p1/locations/us-central1/keyRings/r1/cryptoKeys/k1', ) + self.assertIn('export_info.json.enc', meta['file_paths']) + self.assertIn('export_info-handle.enc', meta['file_paths']) + self.assertTrue(str(meta['exportTime']).isdigit()) + comp_by_type = { + c['type']: c for c in meta['exportMetrics']['componentMetrics'] + } + self.assertEqual(set(comp_by_type), {'ALL', 'DB', 'FS'}) + self.assertGreater(comp_by_type['DB']['sizeGb'], 0) + self.assertEqual( + meta['instanceInfra']['deploymentConfigs'][0]['replicas'], 3 + ) + self.assertEqual( + meta['instanceInfra']['deploymentConfigs'][0]['type'], 'LOOKER' + ) + with open( + os.path.join(final_dir, 'export_info.json.enc'), encoding='utf-8' + ) as eif: + export_info = json.load(eif) + self.assertEqual( + export_info['instanceInfra']['deploymentConfigs'][0]['replicas'], 3 + ) + self.assertEqual( + export_info['componentConfigs'][0]['exportType']['mysqlExportType'], + 'MYSQLDUMP', + ) with tarfile.open(os.path.join(final_dir, 'mysql-data'), 'r:gz') as tf: self.assertEqual(tf.getnames(), ['looker']) From b34b724010c349b35028f090c5136ee53237bdbb Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Tue, 24 Nov 2026 17:33:31 +0000 Subject: [PATCH 3/7] fix(export-to-core): address PR review comments and document On-Prem tier upgrade semantics --- export-to-core/README.md | 5 +- export-to-core/looker_export.py | 115 +++++++++++++++--- export-to-core/tests/test_export_to_core.py | 122 +++++++++++++++++++- 3 files changed, 220 insertions(+), 22 deletions(-) diff --git a/export-to-core/README.md b/export-to-core/README.md index d14a448..649ce00 100644 --- a/export-to-core/README.md +++ b/export-to-core/README.md @@ -189,7 +189,8 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a | `EXCLUDE_MARKETPLACE` | Set to `true` to exclude Looker Marketplace directories and tables from the export. | `false` | | `DISABLE_SCHEDULED_PLANS` | Set `scheduled_plan.enabled = FALSE` in the exported database artifact (leaves live source DB untouched) to prevent automatic runs immediately after import. | `true` | | `LOOKER_INSTANCE_ID` | Optional source identifier recorded as `looker_instance` in `metadata.json`. | `onprem-export` | -| `LOOKER_REPLICAS` | Optional cluster node/replica count recorded in `instanceInfra` for Looker (Google Cloud core) import sizing (auto-detected from active `node` table heartbeats when unset). | *(auto)* | +| `EXPORT_INSTANCE_INFRA` | Set to `true` to include source infrastructure sizing (`instanceInfra` in `metadata.json` and `export_info.json.enc`). **Note:** `instanceInfra` is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs (never downgrading larger target instances); if not specified (`EXPORT_INSTANCE_INFRA=false`), the import lands on the default infrastructure that Looker (Google Cloud core) provides. | `true` | +| `LOOKER_REPLICAS` | Optional cluster node/replica count recorded in `instanceInfra` for Looker (Google Cloud core) import tier upgrade (auto-detected from active `node` table heartbeats when unset). | *(auto)* | | `LOOKER_CPUS` | Optional per-node CPU count recorded in `instanceInfra` (auto-detected from host logical vCPUs when unset). | *(auto)* | | `LOOKER_MEMORY_GB` | Optional per-node memory in GiB recorded in `instanceInfra` (auto-detected from running Looker JVM `-Xmx` or host `MemTotal` when unset). | *(auto)* | | `LOOKER_STARTUP_ARGS` | Optional Looker startup flags recorded in `instanceInfra.commandLineArgs` with sensitive values redacted (auto-detected from running Looker JVM when unset). | *(auto)* | @@ -223,7 +224,7 @@ Upon successful completion, `looker_export.py` generates seven files in `${BACKU - `mysql-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `mysql-data`. - `export_info.json.enc`: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) and `componentConfigs`. - `export_info-handle.enc`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `export_info.json.enc`. -- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, `exportMetrics` (component `sizeGb` and durations for `ALL`, `DB`, and `FS`), and `instanceInfra` / `componentConfigs` for Looker (Google Cloud core) import sizing and tiering. +- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, `exportMetrics` (component `sizeGb` and durations for `ALL`, `DB`, and `FS`), `componentConfigs`, and (when `EXPORT_INSTANCE_INFRA=true`) `instanceInfra` — which is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs, landing on the default infrastructure Looker (Google Cloud core) provides if not specified. All output artifacts are created with strict owner-only permissions (`0600`). diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index d75d9f8..b72917a 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -232,6 +232,7 @@ EXCLUDE_MARKETPLACE (default: false) DISABLE_SCHEDULED_PLANS (default: true) LOOKER_INSTANCE_ID (default: onprem-export) + EXPORT_INSTANCE_INFRA (default: true) LOOKER_REPLICAS (optional override; auto-detected from node table) LOOKER_CPUS (optional override; auto-detected from host vCPUs) LOOKER_MEMORY_GB (optional override; auto-detected from JVM/RAM) @@ -240,6 +241,13 @@ DEBUG_LOG_ENABLED (default: true) AUTO_CONFIRM (default: false) +Note on source infrastructure sizing (instanceInfra in metadata.json): + Source replica, CPU, and memory metadata is ONLY used to upgrade Looker + (Google Cloud core) infrastructure based on On-Prem capacity needs (never + downgrading a larger target instance). If not specified (for example, + EXPORT_INSTANCE_INFRA=false), the import lands on the default infrastructure + that Looker (Google Cloud core) provides. + Cryptographic helper subcommands: ./looker_export.py ./looker_export.py @@ -819,6 +827,9 @@ def __init__(self, backup_arg: str | None = None) -> None: self.looker_instance_id = ( os.environ.get('LOOKER_INSTANCE_ID') or 'onprem-export' ) + self.export_instance_infra = ( + (os.environ.get('EXPORT_INSTANCE_INFRA') or 'true').strip().lower() + ) self.looker_replicas_override = ( os.environ.get('LOOKER_REPLICAS') or '' ).strip() @@ -939,6 +950,15 @@ def die(self, message: str) -> None: self.log_error(message) self.cleanup(1) + @staticmethod + def _safe_kill_proc(proc: subprocess.Popen[Any]) -> None: + """Sends SIGKILL to proc, ignoring OSError if proc already exited.""" + try: + proc.kill() + except OSError: + # Process exited between poll() and kill(). + pass + def _terminate_active_procs(self) -> None: """Terminates any running child subprocesses before directory cleanup.""" for proc in list(self._active_procs): @@ -948,9 +968,10 @@ def _terminate_active_procs(self) -> None: try: proc.wait(timeout=5) except subprocess.TimeoutExpired: - proc.kill() + self._safe_kill_proc(proc) proc.wait() except OSError: + # Process already exited during teardown. pass self._active_procs.clear() @@ -970,7 +991,7 @@ def _run_tracked_subprocess( if proc in self._active_procs: self._active_procs.remove(proc) if proc.poll() is None: - proc.kill() + self._safe_kill_proc(proc) proc.wait() def _stream_command_to_encrypted_artifact( @@ -994,7 +1015,7 @@ def _stream_command_to_encrypted_artifact( if self._cleaned_up: raise if proc.poll() is None: - proc.kill() + self._safe_kill_proc(proc) proc.wait() self.die(f'{err_msg}: {err}') except ( @@ -1004,14 +1025,14 @@ def _stream_command_to_encrypted_artifact( tink.TinkError, ) as err: if proc.poll() is None: - proc.kill() + self._safe_kill_proc(proc) proc.wait() self.die(f'{err_msg}: {err}') finally: if proc in self._active_procs: self._active_procs.remove(proc) if rc is None and proc.poll() is None: - proc.kill() + self._safe_kill_proc(proc) proc.wait() if rc != 0: self.die(err_msg) @@ -1020,12 +1041,14 @@ def _should_use_pigz(self) -> bool: """Returns True when pigz parallel compression is enabled and available.""" return self.use_pigz != 'false' and shutil.which('pigz') is not None - @staticmethod - def _kill_and_reap(procs: Sequence[subprocess.Popen[Any] | None]) -> None: + @classmethod + def _kill_and_reap( + cls, procs: Sequence[subprocess.Popen[Any] | None] + ) -> None: """Terminates and reaps any still-running child processes in procs.""" for proc in procs: if proc is not None and proc.poll() is None: - proc.kill() + cls._safe_kill_proc(proc) for proc in procs: if proc is not None: proc.wait() @@ -1099,7 +1122,7 @@ def _stream_tar_archive_to_encrypted_artifact( if proc in self._active_procs: self._active_procs.remove(proc) if rc_val is None and proc.poll() is None: - proc.kill() + self._safe_kill_proc(proc) proc.wait() if tar_rc != 0 or pigz_rc != 0: @@ -1244,8 +1267,16 @@ def _try_install_pigz(self) -> bool: is_root = hasattr(os, 'geteuid') and os.geteuid() == 0 interactive = self.auto_confirm != 'true' and sys.stdin.isatty() apt_steps = ( - ('apt-get', 'update', '-qq'), - ('apt-get', 'install', '-y', '-qq', 'pigz'), + ('env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get', 'update', '-qq'), + ( + 'env', + 'DEBIAN_FRONTEND=noninteractive', + 'apt-get', + 'install', + '-y', + '-qq', + 'pigz', + ), ) pkg_managers: tuple[tuple[str, Sequence[Sequence[str]]], ...] = ( ('apt-get', apt_steps), @@ -2113,7 +2144,28 @@ def _detect_running_looker_jvm(self) -> tuple[float | None, str]: return None, '' def discover_source_infra(self) -> None: - """Detects source Looker replica count, CPUs, memory, and startup flags.""" + """Detects source Looker replica count, CPUs, memory, and startup flags. + + Source infrastructure sizing (instanceInfra in metadata.json) is ONLY used + during import to upgrade Looker (Google Cloud core) infrastructure based on + On-Prem needs. If not specified (for example, EXPORT_INSTANCE_INFRA=false), + the imported instance lands on the default infrastructure that Looker Core + provides. + """ + if self.export_instance_infra not in ('true', 'false'): + self.preflight_fail( + 'Source Infrastructure', + "EXPORT_INSTANCE_INFRA must be 'true' or 'false' " + f"('{self.export_instance_infra}').", + ) + return + if self.export_instance_infra == 'false': + self.log_debug( + 'EXPORT_INSTANCE_INFRA=false; omitting instanceInfra so import ' + 'lands on the default infrastructure Looker Core provides.' + ) + return + replicas = 1 if self.looker_replicas_override: try: @@ -2137,9 +2189,15 @@ def discover_source_infra(self) -> None: if out_str.isdigit(): parsed_count = int(out_str) if parsed_count <= 0: - total_res = self.run_mysql_query('SELECT COUNT(*) FROM `node`;') - if total_res.returncode == 0: - out_str = (total_res.stdout or '').strip() + # When Looker is stopped before export, count only nodes active within + # 15 minutes of the latest cluster heartbeat rather than stale rows. + latest_cluster_res = self.run_mysql_query( + 'SELECT COUNT(*) FROM `node` ' + 'WHERE `last_heartbeat` >= (' + 'SELECT MAX(`last_heartbeat`) - INTERVAL 15 MINUTE FROM `node`);' + ) + if latest_cluster_res.returncode == 0: + out_str = (latest_cluster_res.stdout or '').strip() if out_str.isdigit(): parsed_count = int(out_str) if parsed_count > 0: @@ -2291,6 +2349,11 @@ def print_normalized_inputs_and_confirm(self) -> None: f" PIGZ_THREADS : {self.pigz_threads or 'auto'}" ) self.log_info(f' AUTO_INSTALL_PIGZ : {self.auto_install_pigz}') + self.log_info( + f' EXPORT_INSTANCE_INFRA : {self.export_instance_infra} ' + '(only used to upgrade Looker Core infra based on On-Prem needs; ' + 'if not specified, lands on default Core infra)' + ) self.log_info( f' KEEP_INTERMEDIATE_FILES : {self.keep_intermediate_files}' ) @@ -2316,6 +2379,18 @@ def print_validation_summary_and_confirm(self) -> None: f'{len(self.schema_only_tables_existing)} schema-only, ' f"plus filtered '{SETTING_DB_TABLE}'" ) + if self.export_instance_infra == 'true': + self.log_info( + f' Source Infra Sizing : replicas={self.detected_replicas}, ' + f'cpus={self.detected_cpus}, memory_gb={self.detected_memory_gb} GiB ' + '(only used to upgrade Looker Core infra based on On-Prem needs; ' + 'if not specified, lands on default Core infra)' + ) + else: + self.log_info( + ' Source Infra Sizing : omitted (EXPORT_INSTANCE_INFRA=false; ' + 'import will land on default Looker Core infra)' + ) if self.preflight_fail_count > 0: self.die( @@ -3231,9 +3306,12 @@ def generate_export_info(self) -> None: ) export_info_payload: dict[str, Any] = { 'sourceInstance': self.looker_instance_id or 'onprem-export', - 'instanceInfra': self._build_instance_infra_payload(), 'componentConfigs': self._build_component_configs_payload(), } + if self.export_instance_infra == 'true': + export_info_payload['instanceInfra'] = ( + self._build_instance_infra_payload() + ) raw_bytes = (json.dumps(export_info_payload, indent=2) + '\n').encode( 'utf-8' ) @@ -3310,7 +3388,7 @@ def generate_metadata_json(self) -> None: start_dt = self.export_start_dt or now_dt export_time_us = str(int(start_dt.timestamp() * 1_000_000)) - metadata_payload = { + metadata_payload: dict[str, Any] = { 'looker_instance': self.looker_instance_id or 'onprem-export', 'looker_version': self.detected_looker_version or 'unknown', 'export_encryption_key': { @@ -3328,9 +3406,10 @@ def generate_metadata_json(self) -> None: ], 'exportTime': export_time_us, 'exportMetrics': self._build_export_metrics_payload(now_dt), - 'instanceInfra': self._build_instance_infra_payload(), 'componentConfigs': self._build_component_configs_payload(), } + if self.export_instance_infra == 'true': + metadata_payload['instanceInfra'] = self._build_instance_infra_payload() with open(out_meta, 'w', encoding='utf-8') as mf: json.dump(metadata_payload, mf, indent=2) mf.write('\n') diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index 138845b..2ec1c38 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -451,8 +451,26 @@ def _run(cmd, **kw): cmds, [ ['sudo', '-n', 'true'], - ['sudo', '-n', 'apt-get', 'update', '-qq'], - ['sudo', '-n', 'apt-get', 'install', '-y', '-qq', 'pigz'], + [ + 'sudo', + '-n', + 'env', + 'DEBIAN_FRONTEND=noninteractive', + 'apt-get', + 'update', + '-qq', + ], + [ + 'sudo', + '-n', + 'env', + 'DEBIAN_FRONTEND=noninteractive', + 'apt-get', + 'install', + '-y', + '-qq', + 'pigz', + ], ], ) @@ -1308,6 +1326,106 @@ def test_pigz_parallel_compression_and_use_pigz_false_override(self): with tarfile.open(os.path.join(fdir, 'fs-data'), 'r:gz') as tf: self.assertTrue(any(n.startswith('modelshare') for n in tf.getnames())) + def test_pr36_review_fixes_and_export_instance_infra_false(self): + # 1. Verify _kill_and_reap tolerates ProcessLookupError / OSError on kill(). + class _RacyProc: + def __init__(self): + self.waited = False + + def poll(self): + return None + + def kill(self): + raise ProcessLookupError('No such process') + + def wait(self): + self.waited = True + return 0 + + exp_mod = _load_module_with_stubs('looker_export', LOOKER_EXPORT_PY) + racy = _RacyProc() + exp_mod.LookerExporter._kill_and_reap((racy,)) + self.assertTrue(racy.waited) + + # 2. Verify _try_install_pigz passes env DEBIAN_FRONTEND=noninteractive + # inside sudo argv so sudo env_reset cannot strip it. + with tempfile.TemporaryDirectory() as tmpdir: + exp = exp_mod.LookerExporter(backup_arg=os.path.join(tmpdir, 'b')) + exp.auto_confirm = 'true' + recorded_cmds = [] + + def _fake_which(binary): + if binary == 'pigz': + return '/usr/bin/pigz' if len(recorded_cmds) >= 3 else None + if binary in ('apt-get', 'sudo'): + return f'/usr/bin/{binary}' + return None + + def _fake_run(cmd, **_kwargs): + recorded_cmds.append(list(cmd)) + return subprocess.CompletedProcess(cmd, 0, stdout='', stderr='') + + with ( + mock.patch.object( + exp_mod.shutil, 'which', side_effect=_fake_which + ), + mock.patch.object( + exp_mod.os, 'geteuid', return_value=1000 + ), + mock.patch.object( + exp_mod.subprocess, 'run', side_effect=_fake_run + ), + ): + self.assertTrue(exp._try_install_pigz()) + self.assertEqual( + recorded_cmds[1][:4], + ['sudo', '-n', 'env', 'DEBIAN_FRONTEND=noninteractive'], + ) + self.assertEqual( + recorded_cmds[2][:4], + ['sudo', '-n', 'env', 'DEBIAN_FRONTEND=noninteractive'], + ) + + # 3. Verify EXPORT_INSTANCE_INFRA=false omits instanceInfra so import + # lands on default Looker Core infrastructure. + fx = self._create_hermetic_fixture(tmpdir) + bdir = os.path.join(tmpdir, 'backup_no_infra') + proc = subprocess.run( + [sys.executable, LOOKER_EXPORT_PY], + env={ + **os.environ, + 'PATH': f"{fx['bin_dir']}:{os.environ.get('PATH', '')}", + 'PYTHONPATH': fx['pylib_dir'], + 'ON_PREM_LOOKER_DATA_DIR': fx['onprem'], + 'BACKUP_DIR': bdir, + 'DB_HOST': '127.0.0.1', + 'DB_PORT': '3306', + 'DB_USER': 'looker', + 'DB_NAME': 'looker', + 'MYSQL_PWD': 's3cr3t_pw', + 'LOOKER_MASTER_KEY': base64.b64encode(b'K' * 32).decode('ascii'), + 'KMS_KEY_NAME': ( + 'projects/p1/locations/us-central1/keyRings/r1/cryptoKeys/k1' + ), + 'EXPORT_INSTANCE_INFRA': 'false', + 'AUTO_CONFIRM': 'true', + }, + check=False, + capture_output=True, + text=True, + ) + self.assertEqual(proc.returncode, 0, msg=proc.stderr) + self.assertIn( + 'import will land on default Looker Core infra', + proc.stderr, + ) + with open( + os.path.join(bdir, 'final_artifacts', 'metadata.json'), + encoding='utf-8', + ) as mf: + meta = json.load(mf) + self.assertNotIn('instanceInfra', meta) + if __name__ == '__main__': unittest.main() From aaf712ea410884ee2748e2949ed6b59a6444b7b2 Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Wed, 25 Nov 2026 06:10:55 +0000 Subject: [PATCH 4/7] refactor(export-to-core): keep instanceInfra in export_info.json.enc and exportMetrics in metadata.json --- export-to-core/README.md | 8 ++++---- export-to-core/looker_export.py | 15 ++++++--------- export-to-core/tests/test_export_to_core.py | 20 ++++++++++++++------ 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/export-to-core/README.md b/export-to-core/README.md index 649ce00..e183438 100644 --- a/export-to-core/README.md +++ b/export-to-core/README.md @@ -189,7 +189,7 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a | `EXCLUDE_MARKETPLACE` | Set to `true` to exclude Looker Marketplace directories and tables from the export. | `false` | | `DISABLE_SCHEDULED_PLANS` | Set `scheduled_plan.enabled = FALSE` in the exported database artifact (leaves live source DB untouched) to prevent automatic runs immediately after import. | `true` | | `LOOKER_INSTANCE_ID` | Optional source identifier recorded as `looker_instance` in `metadata.json`. | `onprem-export` | -| `EXPORT_INSTANCE_INFRA` | Set to `true` to include source infrastructure sizing (`instanceInfra` in `metadata.json` and `export_info.json.enc`). **Note:** `instanceInfra` is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs (never downgrading larger target instances); if not specified (`EXPORT_INSTANCE_INFRA=false`), the import lands on the default infrastructure that Looker (Google Cloud core) provides. | `true` | +| `EXPORT_INSTANCE_INFRA` | Set to `true` to include source infrastructure sizing (`instanceInfra` in `export_info.json.enc`). **Note:** `instanceInfra` is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs (never downgrading larger target instances); if not specified (`EXPORT_INSTANCE_INFRA=false`), the import lands on the default infrastructure that Looker (Google Cloud core) provides. | `true` | | `LOOKER_REPLICAS` | Optional cluster node/replica count recorded in `instanceInfra` for Looker (Google Cloud core) import tier upgrade (auto-detected from active `node` table heartbeats when unset). | *(auto)* | | `LOOKER_CPUS` | Optional per-node CPU count recorded in `instanceInfra` (auto-detected from host logical vCPUs when unset). | *(auto)* | | `LOOKER_MEMORY_GB` | Optional per-node memory in GiB recorded in `instanceInfra` (auto-detected from running Looker JVM `-Xmx` or host `MemTotal` when unset). | *(auto)* | @@ -222,9 +222,9 @@ Upon successful completion, `looker_export.py` generates seven files in `${BACKU - `fs-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `fs-data`. - `mysql-data`: Tink Streaming AEAD-encrypted `.tar.gz` archive containing the Looker database export (`mysqldump` SQL dump or `mydumper` + `zstd` archive). - `mysql-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `mysql-data`. -- `export_info.json.enc`: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) and `componentConfigs`. +- `export_info.json.enc`: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing `componentConfigs` and (when `EXPORT_INSTANCE_INFRA=true`) source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) — which is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs, landing on the default infrastructure Looker (Google Cloud core) provides if not specified. - `export_info-handle.enc`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `export_info.json.enc`. -- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, `exportMetrics` (component `sizeGb` and durations for `ALL`, `DB`, and `FS`), `componentConfigs`, and (when `EXPORT_INSTANCE_INFRA=true`) `instanceInfra` — which is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs, landing on the default infrastructure Looker (Google Cloud core) provides if not specified. +- `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, and `exportMetrics` (component `sizeGb`, `duration`, `retryCount`, `startTime`, and `endTime` for `ALL`, `DB`, and `FS`). All output artifacts are created with strict owner-only permissions (`0600`). @@ -232,7 +232,7 @@ All output artifacts are created with strict owner-only permissions (`0600`). ## Next Steps: Import into Looker (Google Cloud core) -1. Upload the five files inside `final_artifacts/` to a dedicated folder in a Google Cloud Storage bucket in the same region as your target Looker (Google Cloud core) instance: +1. Upload all files inside `final_artifacts/` to a dedicated folder in a Google Cloud Storage bucket in the same region as your target Looker (Google Cloud core) instance: ```bash gcloud storage cp /mnt/backups/looker_export/final_artifacts/* gs://// ``` diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index b72917a..3a402d4 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -241,7 +241,7 @@ DEBUG_LOG_ENABLED (default: true) AUTO_CONFIRM (default: false) -Note on source infrastructure sizing (instanceInfra in metadata.json): +Note on source infrastructure sizing (instanceInfra in export_info.json.enc): Source replica, CPU, and memory metadata is ONLY used to upgrade Looker (Google Cloud core) infrastructure based on On-Prem capacity needs (never downgrading a larger target instance). If not specified (for example, @@ -2146,11 +2146,11 @@ def _detect_running_looker_jvm(self) -> tuple[float | None, str]: def discover_source_infra(self) -> None: """Detects source Looker replica count, CPUs, memory, and startup flags. - Source infrastructure sizing (instanceInfra in metadata.json) is ONLY used - during import to upgrade Looker (Google Cloud core) infrastructure based on - On-Prem needs. If not specified (for example, EXPORT_INSTANCE_INFRA=false), - the imported instance lands on the default infrastructure that Looker Core - provides. + Source infrastructure sizing (instanceInfra in export_info.json.enc) is ONLY + used during import to upgrade Looker (Google Cloud core) infrastructure + based on On-Prem needs. If not specified (for example, + EXPORT_INSTANCE_INFRA=false), the imported instance lands on the default + infrastructure that Looker Core provides. """ if self.export_instance_infra not in ('true', 'false'): self.preflight_fail( @@ -3406,10 +3406,7 @@ def generate_metadata_json(self) -> None: ], 'exportTime': export_time_us, 'exportMetrics': self._build_export_metrics_payload(now_dt), - 'componentConfigs': self._build_component_configs_payload(), } - if self.export_instance_infra == 'true': - metadata_payload['instanceInfra'] = self._build_instance_infra_payload() with open(out_meta, 'w', encoding='utf-8') as mf: json.dump(metadata_payload, mf, indent=2) mf.write('\n') diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index 2ec1c38..9d998f9 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -1076,12 +1076,9 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): } self.assertEqual(set(comp_by_type), {'ALL', 'DB', 'FS'}) self.assertGreater(comp_by_type['DB']['sizeGb'], 0) - self.assertEqual( - meta['instanceInfra']['deploymentConfigs'][0]['replicas'], 3 - ) - self.assertEqual( - meta['instanceInfra']['deploymentConfigs'][0]['type'], 'LOOKER' - ) + self.assertTrue(comp_by_type['ALL']['duration'].endswith('s')) + self.assertNotIn('instanceInfra', meta) + self.assertNotIn('componentConfigs', meta) with open( os.path.join(final_dir, 'export_info.json.enc'), encoding='utf-8' ) as eif: @@ -1089,6 +1086,9 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): self.assertEqual( export_info['instanceInfra']['deploymentConfigs'][0]['replicas'], 3 ) + self.assertEqual( + export_info['instanceInfra']['deploymentConfigs'][0]['type'], 'LOOKER' + ) self.assertEqual( export_info['componentConfigs'][0]['exportType']['mysqlExportType'], 'MYSQLDUMP', @@ -1425,6 +1425,14 @@ def _fake_run(cmd, **_kwargs): ) as mf: meta = json.load(mf) self.assertNotIn('instanceInfra', meta) + self.assertIn('exportMetrics', meta) + with open( + os.path.join(bdir, 'final_artifacts', 'export_info.json.enc'), + encoding='utf-8', + ) as eif: + export_info = json.load(eif) + self.assertNotIn('instanceInfra', export_info) + self.assertIn('componentConfigs', export_info) if __name__ == '__main__': From 3f80eef5c5c62948c89c37899cbf096ea80a9e4a Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Wed, 25 Nov 2026 08:31:25 +0000 Subject: [PATCH 5/7] feat(export-to-core): make source infra sizing and export_info strictly optional --- export-to-core/README.md | 16 +-- export-to-core/looker_export.py | 113 +++++++++++++++----- export-to-core/tests/test_export_to_core.py | 80 +++++++++----- 3 files changed, 145 insertions(+), 64 deletions(-) diff --git a/export-to-core/README.md b/export-to-core/README.md index e183438..141c76f 100644 --- a/export-to-core/README.md +++ b/export-to-core/README.md @@ -189,11 +189,11 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a | `EXCLUDE_MARKETPLACE` | Set to `true` to exclude Looker Marketplace directories and tables from the export. | `false` | | `DISABLE_SCHEDULED_PLANS` | Set `scheduled_plan.enabled = FALSE` in the exported database artifact (leaves live source DB untouched) to prevent automatic runs immediately after import. | `true` | | `LOOKER_INSTANCE_ID` | Optional source identifier recorded as `looker_instance` in `metadata.json`. | `onprem-export` | -| `EXPORT_INSTANCE_INFRA` | Set to `true` to include source infrastructure sizing (`instanceInfra` in `export_info.json.enc`). **Note:** `instanceInfra` is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs (never downgrading larger target instances); if not specified (`EXPORT_INSTANCE_INFRA=false`), the import lands on the default infrastructure that Looker (Google Cloud core) provides. | `true` | -| `LOOKER_REPLICAS` | Optional cluster node/replica count recorded in `instanceInfra` for Looker (Google Cloud core) import tier upgrade (auto-detected from active `node` table heartbeats when unset). | *(auto)* | -| `LOOKER_CPUS` | Optional per-node CPU count recorded in `instanceInfra` (auto-detected from host logical vCPUs when unset). | *(auto)* | -| `LOOKER_MEMORY_GB` | Optional per-node memory in GiB recorded in `instanceInfra` (auto-detected from running Looker JVM `-Xmx` or host `MemTotal` when unset). | *(auto)* | -| `LOOKER_STARTUP_ARGS` | Optional Looker startup flags recorded in `instanceInfra.commandLineArgs` with sensitive values redacted (auto-detected from running Looker JVM when unset). | *(auto)* | +| `EXPORT_INSTANCE_INFRA` | Optional (`true` or `false`). Prompted interactively when unset. Set to `true` (or provide `LOOKER_REPLICAS`, `LOOKER_CPUS`, `LOOKER_MEMORY_GB`) to generate optional `export_info.json.enc` and `export_info-handle.enc` so Looker (Google Cloud core) can upgrade target infrastructure during import based on source capacity needs (never downgrading larger target instances). When `false` (default), those two files are omitted and the import lands on the default or existing infrastructure Looker (Google Cloud core) provides. | `false` | +| `LOOKER_REPLICAS` | Optional source Looker node/replica count recorded in `export_info.json.enc` when `EXPORT_INSTANCE_INFRA=true` (prompted interactively when opting in; defaults to `1`). | `1` *(when enabled)* | +| `LOOKER_CPUS` | Optional per-node vCPU count recorded in `export_info.json.enc` when `EXPORT_INSTANCE_INFRA=true` (prompted interactively when opting in). | *(optional)* | +| `LOOKER_MEMORY_GB` | Optional per-node memory in GiB recorded in `export_info.json.enc` when `EXPORT_INSTANCE_INFRA=true` (prompted interactively when opting in). | *(optional)* | +| `LOOKER_STARTUP_ARGS` | Optional Looker startup flags recorded in `instanceInfra.commandLineArgs` with sensitive values redacted when `EXPORT_INSTANCE_INFRA=true`. | *(optional)* | | `AUTO_CONFIRM` | Set to `true` to skip interactive confirmation prompts (for non-interactive automation). | `false` | | `DEBUG_LOG_ENABLED` | Write verbose `DEBUG` trace entries to `${BACKUP_DIR}/looker_export.log`. | `true` | | `KEEP_INTERMEDIATE_FILES` | Retain unencrypted staging directories under `${BACKUP_DIR}/intermediate/` after exit (debugging only). | `false` | @@ -216,15 +216,15 @@ export PIGZ_THREADS="8" # Optional: parallel pigz threads (default: a ## Output Artifacts -Upon successful completion, `looker_export.py` generates seven files in `${BACKUP_DIR}/final_artifacts/`: +Upon successful completion, `looker_export.py` generates five required files in `${BACKUP_DIR}/final_artifacts/` (plus two optional `export_info` files if you opt in to providing source infrastructure sizing): - `fs-data`: Tink Streaming AEAD-encrypted `.tar.gz` archive containing normalized LookML Git and Looker file system directories. - `fs-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `fs-data`. - `mysql-data`: Tink Streaming AEAD-encrypted `.tar.gz` archive containing the Looker database export (`mysqldump` SQL dump or `mydumper` + `zstd` archive). - `mysql-handle`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `mysql-data`. -- `export_info.json.enc`: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing `componentConfigs` and (when `EXPORT_INSTANCE_INFRA=true`) source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) — which is **only** used to upgrade Looker (Google Cloud core) infrastructure based on customer-hosted (On-Prem) capacity needs, landing on the default infrastructure Looker (Google Cloud core) provides if not specified. -- `export_info-handle.enc`: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `export_info.json.enc`. - `metadata.json`: Export manifest containing the Looker instance identifier (`looker_instance`), detected Looker version (`looker_version`), canonical Cloud KMS CryptoKey resource (`export_encryption_key.cmek`), Cloud KMS-encrypted 32-byte Looker master key (`looker_encryption_key`), migration `source`, exported `file_paths`, `exportTime`, and `exportMetrics` (component `sizeGb`, `duration`, `retryCount`, `startTime`, and `endTime` for `ALL`, `DB`, and `FS`). +- `export_info.json.enc` *(Optional — generated only when opting in via interactive prompt or `EXPORT_INSTANCE_INFRA=true`)*: Tink Streaming AEAD-encrypted `ExportInfo` manifest containing `componentConfigs` and source Looker infrastructure sizing (`instanceInfra` replicas, CPUs, memory, sanitized startup args) used **only** to upgrade Looker (Google Cloud core) infrastructure during import based on source capacity needs (never downgrading larger target instances). +- `export_info-handle.enc` *(Optional — generated only alongside `export_info.json.enc`)*: Cloud KMS envelope-encrypted Tink keyset handle (DEK) for `export_info.json.enc`. All output artifacts are created with strict owner-only permissions (`0600`). diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index 3a402d4..906255f 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -232,21 +232,23 @@ EXCLUDE_MARKETPLACE (default: false) DISABLE_SCHEDULED_PLANS (default: true) LOOKER_INSTANCE_ID (default: onprem-export) - EXPORT_INSTANCE_INFRA (default: true) - LOOKER_REPLICAS (optional override; auto-detected from node table) - LOOKER_CPUS (optional override; auto-detected from host vCPUs) - LOOKER_MEMORY_GB (optional override; auto-detected from JVM/RAM) - LOOKER_STARTUP_ARGS (optional override; auto-detected from Looker JVM) + EXPORT_INSTANCE_INFRA (optional; default: false; prompted in TTY) + LOOKER_REPLICAS (optional Looker node count when upscaling; default: 1) + LOOKER_CPUS (optional vCPUs per Looker node when upscaling) + LOOKER_MEMORY_GB (optional GiB RAM per Looker node when upscaling) + LOOKER_STARTUP_ARGS (optional Looker startup flags when upscaling) KEEP_INTERMEDIATE_FILES (default: false) DEBUG_LOG_ENABLED (default: true) AUTO_CONFIRM (default: false) -Note on source infrastructure sizing (instanceInfra in export_info.json.enc): - Source replica, CPU, and memory metadata is ONLY used to upgrade Looker - (Google Cloud core) infrastructure based on On-Prem capacity needs (never - downgrading a larger target instance). If not specified (for example, - EXPORT_INSTANCE_INFRA=false), the import lands on the default infrastructure - that Looker (Google Cloud core) provides. +Note on optional source infrastructure sizing (export_info.json.enc): + Providing source infrastructure sizing is completely optional (default: + EXPORT_INSTANCE_INFRA=false; prompted interactively when unset). When you opt + in, looker_export.py writes export_info.json.enc and export_info-handle.enc so + Looker (Google Cloud core) can upgrade target infrastructure based on your + source capacity needs (never downgrading a larger target instance). When + omitted, those two files are not generated and the import lands on the default + or existing infrastructure that Looker (Google Cloud core) provides. Cryptographic helper subcommands: ./looker_export.py @@ -827,9 +829,7 @@ def __init__(self, backup_arg: str | None = None) -> None: self.looker_instance_id = ( os.environ.get('LOOKER_INSTANCE_ID') or 'onprem-export' ) - self.export_instance_infra = ( - (os.environ.get('EXPORT_INSTANCE_INFRA') or 'true').strip().lower() - ) + raw_export_infra = os.environ.get('EXPORT_INSTANCE_INFRA') self.looker_replicas_override = ( os.environ.get('LOOKER_REPLICAS') or '' ).strip() @@ -840,6 +840,20 @@ def __init__(self, backup_arg: str | None = None) -> None: self.looker_startup_args_override = ( os.environ.get('LOOKER_STARTUP_ARGS') or '' ).strip() + has_explicit_sizing = bool( + self.looker_replicas_override + or self.looker_cpus_override + or self.looker_memory_gb_override + ) + self._export_instance_infra_explicit = bool( + (raw_export_infra and raw_export_infra.strip()) or has_explicit_sizing + ) + if raw_export_infra and raw_export_infra.strip(): + self.export_instance_infra = raw_export_infra.strip().lower() + elif has_explicit_sizing: + self.export_instance_infra = 'true' + else: + self.export_instance_infra = 'false' self.exclude_marketplace = os.environ.get('EXCLUDE_MARKETPLACE') or 'false' self.disable_scheduled_plans = ( @@ -1202,6 +1216,47 @@ def _prompt_secret_if_missing( os.environ[env_name] = secret_value return secret_value + def _prompt_line(self, prompt_text: str) -> str: + """Writes an interactive prompt to stderr and reads one line from stdin.""" + sys.stderr.write(f' [PROMPT] {prompt_text}') + sys.stderr.flush() + try: + return sys.stdin.readline().strip() + except OSError: + return '' + + def _prompt_optional_instance_infra(self) -> None: + """Optionally asks interactive users for source Looker sizing to upscale.""" + if self.auto_confirm == 'true' or not sys.stdin.isatty(): + return + if not self._export_instance_infra_explicit: + reply = self._prompt_line( + 'Optional: Provide source Looker node sizing (replicas, vCPUs, ' + 'memory GiB) so Looker Core can upscale target infrastructure ' + 'during import if needed? [y/N]: ' + ) + if not re.fullmatch(r'[Yy]([Ee][Ss])?', reply): + self.export_instance_infra = 'false' + return + self.export_instance_infra = 'true' + self._export_instance_infra_explicit = True + + if self.export_instance_infra != 'true': + return + if not self.looker_replicas_override: + rep_ans = self._prompt_line( + 'Enter source Looker node/replica count (LOOKER_REPLICAS) [1]: ' + ) + self.looker_replicas_override = rep_ans or '1' + if not self.looker_cpus_override: + self.looker_cpus_override = self._prompt_line( + 'Enter vCPUs per Looker node (LOOKER_CPUS, e.g. 8): ' + ) + if not self.looker_memory_gb_override: + self.looker_memory_gb_override = self._prompt_line( + 'Enter memory in GiB per Looker node (LOOKER_MEMORY_GB, e.g. 32): ' + ) + def validate_environment(self) -> None: """Validates required input and secret environment variables.""" self.mysql_pwd = self._prompt_secret_if_missing( @@ -1215,6 +1270,7 @@ def validate_environment(self) -> None: self.kms_key_name = self._prompt_secret_if_missing( self.kms_key_name, 'KMS_KEY_NAME', 'GCP Cloud KMS Key URI' ) + self._prompt_optional_instance_infra() var_map = { 'ON_PREM_LOOKER_DATA_PATH': self.on_prem_looker_data_path, @@ -3297,21 +3353,20 @@ def _build_component_configs_payload(self) -> list[dict[str, Any]]: ] def generate_export_info(self) -> None: - """Encrypts ExportInfo (instanceInfra, replicas, componentConfigs).""" + """Encrypts optional ExportInfo when EXPORT_INSTANCE_INFRA=true.""" + if self.export_instance_infra != 'true': + return out_data = os.path.join(self.final_artifacts_dir, EXPORT_INFO_FILE) out_handle = os.path.join(self.final_artifacts_dir, EXPORT_INFO_HANDLE_FILE) self.log_info( - f'Generating encrypted source infrastructure metadata ' + f'Generating optional encrypted source infrastructure metadata ' f'({EXPORT_INFO_FILE}, {EXPORT_INFO_HANDLE_FILE})...' ) export_info_payload: dict[str, Any] = { 'sourceInstance': self.looker_instance_id or 'onprem-export', 'componentConfigs': self._build_component_configs_payload(), + 'instanceInfra': self._build_instance_infra_payload(), } - if self.export_instance_infra == 'true': - export_info_payload['instanceInfra'] = ( - self._build_instance_infra_payload() - ) raw_bytes = (json.dumps(export_info_payload, indent=2) + '\n').encode( 'utf-8' ) @@ -3388,6 +3443,15 @@ def generate_metadata_json(self) -> None: start_dt = self.export_start_dt or now_dt export_time_us = str(int(start_dt.timestamp() * 1_000_000)) + file_paths = [ + FS_DATA_FILE, + FS_HANDLE_FILE, + MYSQL_DATA_FILE, + MYSQL_HANDLE_FILE, + ] + if self.export_instance_infra == 'true': + file_paths.extend([EXPORT_INFO_FILE, EXPORT_INFO_HANDLE_FILE]) + metadata_payload: dict[str, Any] = { 'looker_instance': self.looker_instance_id or 'onprem-export', 'looker_version': self.detected_looker_version or 'unknown', @@ -3396,14 +3460,7 @@ def generate_metadata_json(self) -> None: }, 'looker_encryption_key': encrypted_master_key, 'source': 'LOOKER_ORIGINAL', - 'file_paths': [ - FS_DATA_FILE, - FS_HANDLE_FILE, - MYSQL_DATA_FILE, - MYSQL_HANDLE_FILE, - EXPORT_INFO_FILE, - EXPORT_INFO_HANDLE_FILE, - ], + 'file_paths': file_paths, 'exportTime': export_time_us, 'exportMetrics': self._build_export_metrics_payload(now_dt), } diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index 9d998f9..312423b 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -531,6 +531,8 @@ def test_stream_tar_archive_with_pigz_aborts_when_tar_exits_nonzero(self): def test_discover_source_infra_and_sanitize_jvm_args(self): with tempfile.TemporaryDirectory() as tmpdir: exp = self.exp.LookerExporter(backup_arg=tmpdir) + self.assertEqual(exp.export_instance_infra, 'false') + exp.export_instance_infra = 'true' exp.db_connection_verified = True fake_ps = ( 'java -Xmx24g -Xms12g --db-password=topsecret ' @@ -562,6 +564,30 @@ def test_discover_source_infra_and_sanitize_jvm_args(self): self.assertIn('-p REDACTED', exp.detected_command_line_args) self.assertIn('--clustered', exp.detected_command_line_args) + # Verify interactive optional prompt (skip vs opt-in). + exp_skip = self.exp.LookerExporter(backup_arg=tmpdir) + with ( + mock.patch.object(self.exp.sys.stdin, 'isatty', return_value=True), + mock.patch.object(self.exp.sys.stdin, 'readline', return_value='\n'), + ): + exp_skip._prompt_optional_instance_infra() + self.assertEqual(exp_skip.export_instance_infra, 'false') + + exp_opt_in = self.exp.LookerExporter(backup_arg=tmpdir) + with ( + mock.patch.object(self.exp.sys.stdin, 'isatty', return_value=True), + mock.patch.object( + self.exp.sys.stdin, + 'readline', + side_effect=['y\n', '2\n', '8\n', '32\n'], + ), + ): + exp_opt_in._prompt_optional_instance_infra() + self.assertEqual(exp_opt_in.export_instance_infra, 'true') + self.assertEqual(exp_opt_in.looker_replicas_override, '2') + self.assertEqual(exp_opt_in.looker_cpus_override, '8') + self.assertEqual(exp_opt_in.looker_memory_gb_override, '32') + class CollectDiagnosticsTest(unittest.TestCase): """Tests collect_looker_diagnostics.py filesystem/report behavior.""" @@ -1050,13 +1076,17 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): 'fs-handle', 'mysql-data', 'mysql-handle', - 'export_info.json.enc', - 'export_info-handle.enc', 'metadata.json', ): artifact = os.path.join(final_dir, name) self.assertTrue(os.path.isfile(artifact), msg=f'Missing {name}') self.assertEqual(stat.S_IMODE(os.stat(artifact).st_mode), 0o600) + self.assertFalse( + os.path.exists(os.path.join(final_dir, 'export_info.json.enc')) + ) + self.assertFalse( + os.path.exists(os.path.join(final_dir, 'export_info-handle.enc')) + ) with open( os.path.join(final_dir, 'metadata.json'), encoding='utf-8' @@ -1068,8 +1098,8 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): meta['export_encryption_key']['cmek'], 'projects/p1/locations/us-central1/keyRings/r1/cryptoKeys/k1', ) - self.assertIn('export_info.json.enc', meta['file_paths']) - self.assertIn('export_info-handle.enc', meta['file_paths']) + self.assertNotIn('export_info.json.enc', meta['file_paths']) + self.assertNotIn('export_info-handle.enc', meta['file_paths']) self.assertTrue(str(meta['exportTime']).isdigit()) comp_by_type = { c['type']: c for c in meta['exportMetrics']['componentMetrics'] @@ -1079,20 +1109,6 @@ def test_mysqldump_export_normalizes_sql_and_git_and_path_aliases(self): self.assertTrue(comp_by_type['ALL']['duration'].endswith('s')) self.assertNotIn('instanceInfra', meta) self.assertNotIn('componentConfigs', meta) - with open( - os.path.join(final_dir, 'export_info.json.enc'), encoding='utf-8' - ) as eif: - export_info = json.load(eif) - self.assertEqual( - export_info['instanceInfra']['deploymentConfigs'][0]['replicas'], 3 - ) - self.assertEqual( - export_info['instanceInfra']['deploymentConfigs'][0]['type'], 'LOOKER' - ) - self.assertEqual( - export_info['componentConfigs'][0]['exportType']['mysqlExportType'], - 'MYSQLDUMP', - ) with tarfile.open(os.path.join(final_dir, 'mysql-data'), 'r:gz') as tf: self.assertEqual(tf.getnames(), ['looker']) @@ -1386,10 +1402,10 @@ def _fake_run(cmd, **_kwargs): ['sudo', '-n', 'env', 'DEBIAN_FRONTEND=noninteractive'], ) - # 3. Verify EXPORT_INSTANCE_INFRA=false omits instanceInfra so import - # lands on default Looker Core infrastructure. + # 3. Verify optional customer-supplied infra sizing generates + # export_info.json.enc + export_info-handle.enc when opted in. fx = self._create_hermetic_fixture(tmpdir) - bdir = os.path.join(tmpdir, 'backup_no_infra') + bdir = os.path.join(tmpdir, 'backup_with_infra') proc = subprocess.run( [sys.executable, LOOKER_EXPORT_PY], env={ @@ -1407,7 +1423,10 @@ def _fake_run(cmd, **_kwargs): 'KMS_KEY_NAME': ( 'projects/p1/locations/us-central1/keyRings/r1/cryptoKeys/k1' ), - 'EXPORT_INSTANCE_INFRA': 'false', + 'EXPORT_INSTANCE_INFRA': 'true', + 'LOOKER_REPLICAS': '3', + 'LOOKER_CPUS': '12', + 'LOOKER_MEMORY_GB': '32', 'AUTO_CONFIRM': 'true', }, check=False, @@ -1415,10 +1434,6 @@ def _fake_run(cmd, **_kwargs): text=True, ) self.assertEqual(proc.returncode, 0, msg=proc.stderr) - self.assertIn( - 'import will land on default Looker Core infra', - proc.stderr, - ) with open( os.path.join(bdir, 'final_artifacts', 'metadata.json'), encoding='utf-8', @@ -1426,13 +1441,22 @@ def _fake_run(cmd, **_kwargs): meta = json.load(mf) self.assertNotIn('instanceInfra', meta) self.assertIn('exportMetrics', meta) + self.assertIn('export_info.json.enc', meta['file_paths']) + self.assertIn('export_info-handle.enc', meta['file_paths']) with open( os.path.join(bdir, 'final_artifacts', 'export_info.json.enc'), encoding='utf-8', ) as eif: export_info = json.load(eif) - self.assertNotIn('instanceInfra', export_info) - self.assertIn('componentConfigs', export_info) + looker_cfg = export_info['instanceInfra']['deploymentConfigs'][0] + self.assertEqual(looker_cfg['type'], 'LOOKER') + self.assertEqual(looker_cfg['replicas'], 3) + self.assertEqual(looker_cfg['cpus'], 12.0) + self.assertEqual(looker_cfg['memoryGb'], 32.0) + self.assertEqual( + export_info['componentConfigs'][0]['exportType']['mysqlExportType'], + 'MYSQLDUMP', + ) if __name__ == '__main__': From c0652abcc2f2f8aeb71abc19a0c2452ff17cf5d8 Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Wed, 25 Nov 2026 11:01:59 +0000 Subject: [PATCH 6/7] style(export-to-core): align usage config hints in looker_export.py --- export-to-core/looker_export.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index 906255f..f2b585c 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -226,17 +226,17 @@ USE_MYDUMPER / ENABLE_PARALLEL_EXPORT (default: false) MYDUMPER_THREADS (default: 4) MYDUMPER_CHUNK_ROWS (default: 50000) - USE_PIGZ (default: auto; auto | true | false) - PIGZ_THREADS (default: auto / all online vCPUs) + USE_PIGZ (default: auto) + PIGZ_THREADS (default: all vCPUs) AUTO_INSTALL_PIGZ (default: true) EXCLUDE_MARKETPLACE (default: false) DISABLE_SCHEDULED_PLANS (default: true) LOOKER_INSTANCE_ID (default: onprem-export) - EXPORT_INSTANCE_INFRA (optional; default: false; prompted in TTY) - LOOKER_REPLICAS (optional Looker node count when upscaling; default: 1) - LOOKER_CPUS (optional vCPUs per Looker node when upscaling) - LOOKER_MEMORY_GB (optional GiB RAM per Looker node when upscaling) - LOOKER_STARTUP_ARGS (optional Looker startup flags when upscaling) + EXPORT_INSTANCE_INFRA (default: false; optional) + LOOKER_REPLICAS (optional; default: 1) + LOOKER_CPUS (optional vCPUs per node) + LOOKER_MEMORY_GB (optional GiB per node) + LOOKER_STARTUP_ARGS (optional startup flags) KEEP_INTERMEDIATE_FILES (default: false) DEBUG_LOG_ENABLED (default: true) AUTO_CONFIRM (default: false) From 5f416d97b74b6197fa731a1344c8ddb3990e943b Mon Sep 17 00:00:00 2001 From: Manoj Kidambi Date: Wed, 25 Nov 2026 11:07:50 +0000 Subject: [PATCH 7/7] fix(export-to-core): preserve LOOKER_MEMORY_GB override and shlex-redact quoted args --- export-to-core/looker_export.py | 40 ++++++++++++++++++--- export-to-core/tests/test_export_to_core.py | 29 +++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/export-to-core/looker_export.py b/export-to-core/looker_export.py index f2b585c..360c8ab 100755 --- a/export-to-core/looker_export.py +++ b/export-to-core/looker_export.py @@ -29,6 +29,7 @@ import json import os import re +import shlex import shutil import signal import stat @@ -749,20 +750,45 @@ def _parse_jvm_xmx_gb(cmd_line: str) -> float | None: return round(amount * multipliers[unit], 2) +def _has_unclosed_quote(val: str) -> str | None: + """Returns the opening quote char if val starts with an unclosed quote.""" + if val and val[0] in ('"', "'") and (len(val) == 1 or val[-1] != val[0]): + return val[0] + return None + + def _sanitize_command_line_args(raw_args: str) -> str: """Redacts sensitive flag values from captured Looker startup arguments.""" - tokens = raw_args.strip().split() + cleaned = raw_args.strip() + if not cleaned: + return '' + split_failed = False + try: + tokens = shlex.split(cleaned) + except ValueError: + split_failed = True + tokens = cleaned.split() + sanitized: list[str] = [] redact_next = False + skip_until_quote: str | None = None for tok in tokens: + if skip_until_quote is not None: + if skip_until_quote in tok: + skip_until_quote = None + continue if redact_next: sanitized.append('REDACTED') redact_next = False + if split_failed: + skip_until_quote = _has_unclosed_quote(tok) continue if '=' in tok: - flag_name, _ = tok.split('=', 1) + flag_name, flag_val = tok.split('=', 1) if _SENSITIVE_ARG_RE.search(flag_name): sanitized.append(f'{flag_name}=REDACTED') + if split_failed: + skip_until_quote = _has_unclosed_quote(flag_val) continue elif tok in ('-p', '--password') or ( tok.startswith('-') and _SENSITIVE_ARG_RE.search(tok) @@ -771,7 +797,7 @@ def _sanitize_command_line_args(raw_args: str) -> str: redact_next = True continue sanitized.append(tok) - return ' '.join(sanitized) + return ' '.join(sanitized) if split_failed else shlex.join(sanitized) def _format_rfc3339_utc(dt_val: datetime.datetime) -> str: @@ -2275,9 +2301,11 @@ def discover_source_infra(self) -> None: host_mem_gb = self._detect_host_memory_gb() jvm_xmx_gb, jvm_cmd_args = self._detect_running_looker_jvm() mem_gb = jvm_xmx_gb if jvm_xmx_gb is not None else host_mem_gb + memory_overridden = False if self.looker_memory_gb_override: try: mem_gb = max(0.1, float(self.looker_memory_gb_override)) + memory_overridden = True except ValueError: self.preflight_warn( 'Source Infrastructure', @@ -2285,7 +2313,11 @@ def discover_source_infra(self) -> None: f'using detected memory ({mem_gb} GiB).', ) self.detected_memory_gb = round(mem_gb, 2) - self.detected_limit_memory_gb = round(max(host_mem_gb, mem_gb), 2) + self.detected_limit_memory_gb = ( + round(mem_gb, 2) + if memory_overridden + else round(max(host_mem_gb, mem_gb), 2) + ) if self.looker_startup_args_override: self.detected_command_line_args = _sanitize_command_line_args( diff --git a/export-to-core/tests/test_export_to_core.py b/export-to-core/tests/test_export_to_core.py index 312423b..6228a02 100755 --- a/export-to-core/tests/test_export_to_core.py +++ b/export-to-core/tests/test_export_to_core.py @@ -564,6 +564,35 @@ def test_discover_source_infra_and_sanitize_jvm_args(self): self.assertIn('-p REDACTED', exp.detected_command_line_args) self.assertIn('--clustered', exp.detected_command_line_args) + # Verify explicit LOOKER_MEMORY_GB override isn't inflated by host RAM. + exp.looker_memory_gb_override = '16' + with ( + mock.patch.object(exp, '_detect_host_memory_gb', return_value=128.0), + mock.patch.object( + exp, '_detect_running_looker_jvm', return_value=(None, '') + ), + ): + exp.discover_source_infra() + self.assertEqual(exp.detected_memory_gb, 16.0) + self.assertEqual(exp.detected_limit_memory_gb, 16.0) + + # Verify quoted sensitive values with spaces and malformed quotes. + quoted_sanitized = self.exp._sanitize_command_line_args( + '--port=9999 --password="my secret" --api-token \'two words\' ' + '--log-dir="/var/log/my looker"' + ) + self.assertNotIn('secret', quoted_sanitized) + self.assertNotIn('words', quoted_sanitized) + self.assertIn('--password=REDACTED', quoted_sanitized) + self.assertIn('--api-token REDACTED', quoted_sanitized) + self.assertIn("'--log-dir=/var/log/my looker'", quoted_sanitized) + + unclosed_sanitized = self.exp._sanitize_command_line_args( + '--port=9999 --password="my secret' + ) + self.assertNotIn('secret', unclosed_sanitized) + self.assertEqual(unclosed_sanitized, '--port=9999 --password=REDACTED') + # Verify interactive optional prompt (skip vs opt-in). exp_skip = self.exp.LookerExporter(backup_arg=tmpdir) with (