Managing uptime checks

An uptime check is a request sent to a resource to see if it responds. You can use uptime checks to determine the availability of a VM instance, an App Engine service, a URL, or an AWS load balancer.

You can monitor the availability of a resource by creating an alerting policy that creates an incident if the uptime check fails. The alerting policy can be configured to notify you by email or through a different channel, and that notification can include details about the resource that failed to respond. You also have the option to observe the results of uptime checks in the Monitoring uptime-check dashboards.

This page shows you how to do the following:

  • Create a new uptime check.
  • View the dashboard for an uptime check.
  • Edit an uptime check.
  • Delete an uptime check.

See the What's next section for links to pricing pages and to pages that describe monitoring your uptime checks.

Before you begin

  1. Your use of uptime checks is affected by any firewalls protecting your service.

    • If the resource you are checking isn't publicly available, you must configure the resource's firewall to permit incoming traffic from the uptime-check servers. See Getting IP addresses to download a list of the IP addresses.
    • If the resource you are checking doesn't have an external IP address, uptime checks are unable to reach it.
  2. The uptime check doesn't load page assets or run JavaScript, and the default configuration of an uptime check doesn't include authentication.

    For HTTP and HTTPS, if the response is a redirection to another URL, the check retrieves the data from that URL. Lastly, the uptime check evaluates the data to determine if the check succeeded or failed.

    To succeed, these conditions must be met:

    • The HTTP status is Success.
    • The data has no required content or the required content is present.

Creating an uptime check

This section explains how to create and configure uptime checks.

Using the API

API

Call the projects.uptimeCheckConfigs.create method. Set the method's parameters as follows:

  • parent: Required. This must be the name of the project in which to create the uptime check. Replace [PROJECT_ID] with your Google Cloud project ID. The format is:

    projects/[PROJECT_ID]
    
  • The request body must contain an UptimeCheckConfig object for the new uptime check. This page provides information on only a few fields. For complete documentation on this object and its fields, see UptimeCheckConfig:

    • Leave the name field of the configuration obejct blank. The system sets this field when it constructs the response configuration object.

    • If you are configuring an HTTP or HTTPS check, then you must populate the HttpCheck field of the UptimeCheckConfig object. In this object, set the requestMethod field as GET or POST. If this field is omitted or set to METHOD_UNSPECIFIED, then a GET request is issued.

      If you are configuring a POST request, then complete the contentType and body fields.

The create method returns the UptimeCheckConfig object for the new configuration.

If the created uptime configuration doesn't work as expected, see the Check failures section on this page.

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();
    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

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.request_method = monitoring_v3.enums.UptimeCheckConfig.HttpCheck.RequestMethod.GET
    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"

  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

There can be a delay of up to 5 minutes before the uptime check results start to flow into Monitoring. During that time, the uptime check dashboard reports the status as "no data available."

Using the Cloud Console

The process of creating an uptime check using the Cloud Console is being updated. This section describes how to create an uptime check using the new flow and the classic flow. The first few steps of both flows are identical. You can tell if you are using the new flow or the classic flow, by the Create uptime check form.

