创建公开拨测

本文档介绍了如何创建公开拨测。公开拨测可以从全球多个位置向可公开访问的网址或资源发出请求,以查看资源是否响应。 Google Cloud 如需了解如何为专用网络创建拨测,请参阅创建非公开拨测

公开拨测可以确定以下受监控的资源的可用性:

如需查看有关管理和监控拨测的信息链接,请参阅本文档的后续步骤部分。

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

正常运行时间检查简介

对于 HTTP 和 HTTPS,将遵循所有网址重定向,并使用拨测收到的最终响应来评估任何成功标准。对于 HTTPS 检查,SSL 证书过期时间根据最终响应中收到的服务器证书计算。

正常运行时间检查必须满足以下条件才能成功:

  • HTTP 状态必须与您指定的条件一致。
  • 响应数据不包含所需内容,或者所需内容已存在。

正常运行时间检查不会加载页面资源或运行 JavaScript,并且正常运行时间检查的默认配置不包含身份验证。

准备工作

在将存储正常运行时间检查的 Google Cloud 项目中,完成以下步骤:

  1. 如需获得创建正常运行时间检查所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:

    • Monitoring Editor (roles/monitoring.editor) - Google Cloud 控制台用户
    • Monitoring Uptime Check Configurations Editor (roles/monitoring.uptimeCheckConfigEditor) - API 用户
    • Monitoring AlertPolicy Editor (roles/monitoring.alertPolicyEditor) - API 用户
    • Monitoring NotificationChannel Editor (roles/monitoring.notificationChannelEditor) - API 用户

    如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

  2. 请验证您要检查的资源是否具有公共端点,或者是否位于可配置的防火墙后面。

    对于所有其他配置,您必须创建非公开拨测。如需了解详情,请参阅创建非公开拨测

  3. 如果您的资源位于防火墙后面,请将该防火墙配置为允许来自正常运行时间检查服务器 IP 地址的传入流量。如需了解详情,请参阅列出拨测服务器 IP 地址

  4. 配置您要用于接收通知的通知渠道。我们建议您创建多种类型的通知渠道。如需了解详情,请参阅创建和管理通知渠道

  5. 为正常运行时间检查指定至少三个检查工具。 拨测区域 USA 包含 USA_OREGONUSA_IOWAUSA_VIRGINIA 区域。每个 USA_* 区域都有一个检查工具,USA 包含所有三个检查工具。其他拨测区域 EUROPESOUTH_AMERICAASIA_PACIFIC 各有一个拨测工具。

    如果您在使用 Google Cloud 控制台时选择全球,或者在使用 API 时选择 REGION_UNSPECIFIED,则系统会从所有拨测区域发出拨测。

  6. 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.

    Terraform

    如需在本地开发环境中使用本页面上的 Terraform 示例,请安装并初始化 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

    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 时进行身份验证

创建拨测

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

如需为配置了至少一个 TCP 或 HTTP/s 端口的外部负载平衡器创建正常运行时间检查,您可以按照以下说明操作。另一种方法是前往相应服务的服务详情页面,然后点击创建正常运行时间检查。如果您从服务详情页面开始,系统会预先填充服务专用字段。

控制台

