Esegui un job Spark su Google Kubernetes Engine

Questo documento mostra come creare un cluster virtuale Managed Service for Apache Spark su GKE e quindi eseguire un job Spark sul cluster.

Panoramica delle opzioni

Sebbene Managed Service for Apache Spark su GKE offra un controllo efficace per gli ambienti containerizzati, Google Cloud fornisce anche opzioni serverless e completamente gestite che possono semplificare le operazioni e accelerare lo sviluppo. Per un confronto tra le opzioni di deployment di Spark Managed Service for Apache Spark, consulta Scegliere il servizio Spark migliore.

Prima di iniziare

  1. Accedi al tuo account Google Cloud . Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche 300 $di crediti senza costi per l'esecuzione, il test e il deployment dei carichi di lavoro.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that you have the permissions required to complete this guide.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the Dataproc API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  6. Installa Google Cloud CLI.

  7. Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

  8. Per inizializzare gcloud CLI, esegui questo comando:

    gcloud init
  9. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  10. Verify that you have the permissions required to complete this guide.

  11. Verify that billing is enabled for your Google Cloud project.

  12. Enable the Dataproc API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  13. Installa Google Cloud CLI.

  14. Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.

  15. Per inizializzare gcloud CLI, esegui questo comando:

    gcloud init
  16. Devi aver creato un cluster Google Kubernetes Engine (GKE) zonale o regionale standard (non Autopilot) con Workload Identity abilitato sul cluster.

Ruoli obbligatori

Per eseguire gli esempi riportati in questa pagina sono necessari determinati ruoli IAM. A seconda delle policy dell'organizzazione, questi ruoli potrebbero essere già stati concessi. Per controllare le concessioni dei ruoli, consulta Devi concedere i ruoli?.

Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Ruoli utente

Per ottenere le autorizzazioni necessarie per creare un cluster Managed Service for Apache Spark, chiedi all'amministratore di concederti i seguenti ruoli IAM:

Ruolo service account

Per assicurarti che il account di servizio predefinito di Compute Engine disponga delle autorizzazioni necessarie per creare un cluster Managed Service for Apache Spark, chiedi all'amministratore di concedere il ruolo IAM Dataproc Worker (roles/dataproc.worker) al account di servizio predefinito di Compute Engine sul progetto.

Crea un cluster virtuale

Un cluster virtuale Managed Service for Apache Spark su GKE viene creato come piattaforma di deployment per i componenti di Managed Service for Apache Spark. Si tratta di una risorsa virtuale e, a differenza di un cluster Managed Service for Apache Spark su Compute Engine, non include VM master e worker Managed Service for Apache Spark separate.

  • Managed Service for Apache Spark su GKE crea pool di nodi all'interno di un cluster GKE quando crei un cluster virtuale Managed Service for Apache Spark su GKE.

  • I job Managed Service for Apache Spark su GKE vengono eseguiti come pod su questi node pool. I pool di nodi e la pianificazione dei pod sui pool di nodi sono gestiti da GKE.

  • Crea più cluster virtuali. Puoi creare ed eseguire più cluster virtuali su un cluster GKE per ottenere un utilizzo delle risorse migliorato condividendo i pool di nodi tra i cluster virtuali.

    • Ogni cluster virtuale:
      • viene creato con proprietà separate, tra cui la versione del motore Spark e l'identità del workload
      • è isolato all'interno di uno spazio dei nomi GKE separato sul cluster GKE

Console

La creazione di un cluster Managed Service for Apache Spark su GKE non è supportata nella console Google Cloud .

gcloud

