Crea un cluster

Crea un cluster

Requisiti:

  • Nome: il nome del cluster deve iniziare con una lettera minuscola seguita da un numero massimo di 51 lettere minuscole, numeri e trattini e non può terminare con un trattino.

  • Regione del cluster: devi specificare una regione Compute Engine per il cluster, ad esempio us-east1 o europe-west1, per isolare le risorse del cluster, come le istanze VM e i metadati del cluster archiviati in Cloud Storage, all'interno della regione.

    • Per saperne di più sulle regioni Compute Engine, consulta Regione del cluster per altre informazioni.
    • Per informazioni sulla selezione di una regione, consulta Regioni e zone disponibili. Puoi anche eseguire il comando gcloud compute regions list per visualizzare un elenco delle regioni disponibili.
  • Connettività: le istanze di macchine virtuali Compute Engine (VM) in un cluster Managed Service for Apache Spark, composto da VM master e worker, richiedono una connettività incrociata di rete IP interna completa. La rete VPC default fornisce questa connettività (vedi Configurazione della rete del cluster Managed Service for Apache Spark).

  • Tipo di macchina (consigliato): anche se la specifica di un tipo di macchina è facoltativa, Google consiglia di selezionare esplicitamente un tipo di macchina per le VM master e worker nel cluster. Se non specifichi un tipo di macchina, Managed Service for Apache Spark seleziona dinamicamente i tipi di macchina in base alla disponibilità delle risorse. Questa selezione dinamica può comportare variazioni sia in termini di costi che di prestazioni.

    • Per saperne di più sulla scelta di un tipo di macchina, consulta Tipi di macchina supportati.
    • Per mitigare i potenziali problemi di indisponibilità delle risorse, ti consigliamo di utilizzare le VM flessibili, che ti consentono di specificare un elenco di tipi di macchina accettabili.

Console

Apri la pagina della Google Cloud console Crea cluster per visualizzare le impostazioni predefinite del cluster. Puoi confermare o modificare le impostazioni predefinite visualizzate, quindi fare clic su Configurazione aggiuntiva per personalizzare ulteriormente il cluster.

Fai clic su Crea cluster per creare il cluster. Il nome del cluster viene visualizzato nella pagina Cluster e il relativo stato viene aggiornato a Running dopo il provisioning del cluster. Fai clic sul nome del cluster per aprire la pagina dei dettagli del cluster, dove puoi esaminare i job, le istanze e le impostazioni di configurazione del cluster e connetterti alle interfacce web in esecuzione sul cluster.

gcloud

Per creare un cluster Managed Service for Apache Spark dalla riga di comando, esegui il comando gcloud dataproc clusters create localmente in una finestra del terminale o in Cloud Shell.

gcloud dataproc clusters create CLUSTER_NAME \
    --region=REGION \
    --master-machine-type=MASTER_MACHINE_TYPE \
    --worker-machine-type=WORKER_MACHINE_TYPE

Il comando crea un cluster. Anche se i tipi di macchina master e worker sono facoltativi, ti consigliamo di specificarli esplicitamente utilizzando i flag --master-machine-type e --worker-machine-type (ad esempio, n4-standard-4) per garantire costi e prestazioni coerenti. Se non specifichi i tipi di macchina, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse. Per informazioni sull'utilizzo dei flag della riga di comando per personalizzare le impostazioni del cluster, consulta il comando gcloud dataproc clusters create.

Crea un cluster con un file YAML

  1. Esegui il seguente comando gcloud per esportare la configurazione di un cluster Managed Service for Apache Spark esistente in un file cluster.yaml.
    gcloud dataproc clusters export EXISTING_CLUSTER_NAME \
        --region=REGION \
        --destination=cluster.yaml
    
  2. Crea un nuovo cluster importando la configurazione del file YAML.
    gcloud dataproc clusters import NEW_CLUSTER_NAME \
        --region=REGION \
        --source=cluster.yaml
    

**Nota:** durante l'operazione di esportazione, i campi specifici del cluster, come il nome del cluster, i campi di sola uscita e le etichette applicate automaticamente, vengono filtrati. Questi campi non sono consentiti nel file YAML importato utilizzato per creare un cluster.

REST

Questa sezione mostra come creare un cluster. Anche se la specifica dei tipi di macchina è facoltativa, ti consigliamo di includere esplicitamente machine_type_uri in master_config e worker_config (ad esempio, n4-standard-4) per garantire costi e prestazioni coerenti. Se non specifichi i tipi di macchina, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse.

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

Metodo HTTP e URL:

POST https://dataproc.googleapis.com/v1/projects/PROJECT/regions/REGION/clusters

Corpo JSON della richiesta:

{
  "project_id":"PROJECT",
  "cluster_name":"CLUSTER_NAME",
  "config":{
    "master_config":{
      "num_instances":1,
      "machine_type_uri":"MASTER_MACHINE_TYPE",
      "image_uri":""
    },
    "softwareConfig": {
      "imageVersion": "",
      "properties": {},
      "optionalComponents": []
    },
    "worker_config":{
      "num_instances":2,
      "machine_type_uri":"WORKER_MACHINE_TYPE",
      "image_uri":""
    },
    "gce_cluster_config":{
      "zone_uri":"ZONE"
    }
  }
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
"name": "projects/PROJECT/regions/REGION/operations/b5706e31......",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.dataproc.v1.ClusterOperationMetadata",
    "clusterName": "CLUSTER_NAME",
    "clusterUuid": "5fe882b2-...",
    "status": {
      "state": "PENDING",
      "innerState": "PENDING",
      "stateStartTime": "2019-11-21T00:37:56.220Z"
    },
    "operationType": "CREATE",
    "description": "Create cluster with 2 workers",
    "warnings": [
      "For PD-Standard without local SSDs, we strongly recommend provisioning 1TB ...""
    ]
  }
}

Go

  1. Installa la libreria client.
  2. Configura le credenziali predefinite dell'applicazione.
  3. Esegui il codice.

    Nota: anche se la specifica dei tipi di macchina è facoltativa, ti consigliamo di impostare esplicitamente i tipi di macchina master e worker nella configurazione del cluster (ad esempio, su n4-standard-4) per garantire costi e prestazioni coerenti. Se omessi, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse.

    import (
    	"context"
    	"fmt"
    	"io"
    
    	dataproc "cloud.google.com/go/dataproc/apiv1"
    	"cloud.google.com/go/dataproc/apiv1/dataprocpb"
    	"google.golang.org/api/option"
    )
    
    func createCluster(w io.Writer, projectID, region, clusterName string) error {
    	// projectID := "your-project-id"
    	// region := "us-central1"
    	// clusterName := "your-cluster"
    	ctx := context.Background()
    
    	// Create the cluster client.
    	endpoint := region + "-dataproc.googleapis.com:443"
    	clusterClient, err := dataproc.NewClusterControllerClient(ctx, option.WithEndpoint(endpoint))
    	if err != nil {
    		return fmt.Errorf("dataproc.NewClusterControllerClient: %w", err)
    	}
    	defer clusterClient.Close()
    
    	// Create the cluster config.
    	req := &dataprocpb.CreateClusterRequest{
    		ProjectId: projectID,
    		Region:    region,
    		Cluster: &dataprocpb.Cluster{
    			ProjectId:   projectID,
    			ClusterName: clusterName,
    			Config: &dataprocpb.ClusterConfig{
    				MasterConfig: &dataprocpb.InstanceGroupConfig{
    					NumInstances:   1,
    					MachineTypeUri: "n1-standard-2",
    				},
    				WorkerConfig: &dataprocpb.InstanceGroupConfig{
    					NumInstances:   2,
    					MachineTypeUri: "n1-standard-2",
    				},
    			},
    		},
    	}
    
    	// Create the cluster.
    	op, err := clusterClient.CreateCluster(ctx, req)
    	if err != nil {
    		return fmt.Errorf("CreateCluster: %w", err)
    	}
    
    	resp, err := op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("CreateCluster.Wait: %w", err)
    	}
    
    	// Output a success message.
    	fmt.Fprintf(w, "Cluster created successfully: %s", resp.ClusterName)
    	return nil
    }
    

