管理正常运行时间检查

Stackdriver 可以从世界各地访问您的服务以验证该服务的可用性。您可以在提醒政策中使用这些正常运行时间检查的结果,也可以在 Monitoring 正常运行时间检查信息中心直接监控结果。

本页面介绍如何执行以下操作:

  • 创建新的正常运行时间检查。
  • 列出现有的正常运行时间检查。
  • 修改正常运行时间检查。
  • 删除正常运行时间检查。

要查看正常运行时间检查的状态,或获取可用于执行正常运行时间检查的 IP 地址列表,请参阅获取 IP 地址。要使用 API 确定正常运行时间检查的状态,请监控指标 monitoring.googleapis.com/uptime_check/check_passed。如需了解详情,请参阅 GCP 指标列表

准备工作

  1. 能否使用正常运行时间检查取决于保护您的服务的防火墙。

    • 如果您检查的资源不是公开提供的,您必须将资源的防火墙配置为允许正常运行时间检查服务器的流量传入。请参阅获取 IP 地址以下载 IP 地址列表。
    • 如果您正在检查的资源没有外部 IP 地址,则正常运行时间检查将无法访问该资源。
  2. 正常运行时间检查不会加载页面资源或运行 JavaScript。正常运行时间检查的默认配置不包括身份验证。您可以使用 Advanced Options 启用身份验证。

    对于 HTTP 和 HTTPS,正常运行时间检查会发出 GET 命令并检索原始数据。如果 GET 响应重定向到另一个网址,则检查将从该网址检索数据。最后,正常运行时间检查会评估数据,以确定检查是成功还是失败。

    要确保检查成功,必须满足以下两个条件:

    • HTTP 状态为 Success
    • 数据不包含所需内容,或者所需内容已存在。所需内容通过 Advanced options 来指定。

创建正常运行时间检查

本部分介绍如何创建和配置正常运行时间检查。

控制台

  1. 在 Stackdriver Monitoring 控制台中,转到 Uptime Checks > Uptime Checks Overview

    转到“Uptime Checks Overview”

  2. 在右上角,点击 Add uptime check

  3. New uptime check 窗口中,按照本页面中的基本选项所述,填写检查的各个字段。

    创建正常运行时间检查

  4. (可选)要访问端口、自定义标头和身份验证的配置,请点击 Advanced Options。如需了解详情,请参阅本页面中的高级选项

  5. 要查看正常运行时间检查的结果,请点击 Test。如果结果与预期不符,请参阅下面的检查失败部分,更正您的配置,然后再次执行该测试。

  6. 点击 Save。如果有任何必填字段缺失,您将无法保存正常运行时间检查。如果 Save 按钮无法使用,请检查是否有值缺失。您必须在 Hostname 字段中输入值。

API

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

  • parent:必需。必须是将在其中创建正常运行时间检查的项目的名称。将 [PROJECT_ID] 替换为您的 GCP 项目 ID。格式如下:

    projects/[PROJECT_ID]
    
  • 请求正文必须包含新正常运行时间检查的 UptimeCheckConfig 对象。如需了解该对象中的字段,请参阅本页面中的基本选项高级选项部分。

    请将配置对象的 name 字段留空,因为该字段将在返回的配置对象中设置。

create 方法会返回新配置的 UptimeCheckConfig 对象。

如果创建的正常运行时间配置未按照预期方式工作,请参阅本页面中的检查失败部分。

C#

public static object CreateUptimeCheck(string projectId, string hostName,
    string displayName)
{
    // Define a new config.
    var config = new UptimeCheckConfig()
    {
        DisplayName = displayName,
        MonitoredResource = new MonitoredResource()
        {
            Type = "uptime_url",
            Labels = { { "host", hostName } }
        },
        HttpCheck = new UptimeCheckConfig.Types.HttpCheck()
        {
            Path = "/",
            Port = 80,
        },
        Timeout = TimeSpan.FromSeconds(10).ToDuration(),
        Period = TimeSpan.FromMinutes(5).ToDuration()
    };
    // Create a client.
    var client = UptimeCheckServiceClient.Create();
    string projectName = new ProjectName(projectId).ToString();
    // Create the config.
    var newConfig = client.CreateUptimeCheckConfig(projectName, config,
        CallSettings.FromCallTiming(CallTiming.FromTimeout(TimeSpan.FromMinutes(2))));
    Console.WriteLine(newConfig.Name);
    return 0;
}