New flow

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. Click Create Uptime check.

  4. If the Create uptime check window looks like the following screenshot, then continue with these instructions; otherwise, click the Classic flow tab on this table and continue with those instructions:

    Create an uptime check dialog.

  5. Enter a descriptive title for the Uptime check and then click Next.

  6. Specify the target of the uptime check:

    1. Select the protocol. You have the options of HTTP, HTTPS, and TCP.

    2. Choose one of the following resource types:

      • URL: Any IPv4 address or hostname. Path and port are entered separately.
      • App Engine: App Engine applications (modules).
      • Instance: Compute Engine or AWS EC2 instances.
      • Elastic Load Balancer: AWS load balancer.
    3. Enter the protocol-specific fields:

      • For TCP checks, enter the port.

      • For HTTP and HTTPS checks, you have the option to enter a path within your host or resource. All uptime checks that use these protocols send a request to http://target/path. In this expression, for a URL resource, target is a hostname or IP address. For an App Engine resource, target is a hostname derived from the service name. For instance and load balancer resources, target is an IP address derived from the name you provided for the resource or the group of resources.

        If you leave the path field blank or if you set the value to /, then the request is issued to http://target/.

        To issue an uptime check to the URL resource example.com/tester, set the hostname field to example.com and the path field to /tester.

        Suppose you've deployed a server to App Engine with a dispatcher that supports / and /hello. If you leave the path field empty, then the uptime check is sent to the / handler. To issue the uptime check to the /hello handler, set the value of the path field to /hello.

    4. Enter the resource-specific fields:

      • For URL resources, enter the host name in the Hostname field. For example, enter example.com.

      • For App Engine resources, enter the service name in the Service field.

      • For Elastic Load Balancer and Instance resources, complete the following fields:

        • To issue an uptime check to a single instance or load balancer, in the Applies to field, select Single and then use the menu to select the specific instance or load balancer.
        • To issue an uptime check to a Monitoring group, in the Applies to field, select Group, and then use the menu to select the group name.
    5. The field Check frequency controls how often the uptime check executes. You can leave at the default value or select a value from the menu of options.

    6. To configure checker regions, or to configure SSL certificates, authentication, headers, and ports for HTTP and HTTPS checks, click More target options:

      • Regions: Select the regions where the uptime checks are to receive requests. An uptime check must have at least 3 checkers. There is 1 checker in all regions except the United States, which has 3 checkers. The default setting, Global includes all regions.
      • General: Fill this field in to check virtual hosts. This field isn't available for TCP checks.
      • Port: Specify a port number.
      • Custom Headers: Supply custom headers, and encrypt them if desired. Encryption hides the headers' values in the form. Use encryption for headers related to authentication that you don't want visible to others.

      • Authentication: Provide a single username and password. These values are sent as an Authorization header. If you set values here, don't set a separate Authorization header; if you set an Authorization header, don't set values here. Passwords are always hidden in the form. This field isn't available for TCP checks.

      • SSL Certificate Validation: If you selected HTTPS for a URL resource, then by default, the service attempts to connect over HTTPS and validates the SSL certificate. The uptime check fails if a URL has an invalid certificate. Reasons for an invalid certificate include an expired certificate, a self-signed certificate, a certificate with a domain-name mistmach, and a certificate that uses the AIA extension.

        To force a HTTPS uptime check to validate the SSL certificate, ensure that Validate SSL certificates is selected.

        To disable SSL certificate validation, ensure that Validate SSL certificates is clear.

        If you have SSL Certificates with Authority Information Access (AIA) Extensions, then you must disable SSL certificate validation. These types of certificates aren't supported and fail the validation sequence. Typically, the error message is "Responded with SSL handshake Error in 10000 ms".

        You can use the metric monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires to create an alert that notifies you before your certificate expires. For more information, see Sample policies: Uptime-check policy.

        Select Validate SSL certificates checkbox.

    7. Click Next.

  7. Complete the Response Validation pane.

    • Select the Response Timeout from the menu of options. You can choose any value between 1 to 60 seconds. An uptime check fails if no response is received from more than one location within this timeout. The uptime check passes if any location responds.
    • For content matching, ensure that the toggle label is Content matching is enabled:

      • Select the Response content match type from the menu of options. This field determines how the response content is compared to the returned data. For example, if the response content is abcd and the content match type is Contains, then the uptime check is successful if the response data contains abcd. The uptime check fails if the response doesn't contain abcd.
      • Enter the Response content. This must be a string no longer than 1024 bytes. In the API, this is the ContentMatcher object.
    • If you don't want uptime checks sent to Cloud Logging, then uncheck Log check failures.

    • Click Next

  8. Complete the Alert & notification pane:

    Create an alerting policy if you want your uptime check monitored for you. If you create an alerting policy, then an incident is created when your uptime check fails and a notification is sent to all notification channels attached to the policy. For example, if you add an email address to the policy, then an email is sent to that address when an incident is created.

    You can create the alerting policy in this step, or you can add the alerting policy after the check is created. The creation of an alerting policy for the uptime check is controlled by a button:

    • If the button text is Do not create an alert, then an alerting policy won't be created and all fields are disabled. If you want to create an alerting policy, click the button.
    • If the button text is Create an alert, then an alerting policy is to be created and all fields are enabled. If you don't want to create an alerting policy, click the button.

    To create an alerting policy as part of this flow, do the following:

    1. Ensure the button text is Create an alert.
    2. In the name field, enter a name for the alerting policy or use the default name.
    3. To add one or more notification channels to the alerting policy, in the text box labeled Notification channels, click Menu . Select the channels to add and click OK. The notifications channels are grouped alphabetically for each channel type.

      If a notification channel that you want to add to the alerting policy isn't listed, click Manage notification channels.

      Notification dialog displaying the refresh and manage channels buttons.

      You are taken to the Notification channels window in a new browser tab. Add the notification channels and then return to this tab, click Refresh , and then select the notification channels to add to the alerting policy.

    4. In the duration field, select how long the uptime checks must fail before an incident is created. By default, the alerting policy is configured to create an incident if at least 2 regions report uptime check failures for a duration of 1 minute.

    See Managing policies for information on disabling, editing, and deleting alerting policies.

  9. To verify your uptime check configuration, click Test. If the result isn't what you expect, see the Check failures section below, correct your configuration, and then repeat the verification step.

  10. Click Create. If required data is missing, the save action fails and a list of fields that require data is displayed next to the dialog buttons. After you save your changes, the Uptime check created dialog is displayed.

