Storage Control List Anywhere Caches

Storage Control List Anywhere Caches

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 client libraries.

namespace storagecontrol = google::cloud::storagecontrol_v2;
[](storagecontrol::StorageControlClient client,
   std::string const& bucket_name) {
  auto const parent = std::string{"projects/_/buckets/"} + bucket_name;
  for (auto anywhere_cache : client.ListAnywhereCaches(parent)) {
    if (!anywhere_cache) throw std::move(anywhere_cache).status();
    std::cout << anywhere_cache->name() << "\n";
  }
}

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 client libraries.


import com.google.storage.control.v2.AnywhereCache;
import com.google.storage.control.v2.BucketName;
import com.google.storage.control.v2.ListAnywhereCachesRequest;
import com.google.storage.control.v2.StorageControlClient;
import com.google.storage.control.v2.StorageControlClient.ListAnywhereCachesPagedResponse;
import java.io.IOException;

public final class AnywhereCacheList {

  public static void anywhereCacheList(String bucketName) throws IOException {
    try (StorageControlClient storageControl = StorageControlClient.create()) {

      ListAnywhereCachesRequest request =
          ListAnywhereCachesRequest.newBuilder()
              .setParent(BucketName.format("_", bucketName))
              .build();

      ListAnywhereCachesPagedResponse page = storageControl.listAnywhereCaches(request);
      for (AnywhereCache anywhereCache : page.iterateAll()) {
        System.out.println(anywhereCache.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 client libraries.

const {StorageControlClient} = require('@google-cloud/storage-control');
const {status} = require('@grpc/grpc-js');

const client = new StorageControlClient();

/**
 * Lists all Anywhere Cache instances for a given bucket.
 *
 * Anywhere Cache provides a way to cache frequently accessed objects closer to
 * your applications, reducing latency and egress costs.
 *
 * @param {string} bucketName The name of the bucket to list Anywhere Caches for.
 */
async function listAnywhereCaches(bucketName) {
  const parent = `projects/_/buckets/${bucketName}`;

  const request = {
    parent: parent,
  };

  try {
    const [anywhereCaches] = await client.listAnywhereCaches(request);

    if (anywhereCaches.length === 0) {
      console.log(`No Anywhere Caches found for bucket ${bucketName}.`);
      return;
    }

    console.log('Anywhere Caches:');
    for (const cache of anywhereCaches) {
      console.log(`- Name: ${cache.name}`);
      console.log(`  Zone: ${cache.zone}`);
      console.log(`  State: ${cache.state}`);
      console.log(`  TTL: ${cache.ttl ? cache.ttl.seconds + 's' : 'N/A'}`);
      console.log(`  Admission Policy: ${cache.admissionPolicy || 'N/A'}`);
      if (cache.createTime) {
        const createTime = new Date(
          cache.createTime.seconds * 1000 + cache.createTime.nanos / 1000000,
        );
        console.log(`  Create Time: ${createTime}`);
      }
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(
        `Error: The specified bucket '${bucketName}' was not found.`,
      );
      console.error(
        'Please ensure the bucket exists and is accessible within the project.',
      );
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(
        `Error: Permission denied. Ensure the service account has the necessary permissions (e.g., storage.anywhereCaches.list) for bucket '${bucketName}'.`,
      );
    } else {
      console.error('Error listing Anywhere Caches:', err);
    }
  }
}

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 client libraries.

use Google\Cloud\Storage\Control\V2\Client\StorageControlClient;
use Google\Cloud\Storage\Control\V2\ListAnywhereCachesRequest;

/**
 * Lists Anywhere Cache instances for a given bucket.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function list_anywhere_caches(string $bucketName): void
{
    $storageControlClient = new StorageControlClient();

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

    $request = new ListAnywhereCachesRequest([
        'parent' => $formattedName,
    ]);

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

    foreach ($response as $anywhereCache) {
        printf('Anywhere cache name: %s' . PHP_EOL, $anywhereCache->getName());
    }
}

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 client libraries.

import google.api_core.exceptions
from google.cloud import storage_control_v2


def list_anywhere_caches(
    bucket_name: str,
) -> None:
    """Lists Anywhere Cache instances for a given bucket.

    Args:
        bucket_name: The name of the bucket to list Anywhere Caches for.
    """
    client = storage_control_v2.StorageControlClient()

    parent = f"projects/_/buckets/{bucket_name}"

    try:
        anywhere_caches = client.list_anywhere_caches(parent=parent)

        found_caches = False
        print(f"Anywhere Caches for bucket '{bucket_name}':")
        for cache in anywhere_caches:
            found_caches = True
            print(f"  Name: {cache.name}")
            print(f"  Zone: {cache.zone}")
            print(f"  State: {cache.state}")
            print(f"  TTL: {cache.ttl.seconds} seconds")
            print(f"  Admission Policy: {cache.admission_policy}")
            print("----------------------------------------")

        if not found_caches:
            print("  No Anywhere Cache instances found for this bucket.")

    except google.api_core.exceptions.NotFound:
        print(f"Error: Bucket '{bucket_name}' not found.")
        print("Please ensure the bucket name is correct and the bucket exists.")
    except google.api_core.exceptions.PermissionDenied:
        print(
            f"Error: Permission denied to list Anywhere Caches for bucket '{bucket_name}'."
        )
        print(
            "Please ensure the authenticated service account has 'storage.anywhereCaches.list' permission."
        )
    except google.api_core.exceptions.GoogleAPIError as e:
        print(f"An unexpected API error occurred: {e}")
        print("Please check the error details and your project/bucket configuration.")

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 client libraries.

require "google/cloud/storage/control"

def list_anywhere_caches bucket_name:
  # The Name of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # Create a client object. The client can be reused for multiple calls.
  storage_control_client = Google::Cloud::Storage::Control.storage_control
  # Set project to "_" to signify global bucket
  parent = "projects/_/buckets/#{bucket_name}"

  # Create a request.
  request = Google::Cloud::Storage::Control::V2::ListAnywhereCachesRequest.new(
    parent: parent
  )
  # The request lists all caches in the specified bucket.
  # The caches are identified by the specified bucket name.
  begin
    result = storage_control_client.list_anywhere_caches request
    result.response.anywhere_caches.each do |item|
      puts "AnywhereCache #{item.name} found in list."
    end
  rescue Google::Cloud::Error => e
    puts "Failed to list AnywhereCaches. Error: #{e.message}"
  end
end

What's next

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