Java

private static void createUptimeCheck(
    String projectId, String displayName, String hostName, String pathName) throws IOException {
  CreateUptimeCheckConfigRequest request = CreateUptimeCheckConfigRequest
      .newBuilder()
      .setParent(ProjectName.format(projectId))
      .setUptimeCheckConfig(UptimeCheckConfig
          .newBuilder()
          .setDisplayName(displayName)
          .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.createUptimeCheckConfig(request);
    System.out.println("Uptime check created: " + config.getDisplayName());
  } catch (Exception e) {
    usage("Exception creating uptime check: " + e.toString());
    throw e;
  }
}

Go

// create creates an example uptime check.
func create(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %v", err)
	}
	defer client.Close()
	req := &monitoringpb.CreateUptimeCheckConfigRequest{
		Parent: "projects/" + projectID,
		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
			DisplayName: "new uptime check",
			Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{
				MonitoredResource: &monitoredres.MonitoredResource{
					Type: "uptime_url",
					Labels: map[string]string{
						"host": "example.com",
					},
				},
			},
			CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_{
				HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{
					Path: "/",
					Port: 80,
				},
			},
			Timeout: &duration.Duration{Seconds: 10},
			Period:  &duration.Duration{Seconds: 300},
		},
	}
	config, err := client.CreateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateUptimeCheckConfig: %v", err)
	}
	fmt.Fprintf(w, "Successfully created uptime check %q\n", config.GetDisplayName())
	return config, nil
}

Node.js

// 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 hostname = 'mydomain.com';

const request = {
  // i.e. parent: 'projects/my-project-id'
  parent: client.projectPath(projectId),
  uptimeCheckConfig: {
    displayName: 'My Uptime Check',
    monitoredResource: {
      // See the Uptime Check docs for supported MonitoredResource types
      type: 'uptime_url',
      labels: {host: hostname},
    },
    httpCheck: {path: '/', port: 80},
    timeout: {seconds: 10},
    period: {seconds: 300},
  },
};

// Creates an uptime check config for a GCE instance
const [uptimeCheckConfig] = await client.createUptimeCheckConfig(request);
console.log('Uptime check created:');
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

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\UptimeCheckConfig;
use Google\Api\MonitoredResource;

/**
 * Example:
 * ```
 * create_uptime_check($projectId, 'myproject.appspot.com', 'Test Uptime Check!');
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $hostName
 * @param string $displayName
 */
function create_uptime_check($projectId, $hostName = 'example.com', $displayName = 'New uptime check')
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);

    $monitoredResource = new MonitoredResource();
    $monitoredResource->setType('uptime_url');
    $monitoredResource->setLabels(['host' => $hostName]);

    $uptimeCheckConfig = new UptimeCheckConfig();
    $uptimeCheckConfig->setDisplayName($displayName);
    $uptimeCheckConfig->setMonitoredResource($monitoredResource);

    $uptimeCheckConfig = $uptimeCheckClient->createUptimeCheckConfig(
        $uptimeCheckClient->projectName($projectId),
        $uptimeCheckConfig
    );

    printf('Created an uptime check: %s' . PHP_EOL, $uptimeCheckConfig->getName());
}

Python

def create_uptime_check_config(project_name, host_name=None,
                               display_name=None):
    config = monitoring_v3.types.uptime_pb2.UptimeCheckConfig()
    config.display_name = display_name or 'New uptime check'
    config.monitored_resource.type = 'uptime_url'
    config.monitored_resource.labels.update(
        {'host': host_name or 'example.com'})
    config.http_check.path = '/'
    config.http_check.port = 80
    config.timeout.seconds = 10
    config.period.seconds = 300

    client = monitoring_v3.UptimeCheckServiceClient()
    new_config = client.create_uptime_check_config(project_name, config)
    pprint.pprint(new_config)
    return new_config

