com.google.monitoring.v3.ProjectName Java Examples

The following examples show how to use com.google.monitoring.v3.ProjectName. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void restoreRevisedPolicies(
    String projectId, boolean isSameProject, List<AlertPolicy> policies) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    for (AlertPolicy policy : policies) {
      if (!isSameProject) {
        policy = client.createAlertPolicy(ProjectName.of(projectId), policy);
      } else {
        try {
          client.updateAlertPolicy(null, policy);
        } catch (Exception e) {
          policy =
              client.createAlertPolicy(
                  ProjectName.of(projectId), policy.toBuilder().clearName().build());
        }
      }
      System.out.println(String.format("Restored %s", policy.getName()));
    }
  }
}
 
Example #2
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Returns the first page of all metric descriptors. */
void listMetricDescriptors() throws IOException {
  // [START monitoring_list_descriptors]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  final MetricServiceClient client = MetricServiceClient.create();
  ProjectName name = ProjectName.of(projectId);

  ListMetricDescriptorsRequest request =
      ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();
  ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);

  System.out.println("Listing descriptors: ");

  for (MetricDescriptor d : response.iterateAll()) {
    System.out.println(d.getName() + " " + d.getDisplayName());
  }
  // [END monitoring_list_descriptors]
}
 
Example #3
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Gets all monitored resource descriptors. */
void listMonitoredResources() throws IOException {
  // [START monitoring_list_resources]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  final MetricServiceClient client = MetricServiceClient.create();
  ProjectName name = ProjectName.of(projectId);

  ListMonitoredResourceDescriptorsRequest request =
      ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build();

  System.out.println("Listing monitored resource descriptors: ");

  ListMonitoredResourceDescriptorsPagedResponse response =
      client.listMonitoredResourceDescriptors(request);

  for (MonitoredResourceDescriptor d : response.iterateAll()) {
    System.out.println(d.getType());
  }
  // [END monitoring_list_resources]
}
 
Example #4
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static void listAlertPolicies(String projectId) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId));

    System.out.println("Alert Policies:");
    for (AlertPolicy policy : response.iterateAll()) {
      System.out.println(
          String.format("\nPolicy %s\nalert-id: %s", policy.getDisplayName(), policy.getName()));
      int channels = policy.getNotificationChannelsCount();
      if (channels > 0) {
        System.out.println("notification-channels:");
        for (int i = 0; i < channels; i++) {
          System.out.println("\t" + policy.getNotificationChannels(i));
        }
      }
      if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) {
        System.out.println(policy.getDocumentation().getContent());
      }
    }
  }
}
 
Example #5
Source File: UptimeSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #6
Source File: CreateTimeSeriesExporter.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
CreateTimeSeriesExporter(
    String projectId,
    MetricServiceClient metricServiceClient,
    MonitoredResource monitoredResource,
    @javax.annotation.Nullable String metricNamePrefix,
    Map<LabelKey, LabelValue> constantLabels) {
  projectName = ProjectName.newBuilder().setProject(projectId).build();
  this.metricServiceClient = metricServiceClient;
  this.monitoredResource = monitoredResource;
  this.domain = StackdriverExportUtils.getDomain(metricNamePrefix);
  this.constantLabels = constantLabels;
}
 
Example #7
Source File: MetricScaler.java    From cloud-bigtable-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for the auto-scaler with the minimum required information: project and instance ids.
 * @param projectId
 * @param instanceId
 * @throws GeneralSecurityException
 * @throws IOException
 */
public MetricScaler(String projectId, String instanceId)
    throws GeneralSecurityException, IOException {
  clusterUtility = BigtableClusterUtilities.forInstance(projectId, instanceId);
  Cluster cluster = clusterUtility.getSingleCluster();
  this.clusterId = new BigtableClusterName(cluster.getName()).getClusterId();
  this.zoneId = BigtableClusterUtilities.getZoneId(cluster);
  // Instantiates a client
  metricServiceClient = MetricServiceClient.create();
  projectName = ProjectName.create(projectId);
}
 
