- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6.6k
feat(dataproc): create pyspark nodegroup cluster sample #13513
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            13 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      0ced200
              
                Create submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa 1921249
              
                Update submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa ca20564
              
                Update submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa ca33daa
              
                Delete submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa b0ec3fc
              
                Update submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa 86ed4a0
              
                Update submit_pyspark_job_to_driver_node_group_cluster.py
              
              
                Supriya-Koppa f130cb7
              
                Create submit_pyspark_job_to_driver_node_group_cluster_test.py
              
              
                Supriya-Koppa f8025b3
              
                fix: reduce quota issues by dropping tested versions
              
              
                glasnt e05f622
              
                auto format document
              
              
                glasnt 1860bc7
              
                ci: test current required versions, only
              
              
                glasnt 1fa720d
              
                Ref #13456 only test one python version, quota issues
              
              
                glasnt 490a901
              
                ci: unique cluster name for tests
              
              
                glasnt a503355
              
                confirm name to naming regex
              
              
                glasnt File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
  
    
      
          
            107 changes: 107 additions & 0 deletions
          
          107 
        
  dataproc/snippets/submit_pyspark_job_to_driver_node_group_cluster.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| #!/usr/bin/env python | ||
|  | ||
| # Copyright 2025 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|  | ||
| # This sample walks a user through submitting a Spark job to a | ||
| # Dataproc driver node group cluster using the Dataproc | ||
| # client library. | ||
|  | ||
| # Usage: | ||
| # python submit_pyspark_job_to_driver_node_group_cluster.py \ | ||
| # --project_id <PROJECT_ID> --region <REGION> \ | ||
| # --cluster_name <CLUSTER_NAME> | ||
|  | ||
| # [START dataproc_submit_pyspark_job_to_driver_node_group_cluster] | ||
|  | ||
| import re | ||
|  | ||
| from google.cloud import dataproc_v1 as dataproc | ||
| from google.cloud import storage | ||
|  | ||
|  | ||
| def submit_job(project_id, region, cluster_name): | ||
| """Submits a PySpark job to a Dataproc cluster with a driver node group. | ||
|  | ||
| Args: | ||
| project_id (str): The ID of the Google Cloud project. | ||
| region (str): The region where the Dataproc cluster is located. | ||
| cluster_name (str): The name of the Dataproc cluster. | ||
| """ | ||
| # Create the job client. | ||
| job_client = dataproc.JobControllerClient( | ||
| client_options={"api_endpoint": f"{region}-dataproc.googleapis.com:443"} | ||
| ) | ||
|  | ||
| driver_scheduling_config = dataproc.DriverSchedulingConfig( | ||
| memory_mb=2048, # Example memory in MB | ||
| vcores=2, # Example number of vcores | ||
| ) | ||
|  | ||
| # Create the job config. The main Python file URI points to the script in | ||
| # a Google Cloud Storage bucket. | ||
| job = { | ||
| "placement": {"cluster_name": cluster_name}, | ||
| "pyspark_job": { | ||
| "main_python_file_uri": "gs://dataproc-examples/pyspark/hello-world/hello-world.py" | ||
|         
                  glasnt marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| }, | ||
| "driver_scheduling_config": driver_scheduling_config, | ||
| } | ||
|  | ||
| operation = job_client.submit_job_as_operation( | ||
| request={"project_id": project_id, "region": region, "job": job} | ||
| ) | ||
| response = operation.result() | ||
|  | ||
| # Dataproc job output gets saved to the Google Cloud Storage bucket | ||
| # allocated to the job. Use a regex to obtain the bucket and blob info. | ||
| matches = re.match("gs://(.*?)/(.*)", response.driver_output_resource_uri) | ||
| if not matches: | ||
| raise ValueError( | ||
| f"Unexpected driver output URI: {response.driver_output_resource_uri}" | ||
| ) | ||
|  | ||
| output = ( | ||
| storage.Client() | ||
| .get_bucket(matches.group(1)) | ||
| .blob(f"{matches.group(2)}.000000000") | ||
| .download_as_bytes() | ||
| .decode("utf-8") | ||
| ) | ||
|  | ||
| print(f"Job finished successfully: {output}") | ||
|  | ||
|  | ||
| # [END dataproc_submit_pyspark_job_to_driver_node_group_cluster] | ||
|  | ||
| if __name__ == "__main__": | ||
| import argparse | ||
|  | ||
| parser = argparse.ArgumentParser( | ||
| description="Submits a Spark job to a Dataproc driver node group cluster." | ||
| ) | ||
| parser.add_argument( | ||
| "--project_id", help="The Google Cloud project ID.", required=True | ||
| ) | ||
| parser.add_argument( | ||
| "--region", | ||
| help="The Dataproc region where the cluster is located.", | ||
| required=True, | ||
| ) | ||
| parser.add_argument( | ||
| "--cluster_name", help="The name of the Dataproc cluster.", required=True | ||
| ) | ||
|  | ||
| args = parser.parse_args() | ||
| submit_job(args.project_id, args.region, args.cluster_name) | ||
        
          
  
    
      
          
            88 changes: 88 additions & 0 deletions
          
          88 
        
  dataproc/snippets/submit_pyspark_job_to_driver_node_group_cluster_test.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| # Copyright 2020 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|  | ||
