Managing uptime checks

Cloud Monitoring can verify the availability of your service by accessing it from locations around the world. You can use the results from these uptime checks in your alerting policies, or you can directly monitor the results 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.

You might also be interested in the following:

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. The default configuration of an uptime check doesn't include authentication. You can enable authentication using the Advanced options.

    For HTTP and HTTPS, the uptime check issues a GET command and retrieves the raw data. If the GET 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, two conditions must be met:

    • The HTTP status is Success.
    • The data has no required content or the required content is present. Required content is specified using the Advanced options.

Creating an uptime check

This section explains how to create and configure uptime checks.

Console

  1. In the Cloud Console, select Monitoring:

    Go to Monitoring

  2. Click Uptime checks.

  3. Click Create Uptime check.

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

    Create an uptime check dialog.

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

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

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

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

    Uptime check created dialog.

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 new uptime check. The fields in the object are explained in the Basic options and Advanced options sections on this page.

    Leave the name field of the configuration object blank as it is set in the returned configuration object.

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

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

To create a new uptime check, you specify values for the uptime check's configuration. When creating the uptime check in the Cloud Console, you fill in a form. When creating the uptime check in the API, you supply the corresponding parameters to 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 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. Complete the connection information, depending on your check type and resource type:

    • If you select a Check type of TCP, then complete the following:

      • 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.
      • Replace Response content with a string (max 1024 bytes).
    • If you select a Resource type of URL or App Engine, then do the following:

      • Hostname: Enter the service's host name. For example, enter example.com.

      • Path (HTTP, HTTPS): Enter a path within your host or resource or use the default path. For example, to probe example.com, leave this field blank. To probe example.com/tester, enter /tester. Don't include the prefix example.com. In the API, leave this field blank to use the default value, /.

    • If you select a Resource type of Elastic Load Balancer or Instance, then do the following:

      • Applies to: Select Single or Group. 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.

      • Path (HTTP, HTTPS): Enter a path within your host or resource or use the default path.

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

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.

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

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

Editing an uptime check

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

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

Before deleting an uptime check, remove the check from any alerting policies that use it. If you don't remove the uptime check, you can't delete the uptime check through the Monitoring console. If you delete the uptime check through the API, the alerting policy ignores the missing uptime check. The policy doesn't create an incident for the missing 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 Google 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/v3"

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