管理拨测

本文档介绍了如何使用 Google Cloud 控制台、Google Cloud CLI、Cloud Monitoring API 和客户端库来管理拨测。

只有 Google Cloud 项目支持此功能。

准备工作

在存储您的正常运行时间检查的 Google Cloud 项目中完成以下操作:

  • Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    C#

    如需在本地开发环境中使用本页面上的 .NET 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    Go

    如需在本地开发环境中使用本页面上的 Go 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    Java

    如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    Node.js

    如需在本地开发环境中使用本页面上的 Node.js 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    PHP

    如需在本地开发环境中使用本页面上的 PHP 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置 ADC

    Python

    如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    Ruby

    如需在本地开发环境中使用本页面上的 Ruby 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

    Google Cloud

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

    如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

列出所有拨测

控制台

  1. 在 Google Cloud 控制台中,前往  拨测页面:

    前往拨测

    如果您使用搜索栏查找此页面,请选择子标题为监控的结果。

    以下示例展示了拨测示例页面:

    包含过滤条件的拨测概览示例

  2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。

  3. (可选)要限制列出的拨测,请添加过滤条件。

    每个过滤条件都由名称和值组成。 您可以将该值设置为与正常运行时间检查名称完全匹配或部分匹配。匹配不区分大小写。例如,如需列出名称包含 default 的所有正常运行时间检查,请执行以下操作:

    • 点击过滤表格,然后选择显示名称
    • 输入 default,然后按回车键。

    如果您有多个过滤条件,则除非您插入 OR 过滤条件,否则这些过滤条件会由逻辑 AND 自动联接。前一示例使用 OR 过滤条件,以便在拨测名称与 defaultTesting check 匹配时列出拨测。

gcloud

如需列出您的正常运行时间检查和合成监控工具,请运行 gcloud monitoring uptime list-configs 命令:

gcloud monitoring uptime list-configs --project=PROJECT_ID

在运行上一个命令之前,请替换以下内容:

  • PROJECT_ID:项目的标识符。

返回的数据包括以下内容:

  • 名称和显示名称。
  • 检查标识符。
  • 受监控的资源。
  • 两次检查之间的间隔。

您可以配置 Google Cloud CLI 命令来过滤和排序结果。

REST

如需列出您的正常运行时间检查和合成监控工具,请调用 projects.uptimeCheckConfigs.list 方法。指定以下参数:

  • parent:必需。要列出其正常运行时间检查的项目。 此字段的格式如下:

    projects/PROJECT_ID
    

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object ListUptimeCheckConfigs(string projectId)
{
    var client = UptimeCheckServiceClient.Create();
    var configs = client.ListUptimeCheckConfigs(new ProjectName(projectId));
    foreach (UptimeCheckConfig config in configs)
    {
        Console.WriteLine(config.Name);
    }
    return 0;
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

private static void listUptimeChecks(String projectId) throws IOException {
  ListUptimeCheckConfigsRequest request =
      ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request);
    for (UptimeCheckConfig config : response.iterateAll()) {
      System.out.println(config.getDisplayName());
    }
  } catch (Exception e) {
    usage("Exception listing uptime checks: " + e.toString());
    throw e;
  }
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// list is an example of listing the uptime checks in projectID.
func list(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.ListUptimeCheckConfigsRequest{
		Parent: "projects/" + projectID,
	}
	it := client.ListUptimeCheckConfigs(ctx, req)
	for {
		config, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListUptimeCheckConfigs: %w", err)
		}
		fmt.Fprintln(w, config)
	}
	fmt.Fprintln(w, "Done listing uptime checks")
	return nil
}

Node.js

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.UptimeCheckServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  parent: client.projectPath(projectId),
};

// Retrieves an uptime check config
const [uptimeCheckConfigs] = await client.listUptimeCheckConfigs(request);