Classic flow

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. Click Create Uptime check.

  4. If the Create uptime check window looks like the following screenshot, then continue with these instructions; otherwise, click the New flow tab on this table and continue with those instructions:

    Classic view of the create an uptime check dialog.

  5. In the New uptime check window, fill in the fields for the check, as described in Basic options.

  6. (Optional) Click Show advanced options. For more information on the advanced options, see Advanced options.

  7. To verify your uptime check configuration, click Test. If the result isn't what you expect, see the Check failures section below, correct your configuration, and then repeat the verification step.

  8. Click Save. If required data is missing, the save action fails and a list of fields that require data is displayed next to the dialog buttons. After you save your changes, the Uptime check created dialog is displayed.

  9. (Optional) To be notified of an uptime failure, click Create alert policy. If you don't want to create an alerting policy now, click No, Thanks. You can always create an alerting policy for an uptime check. For more information, see Monitoring uptime checks.

    Uptime check created dialog.

There can be a delay of up to 5 minutes before the uptime check results start to flow into Monitoring. During that time, the uptime check dashboard reports the status as "no data available."

Basic options for the classic interface

This section describes the fields that you use when creating an uptime check when you use the classic interface of the Cloud Console, or when you use the API. When you use the API, you supply the corresponding values in an UptimeCheckConfig object.

  1. Title: A name to identify your check. For example, Example.com uptime check.

  2. Check Type: Select an HTTP, HTTPS, or TCP protocol.

    If you are using the API and the check type is HTTP or HTTPS, you can configure the check to issue a POST request. See the API example above.

    If you select HTTPS, the service attempts to connect over HTTPS and validates the SSL certificate. By default, an expired or self-signed certificate causes the uptime check to fail.

    To disable SSL certificate validation, uncheck Validate SSL Certificates.

  3. Resource type: Choose one of the following resource types:

    • App Engine: App Engine applications (modules).
    • Elastic Load Balancer: AWS load balancer.
    • Instance: Compute Engine or AWS EC2 instances. In the API, this is split into gce_instance and aws_ec2_instance.
    • URL: Any IPv4 address or hostname. Path and port are entered separately.
  4. Enter the protocol-specific fields:

    • For TCP checks, enter the port.

    • For HTTP and HTTPS checks, you have the option to enter a path within your host or resource. All uptime checks that use these protocols send a request to http://target/path. In this expression, for a URL resource, target is a hostname or IP address. For a App Engine resource, target is a hostname derived from the service name. For instance and load balancers, target is an IP address derived from the name you provided for the resource or the group of resources.

      If you leave the path field blank or if you set the value to /, then the HTTP request is issued to http://target/.

      To issue an uptime check to the URL resource example.com/tester, set the hostname field to example.com and the path field to /tester.

      Suppose you've deployed a server to App Engine with a dispatcher that supports / and /hello. If you leave the path field empty, then the uptime check is sent to the / handler. To issue the uptime check to the /hello handler, set the value of the path field to /hello.

  5. Enter the resource-specific fields:

    • If you select a Resource type of URL, then enter the host name. For example, enter example.com.

    • If you select a Resource type of App Engine, then select the service name.

    • If you select a Resource type of Elastic Load Balancer or Instance, then you specify if the uptime check applies to a single resource or to a group of resources. To apply the uptime check to an instance or a load balancer, select Single and then select the specific instance or load balancer. To apply the uptime check to a group of instances, or to a group of load balancers, select Group and then select the group name. If you use the API, fill in the monitored resource with the required resource labels, as described in the Monitored resource list.

  6. Check every: Choose 1, 5, 10, or 15 minutes. This value determines the cadence of uptime checks. For example, if you select 5 minutes, then every 5 minutes each geographic location issues an uptime check.