Ruby

def create_uptime_check_config project_id: nil, host_name: nil, display_name: nil
  require "google/cloud/monitoring/v3"

  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  project_name = Google::Cloud::Monitoring::V3::UptimeCheckServiceClient.project_path project_id
  config = {
    display_name:       display_name.nil? ? "New uptime check" : display_name,
    monitored_resource: {
      type:   "uptime_url",
      labels: { "host" => host_name.nil? ? "example.com" : host_name }
    },
    http_check:         { path: "/", port: 80 },
    timeout:            { seconds: 10 },
    period:             { seconds: 300 }
  }
  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  new_config = client.create_uptime_check_config project_name, config
  puts new_config.name
  new_config
end

正常运行时间检查结果最长可能会延迟 25 分钟才开始流入 Monitoring。在此期间,正常运行时间检查信息中心会将状态报告为“no data available”。

基本选项

要创建新的正常运行时间检查,您需要为正常运行时间检查的配置指定值。在 Stackdriver Monitoring 控制台中创建正常运行时间检查时,您需要填写表单。在 API 中创建正常运行时间检查时,您需要为 UptimeCheckConfig 对象提供相应的参数。

  1. Title:用于标识您的检查的名称。例如:Example.com uptime check

  2. Check Type:选择 HTTPHTTPSTCP 协议。

    如果选择 HTTPS,则服务会尝试通过 HTTPS 进行连接,但不验证 SSL 证书。例如,已过期证书或自签名证书不会导致检查失败。

  3. Resource type:选择以下资源类型之一。

    • App Engine:App Engine 应用(模块)。
    • Elastic Load Balancer:AWS 负载平衡器。
    • Instance:Compute Engine 或 AWS EC2 实例。在 API 中,此资源类型分为 gce_instanceaws_ec2_instance
    • URL:任何 IPv4 地址或主机名。路径和端口分开输入。
  4. 根据您的检查类型 (Check Type) 和资源类型 (Resource type) 填写连接信息:

    • Applies to(App Engine、ELB 或 Instance):您可以将正常运行时间检查应用于单个资源或一组资源,如 All instances。如果您选择单个资源,请从菜单中列出的现有资源中选择一个。如果使用 API,请填写受监控的资源和所需的资源标签,如受监控资源列表中所述。

    • Module (App Engine):指定您的应用模块。

    • Hostname(除 App Engine 以外的所有类型):指定您的服务的主机名。例如,输入 example.com

    • Path(HTTP、HTTPS):输入您主机或资源中的路径,或者使用默认路径。例如,要探测 example.com,请将此字段留空。要探测 example.com/tester,请输入 /tester。请勿包含前缀 example.com。在 API 中,将此字段留空以使用默认值 /

    • Port(HTTP、HTTPS、TCP):选择连接端口。

      • 对于 HTTP 和 HTTPS 检查,此选项位于 Advanced Options 下方。
      • 在 API 中,将此字段留空以使用默认值:80(用于 TCP 或 HTTP 检查)或 443(用于 HTTPS 检查)。
    • Response content contains the text(HTTP、HTTPS、TCP):输入一个字符串(最多 1024 个字节);如果检查响应中存在该字符串,则表明检查成功。如果该字符串未出现在响应中的任何位置,则表明检查将失败。

      • 对于 HTTP 和 HTTPS 检查,此字段显示在 Advanced Options 下方。
      • 在 API 中,这是 ContentMatcher 对象。
  5. Check every:每 151015 分钟检查一次。例如,如果选择 5 分钟,则每个地理位置每 5 分钟尝试连接一次您的服务。如果使用默认的 6 个位置,并且每 5 分钟检查一次,则您的服务平均每分钟看到 1.2 个请求。如果每 1 分钟检查一次,则您的服务平均每分钟看到 6 个请求。