| import os | ||
| import subprocess | ||
| import uuid | ||
|  | ||
| import backoff | ||
| from google.api_core.exceptions import ( | ||
| Aborted, | ||
| InternalServerError, | ||
| NotFound, | ||
| ServiceUnavailable, | ||
| ) | ||
| from google.cloud import dataproc_v1 as dataproc | ||
|  | ||
| import submit_pyspark_job_to_driver_node_group_cluster | ||
|  | ||
| PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] | ||
| REGION = "us-central1" | ||
| CLUSTER_NAME = f"py-ps-test-{str(uuid.uuid4())}" | ||
|  | ||
| cluster_client = dataproc.ClusterControllerClient( | ||
| client_options={"api_endpoint": f"{REGION}-dataproc.googleapis.com:443"} | ||
| ) | ||
|  | ||
|  | ||
| @backoff.on_exception(backoff.expo, (Exception), max_tries=5) | ||
| def teardown(): | ||
| try: | ||
| operation = cluster_client.delete_cluster( | ||
| request={ | ||
| "project_id": PROJECT_ID, | ||
| "region": REGION, | ||
| "cluster_name": CLUSTER_NAME, | ||
| } | ||
| ) | ||
| # Wait for cluster to delete | ||
| operation.result() | ||
| except NotFound: | ||
| print("Cluster already deleted") | ||
|  | ||
|  | ||
| @backoff.on_exception( | ||
| backoff.expo, | ||
| ( | ||
| InternalServerError, | ||
| ServiceUnavailable, | ||
| Aborted, | ||
| ), | ||
| max_tries=5, | ||
| ) | ||
| def test_workflows(capsys): | ||
| # Setup driver node group cluster. TODO: cleanup b/424371877 | ||
| command = f"""gcloud dataproc clusters create {CLUSTER_NAME} \ | ||
| --region {REGION} \ | ||
| --project {PROJECT_ID} \ | ||
| --driver-pool-size=1 \ | ||
| --driver-pool-id=pytest""" | ||
|  | ||
| output = subprocess.run( | ||
| command, | ||
| capture_output=True, | ||
| shell=True, | ||
| check=True, | ||
| ) | ||
| print(output) | ||
|  | ||
| # Wrapper function for client library function | ||
| submit_pyspark_job_to_driver_node_group_cluster.submit_job( | ||
| PROJECT_ID, REGION, CLUSTER_NAME | ||
| ) | ||
|  | ||
| out, _ = capsys.readouterr() | ||
| assert "Job finished successfully" in out | ||
|  | ||
| # cluster deleted in teardown() | 
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.