Java

  1. Installa la libreria client.
  2. Configura le credenziali predefinite dell'applicazione.
  3. Esegui il codice.

    Nota: anche se la specifica dei tipi di macchina è facoltativa, ti consigliamo di impostare esplicitamente i tipi di macchina master e worker nella configurazione del cluster (ad esempio, su n4-standard-4) per garantire costi e prestazioni coerenti. Se omessi, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse.

    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.dataproc.v1.Cluster;
    import com.google.cloud.dataproc.v1.ClusterConfig;
    import com.google.cloud.dataproc.v1.ClusterControllerClient;
    import com.google.cloud.dataproc.v1.ClusterControllerSettings;
    import com.google.cloud.dataproc.v1.ClusterOperationMetadata;
    import com.google.cloud.dataproc.v1.InstanceGroupConfig;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    public class CreateCluster {
    
      public static void createCluster() throws IOException, InterruptedException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String region = "your-project-region";
        String clusterName = "your-cluster-name";
        createCluster(projectId, region, clusterName);
      }
    
      public static void createCluster(String projectId, String region, String clusterName)
          throws IOException, InterruptedException {
        String myEndpoint = String.format("%s-dataproc.googleapis.com:443", region);
    
        // Configure the settings for the cluster controller client.
        ClusterControllerSettings clusterControllerSettings =
            ClusterControllerSettings.newBuilder().setEndpoint(myEndpoint).build();
    
        // Create a cluster controller client with the configured settings. The client only needs to be
        // created once and can be reused for multiple requests. Using a try-with-resources
        // closes the client, but this can also be done manually with the .close() method.
        try (ClusterControllerClient clusterControllerClient =
            ClusterControllerClient.create(clusterControllerSettings)) {
          // Configure the settings for our cluster.
          InstanceGroupConfig masterConfig =
              InstanceGroupConfig.newBuilder()
                  .setMachineTypeUri("n1-standard-2")
                  .setNumInstances(1)
                  .build();
          InstanceGroupConfig workerConfig =
              InstanceGroupConfig.newBuilder()
                  .setMachineTypeUri("n1-standard-2")
                  .setNumInstances(2)
                  .build();
          ClusterConfig clusterConfig =
              ClusterConfig.newBuilder()
                  .setMasterConfig(masterConfig)
                  .setWorkerConfig(workerConfig)
                  .build();
          // Create the cluster object with the desired cluster config.
          Cluster cluster =
              Cluster.newBuilder().setClusterName(clusterName).setConfig(clusterConfig).build();
    
          // Create the Cloud Dataproc cluster.
          OperationFuture<Cluster, ClusterOperationMetadata> createClusterAsyncRequest =
              clusterControllerClient.createClusterAsync(projectId, region, cluster);
          Cluster response = createClusterAsyncRequest.get();
    
          // Print out a success message.
          System.out.printf("Cluster created successfully: %s", response.getClusterName());
    
        } catch (ExecutionException e) {
          System.err.println(String.format("Error executing createCluster: %s ", e.getMessage()));
        }
      }
    }

Node.js

  1. Installa la libreria client.
  2. Configura le credenziali predefinite dell'applicazione.
  3. Esegui il codice.

    Nota: anche se la specifica dei tipi di macchina è facoltativa, ti consigliamo di impostare esplicitamente i tipi di macchina master e worker nella configurazione del cluster (ad esempio, su n4-standard-4) per garantire costi e prestazioni coerenti. Se omessi, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse.

    const dataproc = require('@google-cloud/dataproc');
    
    // TODO(developer): Uncomment and set the following variables
    // projectId = 'YOUR_PROJECT_ID'
    // region = 'YOUR_CLUSTER_REGION'
    // clusterName = 'YOUR_CLUSTER_NAME'
    
    // Create a client with the endpoint set to the desired cluster region
    const client = new dataproc.v1.ClusterControllerClient({
      apiEndpoint: `${region}-dataproc.googleapis.com`,
      projectId: projectId,
    });
    
    async function createCluster() {
      // Create the cluster config
      const request = {
        projectId: projectId,
        region: region,
        cluster: {
          clusterName: clusterName,
          config: {
            masterConfig: {
              numInstances: 1,
              machineTypeUri: 'n1-standard-2',
            },
            workerConfig: {
              numInstances: 2,
              machineTypeUri: 'n1-standard-2',
            },
          },
        },
      };
    
      // Create the cluster
      const [operation] = await client.createCluster(request);
      const [response] = await operation.promise();
    
      // Output a success message
      console.log(`Cluster created successfully: ${response.clusterName}`);

Python

  1. Installa la libreria client.
  2. Configura le credenziali predefinite dell'applicazione.
  3. Esegui il codice.

    Nota: anche se la specifica dei tipi di macchina è facoltativa, ti consigliamo di impostare esplicitamente i tipi di macchina master e worker nella configurazione del cluster (ad esempio, su n4-standard-4) per garantire costi e prestazioni coerenti. Se omessi, i tipi di macchina predefiniti vengono selezionati dinamicamente in base alla disponibilità delle risorse.

    from google.cloud import dataproc_v1 as dataproc
    
    
    def create_cluster(project_id, region, cluster_name):
        """This sample walks a user through creating a Cloud Dataproc cluster
        using the Python client library.
    
        Args:
            project_id (string): Project to use for creating resources.
            region (string): Region where the resources should live.
            cluster_name (string): Name to use for creating a cluster.
        """
    
        # Create a client with the endpoint set to the desired cluster region.
        cluster_client = dataproc.ClusterControllerClient(
            client_options={"api_endpoint": f"{region}-dataproc.googleapis.com:443"}
        )
    
        # Create the cluster config.
        cluster = {
            "project_id": project_id,
            "cluster_name": cluster_name,
            "config": {
                "master_config": {"num_instances": 1, "machine_type_uri": "n1-standard-2"},
                "worker_config": {"num_instances": 2, "machine_type_uri": "n1-standard-2"},
            },
        }
    
        # Create the cluster.
        operation = cluster_client.create_cluster(
            request={"project_id": project_id, "region": region, "cluster": cluster}
        )
        result = operation.result()
    
        # Output a success message.
        print(f"Cluster created successfully: {result.cluster_name}")