Criar modelo de sessão (v1)

Crie um modelo de sessão do Dataproc em uma região especificada.

Exemplo de código

Go

Antes de testar este exemplo, siga as instruções de configuração do Go no Guia de início rápido do Serviço Gerenciado para Apache Spark: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Go do Serviço Gerenciado para Apache Spark.

Para autenticar no Serviço Gerenciado para Apache Spark, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


import (
	"context"
	"fmt"
	"io"

	dataproc "cloud.google.com/go/dataproc/v2/apiv1"
	"cloud.google.com/go/dataproc/v2/apiv1/dataprocpb"
	"google.golang.org/api/option"
)

// createSessionTemplate creates a Dataproc session template in the specified region.
func createSessionTemplate(ctx context.Context, w io.Writer, projectID string, locationID string, sessionTemplateID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)
	sessionTemplate := &dataprocpb.SessionTemplate{
		Name:        fmt.Sprintf("projects/%s/locations/%s/sessionTemplates/%s", projectID, locationID, sessionTemplateID),
		Description: "Sample Dataproc Session Template",
		SessionConfig: &dataprocpb.SessionTemplate_JupyterSession{
			JupyterSession: &dataprocpb.JupyterConfig{
				Kernel:      dataprocpb.JupyterConfig_PYTHON,
				DisplayName: "Example Jupyter Session",
			},
		},
	}

	// Dataproc API calls require regional endpoints.
	endpoint := fmt.Sprintf("%s-dataproc.googleapis.com:443", locationID)
	client, err := dataproc.NewSessionTemplateControllerClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewSessionTemplateControllerClient failed: %w", err)
	}
	defer client.Close()

	req := &dataprocpb.CreateSessionTemplateRequest{
		Parent:          parent,
		SessionTemplate: sessionTemplate,
	}

	resp, err := client.CreateSessionTemplate(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateSessionTemplate: %w", err)
	}

	fmt.Fprintf(w, "Created session template: %s\n", resp.GetName())
	return nil
}

Java

Antes de testar este exemplo, siga as instruções de configuração do Java no Guia de início rápido do Serviço Gerenciado para Apache Spark: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Java do Serviço Gerenciado para Apache Spark.

Para autenticar no Serviço Gerenciado para Apache Spark, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.cloud.dataproc.v1.JupyterConfig;
import com.google.cloud.dataproc.v1.SessionTemplate;
import com.google.cloud.dataproc.v1.SessionTemplateControllerClient;
import com.google.cloud.dataproc.v1.SessionTemplateControllerSettings;
import java.io.IOException;

public class CreateSessionTemplate {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    String sessionTemplateId = "example-session-template-id";
    createSessionTemplate(projectId, locationId, sessionTemplateId);
  }

  public static void createSessionTemplate(
      String projectId, String locationId, String sessionTemplateId) throws IOException {
    // Configure regional endpoint for Dataproc control plane operations
    String endpoint = String.format("%s-dataproc.googleapis.com:443", locationId);
    SessionTemplateControllerSettings settings =
        SessionTemplateControllerSettings.newBuilder().setEndpoint(endpoint).build();

    try (SessionTemplateControllerClient client = SessionTemplateControllerClient.create(settings)) {
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);
      SessionTemplate sessionTemplate =
          SessionTemplate.newBuilder()
              .setName(String.format("%s/sessionTemplates/%s", parent, sessionTemplateId))
              .setDescription("Session template configured with Python Jupyter kernel")
              .setJupyterSession(
                  JupyterConfig.newBuilder()
                      .setKernel(JupyterConfig.Kernel.PYTHON)
                      .setDisplayName("Example Jupyter Session")
                      .build())
              .build();

      SessionTemplate response = client.createSessionTemplate(parent, sessionTemplate);
      System.out.println("Created session template: " + response.getName());
    }
  }
}

Node.js

Antes de testar este exemplo, siga as instruções de configuração do Node.js no Guia de início rápido do Serviço Gerenciado para Apache Spark: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Node.js do Serviço Gerenciado para Apache Spark.

Para autenticar no Serviço Gerenciado para Apache Spark, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

'use strict';

const {SessionTemplateControllerClient} = require('@google-cloud/dataproc');
const {status} = require('@grpc/grpc-js');

/**
 * Creates a Dataproc session template.
 *
 * @param {string} projectId - The Google Cloud project ID where the session template is created.
 * @param {string} locationId - The Dataproc region where the session template resides (for example, 'us-central1').
 * @param {string} sessionTemplateId - The caller-specified identifier for the session template, conforming to RFC 1035 (1-63 characters, matching [a-z]([-a-z0-9]*[a-z0-9])?).
 */
async function createSessionTemplate(projectId, locationId, sessionTemplateId) {
  // Dataproc regional endpoints require configuring apiEndpoint with the matching region.
  const client = new SessionTemplateControllerClient({
    apiEndpoint: `${locationId}-dataproc.googleapis.com`,
  });

  try {
    const parent = `projects/${projectId}/locations/${locationId}`;
    const sessionTemplate = {
      name: `${parent}/sessionTemplates/${sessionTemplateId}`,
      jupyterSession: {
        kernel: 'PYTHON',
        displayName: 'example-jupyter-session',
      },
    };

    const [response] = await client.createSessionTemplate({
      parent,
      sessionTemplate,
    });

    console.log(`Created session template: ${response.name}`);
    return response;
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.error(`Session template already exists: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { createSessionTemplate };

Python

Antes de testar este exemplo, siga as instruções de configuração do Python no Guia de início rápido do Serviço Gerenciado para Apache Spark: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Python do Serviço Gerenciado para Apache Spark.

Para autenticar no Serviço Gerenciado para Apache Spark, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.api_core.client_options import ClientOptions
import google.api_core.exceptions
from google.cloud import dataproc_v1


def create_session_template(
    project_id: str, location_id: str, session_template_id: str
) -> None:
    """Creates a Dataproc session template.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The Dataproc region for the session template, for example us-central1.
        session_template_id: The caller-chosen identifier for the session template.
    """
    endpoint = f"{location_id}-dataproc.googleapis.com:443"
    client = dataproc_v1.SessionTemplateControllerClient(
        client_options=ClientOptions(api_endpoint=endpoint)
    )

    parent = f"projects/{project_id}/locations/{location_id}"
    session_template = dataproc_v1.SessionTemplate(
        name=f"projects/{project_id}/locations/{location_id}/sessionTemplates/{session_template_id}",
        jupyter_session=dataproc_v1.JupyterConfig(
            kernel=dataproc_v1.JupyterConfig.Kernel.PYTHON,
            display_name="example-jupyter-session",
        ),
    )

    try:
        response = client.create_session_template(
            parent=parent,
            session_template=session_template,
        )
        print(f"Created session template: {response.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Failed to create session template: {error}")

A seguir

Para pesquisar e filtrar exemplos de código de outros Google Cloud produtos, consulte a Google Cloud pesquisa de exemplos de código.