高级选项

Advanced options(高级选项)部分适用于 HTTP、HTTPS 和 TCP 检查类型。

对于 HTTP 和 HTTPS,正常运行时间检查会发出 GET 命令并检索原始数据。如果 GET 响应重定向到另一个网址,则检查将从该网址检索数据。最后,正常运行时间检查会评估数据,以确定检查是成功还是失败。

要确保检查成功,必须满足以下两个条件:

  1. HTTP 状态为 Success
  2. 数据不包含所需内容,或者所需内容已存在。所需内容通过 Advanced options 来指定。

这些设置为可选设置,且因检查类型而异:

  • HTTP Host Header:填写此字段以检查虚拟主机。此字段不适用于 TCP 检查。

  • Port:指定端口号。对于 TCP 检查,此字段显示在 Basic Options 中。

  • Response content contains the text:输入一个字符串(最多 1024 个字节);如果检查响应中存在该字符串,则表明检查成功。对于 TCP 检查,此字段显示在 Basic Options 下方。

  • Locations:选择适用的地理区域,让您的检查可以接收请求。您需要选择足够多的区域,以确保至少有三个活跃位置。创建检查时,每个区域中的位置会列在相应区域名称的下方。所选区域中的新检查工具位置会自动将请求发送到已配置的目的地。要始终从所有可用位置发送请求,请选择 Global。要从现有区域中的所有位置发送请求,而不是从新区域中的新位置发送请求,请选择所有现有区域,但不要选择 Global

  • Custom Headers:提供自定义标头,并在必要时对其进行加密。加密后表单中标头的值会被隐藏。如果您不希望团队中的其他成员看到与身份验证相关的标头,请使用加密。此字段不适用于 TCP 检查。

  • Healthcheck Timeout:指定超时,范围从 160 秒。如果来自多个位置的运行状况检查未在配置的超时期限内获得响应,则正常运行时间检查会失败。如果只有一项运行状况检查没有获得响应,则正常运行时间检查不会失败。

  • Authentication:提供一个用户名和密码。这些值将作为 Authorization 标头发送。如果您在此处设置了值,请不要另外再设置 Authorization 标头;如果您设置了 Authorization 标头,则不要在此处设置值。密码将始终隐藏在表单中。此字段不适用于 TCP 检查。

正常运行时间检查的标识符

创建正常运行时间检查后,Stackdriver 会为其分配一个称为“正常运行时间检查 ID”标识符。此标识符可嵌入新正常运行时间检查的资源名称中:

projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]

您可以调用创建或列出正常运行时间检查的方法,然后从其响应中获取正常运行时间检查 ID。此外,您也可以通过 Stackdriver Monitoring 控制台的正常运行时间检查页面,在 Check config 面板的 Check ID 字段中找到正常运行时间检查 ID。

验证正常运行时间检查

在 Stackdriver Monitoring 控制台中创建正常运行时间检查时,您可以在保存配置之前先测试配置。

检查成功

如果以下两个条件均成立,则正常运行时间检查会成功:

  • HTTP 状态为 Success
  • 响应不包含所需内容,或者在响应中成功搜索到所需内容。

检查失败

以下是导致正常运行时间检查失败的原因:

  • Connection Error - Refused:如果您正在使用默认的 HTTP 连接类型,请检查您是否安装了可响应 HTTP 请求的网络服务器。如果您尚未安装网络服务器,则可能会在新实例上发生这种情况;请参阅 Compute Engine 快速入门。如果您使用的是 HTTPS 连接类型,您可能需要执行额外的配置步骤。如需了解防火墙问题,请参阅获取 IP 地址
  • Name or service not found:主机名可能不正确。
  • 403 Forbidden:服务向正常运行时间检查工具返回错误代码。例如,在 Amazon Linux 中,默认的 Apache 网络服务器配置会返回此代码;但在其他一些 Linux 版本中,该网络服务器配置会返回代码 200 (Success)。请参阅 Amazon Linux 的 LAMP 教程或您网络服务器的文档。
  • 404 Not found:路径可能不正确。
  • 408 Request timeout 或无响应:端口号可能不正确、服务可能未运行、服务可能无法访问或者超时值可能太小。检查您的防火墙是否允许来自正常运行服务器的流量;请参阅获取 IP 地址。超时限值通过 Advanced OptionsHealthcheck 部分指定。