Example #8
Source File: MonitoringServlet.java    From tomcat-runtime with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  JsonNode body = objectMapper.readTree(req.getReader());
  String name = body.path("name").asText();
  long token = body.path("token").asLong();

  logger.info("Creating Time series with name " + name + " and token " + token);

  MetricServiceClient serviceClient = MetricServiceClient.create();

  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .addPoints(Point.newBuilder()
              .setValue(TypedValue.newBuilder().setInt64Value(token))
              .setInterval(TimeInterval.newBuilder()
                .setEndTime(Timestamp.now().toProto())))
          .setMetric(Metric.newBuilder().setType(name))
          .build();

  serviceClient.createTimeSeries(
      ProjectName.create(ServiceOptions.getDefaultProjectId()),
      Collections.singletonList(timeSeries));

  resp.setContentType("text/plain");
  resp.getWriter().println("OK");
}
 
Example #9
Source File: DeleteNotificationChannelIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws IOException {
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    String projectId = getProjectId();
    NOTIFICATION_CHANNEL =
        NotificationChannel.newBuilder()
            .setType("email")
            .putLabels("email_address", "[email protected]")
            .build();
    NotificationChannel channel =
        client.createNotificationChannel(ProjectName.of(projectId), NOTIFICATION_CHANNEL);
    NOTIFICATION_CHANNEL_NAME = channel.getName();
  }
}
 
Example #10
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void enablePolicies(String projectId, String filter, boolean enable)
    throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response =
        client.listAlertPolicies(
            ListAlertPoliciesRequest.newBuilder()
                .setName(ProjectName.of(projectId).toString())
                .setFilter(filter)
                .build());

    for (AlertPolicy policy : response.iterateAll()) {
      if (policy.getEnabled().getValue() == enable) {
        System.out.println(
            String.format(
                "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
        continue;
      }
      AlertPolicy updatedPolicy =
          AlertPolicy.newBuilder()
              .setName(policy.getName())
              .setEnabled(BoolValue.newBuilder().setValue(enable))
              .build();
      AlertPolicy result =
          client.updateAlertPolicy(
              FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
      System.out.println(
          String.format(
              "%s %s",
              result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
    }
  }
}
 
Example #11
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}
 
Example #12
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static List<NotificationChannel> getNotificationChannels(String projectId)
    throws IOException {
  List<NotificationChannel> notificationChannels = Lists.newArrayList();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    ListNotificationChannelsPagedResponse listNotificationChannelsResponse =
        client.listNotificationChannels(ProjectName.of(projectId));
    for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) {
      notificationChannels.add(channel);
    }
  }
  return notificationChannels;
}
 
Example #13
Source File: AlertSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static List<AlertPolicy> getAlertPolicies(String projectId) throws IOException {
  List<AlertPolicy> alertPolicies = Lists.newArrayList();
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId));

    for (AlertPolicy policy : response.iterateAll()) {
      alertPolicies.add(policy);
    }
  }
  return alertPolicies;
}
 
Example #14
Source File: UptimeSample.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void listUptimeChecks(String projectId) throws IOException {
  ListUptimeCheckConfigsRequest request =
      ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request);
    for (UptimeCheckConfig config : response.iterateAll()) {
      System.out.println(config.getDisplayName());
    }
  } catch (Exception e) {
    usage("Exception listing uptime checks: " + e.toString());
    throw e;
  }
}
 
Example #15
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series and aggregating and reducing them. */
void listTimeSeriesReduce() throws IOException {
  // [START monitoring_read_timeseries_reduce]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  Aggregation aggregation =
      Aggregation.newBuilder()
          .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
          .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
          .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_reduce]
}
 
Example #16
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series and aggregating them. */
void listTimeSeriesAggregrate() throws IOException {
  // [START monitoring_read_timeseries_align]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  Aggregation aggregation =
      Aggregation.newBuilder()
          .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
          .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setAggregation(aggregation);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_align]
}
 
Example #17
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series using a filter. */
void listTimeSeries(String filter) throws IOException {
  // [START monitoring_read_timeseries_simple]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter(filter)
          .setInterval(interval);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_simple]
}
 
