注册集群

本页面介绍了如何在大区中注册、列出和查看 Game Servers 集群的详细信息。

准备工作

开始之前,我们建议您先了解 Game Servers 概览中的关键概念。请确保您已执行以下任务:

  • 确保您已启用 Game Services API。
  • 启用 Game Services API
  • 选择安装了 Cloud SDK 的 shell,或使用 API 客户端:
  • Cloud Shell

    如需启动 Cloud Shell,请执行以下步骤:

    1. 转到 Google Cloud Console。

      Google Cloud Console

    2. 在控制台的右上角,点击激活 Cloud Shell 按钮:

    控制台下方的框架内会打开一个 Cloud Shell 会话。您可以使用此 shell 运行 gcloud 命令。

    本地 shell

    如需安装 gcloud,请安装 Cloud SDK,其中包含 gcloud 命令行工具。

    确认您已为 gcloud 命令行工具设置所需的默认项目(否则,您需要以后为每个命令明确指定标志 --project):

    gcloud config list project
    

    如果无法运行以下命令来设置默认项目,请将 project-id 替换为所需的项目 ID:

    gcloud config set project project-id
    

    运行以下命令以验证 Google Cloud SDK 的版本。Game Servers 需要 306.0.0 或更高版本的 SDK。

    gcloud version
    

    如需更新安装,请运行以下命令:

    gcloud components update
    

    客户端库

    您可以使用客户端库以编程方式控制 Google Cloud Game Servers。如需了解库和身份验证的使用说明,请参阅客户端库概览

注册集群

确保您已创建 Game Servers 大区

如果您还没有安装了 Agones 的 Google Kubernetes Engine (GKE) 集群,请按照创建 Google Kubernetes Engine 集群安装 Agones 的指南操作。确保您的 Agones 和 Kubernetes 集群版本符合要求,并且您在 agones-system 命名空间中安装了 Agones。

注册游戏服务器集群

gcloud 命令

您可以使用 gcloud 命令行工具在大区中注册 Game Servers 集群。

注册全球性游戏服务器集群

如需注册全球性游戏服务器集群,请执行以下操作:

  1. 运行以下命令并将占位符值(例如 realmID)替换为适当的值:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster=gkeCluster --namespace=default --dry-run
    

    输出会返回 targetState,以便在注册新集群之前对其进行预览。

  2. 如需注册并创建全球性集群,请运行以下命令:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --namespace=default --no-dry-run
    

注册地区级游戏服务器集群

如需注册地区级游戏服务器集群,请执行以下操作:

  1. 运行以下命令并将占位符值(例如 realmID)替换为适当的值:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --location=region --namespace=default --dry-run
    

    输出会返回 targetState,以便在创建新集群之前对其进行预览。

  2. 如需注册并创建地区级集群,请运行以下命令:

    gcloud game servers clusters create gscID --realm=realmID --gke-cluster gkeCluster --location=region --namespace=default --no-dry-run
    

如果 Game Servers 无法验证您尝试挂接的集群,您可能会遇到以下错误:

Cannot connect to the provided Kubernetes cluster "projects/project/locations/location/clusters/gkeCluster, check the name and make sure that the cluster exists

在这种情况下,请确保 gkeCluster 格式正确,集群位于 projectlocation 中。

变量占位符对应于以下说明:

  • gscID 是您可以为此集群指定的唯一标识符。
  • realmID 是您要在其中存储集群的大区的唯一标识符。
  • gkeCluster 是 GKE 集群的完全限定资源路径,例如 projects/<projectId>/locations/<location>/clusters/<clusterId>
  • region 是集群的地区。选择与父级大区相同的地区。

Go