Advanced options for the classic interface

Click Show advanced options to view all advanced settings. The advanced settings that are available depends on the check type:

  • General: Fill this field in to check virtual hosts. This field isn't available for TCP checks.
  • Port: Specify a port number.
  • Response content match type: Specify how string entered in the response content is compared to the actual returned data. For example, if the response content is abcd and you select a content match type of Contains, then the uptime check is successful if the response data contains abcd. The uptime check fails if the response doesn't contain abcd.
  • Response content: Enter a string (max 1024 bytes). In the API, this is the ContentMatcher object.

  • Locations: Select the applicable geographic regions where your check is to receive requests. The default setting is Global with 6 checkers. You must have at least 3 checkers. There are 3 checkers in the region United States. All other regions have 1 checker.

  • Custom Headers: Supply custom headers, and encrypt them if necessary. Encryption hides the headers' values in the form. Use encryption for headers related to authentication that you don't want other members of your team to see.

  • Healthcheck Timeout: Specify a timeout, from 1 to 60 seconds. An uptime check fails if healthchecks from more than one location don't get a response within the configured timeout period. If only one healthcheck doesn't get a response, then the uptime check doesn't fail.

  • Authentication: Provide a single username and password. These values are sent as an Authorization header. If you set values here, don't set a separate Authorization header; if you set an Authorization header, don't set values here. Passwords are always hidden in the form. This field isn't available for TCP checks.

  • SSL Certificate Validation: Select Validate SSL certificates checkbox. An uptime check fails if a URL has an invalid certificate. Reasons for an invalid certificate include an expired certificate, a certificate with a domain-name mismatch, or a self-signed certificate. SSL certificate validation is only available for HTTPS checks on URL resources.

    SSL certificates that use the Authority Information Access (AIA) Extension aren't supported and fail the validation sequence. Typically, the error message is "Responded with SSL handshake Error in 10000 ms". If you have this type of SSL certificate, ensure that the Validate SSL certificates checkbox is clear.

    You can use the metric monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires to create an alert that notifies you before your certificate expires. See Sample policies: Uptime-check policy.

Identifiers for uptime checks

When your uptime check is created, Monitoring assigns it an identifier, referred to as the uptime-check ID. This identifier is embedded in the resource name for the new uptime check:

projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]

You can get the uptime-check ID from the response of a method invocation to create or list uptime checks. You can also find the uptime-check ID on the Uptime details window under the section titled Configuration.

Verify your uptime check

When you create an uptime check in the Cloud Console, you can test the configuration before saving.

Check success

An uptime check is successful if two conditions are true:

  • The HTTP status is Success.
  • The response has no required content or, a search of the response for the required content is successful.

Check failure

The following are some possible causes of an uptime check failure:

  • Connection Error - Refused: If you are using the default HTTP connection type, check that you have a web server installed that is responding to HTTP requests. This can happen on a new instance if you haven't installed a web server; see the Quickstart for Compute Engine. If you use an HTTPS connection type, you might have to perform additional configuration steps. For firewall issues, see Getting IP addresses.
  • Name or service not found: The host name might be incorrect.
  • 403 Forbidden: The service is returning an error code to the uptime checker. For example, the default Apache web server configuration returns this code under Amazon Linux, but it returns code 200 (Success) under some other Linux versions. See the LAMP tutorial for Amazon Linux or your web server's documentation.
  • 404 Not found: The path might be incorrect.
  • 408 Request timeout, or no response: The port number might be incorrect, the service might not be running, the service might be inaccessible, or the timeout might be too low. Check that your firewall allows traffic from the uptime servers; see Getting IP addresses. The timeout limit is specified in the Healthcheck part of Advanced Options.

Viewing an uptime check

To view an uptime check, do the following:

Console