创建提醒政策

要获得正常运行时间故障的通知,请为新的正常运行时间检查创建提醒政策。如需了解详情,请参阅正常运行时间检查提醒

列出正常运行时间检查

要列出您当前的正常运行时间检查,请执行以下操作:

控制台

  1. 要查看正常运行时间检查的列表,请在 Stackdriver Monitoring 控制台中,转到 Uptime Checks > Uptime Checks Overview。您的正常运行时间检查可能会列在多个页面上。

    转到“Uptime Checks Overview”

  2. 要过滤检查列表,请执行以下操作之一:

    • 您可以在 Filter 字段中输入文本,以将列表限制为标题中包含该文本的检查。
    • 使用 Filter 字段左侧的按钮来过滤特定组的成员。

    点击一个正常运行时间检查将显示有关该检查的更多详细信息。

API

要获取正常运行时间配置列表,请调用 projects.uptimeCheckConfigs.list 方法。指定以下参数:

  • parent:您想要列出其正常运行时间检查的项目。格式为:

    projects/[PROJECT_ID]
    

要获取特定的正常运行时间检查,请调用 projects.uptimeCheckConfigs.get 方法。指定以下参数:

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

    projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]
    

    您可以从 createlist 方法的响应中获取 [UPTIME_CHECK_ID]。Stackdriver Monitoring 控制台中不显示该 ID。

C#

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

Java

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

// 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: %v", 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: %v", err)
		}
		fmt.Fprintln(w, config)
	}
	fmt.Fprintln(w, "Done listing uptime checks")
	return nil
}

Node.js

// 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

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;

/**
 * Example:
 * ```
 * list_uptime_checks($projectId);
 * ```
 */
function list_uptime_checks($projectId)
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);

    $pages = $uptimeCheckClient->listUptimeCheckConfigs(
        $uptimeCheckClient->projectName($projectId)
    );

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

Python

def list_uptime_check_configs(project_name):
    client = monitoring_v3.UptimeCheckServiceClient()
    configs = client.list_uptime_check_configs(project_name)

    for config in configs:
        pprint.pprint(config)

Ruby

def list_uptime_check_configs project_id
  require "google/cloud/monitoring/v3"

  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  project_name = Google::Cloud::Monitoring::V3::UptimeCheckServiceClient.project_path project_id
  configs = client.list_uptime_check_configs project_name

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

您也可以检索单个正常运行时间检查:

C#

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

private static void getUptimeCheckConfig(String projectId, String checkName) throws IOException {
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    String fullCheckName = UptimeCheckConfigName.format(projectId, checkName);
    UptimeCheckConfig config = client.getUptimeCheckConfig(fullCheckName);
    if (config != null) {
      System.out.println(config.toString());
    } else {
      System.out.println(
          "No uptime check config found with name " + checkName + " in project " + projectId);
    }
  } catch (Exception e) {
    usage("Exception getting uptime check: " + e.toString());
    throw e;
  }
}

Go

// 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: %v", err)
	}
	defer client.Close()
	req := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %v", err)
	}
	fmt.Fprintf(w, "Config: %v", config)
	return config, nil
}

Node.js

// 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.uptimeCheckConfigPath(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

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;

