Storage Control Quickstart Sample

Quickstart sample using the storage control client

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

#include "google/cloud/storagecontrol/v2/storage_control_client.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " bucket-id\n";
    return 1;
  }
  auto const name =
      std::string{"projects/_/buckets/"} + argv[1] + "/storageLayout";

  namespace storagecontrol = ::google::cloud::storagecontrol_v2;
  auto client = storagecontrol::StorageControlClient(
      storagecontrol::MakeStorageControlConnection());

  auto layout = client.GetStorageLayout(name);
  if (!layout) throw std::move(layout).status();
  std::cout << layout->DebugString() << "\n";

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

using Google.Cloud.Storage.Control.V2;
using System;

public class StorageControlQuickstartSample
{
    public StorageLayout StorageControlQuickstart(string bucketName = "your-unique-bucket-name")
    {
        StorageControlClient storageControl = StorageControlClient.Create();

        // Using "_" for projectId means global bucket namespace
        var layoutName = new StorageLayoutName("_", bucketName);
        StorageLayout response = storageControl.GetStorageLayout(layoutName);

        Console.WriteLine($"Bucket {bucketName} has location type {response.LocationType}");
        return response;
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// This sample demonstrates how to set up and make an API call with the
// Storage Control client.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"time"

	control "cloud.google.com/go/storage/control/apiv2"
	controlpb "cloud.google.com/go/storage/control/apiv2/controlpb"
)

func main() {
	// Set this flag to an existing Cloud Storage bucket when running the sample.
	bucketName := flag.String("bucket", "", "Cloud Storage bucket name")
	flag.Parse()
	log.Printf("bucket : %v", *bucketName)

	ctx := context.Background()

	// Create a client.
	client, err := control.NewStorageControlClient(ctx)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer client.Close()

	// Create a request to get the storage layout for the bucket.
	req := &controlpb.GetStorageLayoutRequest{
		Name: fmt.Sprintf("projects/_/buckets/%v/storageLayout", *bucketName),
	}

	// Set a context timeout and send the request.
	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
	defer cancel()

	res, err := client.GetStorageLayout(ctx, req)
	if err != nil {
		log.Fatalf("GetStorageLayout: %v", err)
	}

	// Use response.
	fmt.Printf("Bucket %v has location type %v", bucketName, res.LocationType)
}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.storage.control.v2.GetStorageLayoutRequest;
import com.google.storage.control.v2.StorageControlClient;
import com.google.storage.control.v2.StorageLayout;
import com.google.storage.control.v2.StorageLayoutName;

public class QuickstartStorageControlSample {
  public static void main(String... args) throws Exception {
    String bucketName = args[0]; // "your-bucket-name";

    // Instantiates a client in a try-with-resource to automatically cleanup underlying resources
    try (StorageControlClient storageControlClient = StorageControlClient.create()) {
      GetStorageLayoutRequest request =
          GetStorageLayoutRequest.newBuilder()
              // Set project to "_" to signify global bucket
              .setName(StorageLayoutName.format("_", bucketName))
              .build();
      StorageLayout response = storageControlClient.getStorageLayout(request);
      System.out.printf("Performed getStorageLayout request for %s", response.getName());
    }
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Name of the bucket for which to get the layout
 */
// const bucketName = 'abc123'

// Imports the Control library
const {StorageControlClient} = require('@google-cloud/storage-control').v2;

// Instantiates a client
const controlClient = new StorageControlClient();

async function callGetStorageLayout() {
  // Construct request
  const request = {
    name: `projects/_/buckets/${bucketName}/storageLayout`,
  };

  // Run request
  const [layout] = await controlClient.getStorageLayout(request);

  // Use response
  console.log(
    `Bucket ${bucketName} has location type ${layout.locationType}.`
  );
}

callGetStorageLayout();

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// Includes the autoloader for libraries installed with composer
require __DIR__ . '/../vendor/autoload.php';

// Imports the Google Cloud client library
use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\GetStorageLayoutRequest;

// Instantiates a client
$storageControlClient = new StorageControlClient();

// The name for the new bucket
$bucketName = 'my-new-bucket';

// Set project to "_" to signify global bucket
$formattedName = $storageControlClient->storageLayoutName('_', $bucketName);
$request = (new GetStorageLayoutRequest())->setName($formattedName);

$response = $storageControlClient->getStorageLayout($request);

echo 'Performed get_storage_layout request for ' . $response->getName() . PHP_EOL;

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import storage_control_v2


def storage_control_quickstart(bucket_name: str) -> None:
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    storage_control_client = storage_control_v2.StorageControlClient()
    # The storage layout path uses the global access pattern, in which
    # the “_” denotes this bucket exists in the global namespace.
    layout_path = storage_control_v2.StorageControlClient.storage_layout_path(
        project="_", bucket=bucket_name
    )
    request = storage_control_v2.GetStorageLayoutRequest(
        name=layout_path,
    )
    response = storage_control_client.get_storage_layout(request=request)

    print(f"Performed get_storage_layout request for {response.name}")

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def quickstart bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage/control"

  storage_control = Google::Cloud::Storage::Control.storage_control

  # The storage layout path uses the global access pattern, in which the "_"
  # denotes this bucket exists in the global namespace.
  layout_path = storage_control.storage_layout_path project: "_", bucket: bucket_name

  request = Google::Cloud::Storage::Control::V2::GetStorageLayoutRequest.new name: layout_path

  response = storage_control.get_storage_layout request

  puts "Performed get_storage_layout request for #{response.name}"
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.