import (
	"context"
	"fmt"
	"io"

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

// createCluster registers a game server cluster.
func createCluster(w io.Writer, projectID, location, realmID, clusterID, gkeClusterName string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	// clusterID := "mycluster"
	// gkeClusterName := "projects/1234/locations/us-central1/clusters/gke-cluster"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

	req := &gamingpb.CreateGameServerClusterRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/%s/realms/%s", projectID, location, realmID),
		GameServerClusterId: clusterID,
		GameServerCluster: &gamingpb.GameServerCluster{
			ConnectionInfo: &gamingpb.GameServerClusterConnectionInfo{
				Namespace: "default",
				ClusterReference: &gamingpb.GameServerClusterConnectionInfo_GkeClusterReference{
					GkeClusterReference: &gamingpb.GkeClusterReference{
						Cluster: gkeClusterName,
					},
				},
			},
			Description: "My Game Server Cluster",
		},
	}

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

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

Node.js

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

const client = new GameServerClustersServiceClient();

async function createGameServerCluster() {
  /**
   * 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 = 'The ID of the realm to locate this cluster in';
  // const gameClusterId = 'A unique ID for this Game Server Cluster';
  // const gkeClusterName= 'The full resource name of the GKE cluster to use';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
    gameServerClusterId: gameClusterId,
    gameServerCluster: {
      description: 'My Game Server Cluster',
      connectionInfo: {
        gkeClusterReference: {
          // Provide full resource name of a Kubernetes Engine cluster
          // In the form of 'projects/<project-id>/locations/<location>/clusters/<gke-cluster-name>'
          cluster: gkeClusterName,
        },
        namespace: 'default',
      },
    },
  };

  const [operation] = await client.createGameServerCluster(request);
  const [result] = await operation.promise();

  console.log('Game Server Cluster created:');
  console.log(`\tCluster name: ${result.name}`);
  console.log(`\tCluster description: ${result.description}`);
  console.log(
    `\tGKE cluster: ${result.connectionInfo.gkeClusterReference.cluster}`
  );
}

createGameServerCluster();

Python

def create_cluster(project_id, location, realm_id, cluster_id, gke_cluster_name):
    """Creates a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    gke_cluster_reference = game_server_clusters.GkeClusterReference(
        cluster=gke_cluster_name,
    )
    request = game_server_clusters.CreateGameServerClusterRequest(
        parent=f"projects/{project_id}/locations/{location}/realms/{realm_id}",
        game_server_cluster_id=cluster_id,
        game_server_cluster=game_server_clusters.GameServerCluster(
            description="My Game Server Cluster",
            connection_info=game_server_clusters.GameServerClusterConnectionInfo(
                gke_cluster_reference=gke_cluster_reference,
                namespace="default",
            ),
        ),
    )

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

创建游戏服务器集群后,Game Servers 会根据需要创建 Agones 队列自动扩缩器。Game Servers 不会更改手动创建的 Agones 队列。

列出集群

gcloud 命令

您可以使用 gcloud 命令行工具列出全球性集群或地区级集群。

如需列出全球性集群和地区级集群,请运行以下命令:

gcloud game servers clusters list

如需仅列出一个地区中的集群,请运行以下命令,并将 region 替换为您要在其中列出集群的地区

gcloud game servers clusters list --location=region

如需列出大区中的所有集群,请运行以下命令,并将 realmID 替换为父级大区,而将 region 替换为您要列出其中的集群的地区

gcloud game servers clusters list --realm=realmID --location=region

Go


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

// listGameServerClusters lists the clusters registered with a realm.
func listGameServerClusters(w io.Writer, projectID, location, realmID string) error {
	// projectID := "my-project"
	// location := "global"
	// realmID := "myrealm"
	ctx := context.Background()
	client, err := gaming.NewGameServerClustersClient(ctx)
	if err != nil {
		return fmt.Errorf("NewGameServerClustersClient: %v", err)
	}
	defer client.Close()

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

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

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

	return nil
}

Node.js

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

const client = new GameServerClustersServiceClient();

async function listGameServerClusters() {
  /**
   * 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 = 'The ID of the realm to locate this cluster in';
  const request = {
    // Provide full resource name of a Game Server Realm
    parent: client.realmPath(projectId, location, realmId),
  };

  const results = await client.listGameServerClusters(request);
  const [clusters] = results;

  for (const cluster of clusters) {
    console.log('Game Server Cluster:');
    console.log(`\tCluster name: ${cluster.name}`);
    console.log(`\tCluster description: ${cluster.description}`);
    console.log(
      `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
    );
  }
}

listGameServerClusters();

Python

def list_clusters(project_id, location, realm_id):
    """Lists the existing game server clusters."""

    client = gaming.GameServerClustersServiceClient()

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

    for cluster in response.game_server_clusters:
        print(f"Name: {cluster.name}")

    return response.game_server_clusters

查看有关集群的详细信息

gcloud 命令

您可以使用 gcloud 命令行工具查找有关集群的详细信息,例如创建时间或 GKE 集群详细信息:

如需查看集群的详细信息,请运行以下命令,并将占位符值(如 realmID)替换为适当的值:

gcloud game servers clusters describe gscID --realm realmID --location=region

输出会提供集群的详细信息。

变量占位符对应于以下说明:

  • gscID 是您为游戏服务器集群指定的唯一标识符。
  • realmID 是在其中存储集群的大区的唯一标识符。
  • region 是集群的地区。选择与父级大区相同的地区。

Go


import (
	"context"
	"fmt"
	"io"

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

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

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

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

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

Node.js

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

const client = new GameServerClustersServiceClient();

async function getGameServerCluster() {
  /**
   * 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 = 'The ID of the realm to locate this cluster in';
  // const gameClusterId = 'The unique ID for this Game Server Cluster';
  const request = {
    // Provide full resource name of a Game Server Realm
    name: client.gameServerClusterPath(
      projectId,
      location,
      realmId,
      gameClusterId
    ),
  };

  const [cluster] = await client.getGameServerCluster(request);

  console.log('Game Server Cluster:');
  console.log(`\tCluster name: ${cluster.name}`);
  console.log(`\tCluster description: ${cluster.description}`);
  console.log(
    `\tGKE cluster: ${cluster.connectionInfo.gkeClusterReference.cluster}`
  );
}

getGameServerCluster();

Python

def get_cluster(project_id, location, realm_id, cluster_id):
    """Gets a game server cluster."""

    client = gaming.GameServerClustersServiceClient()

    request = game_server_clusters.GetGameServerClusterRequest(
        name=f"projects/{project_id}/locations/{location}/realms/{realm_id}/gameServerClusters/{cluster_id}",
    )

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

问题排查

IAM 权限错误

如果权限设置不正确,您会看到以下错误:

Cannot connect to the provided Kubernetes cluster "projects/projectId/locations/location/clusters/gkeCluster", make sure that "service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com" has been granted the required permissions to access the cluster

如果发生这种情况,请完成本部分中的步骤来设置 IAM 权限。

当您在 Google Cloud 项目中创建 Game Servers 资源时,Game Servers 还会创建一个 Game Servers Google 管理的服务帐号,其格式为 serviceAccount:service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com。 此服务帐号将被自动授予预定义的 Game Servers roles/gameservices.serviceAgent 角色。此角色赋予 Google 代管式服务帐号管理您注册的 GKE 集群所需的权限。如果您将其撤消,就会看到上述错误消息。

以下命令展示用于向服务帐号授予 Game Servers roles/gameservices.serviceAgent 角色的语法:

gcloud projects add-iam-policy-binding projectId --role roles/gameservices.serviceAgent --member serviceAccount:service-projectNumber@gcp-sa-gameservices.iam.gserviceaccount.com

其中:

  • projectId 是项目的 ID。您可以通过运行 gcloud config get-value project 来获取 projectId
  • 运行 gcloud projects describe projectId 即可检索 projectNumber

后续步骤

了解如何删除集群