Imposta le variabili di ambiente, quindi esegui il comando gcloud dataproc clusters gke create localmente o in Cloud Shell per creare un cluster Managed Service for Apache Spark su GKE.

  1. Imposta le variabili di ambiente:

    DP_CLUSTER=Managed Service for Apache Spark on GKE  cluster-name \
      REGION=region \
      GKE_CLUSTER=GKE cluster-name \
      BUCKET=Cloud Storage bucket-name \
      DP_POOLNAME=node pool-name
      PHS_CLUSTER=Managed Service for Apache Spark PHS server name
    
    Note:

    • DP_CLUSTER: imposta il nome del cluster virtuale Managed Service for Apache Spark, che deve iniziare con una lettera minuscola, seguita da un massimo di 54 lettere minuscole, numeri o trattini. e non può terminare con un trattino.
    • REGION: region deve corrispondere alla regione in cui si trova il cluster GKE.
    • GKE_CLUSTER: il nome del tuo cluster GKE esistente.
    • BUCKET: (facoltativo) puoi specificare il nome di un bucket Cloud Storage, che Managed Service for Apache Spark utilizzerà per archiviare in un'area intermedia gli artefatti. Se non specifichi un bucket, Managed Service for Apache Spark su GKE creerà un bucket di staging.
    • DP_POOLNAME: il nome di un node pool da creare nel cluster GKE.
    • PHS_CLUSTER: (facoltativo) server PHS di Managed Service for Apache Spark da utilizzare per visualizzare la cronologia dei job Spark nei cluster Managed Service for Apache Spark su GKE attivi ed eliminati. Il cluster PHS deve trovarsi nella stessa regione del cluster virtuale Managed Service for Apache Spark su GKE.
  2. Esegui il comando:

    gcloud dataproc clusters gke create ${DP_CLUSTER} \
        --region=${REGION} \
        --gke-cluster=${GKE_CLUSTER} \
        --spark-engine-version=latest \
        --staging-bucket=${BUCKET} \
        --pools="name=${DP_POOLNAME},roles=default" \
        --setup-workload-identity \
        --history-server-cluster=${PHS_CLUSTER}
    
    Note:

    • --spark-engine-version: la versione dell'immagine Spark utilizzata nel cluster Managed Service for Apache Spark. Puoi utilizzare un identificatore, ad esempio 3, 3.1 o latest, oppure puoi specificare la versione secondaria completa, ad esempio 3.1-dataproc-5.
    • --staging-bucket: elimina questo flag per consentire a Managed Service for Apache Spark su GKE di creare un bucket di staging.
    • --pools: questo flag viene utilizzato per specificare un pool di nodi nuovo o esistente che Managed Service for Apache Spark creerà o utilizzerà per eseguire il workload. Elenco delle impostazioni del pool di nodi di Managed Service for Apache Spark su GKE, separate da virgole, ad esempio:
      --pools=name=dp-default,roles=default,machineType=e2-standard-4,min=0,max=10
      
      Devi specificare il pool di nodi name e role. Le altre impostazioni pool di nodi sono facoltative. Puoi utilizzare più flag --pools per specificare più pool di nodi. Almeno un pool di nodi deve avere il ruolo default. Tutti i pool di nodi devono avere la stessa posizione.
    • --setup-workload-identity: questo flag abilita i binding di Workload Identity. Queste associazioni consentono ai service account Kubernetes (KSA) di agire come service account VM Managed Service for Apache Spark (identità del piano dati) predefinito del cluster virtuale.

REST

Completa un virtualClusterConfig nell'ambito di una richiesta API cluster.create.

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • PROJECT: ID progetto Google Cloud
  • REGION: la regione del cluster virtuale Dataproc (la stessa regione del cluster GKE esistente)
  • DP_CLUSTER: nome del cluster Dataproc
  • GKE_CLUSTER: Nome del cluster GKE
  • NODE_POOL: Nome node pool
  • PHS_CLUSTER: nome del cluster del server di cronologia permanente (PHS)
  • BUCKET: (Facoltativo) Nome del bucket di staging. Lascia questo campo vuoto per consentire a Managed Service for Apache Spark su GKE di creare un bucket di staging.

Metodo HTTP e URL:

POST https://dataproc.googleapis.com/v1/projects/project-id/regions/region/clusters

Corpo JSON della richiesta:

