Creating a realm

This page explains how to create, list, and describe Game Servers realms. A realm is a user-defined grouping of game server clusters based on the game's latency requirements for player populations.

Before you begin

Before you start, we recommend you familiarize yourself with key concepts in the Game Servers Overview. Make sure you have also performed the following tasks:

  • Ensure that you have enabled the Game Services API.
  • Enable Game Services API
  • Either choose a shell with Cloud SDK installed, or use an API client:
  • Cloud Shell

    To launch Cloud Shell, perform the following steps:

    1. Go to Google Cloud Console.

      Google Cloud Console

    2. From the upper-right corner of the console, click the Activate Cloud Shell button:

    A Cloud Shell session opens inside a frame lower on the console. You use this shell to run gcloud commands.

    Local shell

    To install gcloud, install the Cloud SDK, which includes the gcloud command-line tool.

    Verify that you have set desired default project for gcloud command-line tool (otherwise you need to specify flag --project explicitly for each command later):

    gcloud config list project
    

    If not you can run the following command to set a default project, replacing PROJECT_ID with your desired project ID :

    gcloud config set project PROJECT_ID
    

    Run the following command to verify your version of the Google Cloud SDK. Game Servers requires version 306.0.0 or higher of the SDK.

    gcloud version
    

    To update your installation, run the following command:

    gcloud components update
    

    curl / PowerShell

    To use the REST API with curl or Windows PowerShell, do the following:

    1. Create a service account.
    2. Download a private key as a JSON file.
    3. Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of the JSON file that contains your service account key. This variable only applies to your current shell session, so if you open a new session, set the variable again.

    Client Library

    Google Cloud Game Servers can be controlled programmatically using a client library. See Client Libraries Overview for instructions on using the library and authenticating.

Creating a realm

Realms can be global or regional. A global realm is a good option if the clusters registered to a realm are from regions that span over various geographical locations, such as North America and South America or Europe and Asia. A regional realm is a good option if clusters are in the same region, such as Europe West. In the event of a network outage between regions, a global realm might not be able to manage clusters in every region. To increase the resiliency against network outages between regions, make sure you create regional realms in regions as close as possible to the associated game server clusters.

For example, if you create clusters in the europe-west1, europe-west2, and europe-west3 regions to serve users in the west of Europe, you can also create a regional realm in one of these regions. This configuration ensures the realm can continue to manage clusters in the event these regions can't be reached from regions in other parts of the world due to a network outage.

If you aren't sure where to create your realm, you can create it as a global realm. As your requirements change, you can create a new realm in a region that is closer to the clusters that it needs to manage. You can then move existing clusters to the new regional realm by first deleting and unregistering clusters from the global realm and then registering them in the new regional realm.

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. Click Create Realm.

  3. In the Realm name box, enter a unique identifier for this realm.

  4. In the Timezone box, select a time zone for this realm. When you schedule time-based events, such as scaling policies, it is for this time zone.

  5. Click Create.

gcloud

You can create realms using the gcloud command-line tool. To create a global realm, run the following command and replace the placeholder values, such as realmID, with appropriate values:

gcloud game servers realms create realmID --time-zone tz

To create a regional realm, run the following command and replace the placeholder values, such as realmID, with appropriate values:

gcloud game servers realms create realmID --time-zone tz --location=region

The variable placeholders correspond to the following descriptions:

  • realmID is a unique identifier that you can specify for this realm.
  • tz is the time zone for this realm. When you schedule time based events, such as scaling policies, it is for this time zone.
  • region is the region for the realm. If you want to control failure domains, specify a region. We recommend that you create a global realm and omit this option.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • LOCATION: The region for the realm. If you want to control failure domains, specify a region from the list of supported locations. We recommend that you specify a global realm.
  • REALM_ID: a user-defined identifier for the new realm
  • TIME_ZONE: The time zone for this realm (for example, US/Eastern). You schedule time-based events, such as scaling policies, for this time zone.

Request JSON body:

{
  "timeZone": "TIME_ZONE"
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.gaming.v1.OperationMetadata",
    "createTime": CREATE_TIME,
    "target": "projects/PROJECT_ID/locations/LOCATION/realms/REALM_ID",
    "verb": "create",
    "requestedCancellation": false,
    "apiVersion": "v1"
  },
  "done": false
}

Go

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// createRealm creates a game server realm.
func createRealm(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewRealmsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRealmsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateRealmRequest{
		Parent:  fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		RealmId: realmID,
		Realm: &gamingpb.Realm{
			TimeZone:    "US/Pacific",
			Description: "My Game Server Realm",
		},
	}

	op, err := client.CreateRealm(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateRealm: %v", err)
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %v", err)
	}

	fmt.Fprintf(w, "Realm created: %v", resp.Name)
	return nil
}