Example #18
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Demonstrates listing time series headers. */
void listTimeSeriesHeaders() throws IOException {
  // [START monitoring_read_timeseries_fields]
  MetricServiceClient metricServiceClient = MetricServiceClient.create();
  String projectId = System.getProperty("projectId");
  ProjectName name = ProjectName.of(projectId);

  // Restrict time to last 20 minutes
  long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setStartTime(Timestamps.fromMillis(startMillis))
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();

  ListTimeSeriesRequest.Builder requestBuilder =
      ListTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
          .setInterval(interval)
          .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);

  ListTimeSeriesRequest request = requestBuilder.build();

  ListTimeSeriesPagedResponse response = metricServiceClient.listTimeSeries(request);

  System.out.println("Got timeseries headers: ");
  for (TimeSeries ts : response.iterateAll()) {
    System.out.println(ts);
  }
  // [END monitoring_read_timeseries_fields]
}
 
Example #19
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a metric descriptor.
 *
 * <p>See:
 * https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create
 *
 * @param type The metric type
 */
void createMetricDescriptor(String type) throws IOException {
  // [START monitoring_create_metric]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");
  String metricType = CUSTOM_METRIC_DOMAIN + "/" + type;

  final MetricServiceClient client = MetricServiceClient.create();
  ProjectName name = ProjectName.of(projectId);

  MetricDescriptor descriptor =
      MetricDescriptor.newBuilder()
          .setType(metricType)
          .addLabels(
              LabelDescriptor.newBuilder()
                  .setKey("store_id")
                  .setValueType(LabelDescriptor.ValueType.STRING))
          .setDescription("This is a simple example of a custom metric.")
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .build();

  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(name.toString())
          .setMetricDescriptor(descriptor)
          .build();

  client.createMetricDescriptor(request);
  // [END monitoring_create_metric]
}
 
Example #20
Source File: CreateMetricDescriptorExporter.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
CreateMetricDescriptorExporter(
    String projectId,
    MetricServiceClient metricServiceClient,
    @javax.annotation.Nullable String metricNamePrefix,
    Map<LabelKey, LabelValue> constantLabels,
    MetricExporter nextExporter) {
  this.projectId = projectId;
  projectName = ProjectName.newBuilder().setProject(projectId).build();
  this.metricServiceClient = metricServiceClient;
  this.domain = StackdriverExportUtils.getDomain(metricNamePrefix);
  this.displayNamePrefix = StackdriverExportUtils.getDisplayNamePrefix(metricNamePrefix);
  this.constantLabels = constantLabels;
  this.nextExporter = nextExporter;
}
 
Example #21
Source File: QuickstartSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception {
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  if (projectId == null) {
    System.err.println("Usage: QuickstartSample -DprojectId=YOUR_PROJECT_ID");
    return;
  }

  // Instantiates a client
  MetricServiceClient metricServiceClient = MetricServiceClient.create();

  // Prepares an individual data point
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();
  TypedValue value = TypedValue.newBuilder().setDoubleValue(3.14).build();
  Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

  List<Point> pointList = new ArrayList<>();
  pointList.add(point);

  ProjectName name = ProjectName.of(projectId);

  // Prepares the metric descriptor
  Map<String, String> metricLabels = new HashMap<String, String>();
  metricLabels.put("store_id", "Pittsburg");
  Metric metric =
      Metric.newBuilder()
          .setType("custom.googleapis.com/my_metric")
          .putAllLabels(metricLabels)
          .build();

  // Prepares the monitored resource descriptor
  Map<String, String> resourceLabels = new HashMap<String, String>();
  resourceLabels.put("instance_id", "1234567890123456789");
  resourceLabels.put("zone", "us-central1-f");
  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

  // Prepares the time series request
  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .setMetric(metric)
          .setResource(resource)
          .addAllPoints(pointList)
          .build();
  List<TimeSeries> timeSeriesList = new ArrayList<>();
  timeSeriesList.add(timeSeries);

  CreateTimeSeriesRequest request =
      CreateTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .addAllTimeSeries(timeSeriesList)
          .build();

  // Writes time series data
  metricServiceClient.createTimeSeries(request);

  System.out.printf("Done writing time series data.%n");

  metricServiceClient.close();
}
 