如需使用 Google Cloud 控制台创建正常运行时间检查,请执行以下操作:

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

    前往拨测

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

  2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
  3. 点击创建拨测

    创建正常运行时间检查对话框。

  4. 指定正常运行时间检查的目标:

    1. 选择协议。您可以选择 HTTPHTTPSTCP

    2. 选择以下资源类型之一:

      • 网址:任何 IPv4 地址或主机名。路径和端口分开输入。
      • Kubernetes LoadBalancer Service:LoadBalancer 类型的 Kubernetes Service。
      • Instance:Compute Engine 或 AWS EC2 实例。
      • App Engine:App Engine 应用(模块)。
      • Elastic Load Balancer:AWS 负载平衡器。
    3. 输入特定于协议的字段:

      • 对于 TCP 检查,请输入端口。

      • 对于 HTTP 和 HTTPS 检查,您可以在主机或资源中输入路径。使用这些协议的所有正常运行时间检查都会向 http://target/path 发送请求。在此表达式中,对于网址资源,target 是主机名或 IP 地址。对于 App Engine 资源,target 是派生自服务名称的主机名。对于实例和负载平衡器资源,target 是根据您为资源或资源组提供的名称派生的 IP 地址。

        如果您将 path 字段留空或将值设置为 /,则将向 http://target/ 发出请求。

        例如,如需向网址资源 example.com/tester 发出正常运行时间检查,请将主机名字段设置为 example.com,将路径字段设置为 /tester

        假设您已使用支持 //hello 的调度程序将服务器部署到 App Engine。如需向“/”处理程序发出正常运行时间检查,请将路径字段留空。如需向 /hello 处理程序发出正常运行时间检查,请将路径字段的值设置为 /hello

    4. 输入特定于资源的字段:

      • 对于网址资源,请在主机名字段中输入主机名。例如,输入 example.com

      • 对于 App Engine 资源,请在服务字段中输入服务名称。

      • 对于 Elastic Load Balancer实例资源,请按如下所示填写应用于字段:

        • 如需向单个实例或负载平衡器发出正常运行时间检查,请选择单个,然后使用菜单选择特定实例或负载平衡器。
        • 如需向 Monitoring 组发出正常运行时间检查,请选择,然后使用菜单选择组名称。
    5. 可选:如需设置正常运行时间检查的执行频率,请使用检查频率字段。

    6. 可选:如需选择检查工具区域,或为 HTTP 和 HTTPS 检查配置 SSL 证书、身份验证、标头和端口,请点击更多目标选项

      • 区域:选择正常运行时间检查将从中接收请求的区域。正常运行时间检查必须至少有 3 个检查工具。除美国有 3 个拨测工具外,其他所有区域都只有 1 个拨测工具。默认设置全球包括所有区域。
      • ICMP Ping:配置正常运行时间检查以发送最多三次 Ping。如需了解详情,请参阅使用 ICMP ping
      • 请求方法:对于 HTTP 检查,请选择请求方法。
      • 正文:对于 HTTP POST 检查,请输入网址编码正文;您必须自行进行编码。对于其他所有检查,请将此字段留空。
      • 主机标头:填写此字段以检查虚拟主机。此字段不适用于 TCP 检查。
      • Port:指定端口号。
      • 自定义标头:提供自定义标头,并根据需要对其进行加密。加密后表单中标头的值会被隐藏。对您不想向他人显示的身份验证相关标头使用加密。
      • 身份验证:这些值将作为 Authorization 标头发送。此字段不适用于 TCP 检查。

        根据需要选择下列其中一项:

        • 基本身份验证:提供单个用户名和密码。密码将始终隐藏在表单中。
        • 服务代理身份验证:启用后,系统会为监控服务代理生成身份令牌。此选项仅适用于 HTTPS 检查。
      • SSL 证书验证:如果您为网址资源选择了 HTTPS,则默认情况下,服务会尝试通过 HTTPS 连接并验证 SSL 证书。如果网址的证书无效,则正常运行时间检查会失败。导致证书无效的原因包括:

        • 证书过期
        • 自签名证书
        • 证书域名不匹配
        • 使用授权信息访问 (AIA) 扩展的证书。

        若要强制执行 HTTPS 正常运行时间检查以验证 SSL 证书,请选择验证 SSL 证书

        如需停用 SSL 证书验证,请清除验证 SSL 证书

        如果您拥有带 AIA 扩展程序的 SSL 证书,则必须停用 SSL 证书验证。这些类型的证书不受支持,且不会通过验证序列。通常,错误消息为“在 10000 毫秒内以 SSL 握手错误响应”。

        您可以使用指标 monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires 创建在证书到期前向您发送通知的提醒政策。如需了解详情,请参阅示例政策:正常运行时间检查政策

        选中验证 SSL 证书复选框。

  5. 点击继续,然后配置响应要求。 本部分中的所有设置均采用默认值:

    • 如需更改正常运行时间检查的超时期限,请使用响应超时字段。如果在此期限内未收到多个位置的响应,则正常运行时间检查会失败。

    • 如需配置拨测以执行内容匹配,请确保切换标签为已启用内容匹配功能

      • 从选项菜单中选择响应内容匹配类型。此字段用于确定如何将响应内容与返回的数据进行比较。例如,假设响应内容为 abcd 且内容匹配类型为包含。只有在响应数据包含 abcd 时,正常运行时间检查才会成功。如需了解详情,请参阅验证响应数据
      • 输入响应内容。响应内容必须是长度不超过 1024 个字节的字符串。在 API 中,此字段是 ContentMatcher 对象。
    • 为了防止由于拨测而创建日志条目,请清除日志检查失败

    • 对于 HTTP 正常运行时间检查,请配置可接受的响应代码。默认情况下,HTTP 正常运行时间检查会将任何 2xx 响应标记为成功响应。

  6. 点击继续,然后配置通知。

    如需在正常运行时间检查失败时收到通知,请创建提醒政策并为该政策配置通知渠道

    1. 可选:更新提醒政策的名称。
    2. 可选:在时长字段中,选择正常运行时间检查必须失败多长时间才发送通知。默认情况下,当至少两个区域报告正常运行时间检查失败的时长达到 1 分钟时,系统会发送通知。
    3. 通知渠道标签的框中,点击 Menu(菜单),选择要添加的渠道,然后点击 OK(确定)。

      在菜单中,系统会针对每种渠道类型按字母顺序将通知渠道分组。

    如果您不想创建提醒政策,请确保切换按钮对应的文本为不创建提醒

  7. 点击继续,然后完成正常运行情况检查:

    1. 为正常运行时间检查输入一个描述性标题。

    2. 可选:如需向正常运行时间检查添加用户定义的标签,请执行以下操作:

      1. 点击 显示用户标签
      2. Key 字段中,输入标签的名称。 标签名称必须以小写字母开头,可以包含小写字母、数字、下划线和短划线。例如,输入 severity
      3. 字段中,输入标签的值。标签值可以包含小写字母、数字、下划线和短划线。例如,输入 critical
      4. 对于每个其他标签,请点击添加用户标签,然后输入标签的键和值。
    3. 要验证您的正常运行时间检查配置,请点击测试。 如果结果与您的预期不符,请参阅检查失败,更正您的配置,然后重复验证步骤。

    4. 点击创建。如果您选择创建,但未填充必填字段,系统会显示错误消息。