To view the detailed status of a single uptime check, do the following:

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. To view the Uptime details window, locate the uptime check that you want to view, then click the uptime check name.

    The following screenshot shows the uptime details for an uptime check with the name "My Uptime Check":

    Sample uptime check dashboard.

    The Uptime details window contains the following information:

    • The selected time interval. By default, the interval is 1 hour.
    • The name of the uptime check. In the sample, the name is My Uptime Check.
    • The uptime percentage and the average latency. The Percent uptime value is a percentage calculated as (S/T)*100, where S is the number of successful check responses and T is the total number of check responses, from all locations. For group checks, the values of S and T are summed across all current group members.

      For example, over a 25-minute period, an uptime check with a one-minute period running from all regions would get 25 requests from each of 6 locations, for a total of 150 requests. If the dashboard reports an 83.3% uptime, then 125 of 150 requests succeeded.

    • The Passed checks and Uptime check latency panes graphically display the number of passed checks and latency of each check as a function of time.

    • The Current status pane displays the status of the most recent checks. A green circle with a check next to a region indicates the last run of the check in that region succeeded; a red circle with an x indicates failure.

    • The Configuration pane shows the configuration of the uptime check. This data is assigned when the uptime check is created. The Check Id value corresponds to the [UPTIME_CHECK_ID] value in API calls.

    • The Alert Policies pane lists information about associated alert policies. In the sample dashboard, one alert policy is configured.

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

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"

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

Editing an uptime check

The uptime check protocol, resource type, and the resource being monitored cannot be changed. If you want to modify these fields, you must create an uptime check with the proper configuration. However, all other fields in an uptime check can be modified after the check is created.

To edit an alerting policy that is associated with an uptime check, in the Monitoring navigation pane, click Alerting, select the policy to be edited, and click Edit.

To edit an uptime check, do the following:

Console

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. Locate the uptime check that you want to edit, then do one of the following:

    • Click More and select Edit.
    • View the uptime check details, and then click Edit.
  4. Change the values of the fields as needed. You can't modify all fields. If the custom header values of a check are hidden, you cannot make them viewable.

  5. To verify if the check works, click Test. If the test fails, see Check failures for possible causes.

  6. Click Save.

API

Call the projects.uptimeCheckConfigs.patch method. Set the parameters to the method as follows:

  • uptimeCheckConfig.name: Required. This is part of the REST URL. It is the resource name of the uptime check to edit:

    projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]
    

    You can get the [UPTIME_CHECK_ID] from the response of a create or list method. The ID isn't shown in the Cloud Console.

  • updateMask: Optional. This is a query parameter: ?updateMask=[FIELD_LIST]. [FIELD_LIST] is a comma-separated list of fields in the UptimeCheckConfig object that should be changed. For example:

    "resource.type,httpCheck.path"
    
  • The request body must contain an UptimeCheckConfig with the new field values.

If updateMask is set, then only the fields listed in updateMask replace the corresponding fields in the existing configuration. If a field has subfields, and the field is listed in the field mask but none of its subfields are, then all subfields of that field replace the corresponding fields.

If updateMask isn't set, then the configuration in the request body replaces the entire existing configuration.

The patch method returns the UptimeCheckConfig object for the altered configuration.

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

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"

  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

There can be a delay of up to 5 minutes before you see the new uptime check results. During that time, the results of the former uptime check are displayed in the dashboards and used in alerting policies.

Deleting an uptime check

If you attempt to delete an uptime check by using the Cloud Console, and there exists an alerting policy that depends on the uptime check, the delete operation fails. Retry the delete after you have removed the uptime check from all alerting policies that use the check.

If you attempt to delete an uptime check by using the Cloud Monitoring API, the uptime check is deleted even if there are alerting policies that depend upon the check. No error is generated. No incident is created for the missing check. Before you delete an uptime check, ensure that there are no alerting polcies that depend upon this check.

To delete an uptime check, do the following:

Console

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. Locate the uptime check that you want to edit, then do one of the following:

    • Click More and select Delete.
    • View the uptime check details, and then click Delete

API

Call the projects.uptimeCheckConfigs.delete method. Fill out the parameter as follows:

  • name: Required. This is the resource name of the uptime check configuration to delete:

    projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]
    

    You can get the [UPTIME_CHECK_ID] from the response of a create or list method. The ID isn't shown in the Cloud Console.

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.projectUptimeCheckConfigPath(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"

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

What's next