Example #22
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Demonstrates writing a time series value for the metric type
 * 'custom.google.apis.com/my_metric'.
 *
 * <p>This method assumes `my_metric` descriptor has already been created as a DOUBLE value_type
 * and GAUGE metric kind. If the metric descriptor doesn't exist, it will be auto-created.
 */
// CHECKSTYLE OFF: VariableDeclarationUsageDistance
void writeTimeSeries() throws IOException {
  // [START monitoring_write_timeseries]
  String projectId = System.getProperty("projectId");
  // Instantiates a client
  MetricServiceClient metricServiceClient = MetricServiceClient.create();

  // Prepares an individual data point
  TimeInterval interval =
      TimeInterval.newBuilder()
          .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
          .build();
  TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
  Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

  List<Point> pointList = new ArrayList<>();
  pointList.add(point);

  ProjectName name = ProjectName.of(projectId);

  // Prepares the metric descriptor
  Map<String, String> metricLabels = new HashMap<>();
  Metric metric =
      Metric.newBuilder()
          .setType("custom.googleapis.com/my_metric")
          .putAllLabels(metricLabels)
          .build();

  // Prepares the monitored resource descriptor
  Map<String, String> resourceLabels = new HashMap<>();
  resourceLabels.put("instance_id", "1234567890123456789");
  resourceLabels.put("zone", "us-central1-f");

  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

  // Prepares the time series request
  TimeSeries timeSeries =
      TimeSeries.newBuilder()
          .setMetric(metric)
          .setResource(resource)
          .addAllPoints(pointList)
          .build();

  List<TimeSeries> timeSeriesList = new ArrayList<>();
  timeSeriesList.add(timeSeries);

  CreateTimeSeriesRequest request =
      CreateTimeSeriesRequest.newBuilder()
          .setName(name.toString())
          .addAllTimeSeries(timeSeriesList)
          .build();

  // Writes time series data
  metricServiceClient.createTimeSeries(request);
  System.out.println("Done writing time series value.");
  // [END monitoring_write_timeseries]
}
 
Example #23
Source File: MonitoringService.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 4 votes vote down vote up
private void flush() {
  HashMap<IMonitoringEvent, Long> flushEvents = null;
  synchronized (aggregateEvents) {
    flushEvents = new HashMap<>(aggregateEvents);
    aggregateEvents.clear();
  }

  try {
    Timestamp flushTime = Timestamps.fromMillis(System.currentTimeMillis());

    List<TimeSeries> timeSeriesList = new ArrayList<>();
    for (IMonitoringEvent event : monitoredEvents) {
      TimeInterval interval = TimeInterval.newBuilder()
          .setEndTime(flushTime)
          .build();
      TypedValue value = TypedValue.newBuilder()
          .setInt64Value(flushEvents.getOrDefault(event, 0L))
          .build();
      Point point = Point.newBuilder()
          .setInterval(interval)
          .setValue(value)
          .build();

      List<Point> pointList = new ArrayList<>();
      pointList.add(point);

      Metric metric = Metric.newBuilder()
          .setType(event.getMetricName())
          .build();

      TimeSeries timeSeries = TimeSeries.newBuilder()
          .setMetric(metric)
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setResource(monitoredResource)
          .addAllPoints(pointList)
          .build();

      timeSeriesList.add(timeSeries);
    }

    ProjectName projectName = ProjectName.of(projectId);
    CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
        .setName(projectName.toString())
        .addAllTimeSeries(timeSeriesList)
        .build();

    client.createTimeSeries(request);

    log.trace("Flushed {} non-zero time series", flushEvents.size());
    if (flushEvents.size() > 0) {
      log.info("Flushed: {}", flushEvents);
    }
  } catch (Throwable e) {
    log.error("Failed to flush time series", e);
  }
}