gcloud

如需创建正常运行时间检查,请运行 gcloud monitoring uptime create 命令:

gcloud monitoring uptime create DISPLAY_NAME REQUIRED_FLAGS OPTIONAL_FLAGS --project=PROJECT_ID

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

  • PROJECT_ID:项目的标识符。

  • DISPLAY_NAME:您的正常运行时间检查的名称。

  • REQUIRED_FLAGS:配置以指定由正常运行时间检查探测的资源。例如,以下命令会创建一个正常运行时间检查,用于测试特定项目的网址 EXAMPLE.com

    gcloud monitoring uptime create DISPLAY_NAME \
    --resource-labels=host=EXAMPLE.com,project_id=PROJECT_ID \
    --resource-type=uptime-url
    

    上一个命令为资源类型 uptime-url 所需的每个标签指定了值。

  • OPTIONAL_FLAGS:配置这些标志以替换默认值。例如,如果协议不是 http,您必须设置 --protocol 标志。

Terraform

如需了解如何应用或移除 Terraform 配置,请参阅基本 Terraform 命令。 如需了解详情,请参阅 Terraform 提供程序参考文档

如需创建正常运行时间检查以及用于监控该检查的提醒政策,请执行以下操作:

  1. 为您的项目安装并配置 Terraform
  2. 修改 Terraform 配置文件并添加 google_monitoring_uptime_check_config 资源,然后应用该配置文件。

    以下示例展示了用于检查公开网址的配置:

    resource "google_monitoring_uptime_check_config" "example" {
        display_name = "example"
        timeout      = "60s"
    
        http_check {
            port = "80"
            request_method = "GET"
        }
    
        monitored_resource {
            type = "uptime_url"
            labels = {
                project_id = "PROJECT_ID"
                host="EXAMPLE.com"
            }
        }
    
        checker_type = "STATIC_IP_CHECKERS"
    }
    

    在上面的表达式中:

    • PROJECT_ID 是您的项目 ID。
    • EXAMPLE.com 是主机网址。
  3. 可选:创建通知渠道和提醒政策:

    以下步骤使用 Google Cloud 控制台创建通知渠道和提醒政策。这种方法可确保提醒政策仅监控正常运行时间检查生成的数据。

    1. 如需创建通知渠道,请执行以下操作:

      1. 在 Google Cloud 控制台中,转到 提醒页面:

        进入提醒

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

      2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
      3. 选择管理通知渠道
      4. 前往您要添加的渠道类型,点击添加,然后完成对话框。
    2. 如需创建提醒政策,请执行以下操作:

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

        前往拨测

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

      2. 在 Google Cloud 控制台的工具栏中,选择您的 Google Cloud 项目。
      3. 找到您的正常运行时间检查,选择 更多,然后选择添加提醒政策
      4. 在对话框中,前往通知和名称部分,展开通知渠道,然后进行选择。
      5. 为提醒政策命名,然后点击创建政策

    您可以通过向配置文件添加 google_monitoring_alert_policy 资源并应用新配置来创建提醒政策。

