Membuat template sesi (v1)

Membuat template sesi Dataproc baru di region yang ditentukan.

Contoh kode

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

'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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di panduan memulai Managed Service untuk Apache Spark menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Managed Service untuk Apache Spark.

Untuk melakukan autentikasi ke Managed Service untuk Apache Spark, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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}")

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .