diff --git a/.nextchanges/bundles/cluster-libraries.md b/.nextchanges/bundles/cluster-libraries.md new file mode 100644 index 00000000000..d40748798cf --- /dev/null +++ b/.nextchanges/bundles/cluster-libraries.md @@ -0,0 +1 @@ +* Add libraries field to clusters. ([#6831](https://github.com/databricks/cli/pull/6831)) diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl new file mode 100644 index 00000000000..c8eba0a0bcb --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/databricks.yml.tmpl @@ -0,0 +1,36 @@ +bundle: + name: wheel-task-declared-libs + +workspace: + root_path: "~/.bundle/$UNIQUE_NAME" + +resources: + clusters: + test_cluster: + cluster_name: "test-cluster-$UNIQUE_NAME" + spark_version: "$DEFAULT_SPARK_VERSION" + node_type_id: "$NODE_TYPE_ID" + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - pypi: + package: requests + - pypi: + package: urllib3 + + jobs: + some_other_job: + name: "[${bundle.target}] Test Wheel Job $UNIQUE_NAME" + tasks: + - task_key: TestTask + existing_cluster_id: "${resources.clusters.test_cluster.cluster_id}" + python_wheel_task: + package_name: my_test_code + entry_point: run + parameters: + - "one" + - "two" + libraries: + - whl: ./dist/*.whl + - pypi: + package: six diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml new file mode 100644 index 00000000000..f9f4880725d --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/out.test.toml @@ -0,0 +1,4 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt new file mode 100644 index 00000000000..96612a33430 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/output.txt @@ -0,0 +1,94 @@ + +=== Deploy the cluster (declares requests and urllib3) and the wheel job that targets it +OK: deployed + +=== Run the job: its task installs the wheel and pypi 'six' on the shared cluster, out of band +OK: job ran + +=== Plan: the job's out-of-band 'six' shows as a removal, the declared libraries are unchanged +>>> plan_pypi_libs +{ + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + } +} + +=== Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests +>>> plan_pypi_libs +{ + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + }, + "libraries[pypi='urllib3;']": { + "action": "update", + "old": { + "pypi": { + "package": "urllib3" + } + }, + "remote": { + "pypi": { + "package": "urllib3" + } + } + } +} + +OK: redeployed + +>>> print_requests.py //libraries/uninstall //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[TEST_CLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "urllib3" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[TEST_CLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.test_cluster + delete resources.jobs.some_other_job + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 2 deleted diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script new file mode 100644 index 00000000000..d1eff7cc290 --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/script @@ -0,0 +1,35 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml +trap "errcode trace '$CLI' bundle destroy --auto-approve" EXIT + +# Show the cluster's pypi library plan entries; build/plan noise and the noisy wheel path go to LOG. +plan_pypi_libs() { + $CLI bundle plan -o json 2>>LOG.plan | jq '.plan["resources.clusters.test_cluster"].changes | with_entries(select(.key | startswith("libraries[pypi")))' +} + +title "Deploy the cluster (declares requests and urllib3) and the wheel job that targets it" +$CLI bundle deploy &> LOG.deploy +cat LOG.deploy | contains.py "clusters.test_cluster" > /dev/null +printf '\n%s\n' "OK: deployed" + +# Normalize server-generated resource IDs before we read requests/plans. +replace_ids.py + +title "Run the job: its task installs the wheel and pypi 'six' on the shared cluster, out of band" +$CLI bundle run some_other_job &> LOG.run +printf '\n%s\n' "OK: job ran" +# Flush the install requests the run recorded so they do not leak into the redeploy assertions. +print_requests.py //libraries/install > /dev/null + +title "Plan: the job's out-of-band 'six' shows as a removal, the declared libraries are unchanged" +trace plan_pypi_libs + +title "Remove the declared 'urllib3' and redeploy: uninstalls urllib3 and the job's libraries, keeps requests" +update_file.py databricks.yml " + - pypi: + package: urllib3" "" +trace plan_pypi_libs +$CLI bundle deploy &> LOG.deploy2 +cat LOG.deploy2 | contains.py "Updated clusters.test_cluster" > /dev/null +printf '\n%s\n' "OK: redeployed" +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml new file mode 100644 index 00000000000..e816575e41b --- /dev/null +++ b/acceptance/bundle/integration_whl/interactive_cluster_declared_libs/test.toml @@ -0,0 +1,8 @@ +# The cluster declares `requests` and `urllib3`; the wheel job's task targets the same cluster via +# existing_cluster_id and installs the wheel and pypi `six` on it. So the cluster reads back +# libraries it never declared and treats them as drift: removing `urllib3` uninstalls it and the +# job's libraries (marked UNINSTALL_ON_RESTART on cloud). Cloud + CloudSlow and the venv/wheel harness are inherited from the parent. +# Direct engine only (cluster libraries are a direct-engine feature). +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] diff --git a/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl b/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl new file mode 100644 index 00000000000..507730ec287 --- /dev/null +++ b/acceptance/bundle/invariant/configs/cluster_libraries.yml.tmpl @@ -0,0 +1,14 @@ +bundle: + name: test-bundle-$UNIQUE_NAME + +resources: + clusters: + foo: + cluster_name: test-cluster-$UNIQUE_NAME + spark_version: 13.3.x-scala2.12 + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/invariant/continue_293/test.toml b/acceptance/bundle/invariant/continue_293/test.toml index a02577b3504..15890459519 100644 --- a/acceptance/bundle/invariant/continue_293/test.toml +++ b/acceptance/bundle/invariant/continue_293/test.toml @@ -23,6 +23,9 @@ EnvMatrixExclude.no_instance_pool = ["INPUT_CONFIG=instance_pool.yml.tmpl"] # cluster_policies resource is not supported on v0.293.0 EnvMatrixExclude.no_cluster_policy = ["INPUT_CONFIG=cluster_policy.yml.tmpl"] +# cluster libraries (clusters.libraries) are not supported on v0.293.0 +EnvMatrixExclude.no_cluster_libraries = ["INPUT_CONFIG=cluster_libraries.yml.tmpl"] + # job_runs resource is not supported on v0.293.0 EnvMatrixExclude.no_job_run = ["INPUT_CONFIG=job_run.yml.tmpl"] diff --git a/acceptance/bundle/invariant/delete_idempotent/out.test.toml b/acceptance/bundle/invariant/delete_idempotent/out.test.toml index 9b900c7722d..5f37ab6036c 100644 --- a/acceptance/bundle/invariant/delete_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/delete_idempotent/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml index 9b900c7722d..5f37ab6036c 100644 --- a/acceptance/bundle/invariant/destroy_idempotent/out.test.toml +++ b/acceptance/bundle/invariant/destroy_idempotent/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/migrate/test.toml b/acceptance/bundle/invariant/migrate/test.toml index 43fb485e622..bfbcf9bb430 100644 --- a/acceptance/bundle/invariant/migrate/test.toml +++ b/acceptance/bundle/invariant/migrate/test.toml @@ -28,6 +28,8 @@ EnvMatrixExclude.no_genie_space = ["INPUT_CONFIG=genie_space.yml.tmpl"] EnvMatrixExclude.no_instance_pool = ["INPUT_CONFIG=instance_pool.yml.tmpl"] # Cluster policies are direct-only; the terraform deploy that seeds the migration fails for them. EnvMatrixExclude.no_cluster_policy = ["INPUT_CONFIG=cluster_policy.yml.tmpl"] +# Cluster libraries are direct-only; the terraform deploy that seeds the migration fails for them. +EnvMatrixExclude.no_cluster_libraries = ["INPUT_CONFIG=cluster_libraries.yml.tmpl"] # AI Gateway securables are direct-only; the terraform deploy that seeds the migration fails for them. EnvMatrixExclude.no_model_service = ["INPUT_CONFIG=model_service.yml.tmpl"] diff --git a/acceptance/bundle/invariant/no_drift/out.test.toml b/acceptance/bundle/invariant/no_drift/out.test.toml index a7c6da3e8ac..16ac514f8f2 100644 --- a/acceptance/bundle/invariant/no_drift/out.test.toml +++ b/acceptance/bundle/invariant/no_drift/out.test.toml @@ -8,6 +8,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/invariant/test.toml b/acceptance/bundle/invariant/test.toml index 09d4507c261..7e51bc36e1e 100644 --- a/acceptance/bundle/invariant/test.toml +++ b/acceptance/bundle/invariant/test.toml @@ -25,6 +25,7 @@ EnvMatrix.INPUT_CONFIG = [ "catalog_optional_fields.yml.tmpl", "cluster.yml.tmpl", "cluster_apply_policy_default_values.yml.tmpl", + "cluster_libraries.yml.tmpl", "cluster_policy.yml.tmpl", "dashboard.yml.tmpl", "job_apply_policy_default_values_job_cluster.yml.tmpl", diff --git a/acceptance/bundle/refschema/out.fields.txt b/acceptance/bundle/refschema/out.fields.txt index b4d9cbd22c8..3264827f9c1 100644 --- a/acceptance/bundle/refschema/out.fields.txt +++ b/acceptance/bundle/refschema/out.fields.txt @@ -461,6 +461,23 @@ resources.clusters.*.jdbc_port int REMOTE resources.clusters.*.kind compute.Kind ALL resources.clusters.*.last_restarted_time int64 REMOTE resources.clusters.*.last_state_loss_time int64 REMOTE +resources.clusters.*.libraries []compute.Library ALL +resources.clusters.*.libraries[*] compute.Library ALL +resources.clusters.*.libraries[*].cran *compute.RCranLibrary ALL +resources.clusters.*.libraries[*].cran.package string ALL +resources.clusters.*.libraries[*].cran.repo string ALL +resources.clusters.*.libraries[*].egg string ALL +resources.clusters.*.libraries[*].jar string ALL +resources.clusters.*.libraries[*].maven *compute.MavenLibrary ALL +resources.clusters.*.libraries[*].maven.coordinates string ALL +resources.clusters.*.libraries[*].maven.exclusions []string ALL +resources.clusters.*.libraries[*].maven.exclusions[*] string ALL +resources.clusters.*.libraries[*].maven.repo string ALL +resources.clusters.*.libraries[*].pypi *compute.PythonPyPiLibrary ALL +resources.clusters.*.libraries[*].pypi.package string ALL +resources.clusters.*.libraries[*].pypi.repo string ALL +resources.clusters.*.libraries[*].requirements string ALL +resources.clusters.*.libraries[*].whl string ALL resources.clusters.*.lifecycle *dresources.StateLifecycle REMOTE STATE resources.clusters.*.lifecycle *resources.LifecycleWithStarted INPUT resources.clusters.*.lifecycle resources.Lifecycle INPUT diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl new file mode 100644 index 00000000000..f5e3173e888 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/databricks.yml.tmpl @@ -0,0 +1,23 @@ +bundle: + name: cluster-libraries-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +artifacts: + my_test_code: + type: whl + path: . + # Use 'python' because 'python3' does not exist in Windows virtualenvs. + build: python setup.py bdist_wheel + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - whl: ./dist/*.whl diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml b/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/output.txt b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt new file mode 100644 index 00000000000..ef3f8cf7c11 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/output.txt @@ -0,0 +1,33 @@ + +=== Deploy a cluster with a local wheel library +OK: cluster created with wheel + +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} + +=== Badness: wheel code changes but version does not, so redeploy does not reinstall it +>>> jq .plan["resources.clusters.mycluster"].action tmp.plan.json +"skip" + +OK: redeployed without reinstalling the changed wheel (known limitation) + +>>> print_requests.py //libraries/install + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/script b/acceptance/bundle/resources/clusters/libraries-content-change/script new file mode 100644 index 00000000000..4dcfa152f27 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/script @@ -0,0 +1,29 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy a cluster with a local wheel library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with wheel" +trace print_requests.py //libraries/install + +# Change only the wheel's code, keeping version 0.0.1 so the built filename - and +# thus the uploaded workspace path - is byte-for-byte identical to the first deploy. +title "Badness: wheel code changes but version does not, so redeploy does not reinstall it" +update_file.py my_test_code/__main__.py "Hello from my func" "Hello from my func v2" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan + +# The wheel path is unchanged, so the cluster plans as "skip" - the library change goes undetected and +# the stale wheel keeps running. +trace jq '.plan["resources.clusters.mycluster"].action' tmp.plan.json +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +printf '\n%s\n' "OK: redeployed without reinstalling the changed wheel (known limitation)" +trace print_requests.py //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare b/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare new file mode 100644 index 00000000000..31e6de1dbf5 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/script.prepare @@ -0,0 +1,3 @@ +uv venv -q .venv +venv_activate +uv pip install -q --no-index setuptools diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/setup.py b/acceptance/bundle/resources/clusters/libraries-content-change/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/resources/clusters/libraries-content-change/test.toml b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml new file mode 100644 index 00000000000..8eba7f22dfc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-content-change/test.toml @@ -0,0 +1,14 @@ +Badness = "A local wheel whose contents change but whose version (and thus workspace path) does not is not detected in non-dev mode, so redeploy does not reinstall it; the stale wheel keeps running. See the TODO in bundle/direct/dresources/cluster.go DoUpdate." + +Cloud = true +CloudSlow = true +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", ".venv", "build", "dist", "my_test_code.egg-info", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl new file mode 100644 index 00000000000..40f63c9241c --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/databricks.yml.tmpl @@ -0,0 +1,18 @@ +bundle: + name: cluster-libraries-repo-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests + repo: https://pypi.org/simple diff --git a/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml b/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-repo/output.txt b/acceptance/bundle/resources/clusters/libraries-repo/output.txt new file mode 100644 index 00000000000..03dfa68dc62 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/output.txt @@ -0,0 +1,21 @@ + +=== Deploy creates the cluster and installs the pypi library +OK: cluster created with pypi library + +=== Plan is a no-op after deploy: the repo round-trips +>>> [CLI] bundle plan +Plan: 0 to add, 0 to change, 0 to delete, 1 unchanged + +=== Changing only the repo is planned as an update +>>> [CLI] bundle plan +update clusters.mycluster + +Plan: 0 to add, 1 to change, 0 to delete, 0 unchanged + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-repo/script b/acceptance/bundle/resources/clusters/libraries-repo/script new file mode 100644 index 00000000000..c44c39e8b1f --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/script @@ -0,0 +1,21 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy creates the cluster and installs the pypi library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with pypi library" + +title "Plan is a no-op after deploy: the repo round-trips" +trace $CLI bundle plan + +title "Changing only the repo is planned as an update" +update_file.py databricks.yml "repo: https://pypi.org/simple" "repo: https://example.invalid/simple" +trace $CLI bundle plan diff --git a/acceptance/bundle/resources/clusters/libraries-repo/test.toml b/acceptance/bundle/resources/clusters/libraries-repo/test.toml new file mode 100644 index 00000000000..4724ab632f1 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-repo/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = false + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl new file mode 100644 index 00000000000..b5d17cb9690 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/databricks.yml.tmpl @@ -0,0 +1,13 @@ +bundle: + name: cluster-libraries-scenarios-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml new file mode 100644 index 00000000000..dd03baaabb6 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/out.test.toml @@ -0,0 +1,4 @@ +Cloud = false +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt new file mode 100644 index 00000000000..c31dc73b484 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/output.txt @@ -0,0 +1,216 @@ + +=== Deploy a cluster that declares no libraries +OK: cluster created + +=== Out of band: a job run (or the UI) installs 'six' on the shared cluster +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} + +=== No libraries section: six is skipped as unmanaged, not drift +>>> plan_libs +{ + "libraries": { + "action": "skip", + "reason": "unmanaged", + "remote": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} + +=== Declare 'requests': plan installs it and uninstalls the out-of-band six +>>> plan_libs +{ + "libraries": { + "action": "update", + "new": [ + { + "pypi": { + "package": "requests" + } + } + ], + "remote": [ + { + "pypi": { + "package": "six" + } + } + ] + }, + "libraries[pypi='requests;']": { + "action": "update", + "new": { + "pypi": { + "package": "requests" + } + } + }, + "libraries[pypi='six;']": { + "action": "update", + "remote": { + "pypi": { + "package": "six" + } + } + } +} + +>>> print_requests.py //libraries/install //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "six" + } + } + ] + } +} +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Drift: 'requests' is uninstalled out of band; plan reinstalls the declared library +>>> print_requests.py //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> plan_libs +{ + "libraries": { + "action": "update", + "old": [ + { + "pypi": { + "package": "requests" + } + } + ], + "new": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> print_requests.py //libraries/install //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[MYCLUSTER_ID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Remove the libraries section: libraries become unmanaged, requests stays installed, no install or uninstall +>>> plan_libs +{ + "libraries": { + "action": "skip", + "reason": "unmanaged", + "old": [ + { + "pypi": { + "package": "requests" + } + } + ], + "remote": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> print_requests.py //libraries/uninstall //libraries/install + +=== No-op redeploy: libraries are unmanaged and nothing changes +>>> plan_libs +{ + "libraries": { + "action": "skip", + "reason": "unmanaged", + "old": [ + { + "pypi": { + "package": "requests" + } + } + ], + "remote": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +>>> print_requests.py //libraries/uninstall //libraries/install + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/script b/acceptance/bundle/resources/clusters/libraries-scenarios/script new file mode 100644 index 00000000000..26e80df1b66 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/script @@ -0,0 +1,68 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt tmp.plan.json +} +trap cleanup EXIT + +# Show the cluster's libraries plan entries; reading the saved plan keeps output identical across READPLAN. +plan_libs() { + jq '.plan["resources.clusters.mycluster"].changes | with_entries(select(.key | startswith("libraries")))' tmp.plan.json +} + +# Deploy output is verbose and differs plan/no-plan; send it to LOG and assert the key line. +title "Deploy a cluster that declares no libraries" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created" + +# Server-generated cluster id, read from state to target the out-of-band calls. +CLUSTER_ID=$(read_id.py mycluster) + +title "Out of band: a job run (or the UI) installs 'six' on the shared cluster" +MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/install --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"six\"}}]}" > /dev/null +trace print_requests.py //libraries/install + +title "No libraries section: six is skipped as unmanaged, not drift" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs + +title "Declare 'requests': plan installs it and uninstalls the out-of-band six" +update_file.py databricks.yml " num_workers: 1" " num_workers: 1 + libraries: + - pypi: + package: requests" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install //libraries/uninstall + +title "Drift: 'requests' is uninstalled out of band; plan reinstalls the declared library" +MSYS_NO_PATHCONV=1 $CLI api post /api/2.0/libraries/uninstall --json "{\"cluster_id\": \"$CLUSTER_ID\", \"libraries\": [{\"pypi\": {\"package\": \"requests\"}}]}" > /dev/null +trace print_requests.py //libraries/uninstall +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install //libraries/uninstall + +title "Remove the libraries section: libraries become unmanaged, requests stays installed, no install or uninstall" +update_file.py databricks.yml " num_workers: 1 + libraries: + - pypi: + package: requests" " num_workers: 1" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "1 unchanged" > /dev/null +trace print_requests.py //libraries/uninstall //libraries/install + +title "No-op redeploy: libraries are unmanaged and nothing changes" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +trace plan_libs +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "1 unchanged" > /dev/null +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml new file mode 100644 index 00000000000..328df03eb91 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-scenarios/test.toml @@ -0,0 +1,9 @@ +# Without a libraries section the cluster's libraries are unmanaged (skipped with reason `unmanaged`), so an out-of-band library (job task lib or API install) is not drift. With a section, every library on the cluster is managed: out-of-band ones are uninstalled, declared ones installed, and drift is corrected. +# Local only: the out-of-band library is injected via the Libraries API, deterministic locally but racy on cloud (the job-installed variant runs on cloud in interactive_cluster_declared_libs). +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +# READPLAN=1 feeds the serialized plan to `bundle deploy --plan`. +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl new file mode 100644 index 00000000000..705177abe13 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/databricks.yml.tmpl @@ -0,0 +1,19 @@ +bundle: + name: cluster-libraries-stopped-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + lifecycle: + started: false + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt new file mode 100644 index 00000000000..d7913bf1bb0 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/output.txt @@ -0,0 +1,14 @@ + +=== Deploy libraries on a started=false cluster +OK: created on stopped cluster + +=== Change the libraries and redeploy the stopped cluster +OK: libraries changed on stopped cluster + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script new file mode 100644 index 00000000000..ec6fea46d5f --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/script @@ -0,0 +1,25 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy libraries on a started=false cluster" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: created on stopped cluster" + +title "Change the libraries and redeploy the stopped cluster" +update_file.py databricks.yml " - pypi: + package: requests" " - pypi: + package: requests + - pypi: + package: numpy" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +cat LOG.redeploy | contains.py "Updated clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: libraries changed on stopped cluster" diff --git a/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml new file mode 100644 index 00000000000..4724ab632f1 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-stopped-cluster/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = false + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl new file mode 100644 index 00000000000..60dbf56bd16 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/databricks.yml.tmpl @@ -0,0 +1,17 @@ +bundle: + name: cluster-libraries-update-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + instance_pool_id: $TEST_INSTANCE_POOL_ID + num_workers: 1 + libraries: + - pypi: + package: requests diff --git a/acceptance/bundle/resources/clusters/libraries-update/out.test.toml b/acceptance/bundle/resources/clusters/libraries-update/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries-update/output.txt b/acceptance/bundle/resources/clusters/libraries-update/output.txt new file mode 100644 index 00000000000..64c9ac77476 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/output.txt @@ -0,0 +1,69 @@ + +=== Create: the declared library installs on the new cluster +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + } + ] + } +} + +=== Update: adding a library installs the declared set on the running cluster +>>> print_requests.py //libraries/install //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} + +=== Delete: emptying the libraries list uninstalls them +>>> print_requests.py //libraries/uninstall //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "pypi": { + "package": "six" + } + } + ] + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries-update/script b/acceptance/bundle/resources/clusters/libraries-update/script new file mode 100644 index 00000000000..9ee680a1e72 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/script @@ -0,0 +1,39 @@ +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); the recorded library requests are the proof. +title "Create: the declared library installs on the new cluster" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.create +cat LOG.create | contains.py "Created clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install + +title "Update: adding a library installs the declared set on the running cluster" +update_file.py databricks.yml " - pypi: + package: requests" " - pypi: + package: requests + - pypi: + package: six" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.update +cat LOG.update | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/install //libraries/uninstall + +# An empty list keeps the libraries managed, so it uninstalls them; dropping the section would leave them unmanaged. +title "Delete: emptying the libraries list uninstalls them" +update_file.py databricks.yml " libraries: + - pypi: + package: requests + - pypi: + package: six +" " libraries: [] +" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.remove +cat LOG.remove | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/uninstall //libraries/install diff --git a/acceptance/bundle/resources/clusters/libraries-update/test.toml b/acceptance/bundle/resources/clusters/libraries-update/test.toml new file mode 100644 index 00000000000..24d1138996d --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries-update/test.toml @@ -0,0 +1,11 @@ +Cloud = true +CloudSlow = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl b/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl new file mode 100644 index 00000000000..2364bafe42a --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/databricks.yml.tmpl @@ -0,0 +1,25 @@ +bundle: + name: cluster-libraries-$UNIQUE_NAME + +workspace: + root_path: ~/.bundle/$UNIQUE_NAME + +artifacts: + my_test_code: + type: whl + path: . + # Use 'python' because 'python3' does not exist in Windows virtualenvs. + build: python setup.py bdist_wheel + +resources: + clusters: + mycluster: + cluster_name: mycluster-$UNIQUE_NAME + spark_version: $DEFAULT_SPARK_VERSION + node_type_id: $NODE_TYPE_ID + num_workers: 1 + data_security_mode: $DATA_SECURITY_MODE + libraries: + - pypi: + package: requests + - whl: ./dist/*.whl diff --git a/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py b/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py new file mode 100644 index 00000000000..909f1f3220d --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/my_test_code/__init__.py @@ -0,0 +1,2 @@ +__version__ = "0.0.1" +__author__ = "Databricks" diff --git a/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py b/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py new file mode 100644 index 00000000000..ea918ce2d53 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/my_test_code/__main__.py @@ -0,0 +1,16 @@ +""" +The entry point of the Python Wheel +""" + +import sys + + +def main(): + # This method will print the provided arguments + print("Hello from my func") + print("Got arguments:") + print(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/acceptance/bundle/resources/clusters/libraries/out.test.toml b/acceptance/bundle/resources/clusters/libraries/out.test.toml new file mode 100644 index 00000000000..17e040e07dc --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/out.test.toml @@ -0,0 +1,5 @@ +Cloud = true +CloudSlow = true +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.DMS = ["", "true"] +EnvMatrix.READPLAN = ["", "1"] diff --git a/acceptance/bundle/resources/clusters/libraries/output.txt b/acceptance/bundle/resources/clusters/libraries/output.txt new file mode 100644 index 00000000000..6e0dc533ca0 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/output.txt @@ -0,0 +1,58 @@ + +=== Deploy a cluster with a pypi and a local wheel library +>>> jq .plan["resources.clusters.mycluster"].new_state.value.libraries tmp.plan.json +[ + { + "pypi": { + "package": "requests" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } +] + +OK: cluster created with libraries + +=== Libraries installed via the Libraries API (wheel rewritten to its uploaded path) +>>> print_requests.py //libraries/install +{ + "method": "POST", + "path": "/api/2.0/libraries/install", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "pypi": { + "package": "requests" + } + }, + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} + +=== Removing the wheel and redeploying uninstalls it +>>> print_requests.py //libraries/uninstall +{ + "method": "POST", + "path": "/api/2.0/libraries/uninstall", + "body": { + "cluster_id": "[UUID]", + "libraries": [ + { + "whl": "/Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME]/artifacts/.internal/my_test_code-0.0.1-py3-none-any.whl" + } + ] + } +} + +>>> [CLI] bundle destroy --auto-approve +The following resources will be deleted: + delete resources.clusters.mycluster + +All files and directories at the following location will be deleted: /Workspace/Users/[USERNAME]/.bundle/[UNIQUE_NAME] + +Destroy: 1 deleted diff --git a/acceptance/bundle/resources/clusters/libraries/script b/acceptance/bundle/resources/clusters/libraries/script new file mode 100644 index 00000000000..ad202b5b699 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/script @@ -0,0 +1,29 @@ +export DATA_SECURITY_MODE=USER_ISOLATION +envsubst < databricks.yml.tmpl > databricks.yml + +cleanup() { + trace $CLI bundle destroy --auto-approve + rm -f out.requests.txt +} +trap cleanup EXIT + +# Deploy output goes to LOG (differs fake vs cloud); echo a pass line instead. +title "Deploy a cluster with a pypi and a local wheel library" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan + +# The plan carries the local wheel rewritten to its uploaded .internal/ path, so +# `bundle deploy --plan` installs it without rebuilding. +trace jq '.plan["resources.clusters.mycluster"].new_state.value.libraries' tmp.plan.json +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.deploy +cat LOG.deploy | contains.py "Created clusters.mycluster" > /dev/null +printf '\n%s\n' "OK: cluster created with libraries" + +title "Libraries installed via the Libraries API (wheel rewritten to its uploaded path)" +trace print_requests.py //libraries/install + +title "Removing the wheel and redeploying uninstalls it" +update_file.py databricks.yml " - whl: ./dist/*.whl" "" +$CLI bundle plan -o json > tmp.plan.json 2>>LOG.plan +$CLI bundle deploy $(readplanarg tmp.plan.json) &> LOG.redeploy +cat LOG.redeploy | contains.py "Updated clusters.mycluster" > /dev/null +trace print_requests.py //libraries/uninstall diff --git a/acceptance/bundle/resources/clusters/libraries/script.prepare b/acceptance/bundle/resources/clusters/libraries/script.prepare new file mode 100644 index 00000000000..31e6de1dbf5 --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/script.prepare @@ -0,0 +1,3 @@ +uv venv -q .venv +venv_activate +uv pip install -q --no-index setuptools diff --git a/acceptance/bundle/resources/clusters/libraries/setup.py b/acceptance/bundle/resources/clusters/libraries/setup.py new file mode 100644 index 00000000000..8b48a92b4ce --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/setup.py @@ -0,0 +1,15 @@ +from setuptools import setup, find_packages + +import my_test_code + +setup( + name="my_test_code", + version=my_test_code.__version__, + author=my_test_code.__author__, + url="https://databricks.com", + author_email="john.doe@databricks.com", + description="my example wheel", + packages=find_packages(include=["my_test_code"]), + entry_points={"group1": "run=my_test_code.__main__:main"}, + install_requires=["setuptools"], +) diff --git a/acceptance/bundle/resources/clusters/libraries/test.toml b/acceptance/bundle/resources/clusters/libraries/test.toml new file mode 100644 index 00000000000..ea6413633ba --- /dev/null +++ b/acceptance/bundle/resources/clusters/libraries/test.toml @@ -0,0 +1,12 @@ +Cloud = true +CloudSlow = true +RecordRequests = true + +EnvMatrix.DATABRICKS_BUNDLE_ENGINE = ["direct"] +EnvMatrix.READPLAN = ["", "1"] + +Ignore = [".databricks", ".venv", "build", "dist", "my_test_code.egg-info", "databricks.yml", "tmp.plan.json"] + +[[Repls]] +Old = "[0-9]{4}-[0-9]{6}-[0-9a-z]{8}" +New = "[UUID]" diff --git a/bundle/config/mutator/validate_cluster_libraries.go b/bundle/config/mutator/validate_cluster_libraries.go new file mode 100644 index 00000000000..f13cd3be373 --- /dev/null +++ b/bundle/config/mutator/validate_cluster_libraries.go @@ -0,0 +1,43 @@ +package mutator + +import ( + "context" + + "github.com/databricks/cli/bundle" + "github.com/databricks/cli/bundle/config/engine" + "github.com/databricks/cli/libs/diag" +) + +type validateClusterLibraries struct { + engine engine.EngineType +} + +// ValidateClusterLibraries returns a mutator that errors when cluster libraries are used with +// the terraform deployment engine. Cluster libraries are only supported in direct deployment mode. +func ValidateClusterLibraries(e engine.EngineType) bundle.Mutator { + return &validateClusterLibraries{engine: e} +} + +func (m *validateClusterLibraries) Name() string { + return "ValidateClusterLibraries" +} + +func (m *validateClusterLibraries) Apply(_ context.Context, b *bundle.Bundle) diag.Diagnostics { + if m.engine.IsDirect() { + return nil + } + + var diags diag.Diagnostics + for key, cluster := range b.Config.Resources.Clusters { + if cluster == nil || len(cluster.Libraries) == 0 { + continue + } + path := "resources.clusters." + key + ".libraries" + diags = diags.Append(diag.Diagnostic{ + Severity: diag.Error, + Summary: "cluster libraries are only supported in direct deployment mode", + Locations: b.Config.GetLocations(path), + }) + } + return diags +} diff --git a/bundle/config/resources/clusters.go b/bundle/config/resources/clusters.go index aec5e886346..75b8f66b93d 100644 --- a/bundle/config/resources/clusters.go +++ b/bundle/config/resources/clusters.go @@ -19,6 +19,9 @@ type Cluster struct { // Lifecycle shadows BaseResource.Lifecycle to add support for lifecycle.started. Lifecycle *LifecycleWithStarted `json:"lifecycle,omitempty"` + // Libraries are installed via the Libraries API, not the cluster spec. + Libraries []compute.Library `json:"libraries,omitempty"` + Permissions []ClusterPermission `json:"permissions,omitempty"` } diff --git a/bundle/deployplan/plan.go b/bundle/deployplan/plan.go index 28ae78dde40..0fd97868ce4 100644 --- a/bundle/deployplan/plan.go +++ b/bundle/deployplan/plan.go @@ -184,6 +184,10 @@ const ( // set but the backend populated (old and new nil, remote set). It is left in place rather // than recreated - the user does not manage it and the value cannot be changed anyway. ReasonImmutableBackendValue = "immutable_backend_value" + // ReasonUnmanaged: the config does not declare the field at all, so the bundle does not manage + // it and whatever the remote reports is not drift (e.g. cluster libraries without a libraries + // section, where job runs install their task libraries cluster-wide). + ReasonUnmanaged = "unmanaged" // Special reason that results in removing this change from the plan ReasonDrop = "!drop" diff --git a/bundle/direct/dresources/cluster.go b/bundle/direct/dresources/cluster.go index a2348a5b6ea..7f1eb26dffc 100644 --- a/bundle/direct/dresources/cluster.go +++ b/bundle/direct/dresources/cluster.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strings" "time" "github.com/databricks/cli/bundle/config/resources" @@ -16,8 +17,12 @@ import ( "github.com/databricks/databricks-sdk-go/marshal" "github.com/databricks/databricks-sdk-go/retries" "github.com/databricks/databricks-sdk-go/service/compute" + "golang.org/x/sync/errgroup" ) +// librariesWaitTimeout bounds how long we poll for libraries to finish installing. +const librariesWaitTimeout = 15 * time.Minute + // clusterWaitTimeout bounds how long we poll for a cluster to reach its target // state (RUNNING/TERMINATED) after create, edit, or start/stop. Provisioning can // legitimately take longer than 15 minutes on capacity-constrained workspaces @@ -33,6 +38,10 @@ type ClusterState struct { compute.ClusterSpec Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` + + // Libraries are installed via the Libraries API, not the cluster spec, and managed as + // part of the cluster (see reconcileLibraries and the install in WaitAfterCreate). + Libraries []compute.Library `json:"libraries,omitempty"` } // Custom marshalers needed because embedded compute.ClusterSpec has its own MarshalJSON @@ -57,6 +66,10 @@ type ClusterRemote struct { compute.ClusterDetails ApplyPolicyDefaultValues bool `json:"apply_policy_default_values,omitempty"` Lifecycle *StateLifecycle `json:"lifecycle,omitempty"` + + // Libraries is populated by DoRead from the Libraries cluster-status API (the cluster + // GET does not return installed libraries), so it participates in drift detection. + Libraries []compute.Library `json:"libraries,omitempty"` } func (r *ClusterRemote) UnmarshalJSON(b []byte) error { @@ -81,6 +94,7 @@ func (r *ResourceCluster) PrepareState(input *resources.Cluster) *ClusterState { s := &ClusterState{ ClusterSpec: input.ClusterSpec, Lifecycle: nil, + Libraries: input.Libraries, } if input.Lifecycle != nil && input.Lifecycle.Started != nil { s.Lifecycle = &StateLifecycle{Started: input.Lifecycle.Started} @@ -131,19 +145,36 @@ func (r *ResourceCluster) RemapState(input *ClusterRemote) *ClusterState { ForceSendFields: utils.FilterFields[compute.ClusterSpec](input.ForceSendFields), }, Lifecycle: input.Lifecycle, + Libraries: input.Libraries, } return spec } func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote, error) { - details, err := r.client.Clusters.GetByClusterId(ctx, id) - if err != nil { + var details *compute.ClusterDetails + var libraries []compute.Library + + // The cluster GET and the library-status GET are independent, so run them concurrently. + g, ctx := errgroup.WithContext(ctx) + g.Go(func() error { + var err error + details, err = r.client.Clusters.GetByClusterId(ctx, id) + return err + }) + g.Go(func() error { + var err error + libraries, err = r.readLibraries(ctx, id) + return err + }) + if err := g.Wait(); err != nil { return nil, err } + remote := &ClusterRemote{ ClusterDetails: *details, ApplyPolicyDefaultValues: false, Lifecycle: nil, + Libraries: libraries, } // The GET response carries apply_policy_default_values only under .spec (a snapshot of the // create/edit settings), not at the top level. Promote it so RemapState is a dumb copy. @@ -161,9 +192,29 @@ func (r *ResourceCluster) DoRead(ctx context.Context, id string) (*ClusterRemote default: remote.Lifecycle = nil } + return remote, nil } +// readLibraries returns the bundle-managed libraries installed on the cluster. +// https://docs.databricks.com/api/workspace/libraries/clusterstatus +func (r *ResourceCluster) readLibraries(ctx context.Context, id string) ([]compute.Library, error) { + statuses, err := r.client.Libraries.ClusterStatusByClusterId(ctx, id) + if err != nil { + return nil, err + } + var libraries []compute.Library + for _, s := range statuses.LibraryStatuses { + // Libraries set for all clusters via the UI are not managed by the bundle; a library + // pending uninstall on restart is on its way out. Skip both. + if s.Library == nil || s.IsLibraryForAllClusters || s.Status == compute.LibraryInstallStatusUninstallOnRestart { + continue + } + libraries = append(libraries, *s.Library) + } + return libraries, nil +} + func (r *ResourceCluster) DoCreate(ctx context.Context, config *ClusterState) (string, *ClusterRemote, error) { wait, err := r.client.Clusters.Create(ctx, makeCreateCluster(&config.ClusterSpec)) if err != nil { @@ -172,14 +223,27 @@ func (r *ResourceCluster) DoCreate(ctx context.Context, config *ClusterState) (s return wait.ClusterId, nil, nil } -// hasClusterChanges reports whether the plan entry contains any Update changes -// to fields that belong to the Cluster Edit API (i.e., not lifecycle-only fields). -func hasClusterChanges(entry *PlanEntry) bool { - return entry.Changes.HasChangeExcept("lifecycle", "lifecycle.started") +// hasClusterSpecChanges reports whether the plan entry changes a Cluster Edit API field — +// anything other than lifecycle (start/stop) and libraries (handled via the Libraries API). +func hasClusterSpecChanges(entry *PlanEntry) bool { + for field, change := range entry.Changes { + if change.Action == deployplan.Skip { + continue + } + node, err := structpath.ParsePath(field) + if err != nil { + continue + } + top, _ := node.Prefix(1).StringKey() + if top != "lifecycle" && top != "libraries" { + return true + } + } + return false } func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *ClusterState, entry *PlanEntry) (*ClusterRemote, error) { - if hasClusterChanges(entry) { + if hasClusterSpecChanges(entry) { // Same retry as in TF provider logic // https://github.com/databricks/terraform-provider-databricks/blob/3eecd0f90cf99d7777e79a3d03c41f9b2aafb004/clusters/resource_cluster.go#L624 _, err := retries.Poll(ctx, clusterWaitTimeout, func() (*compute.WaitGetClusterRunning[struct{}], *retries.Err) { @@ -200,6 +264,20 @@ func (r *ResourceCluster) DoUpdate(ctx context.Context, id string, config *Clust } } + // TODO: a local whl/jar whose workspace path is unchanged but whose contents + // changed (same name+version, non-dev mode) is not detected here, so it is not reinstalled. + // Dev mode handles this via patchwheel (a source-derived version bump). + if entry.Changes.HasChange(librariesPath) { + if err := r.reconcileLibraries(ctx, id, config.Libraries, entry); err != nil { + return nil, err + } + // Installs apply live on a running cluster. Uninstalls are marked UNINSTALL_ON_RESTART + // by the backend and take effect at the cluster's next restart; the bundle never restarts it. + if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { + return nil, err + } + } + if config.Lifecycle == nil || config.Lifecycle.Started == nil { return nil, nil } @@ -244,6 +322,20 @@ func (r *ResourceCluster) WaitAfterCreate(ctx context.Context, id string, config return nil, err } + // Install libraries once the cluster is running: installs only progress on a running cluster. + // TODO: Wait is supposed to be side effect free, but in this case moving it to + // the create will cause a wait for libraries to be installed befor the cluster is installed. + // this increases the risk of losing the cluster. This is a limitation + if len(config.Libraries) > 0 { + err = r.client.Libraries.Install(ctx, compute.InstallLibraries{ClusterId: id, Libraries: config.Libraries}) + if err != nil { + return nil, err + } + if err := r.waitForInstall(ctx, id, config.Libraries); err != nil { + return nil, err + } + } + if config.Lifecycle != nil && config.Lifecycle.Started != nil && !*config.Lifecycle.Started { // started=false: terminate the cluster after it reaches RUNNING. // Note: Delete terminates the cluster; permanent removal is a separate API (permanent-delete). @@ -311,6 +403,16 @@ func (r *ResourceCluster) OverrideChangeDesc(ctx context.Context, p *structpath. if remoteState != nil && remoteState.State == compute.StateRunning { change.Action = deployplan.Resize } + + case "libraries": + // Without a libraries section the bundle does not manage the cluster's libraries, matching + // the behaviour before the field existed: job runs install their task libraries cluster-wide, + // so what the cluster reports is not drift. With no section, New is nil and the difference + // arrives as a single whole-field change; `libraries: []` keeps New non-nil and stays managed. + if p.String() == "libraries" && change.New == nil { + change.Action = deployplan.Skip + change.Reason = deployplan.ReasonUnmanaged + } } return nil } @@ -426,3 +528,150 @@ func makeEditCluster(id string, config *compute.ClusterSpec) compute.EditCluster return edit } + +// librariesPath is the ClusterState path of the libraries slice, used to detect library changes. +var librariesPath = structpath.MustParsePath("libraries") + +// KeyedSlices compares libraries by identity rather than index so reordering (or the +// read-order the status API returns) does not produce phantom diffs. +func (*ResourceCluster) KeyedSlices() map[string]any { + return map[string]any{"libraries": libraryKey} +} + +// reconcileLibraries uninstalls libraries dropped from config and installs the desired set. +// The Libraries API exposes install and uninstall as separate endpoints, so this is two calls. +func (r *ResourceCluster) reconcileLibraries(ctx context.Context, id string, desired []compute.Library, entry *PlanEntry) error { + removed := removedLibraries(desired, entry) + if len(removed) > 0 { + err := r.client.Libraries.Uninstall(ctx, compute.UninstallLibraries{ClusterId: id, Libraries: removed}) + if err != nil { + return err + } + } + if len(desired) > 0 { + return r.client.Libraries.Install(ctx, compute.InstallLibraries{ClusterId: id, Libraries: desired}) + } + return nil +} + +// removedLibraries returns libraries present in the remote state but absent from the desired set. +func removedLibraries(desired []compute.Library, entry *PlanEntry) []compute.Library { + remote, ok := entry.RemoteState.(*ClusterRemote) + if !ok || remote == nil { + return nil + } + desiredKeys := make(map[string]struct{}, len(desired)) + for _, l := range desired { + desiredKeys[libraryMapKey(l)] = struct{}{} + } + var result []compute.Library + for _, l := range remote.Libraries { + if _, ok := desiredKeys[libraryMapKey(l)]; !ok { + result = append(result, l) + } + } + return result +} + +// waitForInstall polls until every desired library reaches a terminal installed state. It returns +// early without waiting when the cluster is not running: installs only progress on a running +// cluster and are queued until it next starts. +func (r *ResourceCluster) waitForInstall(ctx context.Context, id string, desired []compute.Library) error { + if len(desired) == 0 { + return nil + } + details, err := r.client.Clusters.GetByClusterId(ctx, id) + if err != nil { + return err + } + if details.State != compute.StateRunning { + log.Debugf(ctx, "cluster %s is not running (%s); skipping wait for library installation", id, details.State) + return nil + } + + desiredKeys := make(map[string]struct{}, len(desired)) + for _, l := range desired { + typ, val := libraryWaitKey(l) + if typ == "" { + // Unknown library type: it can't be matched in cluster-status, so don't wait for it. + continue + } + desiredKeys[typ+"="+val] = struct{}{} + } + + _, err = retries.Poll(ctx, librariesWaitTimeout, func() (*struct{}, *retries.Err) { + statuses, err := r.client.Libraries.ClusterStatusByClusterId(ctx, id) + if err != nil { + return nil, retries.Halt(err) + } + pending := len(desiredKeys) + for _, s := range statuses.LibraryStatuses { + if s.Library == nil { + continue + } + if _, ok := desiredKeys[libraryWaitMapKey(*s.Library)]; !ok { + continue + } + switch s.Status { + case compute.LibraryInstallStatusFailed: + return nil, retries.Halt(fmt.Errorf("library %s failed to install: %s", libraryWaitMapKey(*s.Library), strings.Join(s.Messages, "; "))) + case compute.LibraryInstallStatusInstalled, compute.LibraryInstallStatusSkipped, compute.LibraryInstallStatusRestored: + pending-- + case compute.LibraryInstallStatusPending, compute.LibraryInstallStatusResolving, compute.LibraryInstallStatusInstalling, compute.LibraryInstallStatusUninstallOnRestart: + // Still in progress (or being removed); keep polling. + } + } + if pending > 0 { + return nil, retries.Continues(fmt.Sprintf("waiting for %d librar(ies) to install on cluster %s", pending, id)) + } + return &struct{}{}, nil + }) + return err +} + +// libraryWaitKey identifies a library by its primary field only, used to match install-status reports. +func libraryWaitKey(l compute.Library) (string, string) { + switch { + case l.Whl != "": + return "whl", l.Whl + case l.Jar != "": + return "jar", l.Jar + case l.Egg != "": + return "egg", l.Egg + case l.Requirements != "": + return "requirements", l.Requirements + case l.Pypi != nil: + return "pypi", l.Pypi.Package + case l.Maven != nil: + return "maven", l.Maven.Coordinates + case l.Cran != nil: + return "cran", l.Cran.Package + } + return "", "" +} + +// libraryKey extends libraryWaitKey with repo/exclusions so a repo-only change is detected. +func libraryKey(l compute.Library) (string, string) { + typ, id := libraryWaitKey(l) + switch { + case l.Pypi != nil: + return typ, id + ";" + l.Pypi.Repo + case l.Maven != nil: + return typ, id + ";" + l.Maven.Repo + ";" + strings.Join(l.Maven.Exclusions, ",") + case l.Cran != nil: + return typ, id + ";" + l.Cran.Repo + } + return typ, id +} + +// libraryMapKey flattens libraryKey into a single string for map lookups. +func libraryMapKey(l compute.Library) string { + f, v := libraryKey(l) + return f + "=" + v +} + +// libraryWaitMapKey flattens libraryWaitKey into a single string for map lookups. +func libraryWaitMapKey(l compute.Library) string { + f, v := libraryWaitKey(l) + return f + "=" + v +} diff --git a/bundle/direct/dresources/cluster_test.go b/bundle/direct/dresources/cluster_test.go new file mode 100644 index 00000000000..7d3af4440d4 --- /dev/null +++ b/bundle/direct/dresources/cluster_test.go @@ -0,0 +1,68 @@ +package dresources + +import ( + "testing" + + "github.com/databricks/cli/bundle/deployplan" + "github.com/databricks/cli/libs/structs/structpath" + "github.com/databricks/databricks-sdk-go/service/compute" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestClusterOverrideChangeDescLibraries(t *testing.T) { + jobLib := []compute.Library{{Whl: "/Workspace/job.whl"}} + + tests := []struct { + name string + path string + change ChangeDesc + action deployplan.ActionType + reason string + }{ + { + name: "no section with remote libraries is unmanaged", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: nil, Remote: jobLib}, + action: deployplan.Skip, + reason: deployplan.ReasonUnmanaged, + }, + { + name: "removed section is unmanaged", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: jobLib, New: nil, Remote: jobLib}, + action: deployplan.Skip, + reason: deployplan.ReasonUnmanaged, + }, + { + name: "empty list stays managed", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: []compute.Library{}, Remote: jobLib}, + action: deployplan.Update, + }, + { + name: "declared libraries stay managed", + path: "libraries", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: jobLib, Remote: nil}, + action: deployplan.Update, + }, + { + // A per-library entry only exists when the config declares a list, so a missing New + // there is a removal to apply, not an unmanaged section. + name: "element removal stays managed", + path: "libraries[whl='/Workspace/job.whl']", + change: ChangeDesc{Action: deployplan.Update, Old: nil, New: nil, Remote: jobLib[0]}, + action: deployplan.Update, + }, + } + + r := &ResourceCluster{} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + change := tt.change + require.NoError(t, r.OverrideChangeDesc(t.Context(), structpath.MustParsePath(tt.path), &change, nil)) + assert.Equal(t, tt.action, change.Action) + assert.Equal(t, tt.reason, change.Reason) + }) + } +} diff --git a/bundle/internal/schema/annotations.yml b/bundle/internal/schema/annotations.yml index 11f39b90d1b..d0ce96db7eb 100644 --- a/bundle/internal/schema/annotations.yml +++ b/bundle/internal/schema/annotations.yml @@ -624,6 +624,9 @@ resources: notebook_path: "./src/my_notebook.py" ``` "$fields": + "libraries": + "description": |- + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. "lifecycle": "description": |- Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. diff --git a/bundle/internal/validation/generated/required_fields.go b/bundle/internal/validation/generated/required_fields.go index 5617f9f5ffa..41e2b93687f 100644 --- a/bundle/internal/validation/generated/required_fields.go +++ b/bundle/internal/validation/generated/required_fields.go @@ -56,6 +56,9 @@ var RequiredFields = map[string][]string{ "resources.clusters.*.init_scripts[*].s3": {"destination"}, "resources.clusters.*.init_scripts[*].volumes": {"destination"}, "resources.clusters.*.init_scripts[*].workspace": {"destination"}, + "resources.clusters.*.libraries[*].cran": {"package"}, + "resources.clusters.*.libraries[*].maven": {"coordinates"}, + "resources.clusters.*.libraries[*].pypi": {"package"}, "resources.clusters.*.permissions[*]": {"level"}, "resources.clusters.*.workload_type": {"clients"}, diff --git a/bundle/libraries/expand_glob_references.go b/bundle/libraries/expand_glob_references.go index 720142fe6d7..ab1da3df68d 100644 --- a/bundle/libraries/expand_glob_references.go +++ b/bundle/libraries/expand_glob_references.go @@ -198,6 +198,13 @@ var pipelineEnvDepsPattern = dyn.NewPattern( dyn.Key("dependencies"), ) +var clusterLibrariesPattern = dyn.NewPattern( + dyn.Key("resources"), + dyn.Key("clusters"), + dyn.AnyKey(), + dyn.Key("libraries"), +) + func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { expanders := []expandPattern{ { @@ -216,6 +223,10 @@ func (e *expand) Apply(ctx context.Context, b *bundle.Bundle) diag.Diagnostics { pattern: pipelineEnvDepsPattern, fn: expandEnvironmentDeps, }, + { + pattern: clusterLibrariesPattern, + fn: expandLibraries, + }, } var diags diag.Diagnostics diff --git a/bundle/libraries/remote_path.go b/bundle/libraries/remote_path.go index bc23bca4446..d45e8ff4c7e 100644 --- a/bundle/libraries/remote_path.go +++ b/bundle/libraries/remote_path.go @@ -139,6 +139,8 @@ func collectLocalLibraries(b *bundle.Bundle) (map[string][]LocationToUpdate, err taskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), envDepsPattern.Append(dyn.AnyIndex()), pipelineEnvDepsPattern.Append(dyn.AnyIndex()), // The AI Runtime task's code_source_path is a local archive (typically an diff --git a/bundle/libraries/same_name_libraries.go b/bundle/libraries/same_name_libraries.go index 49776fbd8c9..8fb140d7aa4 100644 --- a/bundle/libraries/same_name_libraries.go +++ b/bundle/libraries/same_name_libraries.go @@ -17,6 +17,8 @@ var patterns = []dyn.Pattern{ taskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), forEachTaskLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("whl")), + clusterLibrariesPattern.Append(dyn.AnyIndex(), dyn.Key("jar")), envDepsPattern.Append(dyn.AnyIndex()), pipelineEnvDepsPattern.Append(dyn.AnyIndex()), } diff --git a/bundle/libraries/switch_to_patched_wheels.go b/bundle/libraries/switch_to_patched_wheels.go index 56250d713a7..3c5ff184a97 100644 --- a/bundle/libraries/switch_to_patched_wheels.go +++ b/bundle/libraries/switch_to_patched_wheels.go @@ -79,6 +79,22 @@ func (c switchToPatchedWheels) Apply(ctx context.Context, b *bundle.Bundle) diag } } + // Update resources.clusters.*.libraries[*].whl + for clusterName, clusterRef := range b.Config.Resources.Clusters { + if clusterRef == nil { + continue + } + for libInd, lib := range clusterRef.Libraries { + repl := replacements[lib.Whl] + if repl != "" { + log.Debugf(ctx, "Updating resources.clusters.%s.libraries[%d].whl from %s to %s", clusterName, libInd, lib.Whl, repl) + clusterRef.Libraries[libInd].Whl = repl + } else { + log.Debugf(ctx, "Not updating resources.clusters.%s.libraries[%d].whl from %s. Available replacements: %v", clusterName, libInd, lib.Whl, slices.Sorted(maps.Keys(replacements))) + } + } + } + return nil } diff --git a/bundle/phases/plan.go b/bundle/phases/plan.go index aee481b2b14..f937e2e91c9 100644 --- a/bundle/phases/plan.go +++ b/bundle/phases/plan.go @@ -28,6 +28,7 @@ func PreDeployChecks(ctx context.Context, b *bundle.Bundle, isPlan bool, engine mutator.ValidateGitDetails(), mutator.ValidateDirectOnlyResources(engine), mutator.ValidateLifecycleStarted(engine), + mutator.ValidateClusterLibraries(engine), mutator.ValidateCascadeOnDestroy(engine), statemgmt.CheckRunningResource(engine), ) diff --git a/bundle/schema/jsonschema.json b/bundle/schema/jsonschema.json index d6b7dcf0b32..79b576dc88a 100644 --- a/bundle/schema/jsonschema.json +++ b/bundle/schema/jsonschema.json @@ -538,6 +538,10 @@ "$ref": "#/$defs/github.com/databricks/databricks-sdk-go/service/compute.Kind", "x-databricks-launch-stage": "GA" }, + "libraries": { + "description": "A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode.", + "$ref": "#/$defs/slice/github.com/databricks/databricks-sdk-go/service/compute.Library" + }, "lifecycle": { "description": "Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed.", "$ref": "#/$defs/github.com/databricks/cli/bundle/config/resources.LifecycleWithStarted" diff --git a/bundle/terraform_dabs_map/generated.go b/bundle/terraform_dabs_map/generated.go index fc245721c8a..c1d2430d36e 100644 --- a/bundle/terraform_dabs_map/generated.go +++ b/bundle/terraform_dabs_map/generated.go @@ -6,7 +6,8 @@ package terraform_dabs_map // alerts / databricks_alert_v2: 3 tf-only // apps / databricks_app: 6 dabs-only // apps / databricks_app: 1 tf-only -// clusters / databricks_cluster: 26 tf-only +// clusters / databricks_cluster: 1 renames +// clusters / databricks_cluster: 11 tf-only // dashboards / databricks_dashboard: 2 tf-only // database_instances / databricks_database_instance: 1 tf-only // experiments / databricks_mlflow_experiment: 1 tf-only @@ -34,6 +35,9 @@ package terraform_dabs_map // TerraformToDABsFieldMap maps DABs group name → nested TF segments → DABs segment name. // Navigate using TF field name segments; DABs is the corresponding DABs name when it differs. var TerraformToDABsFieldMap = map[string]RenameTree{ + "clusters": { + "library": {NewName: "libraries"}, + }, "jobs": { "environment": {NewName: "environments"}, "git_source": {Children: RenameTree{ @@ -168,27 +172,8 @@ var TerraformOnlyFields = map[string]FieldSet{ }, "idempotency_token": {}, "is_pinned": {}, - "library": { - "cran": { - "package": {}, // databricks_cluster.*.library.cran.package - "repo": {}, // databricks_cluster.*.library.cran.repo - }, - "egg": {}, // databricks_cluster.*.library.egg - "jar": {}, // databricks_cluster.*.library.jar - "maven": { - "coordinates": {}, // databricks_cluster.*.library.maven.coordinates - "exclusions": {}, // databricks_cluster.*.library.maven.exclusions - "repo": {}, // databricks_cluster.*.library.maven.repo - }, - "pypi": { - "package": {}, // databricks_cluster.*.library.pypi.package - "repo": {}, // databricks_cluster.*.library.pypi.repo - }, - "requirements": {}, // databricks_cluster.*.library.requirements - "whl": {}, // databricks_cluster.*.library.whl - }, - "no_wait": {}, - "url": {}, + "no_wait": {}, + "url": {}, }, "dashboards": { "dashboard_change_detected": {}, @@ -571,6 +556,9 @@ var TerraformOnlyFields = map[string]FieldSet{ // DABsToTerraformRenameMap maps DABs group name → nested DABs segments → TF segment name. // Navigate using DABs field name segments; NewName is the TF name when it differs. var DABsToTerraformRenameMap = map[string]RenameTree{ + "clusters": { + "libraries": {NewName: "library"}, + }, "jobs": { "environments": {NewName: "environment"}, "git_source": {Children: RenameTree{ diff --git a/libs/testserver/fake_workspace.go b/libs/testserver/fake_workspace.go index 44d6ccd1889..b73803751b6 100644 --- a/libs/testserver/fake_workspace.go +++ b/libs/testserver/fake_workspace.go @@ -208,6 +208,7 @@ type FakeWorkspace struct { ModelRegistryModels map[string]ml.Model ModelRegistryModelIDs map[string]string // model name -> numeric ID Clusters map[string]compute.ClusterDetails + ClusterLibraries map[string][]compute.Library // cluster id -> installed libraries InstancePools map[string]compute.GetInstancePool ClusterPolicies map[string]compute.Policy Catalogs map[string]catalog.CatalogInfo @@ -549,7 +550,8 @@ func NewFakeWorkspace(url, token string) *FakeWorkspace { SingleUserName: TestUser.UserName, }, }, - InstancePools: map[string]compute.GetInstancePool{}, + InstancePools: map[string]compute.GetInstancePool{}, + ClusterLibraries: map[string][]compute.Library{}, ClusterPolicies: map[string]compute.Policy{ // Seeded so the stateful list keeps backing the variable-lookup tests // (e.g. acceptance/bundle/variables/env_overrides resolves these by name). diff --git a/libs/testserver/handlers.go b/libs/testserver/handlers.go index 750f220bf33..a56e2dc4c0b 100644 --- a/libs/testserver/handlers.go +++ b/libs/testserver/handlers.go @@ -1034,6 +1034,19 @@ func AddDefaultHandlers(server *Server) { return req.Workspace.ClustersPermanentDelete(req) }) + // Cluster libraries: + server.Handle("POST", "/api/2.0/libraries/install", func(req Request) any { + return req.Workspace.LibrariesInstall(req) + }) + + server.Handle("POST", "/api/2.0/libraries/uninstall", func(req Request) any { + return req.Workspace.LibrariesUninstall(req) + }) + + server.Handle("GET", "/api/2.0/libraries/cluster-status", func(req Request) any { + return req.Workspace.LibrariesClusterStatus(req, req.URL.Query().Get("cluster_id")) + }) + // MLflow Experiments: server.Handle("GET", "/api/2.0/mlflow/experiments/get", func(req Request) any { experimentId := req.URL.Query().Get("experiment_id") diff --git a/libs/testserver/jobs.go b/libs/testserver/jobs.go index 6b3e4d74de3..ed2a7ac48b0 100644 --- a/libs/testserver/jobs.go +++ b/libs/testserver/jobs.go @@ -452,6 +452,23 @@ func (s *FakeWorkspace) JobsList() Response { return Response{Body: jobs.ListJobsResponse{Jobs: list}} } +// installTaskLibrariesOnCluster records a task's libraries on its existing (all-purpose) cluster, +// mirroring the Jobs service, which installs task libraries via the Libraries API when a run starts. +// Cluster-status then reports them, matching cloud (where they are cluster-wide, so other jobs and +// interactive sessions see them too). Callers must hold the workspace lock. +func (s *FakeWorkspace) installTaskLibrariesOnCluster(task jobs.Task) { + if task.ExistingClusterId == "" || len(task.Libraries) == 0 { + return + } + installed := s.ClusterLibraries[task.ExistingClusterId] + for _, lib := range task.Libraries { + if !containsLibrary(installed, lib) { + installed = append(installed, lib) + } + } + s.ClusterLibraries[task.ExistingClusterId] = installed +} + func (s *FakeWorkspace) JobsRunNow(req Request) Response { var request jobs.RunNow if err := json.Unmarshal(req.Body, &request); err != nil { @@ -486,6 +503,10 @@ func (s *FakeWorkspace) JobsRunNow(req Request) Response { var tasks []jobs.RunTask if job.Settings != nil { for _, t := range job.Settings.Tasks { + // Mirror the Jobs service installing a task's libraries on its existing + // (all-purpose) cluster at run time, so cluster-status reports them like on cloud. + s.installTaskLibrariesOnCluster(t) + taskRunId := nextID() taskRun := jobs.RunTask{ RunId: taskRunId, diff --git a/libs/testserver/libraries.go b/libs/testserver/libraries.go new file mode 100644 index 00000000000..63042ca8e66 --- /dev/null +++ b/libs/testserver/libraries.go @@ -0,0 +1,87 @@ +package testserver + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + + "github.com/databricks/databricks-sdk-go/service/compute" +) + +func (s *FakeWorkspace) LibrariesInstall(req Request) any { + var request compute.InstallLibraries + if err := json.Unmarshal(req.Body, &request); err != nil { + return Response{StatusCode: http.StatusBadRequest, Body: fmt.Sprintf("request parsing error: %s", err)} + } + + defer s.LockUnlock()() + + if _, ok := s.Clusters[request.ClusterId]; !ok { + return Response{StatusCode: http.StatusNotFound} + } + + // Install is additive and idempotent: installing an already-present library is a no-op. + installed := s.ClusterLibraries[request.ClusterId] + for _, lib := range request.Libraries { + if !containsLibrary(installed, lib) { + installed = append(installed, lib) + } + } + s.ClusterLibraries[request.ClusterId] = installed + + return Response{} +} + +func (s *FakeWorkspace) LibrariesUninstall(req Request) any { + var request compute.UninstallLibraries + if err := json.Unmarshal(req.Body, &request); err != nil { + return Response{StatusCode: http.StatusBadRequest, Body: fmt.Sprintf("request parsing error: %s", err)} + } + + defer s.LockUnlock()() + + installed := s.ClusterLibraries[request.ClusterId] + remaining := make([]compute.Library, 0, len(installed)) + for _, lib := range installed { + if !containsLibrary(request.Libraries, lib) { + remaining = append(remaining, lib) + } + } + s.ClusterLibraries[request.ClusterId] = remaining + + return Response{} +} + +func (s *FakeWorkspace) LibrariesClusterStatus(req Request, clusterId string) any { + defer s.LockUnlock()() + + if _, ok := s.Clusters[clusterId]; !ok { + return Response{StatusCode: http.StatusNotFound} + } + + installed := s.ClusterLibraries[clusterId] + statuses := make([]compute.LibraryFullStatus, 0, len(installed)) + for i := range installed { + statuses = append(statuses, compute.LibraryFullStatus{ + Library: &installed[i], + Status: compute.LibraryInstallStatusInstalled, + }) + } + + return Response{ + Body: compute.ClusterLibraryStatuses{ + ClusterId: clusterId, + LibraryStatuses: statuses, + }, + } +} + +func containsLibrary(libs []compute.Library, target compute.Library) bool { + for _, l := range libs { + if reflect.DeepEqual(l, target) { + return true + } + } + return false +} diff --git a/python/databricks/bundles/clusters/__init__.py b/python/databricks/bundles/clusters/__init__.py index a24c8ac4fdc..0ccecb208b0 100644 --- a/python/databricks/bundles/clusters/__init__.py +++ b/python/databricks/bundles/clusters/__init__.py @@ -61,6 +61,9 @@ "InitScriptInfoParam", "Kind", "KindParam", + "Library", + "LibraryDict", + "LibraryParam", "LifecycleWithStarted", "LifecycleWithStartedDict", "LifecycleWithStartedParam", @@ -70,9 +73,18 @@ "LogAnalyticsInfo", "LogAnalyticsInfoDict", "LogAnalyticsInfoParam", + "MavenLibrary", + "MavenLibraryDict", + "MavenLibraryParam", "NodeTypeFlexibility", "NodeTypeFlexibilityDict", "NodeTypeFlexibilityParam", + "PythonPyPiLibrary", + "PythonPyPiLibraryDict", + "PythonPyPiLibraryParam", + "RCranLibrary", + "RCranLibraryDict", + "RCranLibraryParam", "RuntimeEngine", "RuntimeEngineParam", "S3StorageInfo", @@ -193,6 +205,11 @@ InitScriptInfoParam, ) from databricks.bundles.clusters._models.kind import Kind, KindParam +from databricks.bundles.clusters._models.library import ( + Library, + LibraryDict, + LibraryParam, +) from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, LifecycleWithStartedDict, @@ -208,11 +225,26 @@ LogAnalyticsInfoDict, LogAnalyticsInfoParam, ) +from databricks.bundles.clusters._models.maven_library import ( + MavenLibrary, + MavenLibraryDict, + MavenLibraryParam, +) from databricks.bundles.clusters._models.node_type_flexibility import ( NodeTypeFlexibility, NodeTypeFlexibilityDict, NodeTypeFlexibilityParam, ) +from databricks.bundles.clusters._models.python_py_pi_library import ( + PythonPyPiLibrary, + PythonPyPiLibraryDict, + PythonPyPiLibraryParam, +) +from databricks.bundles.clusters._models.r_cran_library import ( + RCranLibrary, + RCranLibraryDict, + RCranLibraryParam, +) from databricks.bundles.clusters._models.runtime_engine import ( RuntimeEngine, RuntimeEngineParam, diff --git a/python/databricks/bundles/clusters/_models/cluster.py b/python/databricks/bundles/clusters/_models/cluster.py index 3e517975100..042a2c14a52 100644 --- a/python/databricks/bundles/clusters/_models/cluster.py +++ b/python/databricks/bundles/clusters/_models/cluster.py @@ -44,6 +44,7 @@ InitScriptInfoParam, ) from databricks.bundles.clusters._models.kind import Kind, KindParam +from databricks.bundles.clusters._models.library import Library, LibraryParam from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, LifecycleWithStartedParam, @@ -242,6 +243,11 @@ class Cluster(Resource): By using the [simple form](https://docs.databricks.com/compute/simple-form.html), your clusters are automatically using `kind = CLASSIC_PREVIEW`. """ + libraries: VariableOrList[Library] = field(default_factory=list) + """ + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. + """ + lifecycle: VariableOrOptional[LifecycleWithStarted] = None """ Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. @@ -530,6 +536,11 @@ class ClusterDict(TypedDict, total=False): By using the [simple form](https://docs.databricks.com/compute/simple-form.html), your clusters are automatically using `kind = CLASSIC_PREVIEW`. """ + libraries: VariableOrList[LibraryParam] + """ + A list of libraries to install on the cluster. Installed via the Libraries API after the cluster is created. Only supported in direct deployment mode. + """ + lifecycle: VariableOrOptional[LifecycleWithStartedParam] """ Settings that control the deployment lifecycle of the resource, such as preventing it from being destroyed. diff --git a/python/databricks/bundles/clusters/_models/library.py b/python/databricks/bundles/clusters/_models/library.py new file mode 100644 index 00000000000..8961f8fe744 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/library.py @@ -0,0 +1,134 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.clusters._models.maven_library import ( + MavenLibrary, + MavenLibraryParam, +) +from databricks.bundles.clusters._models.python_py_pi_library import ( + PythonPyPiLibrary, + PythonPyPiLibraryParam, +) +from databricks.bundles.clusters._models.r_cran_library import ( + RCranLibrary, + RCranLibraryParam, +) +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class Library: + """""" + + cran: VariableOrOptional[RCranLibrary] = None + """ + Specification of a CRAN library to be installed as part of the library + """ + + egg: VariableOrOptional[str] = None + """ + [DEPRECATED] Deprecated. URI of the egg library to install. Installing Python egg files is deprecated and is not supported in Databricks Runtime 14.0 and above. + """ + + jar: VariableOrOptional[str] = None + """ + URI of the JAR library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "jar": "/Workspace/path/to/library.jar" }`, `{ "jar" : "/Volumes/path/to/library.jar" }` or + `{ "jar": "s3://my-bucket/library.jar" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + maven: VariableOrOptional[MavenLibrary] = None + """ + Specification of a maven library to be installed. For example: + `{ "coordinates": "org.jsoup:jsoup:1.7.2" }` + """ + + pypi: VariableOrOptional[PythonPyPiLibrary] = None + """ + Specification of a PyPi library to be installed. For example: + `{ "package": "simplejson" }` + """ + + requirements: VariableOrOptional[str] = None + """ + URI of the requirements.txt file to install. Only Workspace paths and Unity Catalog Volumes paths are supported. + For example: `{ "requirements": "/Workspace/path/to/requirements.txt" }` or `{ "requirements" : "/Volumes/path/to/requirements.txt" }` + """ + + whl: VariableOrOptional[str] = None + """ + URI of the wheel library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "whl": "/Workspace/path/to/library.whl" }`, `{ "whl" : "/Volumes/path/to/library.whl" }` or + `{ "whl": "s3://my-bucket/library.whl" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + @classmethod + def from_dict(cls, value: "LibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "LibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class LibraryDict(TypedDict, total=False): + """""" + + cran: VariableOrOptional[RCranLibraryParam] + """ + Specification of a CRAN library to be installed as part of the library + """ + + egg: VariableOrOptional[str] + """ + [DEPRECATED] Deprecated. URI of the egg library to install. Installing Python egg files is deprecated and is not supported in Databricks Runtime 14.0 and above. + """ + + jar: VariableOrOptional[str] + """ + URI of the JAR library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "jar": "/Workspace/path/to/library.jar" }`, `{ "jar" : "/Volumes/path/to/library.jar" }` or + `{ "jar": "s3://my-bucket/library.jar" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + maven: VariableOrOptional[MavenLibraryParam] + """ + Specification of a maven library to be installed. For example: + `{ "coordinates": "org.jsoup:jsoup:1.7.2" }` + """ + + pypi: VariableOrOptional[PythonPyPiLibraryParam] + """ + Specification of a PyPi library to be installed. For example: + `{ "package": "simplejson" }` + """ + + requirements: VariableOrOptional[str] + """ + URI of the requirements.txt file to install. Only Workspace paths and Unity Catalog Volumes paths are supported. + For example: `{ "requirements": "/Workspace/path/to/requirements.txt" }` or `{ "requirements" : "/Volumes/path/to/requirements.txt" }` + """ + + whl: VariableOrOptional[str] + """ + URI of the wheel library to install. Supported URIs include Workspace paths, Unity Catalog Volumes paths, and S3 URIs. + For example: `{ "whl": "/Workspace/path/to/library.whl" }`, `{ "whl" : "/Volumes/path/to/library.whl" }` or + `{ "whl": "s3://my-bucket/library.whl" }`. + If S3 is used, please make sure the cluster has read access on the library. You may need to + launch the cluster with an IAM role to access the S3 URI. + """ + + +LibraryParam = LibraryDict | Library diff --git a/python/databricks/bundles/clusters/_models/maven_library.py b/python/databricks/bundles/clusters/_models/maven_library.py new file mode 100644 index 00000000000..25be1599c28 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/maven_library.py @@ -0,0 +1,72 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import ( + VariableOr, + VariableOrList, + VariableOrOptional, +) + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class MavenLibrary: + """""" + + coordinates: VariableOr[str] + """ + Gradle-style maven coordinates. For example: "org.jsoup:jsoup:1.7.2". + """ + + exclusions: VariableOrList[str] = field(default_factory=list) + """ + List of dependences to exclude. For example: `["slf4j:slf4j", "*:hadoop-client"]`. + + Maven dependency exclusions: + https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html. + """ + + repo: VariableOrOptional[str] = None + """ + Maven repo to install the Maven package from. If omitted, both Maven Central Repository + and Spark Packages are searched. + """ + + @classmethod + def from_dict(cls, value: "MavenLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "MavenLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class MavenLibraryDict(TypedDict, total=False): + """""" + + coordinates: VariableOr[str] + """ + Gradle-style maven coordinates. For example: "org.jsoup:jsoup:1.7.2". + """ + + exclusions: VariableOrList[str] + """ + List of dependences to exclude. For example: `["slf4j:slf4j", "*:hadoop-client"]`. + + Maven dependency exclusions: + https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html. + """ + + repo: VariableOrOptional[str] + """ + Maven repo to install the Maven package from. If omitted, both Maven Central Repository + and Spark Packages are searched. + """ + + +MavenLibraryParam = MavenLibraryDict | MavenLibrary diff --git a/python/databricks/bundles/clusters/_models/python_py_pi_library.py b/python/databricks/bundles/clusters/_models/python_py_pi_library.py new file mode 100644 index 00000000000..037c2029f50 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/python_py_pi_library.py @@ -0,0 +1,54 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOr, VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class PythonPyPiLibrary: + """""" + + package: VariableOr[str] + """ + The name of the pypi package to install. An optional exact version specification is also + supported. Examples: "simplejson" and "simplejson==3.8.0". + """ + + repo: VariableOrOptional[str] = None + """ + The repository where the package can be found. If not specified, the default pip index is + used. + """ + + @classmethod + def from_dict(cls, value: "PythonPyPiLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "PythonPyPiLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class PythonPyPiLibraryDict(TypedDict, total=False): + """""" + + package: VariableOr[str] + """ + The name of the pypi package to install. An optional exact version specification is also + supported. Examples: "simplejson" and "simplejson==3.8.0". + """ + + repo: VariableOrOptional[str] + """ + The repository where the package can be found. If not specified, the default pip index is + used. + """ + + +PythonPyPiLibraryParam = PythonPyPiLibraryDict | PythonPyPiLibrary diff --git a/python/databricks/bundles/clusters/_models/r_cran_library.py b/python/databricks/bundles/clusters/_models/r_cran_library.py new file mode 100644 index 00000000000..0bd2c4d5296 --- /dev/null +++ b/python/databricks/bundles/clusters/_models/r_cran_library.py @@ -0,0 +1,50 @@ +# Code generated by pydabs-codegen. DO NOT EDIT. + +from dataclasses import dataclass +from typing import TYPE_CHECKING, TypedDict + +from databricks.bundles.core._transform import _transform +from databricks.bundles.core._transform_to_json import _transform_to_json_value +from databricks.bundles.core._variable import VariableOr, VariableOrOptional + +if TYPE_CHECKING: + from typing_extensions import Self + + +@dataclass(kw_only=True) +class RCranLibrary: + """""" + + package: VariableOr[str] + """ + The name of the CRAN package to install. + """ + + repo: VariableOrOptional[str] = None + """ + The repository where the package can be found. If not specified, the default CRAN repo is used. + """ + + @classmethod + def from_dict(cls, value: "RCranLibraryDict") -> "Self": + return _transform(cls, value) + + def as_dict(self) -> "RCranLibraryDict": + return _transform_to_json_value(self) # type:ignore + + +class RCranLibraryDict(TypedDict, total=False): + """""" + + package: VariableOr[str] + """ + The name of the CRAN package to install. + """ + + repo: VariableOrOptional[str] + """ + The repository where the package can be found. If not specified, the default CRAN repo is used. + """ + + +RCranLibraryParam = RCranLibraryDict | RCranLibrary diff --git a/python/databricks_tests/core/_generated/clusters.py b/python/databricks_tests/core/_generated/clusters.py index c3de32f3016..2de29367b86 100644 --- a/python/databricks_tests/core/_generated/clusters.py +++ b/python/databricks_tests/core/_generated/clusters.py @@ -15,6 +15,7 @@ from databricks.bundles.clusters._models.gcp_attributes import GcpAttributes from databricks.bundles.clusters._models.init_script_info import InitScriptInfo from databricks.bundles.clusters._models.kind import Kind +from databricks.bundles.clusters._models.library import Library from databricks.bundles.clusters._models.lifecycle_with_started import ( LifecycleWithStarted, ) @@ -44,6 +45,7 @@ def _test_case(): "gcp_attributes": {}, "init_scripts": [{}], "kind": "CLASSIC_PREVIEW", + "libraries": [{}], "lifecycle": {}, "permissions": [{"level": "CAN_MANAGE"}], "runtime_engine": "NULL", @@ -65,6 +67,7 @@ def _test_case(): gcp_attributes=GcpAttributes(), init_scripts=[InitScriptInfo()], kind=Kind.CLASSIC_PREVIEW, + libraries=[Library()], lifecycle=LifecycleWithStarted(), permissions=[ ClusterPermission(level=ClusterPermissionLevel.CAN_MANAGE)