C#

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

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();
    ProjectName projectName = new ProjectName(projectId);
    // Create the config.
    var newConfig = client.CreateUptimeCheckConfig(
        projectName,
        config,
        CallSettings.FromExpiration(
            Expiration.FromTimeout(
                TimeSpan.FromMinutes(2))));
    Console.WriteLine(newConfig.Name);
    return 0;
}

Java

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

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.getName());
  } catch (Exception e) {
    usage("Exception creating uptime check: " + e.toString());
    throw e;
  }
}

Go

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


// createGet creates an example uptime check on a GET request.
func createGet(w io.Writer, projectID 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.CreateUptimeCheckConfigRequest{
		Parent: "projects/" + projectID,
		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
			DisplayName: "new GET 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{
					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_GET,
					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 GET: %w", err)
	}
	fmt.Fprintf(w, "Successfully created GET uptime check %q\n", config.GetDisplayName())
	return config, nil
}

// createPost creates an example uptime check on a POST request.
func createPost(w io.Writer, projectID 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.CreateUptimeCheckConfigRequest{
		Parent: "projects/" + projectID,
		UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{
			DisplayName: "new POST 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{
					RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_POST,
					ContentType:   monitoringpb.UptimeCheckConfig_HttpCheck_URL_ENCODED,
					Path:          "/",
					Port:          80,
					Body:          []byte(base64.URLEncoding.EncodeToString([]byte("key: value"))),
				},
			},
			Timeout: &duration.Duration{Seconds: 10},
			Period:  &duration.Duration{Seconds: 300},
		},
	}
	config, err := client.CreateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateUptimeCheckConfig POST: %w", err)
	}
	fmt.Fprintf(w, "Successfully created POST uptime check %q\n", config.GetDisplayName())
	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 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

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

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