{
  "clusterName":"DP_CLUSTER",
  "projectId":"PROJECT",
  "virtualClusterConfig":{
    "auxiliaryServicesConfig":{
      "sparkHistoryServerConfig":{
        "dataprocCluster":"projects/PROJECT/regions/REGION/clusters/PHS_CLUSTER"
      }
    },
    "kubernetesClusterConfig":{
      "gkeClusterConfig":{
        "gkeClusterTarget":"projects/PROJECT/locations/REGION/clusters/GKE_CLUSTER",
        "nodePoolTarget":[
          {
"nodePool":"projects/PROJECT/locations/REGION/clusters/GKE_CLUSTER/nodePools/NODE_POOL",
            "roles":[
              "DEFAULT"
            ]
          }
        ]
      },
      "kubernetesSoftwareConfig":{
        "componentVersion":{
          "SPARK":"latest"
        }
      }
    },
    "stagingBucket":"BUCKET"
  }
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "projectId":"PROJECT",
  "clusterName":"DP_CLUSTER",
  "status":{
    "state":"RUNNING",
    "stateStartTime":"2022-04-01T19:16:39.865716Z"
  },
  "clusterUuid":"98060b77-...",
  "statusHistory":[
    {
      "state":"CREATING",
      "stateStartTime":"2022-04-01T19:14:27.340544Z"
    }
  ],
  "labels":{
    "goog-dataproc-cluster-name":"DP_CLUSTER",
    "goog-dataproc-cluster-uuid":"98060b77-...",
    "goog-dataproc-location":"REGION",
    "goog-dataproc-environment":"prod"
  },
  "virtualClusterConfig":{
    "stagingBucket":"BUCKET",
    "kubernetesClusterConfig":{
      "kubernetesNamespace":"dp-cluster",
      "gkeClusterConfig":{
"gkeClusterTarget":"projects/PROJECT/locations/REGION/clusters/GKE_CLUSTER",
        "nodePoolTarget":[
          {
"nodePool":"projects/PROJECT/locations/REGION/clusters/GKE_CLUSTER/nodePools/NODE_POOL",
            "roles":[
              "DEFAULT"
            ]
          }
        ]
      },
      "kubernetesSoftwareConfig":{
        "componentVersion":{
          "SPARK":"3.1-..."
        },
        "properties":{
          "dpgke:dpgke.unstable.outputOnly.endpoints.sparkHistoryServer":"https://...",
          "spark:spark.eventLog.dir":"gs://BUCKET/.../spark-job-history",
          "spark:spark.eventLog.enabled":"true"
        }
      }
    },
    "auxiliaryServicesConfig":{
      "sparkHistoryServerConfig":{
        "dataprocCluster":"projects/PROJECT/regions/REGION/clusters/PHS_CLUSTER"
      }
    }
  }

Invia un job Spark

Una volta in esecuzione il cluster virtuale Managed Service for Apache Spark su GKE, invia un job Spark utilizzando la console Google Cloud , Google Cloud CLI o l'API Managed Service for Apache Spark jobs.submit (utilizzando richieste HTTP dirette o le librerie client Cloud).

**Esempio di job Spark gcloud CLI:**

gcloud dataproc jobs submit spark \
    --region=${REGION} \
    --cluster=${DP_CLUSTER} \
    --class=org.apache.spark.examples.SparkPi \
    --jars=local:///usr/lib/spark/examples/jars/spark-examples.jar \
    -- 1000

**Esempio di job PySpark gcloud CLI:**

gcloud dataproc jobs submit pyspark \
    --region=${REGION} \
    --cluster=${DP_CLUSTER} \
    local:///usr/lib/spark/examples/src/main/python/pi.py \
    -- 10

**Esempio di job SparkR gcloud CLI:**

gcloud dataproc jobs submit spark-r \
    --region=${REGION} \
    --cluster=${DP_CLUSTER} \
    local:///usr/lib/spark/examples/src/main/r/dataframe.R

Esegui la pulizia