Java

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.gaming.v1.CreateRealmRequest;
import com.google.cloud.gaming.v1.OperationMetadata;
import com.google.cloud.gaming.v1.Realm;
import com.google.cloud.gaming.v1.RealmsServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateRealm {
  public static void createRealm(String projectId, String regionId, String realmId)
      throws InterruptedException, ExecutionException, TimeoutException, IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (RealmsServiceClient client = RealmsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, regionId);
      String realmName = String.format("%s/realms/%s", parent, realmId);

      Realm realm =
          Realm.newBuilder().setName(realmName).setTimeZone("America/Los_Angeles").build();

      CreateRealmRequest request =
          CreateRealmRequest.newBuilder()
              .setParent(parent)
              .setRealmId(realmId)
              .setRealm(realm)
              .build();

      OperationFuture<Realm, OperationMetadata> call = client.createRealmAsync(request);
      Realm result = call.get(1, TimeUnit.MINUTES);

      System.out.println("Realm created: " + result.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.

const {RealmsServiceClient} = require('@google-cloud/game-servers');

const client = new RealmsServiceClient();

async function createRealm() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'A unique identifier for the realm';
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    realmId: realmId,
    realm: {
      // Must use a supported time zone name.
      // See https://cloud.google.com/dataprep/docs/html/Supported-Time-Zone-Values_66194188
      timeZone: 'US/Pacific',
      description: 'My Game Server realm',
    },
  };

  const [operation] = await client.createRealm(request);
  const results = await operation.promise();
  const [realm] = results;

  console.log('Realm created:');

  console.log(`\tRealm name: ${realm.name}`);
  console.log(`\tRealm description: ${realm.description}`);
  console.log(`\tRealm time zone: ${realm.timeZone}`);
}

createRealm();

Python

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.

def create_realm(project_id, location, realm_id):
    """Creates a realm."""

    client = gaming.RealmsServiceClient()

    request = realms.CreateRealmRequest(
        parent=f"projects/{project_id}/locations/{location}",
        realm_id=realm_id,
        realm=realms.Realm(
            description="My Realm",
            time_zone="US/Pacific",
        ),
    )

    operation = client.create_realm(request)
    print(f"Create realm operation: {operation.operation.name}")
    operation.result(timeout=120)

Listing realms

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. You can use the filter box to filter the realms list by different properties.

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • LOCATION: the region for the realms or global

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "realms": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/realms/realm1",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "timeZone": "US/Eastern",
      "etag": "PlXtLrUJ5pHQoZk0Lz-pWkPFN_dt3PXhIpRrJ5HHWu8"
    },
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/realms/realm2",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "timeZone": "America/Eirunepe",
      "etag": "ay1tXqeujLSsSd93n6uhlZwlxdNTOfG7El992Tsiz98"
    },
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/realms/realm3",
      "createTime": CREATE_TIME,
      "updateTime": UPDATE_TIME,
      "timeZone": "Asia/Anadyr",
      "etag": "cBxzV2AWK_zgijSmYA-oXPWv3giwhUzssoWcqjPZFuk"
    }
  ]
}

gcloud

You can list global or regional realms using the gcloud command-line tool.

To list both global and regional realms, run the following command:

gcloud game servers realms list

To list realms in a specific location run the following command and replace region with either global or a Google Cloud region:

gcloud game servers realms list --location=region

Go

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	"google.golang.org/api/iterator"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// listRealms lists the realms in a location.
func listRealms(w io.Writer, projectID, location string) error {
	// projectID := "my-project"
	// location := "global"
	ctx := context.Background()
	client, err := gaming.NewRealmsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRealmsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.ListRealmsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListRealms(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Realm listed: %v\n", resp.Name)
	}

	return nil
}

Java

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import com.google.cloud.gaming.v1.ListRealmsRequest;
import com.google.cloud.gaming.v1.Realm;
import com.google.cloud.gaming.v1.RealmsServiceClient;
import com.google.cloud.gaming.v1.RealmsServiceClient.ListRealmsPagedResponse;
import com.google.common.base.Strings;
import java.io.IOException;