/**
 * 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')
{
    $projectName = 'projects/' . $projectId;
    $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);
    $createUptimeCheckConfigRequest = (new CreateUptimeCheckConfigRequest())
        ->setParent($projectName)
        ->setUptimeCheckConfig($uptimeCheckConfig);

    $uptimeCheckConfig = $uptimeCheckClient->createUptimeCheckConfig($createUptimeCheckConfigRequest);

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

Python

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

def create_uptime_check_config_get(
    project_id: str, host_name: str = None, display_name: str = None
) -> uptime.UptimeCheckConfig:
    """Creates a new uptime check configuration

    Args:
        project_id: Google Cloud project id where the uptime check is created
        host_name: An example label's value for the "host" label
        display_name: A human friendly name of the configuration

    Returns:
        A structure that describes a new created uptime check
    """
    config = monitoring_v3.UptimeCheckConfig()
    config.display_name = display_name or "New GET uptime check"
    config.monitored_resource = {
        "type": "uptime_url",
        "labels": {"host": host_name or "example.com"},
    }
    config.http_check = {
        "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.GET,
        "path": "/",
        "port": 80,
    }
    config.timeout = {"seconds": 10}
    config.period = {"seconds": 300}

    client = monitoring_v3.UptimeCheckServiceClient()
    new_config = client.create_uptime_check_config(
        request={"parent": project_id, "uptime_check_config": config}
    )
    pprint.pprint(new_config)
    return new_config


def create_uptime_check_config_post(
    project_id: str, host_name: str = None, display_name: str = None
) -> uptime.UptimeCheckConfig:
    """Creates a new uptime check configuration

    Args:
        project_id: Google Cloud project id where the uptime check is created
        host_name: An example label's value for the "host" label
        display_name: A human friendly name of the configuration

    Returns:
        A structure that describes a new created uptime check
    """
    config = monitoring_v3.UptimeCheckConfig()
    config.display_name = display_name or "New POST uptime check"
    config.monitored_resource = {
        "type": "uptime_url",
        "labels": {"host": host_name or "example.com"},
    }
    config.http_check = {
        "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.POST,
        "content_type": monitoring_v3.UptimeCheckConfig.HttpCheck.ContentType.URL_ENCODED,
        "body": "foo=bar".encode("utf-8"),
        "path": "/",
        "port": 80,
    }
    config.timeout = {"seconds": 10}
    config.period = {"seconds": 300}

    client = monitoring_v3.UptimeCheckServiceClient()
    new_config = client.create_uptime_check_config(
        request={"parent": project_id, "uptime_check_config": config}
    )
    pprint.pprint(new_config)
    return new_config

Ruby

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

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

  client = Google::Cloud::Monitoring.uptime_check_service
  project_name = client.project_path project: 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 }
  }
  new_config = client.create_uptime_check_config \
    parent:              project_name,
    uptime_check_config: config
  puts new_config.name
  new_config
end

REST

如需创建正常运行时间检查,请调用 projects.uptimeCheckConfigs.create 方法。设置该方法的参数,如下所示:

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

    projects/PROJECT_ID
    
  • 请求正文必须包含新正常运行时间检查的 UptimeCheckConfig 对象。本页介绍了几个字段。如需查看有关此对象及其字段的完整文档,请参阅 UptimeCheckConfig

    • 将配置对象的 name 字段留空。系统会在构造响应配置对象时设置此字段。

    • 如果要配置 HTTP 或 HTTPS 检查,则必须填充 UptimeCheckConfig 对象的 HttpCheck 字段。在此对象中,将 requestMethod 字段设置为 GETPOST。如果省略此字段或将其设置为 METHOD_UNSPECIFIED,则发出 GET 请求。

      如果您要配置 POST 请求,则填写 contentType、可选的 customContentTypebody 字段。

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

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

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

使用 ICMP ping

为帮助您排查公开正常运行时间检查失败的问题,您可以将正常运行时间检查配置为在检查期间发送最多 3 次 ICMP ping。这些 ping 有助于您区分由网络连接问题和应用超时等原因导致的失败。

默认情况下,正常运行时间检查不会发送 ping。每次 ping 都会增加正常运行时间检查的延迟时间。非公开拨测无法发送 ping。

公开正常运行时间检查失败时,系统会将 ping 结果写入 Cloud Logging 日志。如果 ping 失败,系统会将以下字段添加到日志条目的 httpRequest 字段中:

  • rtt_usec:每个未成功的 ping 请求的往返时间。
  • unreachable_count:返回状态代码 ICMP_DEST_UNREACH 的 ping 请求数量。
  • no_answer_count:超时且未返回任何响应的 ping 请求数。

成功的正常运行时间检查的 Ping 结果不会记录。

配置 ping

每个正常运行时间检查配置都包含 HttpCheck 对象或 TcpCheck 对象。这两个对象都包含 pingConfig 字段。使用此字段指定每次检查要包含的 ICMP ping 数量(最多 3 次)。默认情况下,系统不会发送任何 ping。

如需配置 ping,请执行以下任一操作:

验证正常运行时间检查

在 Google Cloud 控制台中创建正常运行时间检查时,您可以先测试配置,然后再保存。

成功的检查

如果满足以下条件,则正常运行时间检查会成功:

  • HTTP 状态与您选择的条件相符。
  • 响应不包含所需内容,或者在响应中成功搜索到所需内容。

失败的检查

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

  • 连接错误 - 拒绝 (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 地址。超时限制是响应验证选项的一部分。

    由于网络拥塞,可能会发生请求超时。例如,由于临时网络拥塞,您可能会发现一个检查器失败,但所有其他检查器都成功。如果提醒政策使用默认配置,单个检查器的失败不会导致系统发送通知。

如果您的正常运行时间检查已配置为发送 ping,则失败的正常运行时间检查的 ping 结果会写入 Cloud Logging。如需了解详情,请参阅使用 ICMP ping

后续步骤