/**
 * 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,
    ]);

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

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

Python

def get_uptime_check_config(config_name):
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(config_name)
    pprint.pprint(config)

Ruby

def get_uptime_check_config config_name
  require "google/cloud/monitoring/v3"

  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  config = client.get_uptime_check_config config_name
  pp config.to_hash
  config
end

修改正常运行时间检查

要修改正常运行时间检查,请执行以下操作:

控制台

  1. 在 Stackdriver Monitoring 控制台中,转到 Uptime Checks > Uptime Checks Overview。您的正常运行时间检查可能会列在多个页面上。

    转到“Uptime Checks Overview”

  2. Uptime Checks Overview 中,点击正常运行时间检查的摘要右侧的 Edit

  3. 根据需要更改字段的值。您无法修改所有字段。如果检查的自定义标头值处于隐藏状态,您就无法显示这些值。

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

  5. 点击 Save

API

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

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

    projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]
    

    您可以从 createlist 方法的响应中获取 [UPTIME_CHECK_ID]。Stackdriver Monitoring 控制台中不显示该 ID。

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

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

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

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

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

C#

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

private static void updateUptimeCheck(
    String projectId, String displayName, String hostName, String pathName) throws IOException {
  String fullCheckName = UptimeCheckConfigName.format(projectId, displayName);

  UpdateUptimeCheckConfigRequest request = UpdateUptimeCheckConfigRequest
      .newBuilder()
      .setUpdateMask(FieldMask
          .newBuilder()
          .addPaths("http_check.path"))
      .setUptimeCheckConfig(UptimeCheckConfig
          .newBuilder()
          .setName(fullCheckName)
          .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

// 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: %v", err)
	}
	defer client.Close()
	getReq := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, getReq)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Successfully updated %v", resourceName)
	return config, nil
}

Node.js

// 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.uptimeCheckConfigPath(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

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;
use Google\Protobuf\FieldMask;

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

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

    $uptimeCheckClient->updateUptimeCheckConfig($uptimeCheck, $fieldMask);

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

Python

def update_uptime_check_config(config_name, new_display_name=None,
                               new_http_check_path=None):
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(config_name)
    field_mask = monitoring_v3.types.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
    client.update_uptime_check_config(config, field_mask)

Ruby

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

  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  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 config, update_mask: field_mask
end

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

删除正常运行时间检查

在删除正常运行时间检查之前,请从使用该检查的所有提醒策略中移除该检查。如果您不移除正常运行时间检查,则无法通过 Monitoring 控制台删除该正常运行时间检查。如果您通过 API 删除正常运行时间检查,则提醒政策会忽略缺失的正常运行时间检查,而不会为缺失的检查创建事件。

要删除正常运行时间检查,请执行以下操作:

控制台

  1. 在 Stackdriver Monitoring 控制台中,转到 Uptime Checks > Uptime Checks Overview

    转到“Uptime Checks Overview”

  2. Uptime Checks Overview 中,在正常运行时间检查的右侧,点击 Delete

API

调用 projects.uptimeCheckConfigs.delete 方法。填写参数,如下所示:

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

    projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]
    

    您可以从 createlist 方法的响应中获取 [UPTIME_CHECK_ID]。Stackdriver Monitoring 控制台中不显示该 ID。

C#

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

Java

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

Go

// 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: %v", err)
	}
	defer client.Close()
	req := &monitoringpb.DeleteUptimeCheckConfigRequest{
		Name: resourceName,
	}
	if err := client.DeleteUptimeCheckConfig(ctx, req); err != nil {
		return fmt.Errorf("DeleteUptimeCheckConfig: %v", err)
	}
	fmt.Fprintf(w, "Successfully deleted %q", resourceName)
	return nil
}

Node.js

// 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.uptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

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

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

PHP

use Google\Cloud\Monitoring\V3\UptimeCheckServiceClient;

/**
 * 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,
    ]);

    $uptimeCheckClient->deleteUptimeCheckConfig($configName);

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

Python

def delete_uptime_check_config(config_name):
    client = monitoring_v3.UptimeCheckServiceClient()
    client.delete_uptime_check_config(config_name)
    print('Deleted ', config_name)

Ruby

def delete_uptime_check_config config_name
  require "google/cloud/monitoring/v3"

  client = Google::Cloud::Monitoring::V3::UptimeCheck.new
  client.delete_uptime_check_config config_name
  puts "Deleted #{config_name}"
end