public class ListRealms {
  public static void listRealms(String projectId, String regionId) throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (RealmsServiceClient client = RealmsServiceClient.create()) {
      String parent = String.format("projects/%s/locations/%s", projectId, regionId);

      ListRealmsPagedResponse response = client.listRealms(parent);
      for (Realm realm : response.iterateAll()) {
        System.out.println("Realm found: " + realm.getName());
      }

      while (!Strings.isNullOrEmpty(response.getNextPageToken())) {
        ListRealmsRequest request =
            ListRealmsRequest.newBuilder()
                .setParent(parent)
                .setPageToken(response.getNextPageToken())
                .build();
        response = client.listRealms(request);
        for (Realm realm : response.iterateAll()) {
          System.out.println("Realm found: " + realm.getName());
        }
      }
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.

const {RealmsServiceClient} = require('@google-cloud/game-servers');

const client = new RealmsServiceClient();

async function listRealms() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  const [results] = await client.listRealms(request);
  for (const realm of results) {
    console.log(`Realm name: ${realm.name}`);
    console.log(`Realm description: ${realm.description}`);
    console.log(`Realm time zone: ${realm.timeZone}`);

    const createTime = realm.createTime;
    const createDate = new Date(createTime.seconds * 1000);
    console.log(`Realm created on: ${createDate.toLocaleDateString()}\n`);
  }
}

listRealms();

Python

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.



def list_realms(project_id, location):
    """Lists the existing realms."""

    client = gaming.RealmsServiceClient()

    response = client.list_realms(
        parent=f"projects/{project_id}/locations/{location}"
    )

    for realm in response.realms:
        print(f"Name: {realm.name}")

    return response.realms

Describing realms

Console

  1. In the Cloud Console, go to the Realms & Clusters page.

    Go to Game Servers

  2. You can use the filter box to filter the realms list by different properties.

  3. In the last table column, click the ellipses and select View details.

gcloud

You can obtain details about a realm, such as the creation time or time zone, using the gcloud command-line tool.

To describe a global realm, run the following command and replace realmID with the identifier for a realm you have previously created:

gcloud game servers realms describe realmID

If you created one or more realms that weren't global, you can describe details about a realm in a specific region. To describe a realm in a region, replace realmID with the identifier for a realm you have previously created and region with the region that the realm is in:

gcloud game servers realms describe realmID --location=region

REST & CMD LINE

Before using any of the request data, make the following replacements:

  • PROJECT_ID: your Google Cloud project ID listed in the IAM Settings
  • LOCATION: the region for the realm or global
  • REALM_ID: a user-defined identifier for the realm

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/realms/REALM_ID",
  "createTime": CREATE_TIME,
  "updateTime": UPDATE_TIME,
  "timeZone": "Asia/Anadyr",
  "etag": "cBxzV2AWK_zgijSmYA-oXPWv3giwhUzssoWcqjPZFuk"
}

Go

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import (
	"context"
	"fmt"
	"io"

	gaming "cloud.google.com/go/gaming/apiv1"
	gamingpb "google.golang.org/genproto/googleapis/cloud/gaming/v1"
)

// getRealm retrieves info on a realm.
func getRealm(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewRealmsClient(ctx)
	if err != nil {
		return fmt.Errorf("NewRealmsClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.GetRealmRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
	}

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

	fmt.Fprintf(w, "Realm retrieved: %v", resp.Name)
	return nil
}

Java

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.


import com.google.cloud.gaming.v1.Realm;
import com.google.cloud.gaming.v1.RealmsServiceClient;
import java.io.IOException;

public class GetRealm {
  public static void getRealm(String projectId, String regionId, String realmId)
      throws IOException {
    // String projectId = "your-project-id";
    // String regionId = "us-central1-f";
    // String realmId = "your-realm-id";
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (RealmsServiceClient client = RealmsServiceClient.create()) {
      String realmName =
          String.format("projects/%s/locations/%s/realms/%s", projectId, regionId, realmId);

      Realm allocationPolicy = client.getRealm(realmName);

      System.out.println("Realm found: " + allocationPolicy.getName());
    }
  }
}

Node.js

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.

const {RealmsServiceClient} = require('@google-cloud/game-servers');

const client = new RealmsServiceClient();

async function getRealm() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'Your Google Cloud Project ID';
  // const location = 'A Compute Engine region, e.g. "us-central1"';
  // const realmId = 'Unique identifier of the realm';
  const request = {
    // Realm name is the full resource name including project ID and location
    name: client.realmPath(projectId, location, realmId),
  };

  const [realm] = await client.getRealm(request);
  console.log(`Realm name: ${realm.name}`);
  console.log(`Realm description: ${realm.description}`);
  console.log(`Realm time zone: ${realm.timeZone}`);

  const createTime = realm.createTime;
  const createDate = new Date(createTime.seconds * 1000);

  console.log(`Realm created on: ${createDate.toLocaleDateString()}`);
}

getRealm();

Python

To learn how to install and use the client library for Game Servers, see Game Servers client libraries.

def get_realm(project_id, location, realm_id):
    """Gets a realm."""

    client = gaming.RealmsServiceClient()

    request = realms.GetRealmRequest(
        name=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
    )

    response = client.get_realm(request)
    print(f"Get realm response:\n{response}")
    return response

What's next