uptimeCheckConfigs.forEach(uptimeCheckConfig => {
  console.log(`ID: ${uptimeCheckConfig.name}`);
  console.log(`  Display Name: ${uptimeCheckConfig.displayName}`);
  console.log('  Resource: %j', uptimeCheckConfig.monitoredResource);
  console.log('  Period: %j', uptimeCheckConfig.period);
  console.log('  Timeout: %j', uptimeCheckConfig.timeout);
  console.log(`  Check type: ${uptimeCheckConfig.check_request_type}`);
  console.log(
    '  Check: %j',
    uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
  );
  console.log(
    `  Content matchers: ${uptimeCheckConfig.contentMatchers
      .map(matcher => matcher.content)
      .join(', ')}`
  );
  console.log(`  Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);
});

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\ListUptimeCheckConfigsRequest;

/**
 * Example:
 * ```
 * list_uptime_checks($projectId);
 * ```
 */
function list_uptime_checks(string $projectId): void
{
    $projectName = 'projects/' . $projectId;
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $listUptimeCheckConfigsRequest = (new ListUptimeCheckConfigsRequest())
        ->setParent($projectName);

    $pages = $uptimeCheckClient->listUptimeCheckConfigs($listUptimeCheckConfigsRequest);

    foreach ($pages->iteratePages() as $page) {
        foreach ($page as $uptimeCheck) {
            print($uptimeCheck->getName() . PHP_EOL);
        }
    }
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def list_uptime_check_configs(project_id: str) -> pagers.ListUptimeCheckConfigsPager:
    """Gets all uptime checks defined in the Google Cloud project

    Args:
        project_id: Google Cloud project id

    Returns:
        A list of configurations.
        Iterating over this object will yield results and resolve additional pages automatically.
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    configs = client.list_uptime_check_configs(request={"parent": project_id})

    for config in configs:
        pprint.pprint(config)
    return configs

Ruby

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def list_uptime_check_configs project_id
  require "google/cloud/monitoring"

  client = Google::Cloud::Monitoring.uptime_check_service
  project_name = client.project_path project: project_id
  configs = client.list_uptime_check_configs parent: project_name

  configs.each { |config| puts config.name }
end

查看拨测的详细信息

控制台

  1. 在 Google Cloud 控制台中,前往  拨测页面:

    前往拨测

    如果您使用搜索栏查找此页面,请选择子标题为监控的结果。

  2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
  3. 找到要查看的拨测,然后点击其名称。

    以下屏幕截图显示了名称为“我的拨测”(My Uptime Check) 的拨测的正常运行时间详细信息:

    拨测信息中心示例。

    正常运行时间详情页面包含以下信息:

    • 选定的时间间隔。默认情况下,时间间隔为 1 小时
    • 正常运行时间检查的名称。在示例中,名称为我的正常运行时间检查 (My Uptime Check)
    • 您添加到正常运行时间检查的标签。
    • 正常运行时间百分比和平均延迟时间。 正常运行时间百分比值是按照 (S/T)*100 计算出的百分比,其中 S 表示检查响应的成功次数,T 是所有位置的检查响应总数。对于群组检查,ST 的值分别是所有当前组成员中相应值的总和。

      例如,在 25 分钟时段内,从所有区域运行一分钟时长的正常运行时间检查会从 6 个位置收到请求,每个位置 25 个,共计 150 个请求。如果信息中心报告的正常运行时间百分比为 83.3%,则表示 150 个请求中有 125 个成功。

    • 已通过检查 (Passed checks)正常运行时间检查延迟时间 (Uptime check latency) 窗格会以图形方式显示已通过检查的数量和每项检查的延迟时间随时间变化的情况。

    • 当前状态窗格会显示最近检查的状态。 区域旁边内含对勾的绿色圆圈表示该区域中最近一次检查成功运行;内含 x 的红色圆圈则表示失败。

    • 配置窗格显示正常运行时间检查的配置。 此数据是在创建正常运行时间检查时分配的。 检查 Id 值对应于 API 调用中的 CHECK_ID 值。

    • 提醒政策窗格列出了关联的提醒政策的相关信息。在示例信息中心中,已配置一个提醒政策。

gcloud

如需列出正常运行时间检查或合成监视器的详细信息,请运行 gcloud monitoring uptime describe 命令:

gcloud monitoring uptime describe CHECK_ID --project=PROJECT_ID

在运行上一个命令之前,请替换以下内容:

  • PROJECT_ID:项目的标识符。
  • CHECK_ID:正常运行时间检查或合成监控工具的标识符。您可以通过运行 gcloud monitoring uptime list-configs 命令并检查 name 字段来找到标识符。如需了解详情,请参阅查找拨测的唯一标识符

为正常运行时间检查返回的数据包括以下内容:

  • 名称和显示名称。
  • 检查标识符。
  • 受监控的资源。
  • 两次检查之间的间隔。

REST

如需列出正常运行时间检查或综合监控器的详细信息,请调用 projects.uptimeCheckConfigs.get 方法。指定以下参数:

  • name:正常运行时间检查配置的完整名称。

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上面的表达式中:

    • PROJECT_ID 是存储正常运行时间检查的项目。

    • CHECK_ID 是正常运行时间检查或合成监控器的标识符。如需了解详情,请参阅查找拨测的唯一标识符

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object GetUptimeCheckConfig(string configName)
{
    var client = UptimeCheckServiceClient.Create();
    UptimeCheckConfig config = client.GetUptimeCheckConfig(configName);
    if (config == null)
    {
        Console.Error.WriteLine(
            "No configuration found with the name {0}", configName);
        return -1;
    }
    Console.WriteLine("Name: {0}", config.Name);
    Console.WriteLine("Display Name: {0}", config.DisplayName);
    Console.WriteLine("Http Path: {0}", config.HttpCheck.Path);
    return 0;
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

private static void getUptimeCheckConfig(String checkName) throws IOException {
  // Create UptimeCheckServiceSettings instance for add retry mechanism
  UptimeCheckServiceSettings.Builder uptimeCheckServiceSettingsBuilder =
      UptimeCheckServiceSettings.newBuilder();
  uptimeCheckServiceSettingsBuilder
      .getUptimeCheckConfigSettings()
      .setRetrySettings(
          uptimeCheckServiceSettingsBuilder
              .getUptimeCheckConfigSettings()
              .getRetrySettings()
              .toBuilder()
              .setInitialRetryDelay(org.threeten.bp.Duration.ofMillis(100L))
              .setRetryDelayMultiplier(1.3)
              .setMaxRetryDelay(MAX_RECONNECT_BACKOFF_TIME)
              .setInitialRpcTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setRpcTimeoutMultiplier(1.0)
              .setMaxRpcTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setTotalTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setMaxAttempts(6)
              .build());
  UptimeCheckServiceSettings uptimeCheckServiceSettings =
      uptimeCheckServiceSettingsBuilder.build();

  // create UptimeCheckServiceClient with retry setting
  try (UptimeCheckServiceClient client =
      UptimeCheckServiceClient.create(uptimeCheckServiceSettings)) {
    UptimeCheckConfig config = client.getUptimeCheckConfig(checkName);
    if (config != null) {
      System.out.println(config.toString());
    } else {
      System.out.println("No uptime check config found with ID " + checkName);
    }
  } catch (Exception e) {
    usage("Exception getting uptime check: " + e.toString());
    throw e;
  }
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// get is an example of getting an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func get(w io.Writer, resourceName string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Config: %v", config)
	return config, nil
}

Node.js

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.UptimeCheckServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Retrieving ${request.name}`);

// Retrieves an uptime check config
const [uptimeCheckConfig] = await client.getUptimeCheckConfig(request);
console.log(`ID: ${uptimeCheckConfig.name}`);
console.log(`Display Name: ${uptimeCheckConfig.displayName}`);
console.log('Resource: %j', uptimeCheckConfig.monitoredResource);
console.log('Period: %j', uptimeCheckConfig.period);
console.log('Timeout: %j', uptimeCheckConfig.timeout);
console.log(`Check type: ${uptimeCheckConfig.check_request_type}`);
console.log(
  'Check: %j',
  uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
);
console.log(
  `Content matchers: ${uptimeCheckConfig.contentMatchers
    .map(matcher => matcher.content)
    .join(', ')}`
);
console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\GetUptimeCheckConfigRequest;

/**
 * Example:
 * ```
 * get_uptime_check($projectId, $configName);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $configName
 */
function get_uptime_check($projectId, $configName)
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $getUptimeCheckConfigRequest = (new GetUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheck = $uptimeCheckClient->getUptimeCheckConfig($getUptimeCheckConfigRequest);

    print('Retrieved an uptime check:' . PHP_EOL);
    print($uptimeCheck->serializeToJsonString() . PHP_EOL);
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def get_uptime_check_config(config_name: str) -> uptime.UptimeCheckConfig:
    """Reads the uptime check configuration

    Args:
        config_name: Uptime check configuration identity

    Returns:
        A structure that describes the updated uptime check
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(request={"name": config_name})
    pprint.pprint(config)
    return config

Ruby

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def get_uptime_check_config config_name
  require "google/cloud/monitoring"

  client = Google::Cloud::Monitoring.uptime_check_service
  config = client.get_uptime_check_config name: config_name
  pp config.to_h
  config
end

修改拨测

您可以修改拨测的某些字段。例如,您可能希望检查更频繁地进行,或者您可能希望增加与响应验证关联的超时。但是,如果您的拨测未配置正确的协议、资源类型或资源,请删除当前拨测并创建新的拨测。

如需了解如何修改用于监控正常运行时间检查的提醒政策,请参阅以下文档:

如需修改公开拨测,您可以在以下任何标签页上使用相应进程。如需修改非公开拨测,请使用控制台API 标签页:

控制台

  1. 在 Google Cloud 控制台中,前往  拨测页面:

    前往拨测

    如果您使用搜索栏查找此页面,请选择子标题为监控的结果。

  2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
  3. 找到要修改的拨测,然后执行以下任一操作:

    • 点击更多 并选择修改
    • 查看正常运行时间检查详情,然后点击修改
  4. 根据需要更改字段的值。您无法修改所有字段。如果检查的自定义标头值处于隐藏状态,您就无法显示这些值。

  5. 如需验证检查是否有效,请点击测试。如果测试失败,请参阅检查失败以了解可能的原因。

  6. 点击保存

gcloud

如需修改正常运行时间检查或合成监控器,请运行 gcloud monitoring uptime update 命令:

gcloud monitoring uptime update CHECK_ID OPTIONAL_FLAGS --project=PROJECT_ID

在运行上一个命令之前,请替换以下内容:

  • PROJECT_ID:项目的标识符。
  • CHECK_ID:正常运行时间检查或合成监控工具的标识符。您可以通过运行 gcloud monitoring uptime list-configs 命令并检查 name 字段来找到标识符。如需了解详情,请参阅查找拨测的唯一标识符

您还必须定义要修改的字段。

例如,如需将正常运行时间检查的周期设置为 10 分钟,请运行以下命令:

gcloud monitoring uptime update CHECK_ID --period=10

REST

调用 projects.uptimeCheckConfigs.patch 方法。为该方法设置参数,如下所示:

  • uptimeCheckConfig.name:必需。这是 REST 网址的一部分,是待修改正常运行时间检查的资源名称:

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上面的表达式中:

    • PROJECT_ID 是存储正常运行时间检查的项目。

    • CHECK_ID 是正常运行时间检查或合成监控器的标识符。如需了解详情,请参阅查找拨测的唯一标识符

  • updateMask:可选。这是一个查询参数:?updateMask=[FIELD_LIST][FIELD_LIST]UptimeCheckConfig 对象中应更改的字段的英文逗号分隔列表。例如:

    "resource.type,httpCheck.path"
    
  • 请求正文必须包含带有新字段值的 UptimeCheckConfig

如果设置了 updateMask,则只有 updateMask 中列出的字段会替换现有配置中的相应字段。如果一个字段具有子字段,并且该字段已在字段掩码中列出但其子字段均未列出,则该字段的所有子字段都将替换相应的字段。

如果未设置 updateMask,则请求正文中的配置将替换整个现有配置。

patch 方法会返回已更改配置的 UptimeCheckConfig 对象。

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object UpdateUptimeCheck(string configName,
    string newHttpPath, string newDisplayName)
{
    var client = UptimeCheckServiceClient.Create();
    var config = client.GetUptimeCheckConfig(configName);
    var fieldMask = new FieldMask();
    if (newDisplayName != null)
    {
        config.DisplayName = newDisplayName;
        fieldMask.Paths.Add("display_name");
    }
    if (newHttpPath != null)
    {
        config.HttpCheck.Path = newHttpPath;
        fieldMask.Paths.Add("http_check.path");
    }
    client.UpdateUptimeCheckConfig(config);
    return 0;
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

private static void updateUptimeCheck(String checkName, String hostName, String pathName)
    throws IOException {

  UpdateUptimeCheckConfigRequest request =
      UpdateUptimeCheckConfigRequest.newBuilder()
          .setUpdateMask(FieldMask.newBuilder().addPaths("http_check.path"))
          .setUptimeCheckConfig(
              UptimeCheckConfig.newBuilder()
                  .setName(checkName)
                  .setMonitoredResource(
                      MonitoredResource.newBuilder()
                          .setType("uptime_url")
                          .putLabels("host", hostName))
                  .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
                  .setTimeout(Duration.newBuilder().setSeconds(10))
                  .setPeriod(Duration.newBuilder().setSeconds(300)))
          .build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    UptimeCheckConfig config = client.updateUptimeCheckConfig(request);
    System.out.println("Uptime check updated: \n" + config.toString());
  } catch (Exception e) {
    usage("Exception updating uptime check: " + e.toString());
    throw e;
  }
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// update is an example of updating an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func update(w io.Writer, resourceName, displayName, httpCheckPath string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	getReq := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, getReq)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %w", err)
	}
	config.DisplayName = displayName
	config.GetHttpCheck().Path = httpCheckPath
	req := &monitoringpb.UpdateUptimeCheckConfigRequest{
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"display_name", "http_check.path"},
		},
		UptimeCheckConfig: config,
	}
	config, err = client.UpdateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("UpdateUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Successfully updated %v", resourceName)
	return config, nil
}

Node.js

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.UptimeCheckServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';
// const displayName = 'A New Display Name';
// const path = '/some/path';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Updating ${request.name} to ${displayName}`);

// Updates the display name and path on an uptime check config
request.uptimeCheckConfig = {
  name: request.name,
  displayName: displayName,
  httpCheck: {
    path: path,
  },
};

request.updateMask = {
  paths: ['display_name', 'http_check.path'],
};

const [response] = await client.updateUptimeCheckConfig(request);
console.log(`${response.name} config updated.`);

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\GetUptimeCheckConfigRequest;
use Google\Cloud\Monitoring\V3\UpdateUptimeCheckConfigRequest;
use Google\Protobuf\FieldMask;

/**
 * Example:
 * ```
 * update_uptime_checks($projectId);
 * ```
 */
function update_uptime_checks(
    string $projectId,
    string $configName,
    string $newDisplayName = null,
    string $newHttpCheckPath = null
): void {
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $getUptimeCheckConfigRequest = (new GetUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheck = $uptimeCheckClient->getUptimeCheckConfig($getUptimeCheckConfigRequest);
    $fieldMask = new FieldMask();
    if ($newDisplayName) {
        $fieldMask->getPaths()[] = 'display_name';
        $uptimeCheck->setDisplayName($newDisplayName);
    }
    if ($newHttpCheckPath) {
        $paths = $fieldMask->getPaths()[] = 'http_check.path';
        $uptimeCheck->getHttpCheck()->setPath($newHttpCheckPath);
    }
    $updateUptimeCheckConfigRequest = (new UpdateUptimeCheckConfigRequest())
        ->setUptimeCheckConfig($uptimeCheck)
        ->setUpdateMask($fieldMask);

    $uptimeCheckClient->updateUptimeCheckConfig($updateUptimeCheckConfigRequest);

    print($uptimeCheck->serializeToString() . PHP_EOL);
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def update_uptime_check_config(
    config_name: str, new_display_name: str = None, new_http_check_path: str = None
) -> uptime.UptimeCheckConfig:
    """Creates a new uptime check configuration

    Args:
        config_name: Uptime check configuration identity
        new_display_name: A new human friendly name of the configuration
        new_http_check_path: A new HTTP endpoint of the configuration

    Returns:
        A structure that describes the updated uptime check
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(request={"name": config_name})
    field_mask = field_mask_pb2.FieldMask()
    if new_display_name:
        field_mask.paths.append("display_name")
        config.display_name = new_display_name
    if new_http_check_path:
        field_mask.paths.append("http_check.path")
        config.http_check.path = new_http_check_path
    changed_config = client.update_uptime_check_config(
        request={"uptime_check_config": config, "update_mask": field_mask}
    )
    pprint.pprint(changed_config)
    return changed_config

Ruby

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def update_uptime_check_config config_name:         nil,
                               new_display_name:    nil,
                               new_http_check_path: nil
  require "google/cloud/monitoring"

  client = Google::Cloud::Monitoring.uptime_check_service
  config = { name: config_name }
  field_mask = { paths: [] }
  unless new_display_name.to_s.empty?
    field_mask[:paths].push "display_name"
    config[:display_name] = new_display_name
  end
  unless new_http_check_path.to_s.empty?
    field_mask[:paths].push "http_check.path"
    config[:http_check] = { path: new_http_check_path }
  end
  client.update_uptime_check_config uptime_check_config: config,
                                    update_mask:         field_mask
end

新的正常运行时间检查结果最长可能会延迟 5 分钟显示。在此期间,之前的正常运行时间检查的结果会显示在信息中心内并应用于提醒政策中。

删除拨测

我们建议您在关闭拨测所监控的服务或资源时删除拨测。

要删除拨测,请执行以下操作:

控制台

  1. 在 Google Cloud 控制台中,前往  拨测页面:

    前往拨测

    如果您使用搜索栏查找此页面,请选择子标题为监控的结果。

  2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
  3. 找到要修改的拨测,然后执行以下任一操作:

    • 点击更多 并选择删除
    • 查看正常运行时间检查详情,然后点击删除

gcloud

如需删除正常运行时间检查或合成监控器,请运行 gcloud monitoring uptime delete 命令:

gcloud monitoring uptime delete CHECK_ID --project=PROJECT_ID

在运行上一个命令之前,请替换以下内容:

  • PROJECT_ID:项目的标识符。
  • CHECK_ID:正常运行时间检查或合成监控工具的标识符。您可以通过运行 gcloud monitoring uptime list-configs 命令并检查 name 字段来找到标识符。如需了解详情,请参阅查找拨测的唯一标识符

REST

如需删除正常运行时间检查或合成监控,请调用 projects.uptimeCheckConfigs.delete 方法。填写参数,如下所示:

  • name:必需。这是待删除正常运行时间检查配置的资源名称:

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上面的表达式中:

    • PROJECT_ID 是存储正常运行时间检查的项目。

    • CHECK_ID 是正常运行时间检查或合成监控器的标识符。如需了解详情,请参阅查找拨测的唯一标识符

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

public static object DeleteUptimeCheckConfig(string configName)
{
    var client = UptimeCheckServiceClient.Create();
    client.DeleteUptimeCheckConfig(configName);
    Console.WriteLine($"Deleted {configName}");
    return 0;
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

private static void deleteUptimeCheckConfig(String checkName) throws IOException {
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    client.deleteUptimeCheckConfig(checkName);
  } catch (Exception e) {
    usage("Exception deleting uptime check: " + e.toString());
    throw e;
  }
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// delete is an example of deleting an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func delete(w io.Writer, resourceName string) error {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.DeleteUptimeCheckConfigRequest{
		Name: resourceName,
	}
	if err := client.DeleteUptimeCheckConfig(ctx, req); err != nil {
		return fmt.Errorf("DeleteUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted %q", resourceName)
	return nil
}

Node.js

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.UptimeCheckServiceClient();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Deleting ${request.name}`);

// Delete an uptime check config
await client.deleteUptimeCheckConfig(request);
console.log(`${request.name} deleted.`);

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\DeleteUptimeCheckConfigRequest;

/**
 * Example:
 * ```
 * delete_uptime_check($projectId, $configName);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $configName
 */
function delete_uptime_check($projectId, $configName)
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $deleteUptimeCheckConfigRequest = (new DeleteUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheckClient->deleteUptimeCheckConfig($deleteUptimeCheckConfigRequest);

    printf('Deleted an uptime check: ' . $configName . PHP_EOL);
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

# `config_name` is the `name` field of an UptimeCheckConfig.
# See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.uptimeCheckConfigs#UptimeCheckConfig.
def delete_uptime_check_config(config_name: str) -> None:
    """Deletes the uptime check configuration

    Args:
        config_name: Uptime check configuration identity
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    client.delete_uptime_check_config(request={"name": config_name})
    print("Deleted ", config_name)

Ruby

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def delete_uptime_check_config config_name
  require "google/cloud/monitoring"

  client = Google::Cloud::Monitoring.uptime_check_service
  client.delete_uptime_check_config name: config_name
  puts "Deleted #{config_name}"
end

监控拨测

我们建议您创建提醒政策,以便在拨测失败时收到通知。如需了解详情,请参阅为正常运行时间检查创建提醒政策

查找拨测的唯一标识符

创建拨测后,Monitoring 会为其分配一个称为“拨测 ID”的标识符。此标识符可嵌入新拨测的资源名称中:

projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID

PROJECT_ID 是存储正常运行时间检查的项目的标识符。

拨测 ID 包含在能够创建或列出拨测的 Cloud Monitoring API 方法的响应中。您也可以在 Google Cloud 控制台的正常运行时间详情页面的配置窗格中找到正常运行时间检查 ID。如需了解如何查看正常运行时间详情页面,请参阅本文档的查看拨测详情 (View details of an uptime check) 部分。

后续步骤