Membuat dan mengelola konfigurasi instance

Halaman ini menjelaskan cara mencantumkan, membuat, memperbarui, menghapus, dan menampilkan detail konfigurasi instance Spanner. Beberapa fungsi konfigurasi instance kustom tidak tersedia di UI konsol Google Cloud. Dalam kasus tersebut, gunakan perintah Google Cloud CLI (gcloud) yang disediakan.

Membuat daftar konfigurasi instance

Anda dapat mencantumkan semua konfigurasi instance Spanner yang tersedia dengan Google Cloud CLI dan library klien. Untuk menemukan daftar semua konfigurasi instance Spanner, lihat Konfigurasi regional dan multi-region.

gcloud

Jalankan perintah gcloud spanner instance-configs list:

gcloud spanner instance-configs list

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

void ListInstanceConfigs(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id) {
  int count = 0;
  auto project = google::cloud::Project(project_id);
  for (auto& config : client.ListInstanceConfigs(project.FullName())) {
    if (!config) throw std::move(config).status();
    ++count;
    std::cout << "Instance config [" << count << "]:\n"
              << config->DebugString();
  }
  if (count == 0) {
    std::cout << "No instance configs found in project " << project_id << "\n";
  }
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;
using System;
using System.Collections.Generic;
using System.Linq;

public class ListInstanceConfigsSample
{
    public IEnumerable<InstanceConfig> ListInstanceConfigs(string projectId)
    {
        var instanceAdminClient = InstanceAdminClient.Create();
        var projectName = ProjectName.FromProject(projectId);
        var instanceConfigs = instanceAdminClient.ListInstanceConfigs(projectName);

        // We print the first 5 elements for demonstration purposes.
        // You can print all configs in the sequence by removing the call to Take(5).
        // The sequence will lazily fetch elements in pages as needed.
        foreach (var instanceConfig in instanceConfigs.Take(5))
        {
            Console.WriteLine($"Available leader options for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");
            foreach (var leader in instanceConfig.LeaderOptions)
            {
                Console.WriteLine(leader);
            }

            Console.WriteLine($"Available optional replica for instance config {instanceConfig.InstanceConfigName.InstanceConfigId}:");
            foreach (var optionalReplica in instanceConfig.OptionalReplicas)
            {
                Console.WriteLine($"Replica type - {optionalReplica.Type}, default leader location - {optionalReplica.DefaultLeaderLocation}, location - {optionalReplica.Location}");
            }
        }
        return instanceConfigs;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/api/iterator"
)

// istInstanceConfigs gets available leader options for all instances
func listInstanceConfigs(w io.Writer, projectName string) error {
	// projectName = `projects/<project>
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	request := &instancepb.ListInstanceConfigsRequest{
		Parent: projectName,
	}
	for {
		iter := instanceAdmin.ListInstanceConfigs(ctx, request)
		for {
			ic, err := iter.Next()
			if err == iterator.Done {
				break
			}
			if err != nil {
				return err
			}
			fmt.Fprintf(w, "Available leader options for instance config %s: %v\n", ic.Name, ic.LeaderOptions)
		}
		pageToken := iter.PageInfo().Token
		if pageToken == "" {
			break
		} else {
			request.PageToken = pageToken
		}
	}

	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.ProjectName;

public class ListInstanceConfigsSample {

  static void listInstanceConfigs() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    listInstanceConfigs(projectId);
  }

  static void listInstanceConfigs(String projectId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final ProjectName projectName = ProjectName.of(projectId);
      for (InstanceConfig instanceConfig :
          instanceAdminClient.listInstanceConfigs(projectName).iterateAll()) {
        System.out.printf(
            "Available leader options for instance config %s: %s%n",
            instanceConfig.getName(),
            instanceConfig.getLeaderOptionsList()
        );
      }
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function listInstanceConfigs() {
  // Lists all available instance configurations in the project.
  // See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available
  // configurations.
  const [instanceConfigs] = await instanceAdminClient.listInstanceConfigs({
    parent: instanceAdminClient.projectPath(projectId),
  });
  console.log(`Available instance configs for project ${projectId}:`);
  instanceConfigs.forEach(instanceConfig => {
    console.log(
      `Available leader options for instance config ${
        instanceConfig.name
      } ('${instanceConfig.displayName}'): 
         ${instanceConfig.leaderOptions.join()}`
    );
  });
}
listInstanceConfigs();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\ListInstanceConfigsRequest;

/**
 * Lists the available instance configurations.
 * Example:
 * ```
 * list_instance_configs();
 * ```
 *
 * @param string $projectId The Google Cloud project ID.
 */
function list_instance_configs(string $projectId = null): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $projectName = InstanceAdminClient::projectName($projectId);
    $request = new ListInstanceConfigsRequest();
    $request->setParent($projectName);
    $resp = $instanceAdminClient->listInstanceConfigs($request);
    foreach ($resp as $element) {
        printf(
            'Available leader options for instance config %s: %s' . PHP_EOL,
            $element->getDisplayName(),
            implode(',', iterator_to_array($element->getLeaderOptions()))
        );
    }
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

def list_instance_config():
    """Lists the available instance configurations."""
    from google.cloud.spanner_admin_instance_v1.types import spanner_instance_admin

    spanner_client = spanner.Client()

    request = spanner_instance_admin.ListInstanceConfigsRequest(
        parent=spanner_client.project_name
    )
    for config in spanner_client.instance_admin_api.list_instance_configs(
        request=request
    ):
        print(
            "Available leader options for instance config {}: {}".format(
                config.name, config.leader_options
            )
        )

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

# project_id  = "Your Google Cloud project ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin

project_path = instance_admin_client.project_path project: project_id
configs = instance_admin_client.list_instance_configs parent: project_path

configs.each do |c|
  puts "Available leader options for instance config #{c.name} : #{c.leader_options}"
end

Menampilkan detail konfigurasi instance

Anda dapat menampilkan detail konfigurasi instance apa pun dengan Google Cloud CLI dan library klien. Saat membuat konfigurasi instance kustom baru, Anda dapat menambahkan lokasi apa pun yang tercantum di bagian optionalReplicas sebagai replika opsional. Jika tidak melihat lokasi replika hanya baca yang diinginkan, Anda dapat meminta wilayah replika hanya baca opsional baru.

Untuk mengetahui informasi selengkapnya, lihat Membuat konfigurasi instance kustom.

gcloud

Jalankan perintah gcloud spanner instance-configs describe:

gcloud spanner instance-configs describe INSTANCE-CONFIG

Berikan nilai berikut:

INSTANCE-CONFIG
Konfigurasi instance, yang menentukan lokasi geografis instance dan memengaruhi cara data direplikasi. Misalnya, eur6 atau us-central1.

Untuk menampilkan detail konfigurasi dasar eur6, jalankan:

gcloud spanner instance-configs describe eur6

Berikut adalah contoh output untuk konfigurasi dasar eur6:

  configType: GOOGLE_MANAGED
  displayName: Europe (Netherlands, Frankfurt)
  freeInstanceAvailability: UNSUPPORTED
  leaderOptions:
  - europe-west3
  - europe-west4
  name: projects/cloud-spanner-demo/instanceConfigs/eur6
  optionalReplicas:
  - displayName: South Carolina
    labels:
      cloud.googleapis.com/country: US
      cloud.googleapis.com/location: us-east1
      cloud.googleapis.com/region: us-east1
    location: us-east1
    type: READ_ONLY
  - displayName: South Carolina
    labels:
      cloud.googleapis.com/country: US
      cloud.googleapis.com/location: us-east1
      cloud.googleapis.com/region: us-east1
    location: us-east1
    type: READ_ONLY
  replicas:
  - defaultLeaderLocation: true
    location: europe-west4
    type: READ_WRITE
  - location: europe-west4
    type: READ_WRITE
  - location: europe-west3
    type: READ_WRITE
  - location: europe-west3
    type: READ_WRITE
  - location: europe-west6
    type: WITNESS

Catatan penggunaan tambahan:

  • baseConfig (khusus untuk konfigurasi kustom) mengarah ke konfigurasi instance dasar. Lihat konfigurasi regional yang tersedia dan konfigurasi multi-region yang tersedia untuk mengetahui daftar konfigurasi instance dasar yang dapat digunakan untuk membuat konfigurasi instance kustom.
  • configType menunjukkan apakah konfigurasi instance ini adalah konfigurasi instance dasar atau konfigurasi instance kustom.
  • etag (khusus konfigurasi kustom) adalah representasi string berenkode base64 dari konfigurasi. Ini digunakan untuk kontrol serentak optimis.

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

void GetInstanceConfig(google::cloud::spanner_admin::InstanceAdminClient client,
                       std::string const& project_id,
                       std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config = client.GetInstanceConfig(project.FullName() +
                                         "/instanceConfigs/" + config_id);
  if (!config) throw std::move(config).status();
  std::cout << "The instanceConfig " << config->name()
            << " exists and its metadata is:\n"
            << config->DebugString();
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


using Google.Cloud.Spanner.Admin.Instance.V1;
using System;
using System.Threading.Tasks;

public class GetInstanceConfigAsyncSample
{
    public async Task<InstanceConfig> GetInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        var instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = InstanceConfigName.FromProjectInstanceConfig(projectId, instanceConfigId);
        var instanceConfig = await instanceAdminClient.GetInstanceConfigAsync(instanceConfigName);

        Console.WriteLine($"Available leader options for instance config {instanceConfigName.InstanceConfigId}:");
        foreach (var leader in instanceConfig.LeaderOptions)
        {
            Console.WriteLine(leader);
        }
        return instanceConfig;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// getInstanceConfig gets available leader options
func getInstanceConfig(w io.Writer, instanceConfigName string) error {
	// defaultLeader = `nam3`
	ctx := context.Background()
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	ic, err := instanceAdmin.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: instanceConfigName,
	})

	if err != nil {
		return fmt.Errorf("could not get instance config %s: %w", instanceConfigName, err)
	}

	fmt.Fprintf(w, "Available leader options for instance config %s: %v", instanceConfigName, ic.LeaderOptions)

	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;

public class GetInstanceConfigSample {

  static void getInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    final String projectId = "my-project";
    final String instanceConfigId = "nam6";
    getInstanceConfig(projectId, instanceConfigId);
  }

  static void getInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);

      final InstanceConfig instanceConfig =
          instanceAdminClient.getInstanceConfig(instanceConfigName.toString());

      System.out.printf(
          "Available leader options for instance config %s: %s%n",
          instanceConfig.getName(),
          instanceConfig.getLeaderOptionsList()
      );
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function getInstanceConfig() {
  // Get the instance config for the multi-region North America 6 (NAM6).
  // See https://cloud.google.com/spanner/docs/instance-configurations#configuration for a list of all available
  // configurations.
  const [instanceConfig] = await instanceAdminClient.getInstanceConfig({
    name: instanceAdminClient.instanceConfigPath(projectId, 'nam6'),
  });
  console.log(
    `Available leader options for instance config ${instanceConfig.name} ('${
      instanceConfig.displayName
    }'): 
         ${instanceConfig.leaderOptions.join()}`
  );
}
getInstanceConfig();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\GetInstanceConfigRequest;

/**
 * Gets the leader options for the instance configuration.
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfig The name of the instance configuration.
 */
function get_instance_config(string $projectId, string $instanceConfig): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $instanceConfigName = InstanceAdminClient::instanceConfigName($projectId, $instanceConfig);

    $request = (new GetInstanceConfigRequest())
        ->setName($instanceConfigName);
    $configInfo = $instanceAdminClient->getInstanceConfig($request);

    printf('Available leader options for instance config %s: %s' . PHP_EOL,
        $instanceConfig,
        implode(',', array_keys(iterator_to_array($configInfo->getLeaderOptions())))
    );
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

def get_instance_config(instance_config):
    """Gets the leader options for the instance configuration."""
    spanner_client = spanner.Client()
    config_name = "{}/instanceConfigs/{}".format(
        spanner_client.project_name, instance_config
    )
    config = spanner_client.instance_admin_api.get_instance_config(name=config_name)
    print(
        "Available leader options for instance config {}: {}".format(
            instance_config, config.leader_options
        )
    )

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

# project_id  = "Your Google Cloud project ID"
# instance_config_id = "Spanner instance config ID"

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin

instance_config_path = instance_admin_client.instance_config_path \
  project: project_id, instance_config: instance_config_id
config = instance_admin_client.get_instance_config name: instance_config_path

puts "Available leader options for instance config #{config.name} : #{config.leader_options}"

Membuat konfigurasi instance kustom

Anda dapat membuat konfigurasi instance regional atau multi-region kustom dan menambahkan replika hanya baca opsional untuk menskalakan pembacaan dan mendukung pembacaan usang latensi rendah. Lihat konfigurasi regional yang tersedia dan konfigurasi multi-region yang tersedia untuk mengetahui daftar konfigurasi instance dasar yang dapat digunakan untuk membuat konfigurasi instance kustom. Anda tidak dapat membuat konfigurasi instance dua region kustom. Untuk mengetahui informasi selengkapnya tentang replikasi dan jenis replika Spanner, lihat Replikasi.

Untuk membuat konfigurasi instance kustom, Anda harus memiliki izin spanner.instanceConfigs.create. Secara default, peran yang memiliki izin spanner.instances.create juga akan memiliki izin spanner.instanceConfigs.create.

Konsol

Anda tidak dapat membuat konfigurasi instance kustom menggunakan Konsol Google Cloud. Untuk membuat instance dengan replika hanya baca, gunakan gcloud CLI atau library klien.

gcloud

Gunakan perintah gcloud spanner instance-configs create:

gcloud spanner instance-configs create CUSTOM-INSTANCE-CONFIG-ID  \
 --display-name=DISPLAY-NAME \
 --base-config=BASE-CONFIG \
 --labels=KEY=VALUE,[...] \
 --replicas=location=LOCATION,type=TYPE[:...]

Anda dapat menggunakan flag --clone-config sebagai cara yang mudah untuk meng-clone konfigurasi instance kustom atau dasar lainnya sekaligus mendeklarasikan lokasi dan jenis replika kustom tertentu.

  gcloud spanner instance-configs create CUSTOM-INSTANCE-CONFIG-ID  \
  --display-name=DISPLAY-NAME \
  --clone-config=INSTANCE-CONFIG \
  --labels=KEY=VALUE,[...] \
  --add-replicas=location=LOCATION,type=TYPE[:...] \
  --skip-replicas=location=LOCATION,type=TYPE[:...]

Berikan nilai berikut:

CUSTOM-INSTANCE-CONFIG-ID
ID permanen yang unik dalam project Google Cloud Anda. Anda tidak dapat mengubah ID konfigurasi instance nanti. Awalan custom- diperlukan untuk menghindari konflik nama dengan konfigurasi instance dasar.
DISPLAY-NAME
Nama yang akan ditampilkan untuk konfigurasi instance kustom di konsol Google Cloud.
Jika Anda memilih untuk menggunakan flag `--base-config` dan `--replicas`, berikan nilai berikut:
BASE-CONFIG
Nama region konfigurasi instance dasar tempat konfigurasi instance kustom Anda didasarkan. Misalnya, eur6 atau regional-us-central1.
LOCATION
Nama region resource penayangan (replika), misalnya, us-east1. Untuk mengetahui nama lokasi yang diterima, jalankan gcloud spanner instance-configs describe INSTANCE-CONFIG dan lihat daftar replicas dan optionalReplicas.
TYPE
Jenis replika. Untuk mengetahui lokasi dan jenis replika yang sesuai yang diterima, jalankan gcloud spanner instance-configs describe INSTANCE-CONFIG dan lihat daftar replicas dan optionalReplicas. Jenisnya adalah salah satu dari berikut:
  • READ_ONLY
  • READ_WRITE
  • WITNESS
Item dalam daftar dipisahkan oleh ":".
Kecuali jika tanda --[clone-config] digunakan, semua replika LOCATION dan TYPE harus ditentukan saat membuat konfigurasi instance kustom, termasuk yang telah ditentukan sebelumnya dalam konfigurasi dasar. Untuk mengetahui informasi selengkapnya, lihat gcloud instance-configs describe help-text.

Jika Anda memilih untuk menggunakan flag --clone-config dan --add-replicas (hanya gunakan --skip-replicas jika ada replika yang ingin Anda lewati agar tidak di-clone), berikan nilai berikut:

  • --clone-config=INSTANCE-CONFIG

    Gunakan tanda ini sebagai cara yang mudah untuk meng-clone konfigurasi instance dasar atau kustom lain sekaligus mendeklarasikan lokasi dan jenis replika kustom tertentu. Kemudian, gunakan --add-replicas=location=LOCATION,type=TYPE untuk menentukan tempat Anda ingin menambahkan replika opsional.

    Misalnya, untuk membuat konfigurasi instance kustom dengan dua replika hanya baca di us-east1 sekaligus menyalin semua lokasi replika lainnya dari konfigurasi instance dasar eur6, jalankan:

    gcloud spanner instance-configs create custom-eur6 --clone-config=eur6 \
    --add-replicas=location=us-east1,type=READ_ONLY:location=us-east1,type=READ_ONLY
    
  • --skip-replicas=location=LOCATION,type=TYPE

    Gunakan flag ini untuk melewati replika agar tidak di-clone.

    Misalnya, untuk membuat konfigurasi instance kustom dengan satu replika hanya baca di us-east4 sekaligus menyalin semua lokasi replika lainnya dari konfigurasi instance dasar nam3 kecuali replika hanya baca di us-central1, jalankan:

    gcloud spanner instance-configs create custom-nam3 --clone-config=nam3 \
      --add-replicas=location=us-east4,type=READ_ONLY \
      --skip-replicas=location=us-central1,type=READ_ONLY
    

Flag dan nilai berikut bersifat opsional:

  • --labels=KEY=VALUE,[...]

    KEY dan VALUE: Daftar pasangan kunci dan nilai untuk ditambahkan ke konfigurasi instance kustom Anda.

    Kunci harus diawali dengan karakter huruf kecil dan hanya berisi tanda hubung (-), garis bawah (_), karakter huruf kecil, dan angka. Nilai hanya boleh berisi tanda hubung (-), garis bawah (_), huruf kecil, dan angka.

  • --validate-only

    Gunakan flag ini untuk memvalidasi bahwa permintaan akan berhasil sebelum menjalankannya.

Misalnya, untuk membuat konfigurasi instance kustom dengan konfigurasi dasar eur6 dengan satu replika hanya baca tambahan di us-east1, jalankan:

gcloud spanner instance-configs create custom-eur6 \
  --display-name="Custom eur6" --clone-config=eur6 \
  --add-replicas=location=us-east1,type=READ_ONLY \

Anda juga dapat membuat konfigurasi instance kustom tanpa flag --clone-config:

gcloud spanner instance-configs create custom-eur6 \
  --display-name="Custom eur6" --base-config=eur6 \
  --replicas=location=europe-west4,type=READ_WRITE:location=europe-west3,type=READ_WRITE:location=europe-west4,type=READ_WRITE:location=europe-west3,type=READ_WRITE:location=europe-west6,type=WITNESS:location=us-east1,type=READ_ONLY

Anda akan melihat output berikut:

Creating instance-config...done.

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

void CreateInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& user_config_id,
    std::string const& base_config_id) {
  auto project = google::cloud::Project(project_id);
  auto base_config = client.GetInstanceConfig(
      project.FullName() + "/instanceConfigs/" + base_config_id);
  if (!base_config) throw std::move(base_config).status();
  if (base_config->optional_replicas().empty()) {
    throw std::runtime_error("No optional replicas in base config");
  }
  google::spanner::admin::instance::v1::CreateInstanceConfigRequest request;
  request.set_parent(project.FullName());
  request.set_instance_config_id(user_config_id);
  auto* request_config = request.mutable_instance_config();
  request_config->set_name(project.FullName() + "/instanceConfigs/" +
                           user_config_id);
  request_config->set_display_name("My instance config");
  // The user-managed instance config must contain all the replicas
  // of the base config plus at least one of the optional replicas.
  *request_config->mutable_replicas() = base_config->replicas();
  for (auto const& replica : base_config->optional_replicas()) {
    *request_config->add_replicas() = replica;
  }
  request_config->set_base_config(base_config->name());
  *request_config->mutable_leader_options() = base_config->leader_options();
  request.set_validate_only(false);
  auto user_config = client.CreateInstanceConfig(request).get();
  if (!user_config) throw std::move(user_config).status();
  std::cout << "Created instance config [" << user_config_id << "]:\n"
            << user_config->DebugString();
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


using System;
using System.Threading.Tasks;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Spanner.Admin.Instance.V1;

public class CreateInstanceConfigAsyncSample
{
    public async Task<InstanceConfig> CreateInstanceConfigAsync(string projectId, string baseInstanceConfigId, string customInstanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, baseInstanceConfigId);
        var instanceConfig = await instanceAdminClient.GetInstanceConfigAsync(instanceConfigName);

        var customInstanceConfigName = new InstanceConfigName(projectId, customInstanceConfigId);

        //Create a custom config.
        InstanceConfig userInstanceConfig = new InstanceConfig
        {
            DisplayName = "C# test custom instance config",
            ConfigType = InstanceConfig.Types.Type.UserManaged,
            BaseConfigAsInstanceConfigName = instanceConfigName,
            InstanceConfigName = customInstanceConfigName,
            //The replicas for the custom instance configuration must include all the replicas of the base
            //configuration, in addition to at least one from the list of optional replicas of the base
            //configuration.
            Replicas = { instanceConfig.Replicas },
            OptionalReplicas =
            {
                new ReplicaInfo
                {
                    Type = ReplicaInfo.Types.ReplicaType.ReadOnly,
                    Location = "us-east1",
                    DefaultLeaderLocation = false
                },
                //The replicas for the custom instance configuration must include all the replicas of the base
                //configuration, in addition to at least one from the list of optional replicas of the base
                //configuration.
                instanceConfig.OptionalReplicas
            }
        };

        var operationResult = await instanceAdminClient.CreateInstanceConfigAsync(new CreateInstanceConfigRequest
        {
            ParentAsProjectName = ProjectName.FromProject(projectId),
            InstanceConfig = userInstanceConfig,
            InstanceConfigId = customInstanceConfigId
        });

        var pollResult = await operationResult.PollUntilCompletedAsync();

        if (pollResult.IsFaulted)
        {
            throw pollResult.Exception;
        }

        Console.WriteLine($"Instance config created successfully");
        Console.WriteLine($"Available custom replication options for instance config {pollResult.Result.Name}\r\n{pollResult.Result.OptionalReplicas}");

        return pollResult.Result;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import (
	"context"
	"fmt"
	"io"
	"time"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// createInstanceConfig creates a custom spanner instance config
func createInstanceConfig(w io.Writer, projectID, userConfigID, baseConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.
	// baseConfigID := "my-base-config"

	// Add timeout to context.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	baseConfig, err := adminClient.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, baseConfigID),
	})
	if err != nil {
		return fmt.Errorf("createInstanceConfig.GetInstanceConfig: %w", err)
	}
	if baseConfig.OptionalReplicas == nil || len(baseConfig.OptionalReplicas) == 0 {
		return fmt.Errorf("CreateInstanceConfig expects base config with at least from the list of optional replicas")
	}
	op, err := adminClient.CreateInstanceConfig(ctx, &instancepb.CreateInstanceConfigRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		// Custom config names must start with the prefix “custom-”.
		InstanceConfigId: userConfigID,
		InstanceConfig: &instancepb.InstanceConfig{
			Name:        fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
			DisplayName: "custom-golang-samples",
			ConfigType:  instancepb.InstanceConfig_USER_MANAGED,
			// The replicas for the custom instance configuration must include all the replicas of the base
			// configuration, in addition to at least one from the list of optional replicas of the base
			// configuration.
			Replicas:   append(baseConfig.Replicas, baseConfig.OptionalReplicas...),
			BaseConfig: baseConfig.Name,
			Labels:     map[string]string{"go_cloud_spanner_samples": "true"},
		},
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Waiting for create operation on projects/%s/instanceConfigs/%s to complete...\n", projectID, userConfigID)
	// Wait for the instance configuration creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Waiting for instance config creation to finish failed: %w", err)
	}
	// The instance configuration may not be ready to serve yet.
	if i.State != instancepb.InstanceConfig_READY {
		fmt.Fprintf(w, "InstanceConfig state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance configuration [%s]\n", userConfigID)
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.CreateInstanceConfigRequest;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.ProjectName;
import com.google.spanner.admin.instance.v1.ReplicaInfo;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class CreateInstanceConfigSample {

  static void createInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String baseInstanceConfigId = "nam11";
    String instanceConfigId = "custom-instance-config4";

    createInstanceConfig(projectId, baseInstanceConfigId, instanceConfigId);
  }

  static void createInstanceConfig(
      String projectId, String baseInstanceConfigId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName baseInstanceConfigName = InstanceConfigName.of(projectId,
          baseInstanceConfigId);
      final InstanceConfig baseConfig =
          instanceAdminClient.getInstanceConfig(baseInstanceConfigName.toString());
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);
      /**
       * The replicas for the custom instance configuration must include all the replicas of the
       * base configuration, in addition to at least one from the list of optional replicas of the
       * base configuration.
       */
      final List<ReplicaInfo> replicas =
          Stream.concat(baseConfig.getReplicasList().stream(),
              baseConfig.getOptionalReplicasList().stream().limit(1)).collect(Collectors.toList());
      final InstanceConfig instanceConfig =
          InstanceConfig.newBuilder().setName(instanceConfigName.toString())
              .setBaseConfig(baseInstanceConfigName.toString())
              .setDisplayName("Instance Configuration").addAllReplicas(replicas).build();
      final CreateInstanceConfigRequest createInstanceConfigRequest =
          CreateInstanceConfigRequest.newBuilder().setParent(ProjectName.of(projectId).toString())
              .setInstanceConfigId(instanceConfigId).setInstanceConfig(instanceConfig).build();
      try {
        System.out.printf("Waiting for create operation for %s to complete...\n",
            instanceConfigName);
        InstanceConfig instanceConfigResult =
            instanceAdminClient.createInstanceConfigAsync(
                createInstanceConfigRequest).get(5, TimeUnit.MINUTES);
        System.out.printf("Created instance configuration %s\n", instanceConfigResult.getName());
      } catch (ExecutionException | TimeoutException e) {
        System.out.printf(
            "Error: Creating instance configuration %s failed with error message %s\n",
            instanceConfig.getName(), e.getMessage());
      } catch (InterruptedException e) {
        System.out.println(
            "Error: Waiting for createInstanceConfig operation to finish was interrupted");
      }
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id'
// const baseInstanceConfigId = 'my-base-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

// Creates a new instance config
async function createInstanceConfig() {
  const [baseInstanceConfig] = await instanceAdminClient.getInstanceConfig({
    name: instanceAdminClient.instanceConfigPath(
      projectId,
      baseInstanceConfigId
    ),
  });
  try {
    console.log(
      `Creating instance config ${instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      )}.`
    );
    const [operation] = await instanceAdminClient.createInstanceConfig({
      instanceConfigId: instanceConfigId,
      parent: instanceAdminClient.projectPath(projectId),
      instanceConfig: {
        name: instanceAdminClient.instanceConfigPath(
          projectId,
          instanceConfigId
        ),
        baseConfig: instanceAdminClient.instanceConfigPath(
          projectId,
          baseInstanceConfigId
        ),
        displayName: instanceConfigId,
        replicas: baseInstanceConfig.replicas.concat(
          baseInstanceConfig.optionalReplicas[0]
        ),
      },
    });
    console.log(
      `Waiting for create operation for ${instanceConfigId} to complete...`
    );
    await operation.promise();
    console.log(`Created instance config ${instanceConfigId}.`);
  } catch (err) {
    console.error(
      'ERROR: Creating instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
createInstanceConfig();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\CreateInstanceConfigRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\GetInstanceConfigRequest;
use Google\Cloud\Spanner\Admin\Instance\V1\InstanceConfig;
use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\ReplicaInfo;

/**
 * Creates a customer managed instance configuration.
 * Example:
 * ```
 * create_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 * @param string $baseConfigId Base configuration ID to be used for creation, e.g. nam11.
 */
function create_instance_config(string $projectId, string $instanceConfigId, string $baseConfigId): void
{
    $instanceAdminClient = new InstanceAdminClient();
    $projectName = InstanceAdminClient::projectName($projectId);
    $instanceConfigName = $instanceAdminClient->instanceConfigName(
        $projectId,
        $instanceConfigId
    );

    // Get a Google Managed instance configuration to use as the base for our custom instance configuration.
    $baseInstanceConfig = $instanceAdminClient->instanceConfigName(
        $projectId,
        $baseConfigId
    );

    $request = new GetInstanceConfigRequest(['name' => $baseInstanceConfig]);
    $baseInstanceConfigInfo = $instanceAdminClient->getInstanceConfig($request);

    $instanceConfig = (new InstanceConfig())
        ->setBaseConfig($baseInstanceConfig)
        ->setName($instanceConfigName)
        ->setDisplayName('My custom instance configuration')
        ->setLabels(['php-cloud-spanner-samples' => true])
        ->setReplicas(array_merge(
            iterator_to_array($baseInstanceConfigInfo->getReplicas()),
            [new ReplicaInfo([
            'location' => 'us-east1',
            'type' => ReplicaInfo\ReplicaType::READ_ONLY,
            'default_leader_location' => false
            ])]
        ));

    $request = new CreateInstanceConfigRequest([
        'parent' => $projectName,
        'instance_config' => $instanceConfig,
        'instance_config_id' => $instanceConfigId
    ]);
    $operation = $instanceAdminClient->createInstanceConfig($request);

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Created instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

def create_instance_config(user_config_name, base_config_id):
    """Creates the new user-managed instance configuration using base instance config."""

    # user_config_name = `custom-nam11`
    # base_config_id = `projects/<project>/instanceConfigs/nam11`
    spanner_client = spanner.Client()
    base_config = spanner_client.instance_admin_api.get_instance_config(
        name=base_config_id
    )

    # The replicas for the custom instance configuration must include all the replicas of the base
    # configuration, in addition to at least one from the list of optional replicas of the base
    # configuration.
    replicas = []
    for replica in base_config.replicas:
        replicas.append(replica)
    replicas.append(base_config.optional_replicas[0])
    operation = spanner_client.instance_admin_api.create_instance_config(
        parent=spanner_client.project_name,
        instance_config_id=user_config_name,
        instance_config=spanner_instance_admin.InstanceConfig(
            name="{}/instanceConfigs/{}".format(
                spanner_client.project_name, user_config_name
            ),
            display_name="custom-python-samples",
            config_type=spanner_instance_admin.InstanceConfig.Type.USER_MANAGED,
            replicas=replicas,
            base_config=base_config.name,
            labels={"python_cloud_spanner_samples": "true"},
        ),
    )
    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)

    print("Created instance configuration {}".format(user_config_name))

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_create_instance_config project_id:, user_config_name:, base_config_id:
  # project_id  = "Your Google Cloud project ID"
  # user_config_name = "Your custom instance configuration name, The name must start with 'custom-'"
  # base_config_id = "Base configuration ID to be used for creation, e.g projects/<project>/instanceConfigs/nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  project_path = instance_admin_client.project_path project: project_id
  base_instance_config = instance_admin_client.get_instance_config name: base_config_id
  # The replicas for the custom instance configuration must include all the replicas of the base
  # configuration, in addition to at least one from the list of optional replicas of the base
  # configuration.
  custom_replicas = []
  base_instance_config.replicas.each do |replica|
    custom_replicas << replica
  end
  custom_replicas << base_instance_config.optional_replicas[0]
  custom_instance_config_id = instance_admin_client.instance_config_path \
    project: project_id, instance_config: user_config_name
  custom_instance_config = {
    name: custom_instance_config_id,
    display_name: "custom-ruby-samples",
    config_type: :USER_MANAGED,
    replicas: custom_replicas,
    base_config: base_config_id,
    labels: { ruby_cloud_spanner_samples: "true" }
  }
  request = {
    parent: project_path,
    # Custom config names must start with the prefix “custom-”.
    instance_config_id: user_config_name,
    instance_config: custom_instance_config
  }
  job = instance_admin_client.create_instance_config request

  puts "Waiting for create instance config operation to complete"

  job.wait_until_done!

  if job.error?
    puts job.error
  else
    puts "Created instance configuration #{user_config_name}"
  end
end

Membuat instance dalam konfigurasi instance kustom

Anda dapat membuat instance dalam konfigurasi instance kustom.

Konsol

Untuk membuat instance dalam konfigurasi instance kustom, gunakan gcloud CLI atau library klien.

gcloud

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

C++

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

C#

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Go

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Java

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Node.js

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

PHP

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Python

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Ruby

Setelah Anda membuat konfigurasi instance kustom, ikuti petunjuk yang diberikan di Membuat instance.

Memperbarui konfigurasi instance kustom

Anda dapat mengubah nama tampilan dan label konfigurasi instance kustom.

Anda tidak dapat mengubah atau memperbarui replika konfigurasi instance kustom. Namun, Anda dapat membuat konfigurasi instance kustom baru dengan replika tambahan, lalu memindahkan instance ke konfigurasi instance kustom baru dengan replika tambahan yang dipilih. Misalnya, jika instance Anda berada di us-central1 dan Anda ingin menambahkan replika us-west1 hanya baca, Anda perlu membuat konfigurasi instance kustom baru dengan us-central1 sebagai konfigurasi dasar dan menambahkan us-west1 sebagai replika hanya baca. Kemudian, pindahkan instance Anda ke konfigurasi instance kustom baru ini.

gcloud

Gunakan perintah gcloud spanner instance-configs update:

gcloud spanner instance-configs update CUSTOM-INSTANCE-CONFIG-ID \
  --display-name=NEW-DISPLAY-NAME \
  --update-labels=KEY=VALUE,[...], \
  --etag=ETAG

Berikan nilai berikut:

CUSTOM-INSTANCE-CONFIG-ID
ID permanen konfigurasi instance kustom Anda. Kode ini akan dimulai dengan custom-.
NEW-DISPLAY-NAME
Nama baru yang akan ditampilkan untuk konfigurasi instance di konsol Google Cloud.
KEY dan VALUE
Daftar key-value pair yang akan diperbarui.
Kunci harus diawali dengan karakter huruf kecil dan hanya berisi tanda hubung (-), garis bawah (_), karakter huruf kecil, dan angka. Nilai hanya boleh berisi tanda hubung (-), garis bawah (_), karakter huruf kecil, dan angka.

Flag dan nilai berikut bersifat opsional:

  • --etag=ETAG: Argumen ETAG dapat digunakan untuk memilih dan melewati update serentak dalam skenario baca-ubah-tulis.
  • --validate-only: Gunakan tanda ini untuk memvalidasi bahwa permintaan akan berhasil sebelum menjalankannya.

Contoh:

gcloud spanner instance-configs update custom-eur6 \
  --display-name="Customer managed europe replicas"

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

void UpdateInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config = client.GetInstanceConfig(project.FullName() +
                                         "/instanceConfigs/" + config_id);
  if (!config) throw std::move(config).status();
  google::spanner::admin::instance::v1::UpdateInstanceConfigRequest request;
  auto* request_config = request.mutable_instance_config();
  request_config->set_name(config->name());
  request_config->mutable_labels()->insert({"key", "value"});
  request.mutable_update_mask()->add_paths("labels");
  request_config->set_etag(config->etag());
  request.set_validate_only(false);
  auto updated_config = client.UpdateInstanceConfig(request).get();
  if (!updated_config) throw std::move(updated_config).status();
  std::cout << "Updated instance config [" << config_id << "]:\n"
            << updated_config->DebugString();
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public class UpdateInstanceConfigAsyncSample
{
    public async Task<Operation<InstanceConfig, UpdateInstanceConfigMetadata>> UpdateInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, instanceConfigId);

        var instanceConfig = new InstanceConfig();
        instanceConfig.InstanceConfigName  = instanceConfigName;

        instanceConfig.DisplayName = "New display name";
        instanceConfig.Labels.Add(new Dictionary<string, string>
        {
            {"cloud_spanner_samples","true"},
            {"updated","true"},
        });

        var updateInstanceConfigOperation = await instanceAdminClient.UpdateInstanceConfigAsync(new UpdateInstanceConfigRequest
        {
            InstanceConfig = instanceConfig,
            UpdateMask = new FieldMask
            {
                Paths = { "display_name", "labels" }
            }
        });

        updateInstanceConfigOperation = await updateInstanceConfigOperation.PollUntilCompletedAsync(); 

        if (updateInstanceConfigOperation.IsFaulted)
        {
            throw updateInstanceConfigOperation.Exception;
        }

        Console.WriteLine("Update Instance Config operation completed successfully.");
        return updateInstanceConfigOperation;
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import (
	"context"
	"fmt"
	"io"
	"time"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateInstanceConfig updates the custom spanner instance config
func updateInstanceConfig(w io.Writer, projectID, userConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.

	// Add timeout to context.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	config, err := adminClient.GetInstanceConfig(ctx, &instancepb.GetInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
	})
	if err != nil {
		return fmt.Errorf("updateInstanceConfig.GetInstanceConfig: %w", err)
	}
	config.DisplayName = "updated custom instance config"
	config.Labels["updated"] = "true"
	op, err := adminClient.UpdateInstanceConfig(ctx, &instancepb.UpdateInstanceConfigRequest{
		InstanceConfig: config,
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"display_name", "labels"},
		},
		ValidateOnly: false,
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Waiting for update operation on %s to complete...\n", userConfigID)
	// Wait for the instance configuration creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Waiting for instance config creation to finish failed: %w", err)
	}
	// The instance configuration may not be ready to serve yet.
	if i.State != instancepb.InstanceConfig_READY {
		fmt.Fprintf(w, "InstanceConfig state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Updated instance configuration [%s]\n", config.Name)
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.FieldMask;
import com.google.spanner.admin.instance.v1.InstanceConfig;
import com.google.spanner.admin.instance.v1.InstanceConfigName;
import com.google.spanner.admin.instance.v1.UpdateInstanceConfigRequest;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class UpdateInstanceConfigSample {

  static void updateInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceConfigId = "custom-instance-config";
    updateInstanceConfig(projectId, instanceConfigId);
  }

  static void updateInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName =
          InstanceConfigName.of(projectId, instanceConfigId);
      final InstanceConfig instanceConfig =
          InstanceConfig.newBuilder()
              .setName(instanceConfigName.toString())
              .setDisplayName("updated custom instance config")
              .putLabels("updated", "true").build();
      /**
       * The field mask must always be specified; this prevents any future
       * fields in [InstanceConfig][google.spanner.admin.instance.v1.InstanceConfig]
       * from being erased accidentally by clients that do not know about them.
       */
      final UpdateInstanceConfigRequest updateInstanceConfigRequest =
          UpdateInstanceConfigRequest.newBuilder()
              .setInstanceConfig(instanceConfig)
              .setUpdateMask(
                  FieldMask.newBuilder().addAllPaths(ImmutableList.of("display_name", "labels"))
                      .build()).build();
      try {
        System.out.printf("Waiting for update operation on %s to complete...\n",
            instanceConfigName);
        InstanceConfig instanceConfigResult =
            instanceAdminClient.updateInstanceConfigAsync(
                updateInstanceConfigRequest).get(5, TimeUnit.MINUTES);
        System.out.printf(
            "Updated instance configuration %s with new display name %s\n",
            instanceConfigResult.getName(), instanceConfig.getDisplayName());
      } catch (ExecutionException | TimeoutException e) {
        System.out.printf(
            "Error: Updating instance config %s failed with error message %s\n",
            instanceConfig.getName(), e.getMessage());
        e.printStackTrace();
      } catch (InterruptedException e) {
        System.out.println(
            "Error: Waiting for updateInstanceConfig operation to finish was interrupted");
      }
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner, protos} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function updateInstanceConfig() {
  // Updates an instance config
  try {
    console.log(
      `Updating instance config ${instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      )}.`
    );
    const [operation] = await instanceAdminClient.updateInstanceConfig({
      instanceConfig: {
        name: instanceAdminClient.instanceConfigPath(
          projectId,
          instanceConfigId
        ),
        displayName: 'updated custom instance config',
        labels: {
          updated: 'true',
          created: Math.round(Date.now() / 1000).toString(), // current time
        },
      },
      // Field mask specifying fields that should get updated in InstanceConfig
      // Only display_name and labels can be updated
      updateMask: (protos.google.protobuf.FieldMask = {
        paths: ['display_name', 'labels'],
      }),
    });
    console.log(
      `Waiting for update operation for ${instanceConfigId} to complete...`
    );
    await operation.promise();
    console.log(`Updated instance config ${instanceConfigId}.`);
  } catch (err) {
    console.error(
      'ERROR: Updating instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
updateInstanceConfig();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\InstanceConfig;
use Google\Cloud\Spanner\Admin\Instance\V1\UpdateInstanceConfigRequest;
use Google\Protobuf\FieldMask;

/**
 * Updates a customer managed instance configuration.
 * Example:
 * ```
 * update_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 */
function update_instance_config(string $projectId, string $instanceConfigId): void
{
    $instanceAdminClient = new InstanceAdminClient();

    $instanceConfigPath = $instanceAdminClient->instanceConfigName($projectId, $instanceConfigId);
    $displayName = 'New display name';

    $instanceConfig = new InstanceConfig();
    $instanceConfig->setName($instanceConfigPath);
    $instanceConfig->setDisplayName($displayName);
    $instanceConfig->setLabels(['cloud_spanner_samples' => true, 'updated' => true]);

    $fieldMask = new FieldMask();
    $fieldMask->setPaths(['display_name', 'labels']);

    $updateInstanceConfigRequest = (new UpdateInstanceConfigRequest())
        ->setInstanceConfig($instanceConfig)
        ->setUpdateMask($fieldMask);

    $operation = $instanceAdminClient->updateInstanceConfig($updateInstanceConfigRequest);

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Updated instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

def update_instance_config(user_config_name):
    """Updates the user-managed instance configuration."""

    # user_config_name = `custom-nam11`
    spanner_client = spanner.Client()
    config = spanner_client.instance_admin_api.get_instance_config(
        name="{}/instanceConfigs/{}".format(
            spanner_client.project_name, user_config_name
        )
    )
    config.display_name = "updated custom instance config"
    config.labels["updated"] = "true"
    operation = spanner_client.instance_admin_api.update_instance_config(
        instance_config=config,
        update_mask=field_mask_pb2.FieldMask(paths=["display_name", "labels"]),
    )
    print("Waiting for operation to complete...")
    operation.result(OPERATION_TIMEOUT_SECONDS)
    print("Updated instance configuration {}".format(user_config_name))

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_update_instance_config user_config_id:
  # user_config_id = "The customer managed instance configuration ID, e.g projects/<project>/instanceConfigs/custom-nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  config = instance_admin_client.get_instance_config name: user_config_id
  config.display_name = "updated custom instance config"
  config.labels["updated"] = "true"
  request = {
    instance_config: config,
    update_mask: { paths: ["display_name", "labels"] },
    validate_only: false
  }
  job = instance_admin_client.update_instance_config request

  puts "Waiting for update instance config operation to complete"

  job.wait_until_done!

  if job.error?
    puts job.error
  else
    puts "Updated instance configuration #{config.name}"
  end
end

Menghapus konfigurasi instance kustom

Untuk menghapus konfigurasi instance kustom, hapus terlebih dahulu instance apa pun dalam konfigurasi instance.

gcloud

Gunakan perintah gcloud spanner instance-configs delete, dengan mengganti CUSTOM-INSTANCE-CONFIG-ID dengan ID konfigurasi instance kustom:

gcloud spanner instance-configs delete CUSTOM-INSTANCE-CONFIG-ID

C++

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

void DeleteInstanceConfig(
    google::cloud::spanner_admin::InstanceAdminClient client,
    std::string const& project_id, std::string const& config_id) {
  auto project = google::cloud::Project(project_id);
  auto config_name = project.FullName() + "/instanceConfigs/" + config_id;
  auto status = client.DeleteInstanceConfig(config_name);
  if (!status.ok()) throw std::move(status);
  std::cout << "Instance config " << config_name << " successfully deleted\n";
}

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


using System;
using System.Threading.Tasks;
using Google.Cloud.Spanner.Admin.Instance.V1;
using Grpc.Core;

public class DeleteInstanceConfigAsyncSample
{

    public async Task DeleteInstanceConfigAsync(string projectId, string instanceConfigId)
    {
        InstanceAdminClient instanceAdminClient = await InstanceAdminClient.CreateAsync();
        var instanceConfigName = new InstanceConfigName(projectId, instanceConfigId);

        try
        {
            await instanceAdminClient.DeleteInstanceConfigAsync(new DeleteInstanceConfigRequest
            {
                InstanceConfigName = instanceConfigName
            });
        }
        catch (RpcException ex) when (ex.Status.StatusCode == StatusCode.NotFound)
        {
            Console.WriteLine("The specified instance config does not exist. It cannot be deleted.");
            return;
        }

        Console.WriteLine("Delete Instance Config operation is completed");
    }
}

Go

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	"cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
)

// deleteInstanceConfig deletes the custom spanner instance config
func deleteInstanceConfig(w io.Writer, projectID, userConfigID string) error {
	// projectID := "my-project-id"
	// userConfigID := "custom-config", custom config names must start with the prefix “custom-”.

	ctx := context.Background()
	adminClient, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer adminClient.Close()
	err = adminClient.DeleteInstanceConfig(ctx, &instancepb.DeleteInstanceConfigRequest{
		Name: fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, userConfigID),
	})
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Deleted instance configuration [%s]\n", userConfigID)
	return nil
}

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.


import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.admin.instance.v1.InstanceAdminClient;
import com.google.spanner.admin.instance.v1.DeleteInstanceConfigRequest;
import com.google.spanner.admin.instance.v1.InstanceConfigName;

class DeleteInstanceConfigSample {

  static void deleteInstanceConfig() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceConfigId = "custom-user-config";
    deleteInstanceConfig(projectId, instanceConfigId);
  }

  static void deleteInstanceConfig(String projectId, String instanceConfigId) {
    try (Spanner spanner =
        SpannerOptions.newBuilder()
            .setProjectId(projectId)
            .build()
            .getService();
        InstanceAdminClient instanceAdminClient = spanner.createInstanceAdminClient()) {
      final InstanceConfigName instanceConfigName = InstanceConfigName.of(projectId,
          instanceConfigId);
      final DeleteInstanceConfigRequest request =
          DeleteInstanceConfigRequest.newBuilder().setName(instanceConfigName.toString()).build();

      try {
        System.out.printf("Deleting %s...\n", instanceConfigName);
        instanceAdminClient.deleteInstanceConfig(request);
        System.out.printf("Deleted instance configuration %s\n", instanceConfigName);
      } catch (SpannerException e) {
        System.out.printf(
            "Error: Deleting instance configuration %s failed with error message: %s\n",
            instanceConfigName, e.getMessage());
      }
    }
  }
}

Node.js

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const instanceConfigId = 'custom-my-instance-config-id';
// const projectId = 'my-project-id';

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instanceAdminClient = spanner.getInstanceAdminClient();

async function deleteInstanceConfig() {
  // Deletes an instance config.

  try {
    // Delete the instance config.
    console.log(`Deleting ${instanceConfigId}...\n`);
    await instanceAdminClient.deleteInstanceConfig({
      name: instanceAdminClient.instanceConfigPath(
        projectId,
        instanceConfigId
      ),
    });
    console.log(`Deleted instance config ${instanceConfigId}.\n`);
  } catch (err) {
    console.error(
      'ERROR: Deleting instance config ',
      instanceConfigId,
      ' failed with error message ',
      err
    );
  }
}
deleteInstanceConfig();

PHP

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

use Google\Cloud\Spanner\Admin\Instance\V1\Client\InstanceAdminClient;
use Google\Cloud\Spanner\Admin\Instance\V1\DeleteInstanceConfigRequest;

/**
 * Deletes a customer managed instance configuration.
 * Example:
 * ```
 * delete_instance_config($instanceConfigId);
 * ```
 *
 * @param string $projectId The Google Cloud Project ID.
 * @param string $instanceConfigId The customer managed instance configuration id. The id must start with 'custom-'.
 */
function delete_instance_config(string $projectId, string $instanceConfigId)
{
    $instanceAdminClient = new InstanceAdminClient();
    $instanceConfigName = $instanceAdminClient->instanceConfigName(
        $projectId,
        $instanceConfigId
    );

    $request = new DeleteInstanceConfigRequest();
    $request->setName($instanceConfigName);

    $instanceAdminClient->deleteInstanceConfig($request);
    printf('Deleted instance configuration %s' . PHP_EOL, $instanceConfigId);
}

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

def delete_instance_config(user_config_id):
    """Deleted the user-managed instance configuration."""
    spanner_client = spanner.Client()
    spanner_client.instance_admin_api.delete_instance_config(name=user_config_id)
    print("Instance config {} successfully deleted".format(user_config_id))

Ruby

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Spanner, lihat library klien Spanner.

require "google/cloud/spanner"
require "google/cloud/spanner/admin/instance"

def spanner_delete_instance_config user_config_id:
  # user_config_id = "The customer managed instance configuration ID, e.g projects/<project>/instanceConfigs/custom-nam11"

  instance_admin_client = Google::Cloud::Spanner::Admin::Instance.instance_admin
  instance_admin_client.delete_instance_config name: user_config_id
  puts "Deleted instance configuration #{user_config_id}"
end

Langkah selanjutnya