com.google.api.MonitoredResource Java Examples

The following examples show how to use com.google.api.MonitoredResource. 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: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static void createInternal(
    @Nullable Credentials credentials,
    String projectId,
    Duration exportInterval,
    MonitoredResource monitoredResource,
    @Nullable String metricNamePrefix,
    Map<LabelKey, LabelValue> constantLabels,
    Duration deadline,
    @Nullable MetricServiceStub stub)
    throws IOException {
  synchronized (monitor) {
    checkState(instance == null, "Stackdriver stats exporter is already created.");
    MetricServiceClient client =
        stub == null
            ? createMetricServiceClient(credentials, deadline)
            : MetricServiceClient.create(stub);
    instance =
        new StackdriverStatsExporter(
            projectId,
            client,
            exportInterval,
            monitoredResource,
            metricNamePrefix,
            constantLabels);
  }
}
 
Example #2
Source File: UptimeSample.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #3
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 #4
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void setResourceForBuilder_GcpInstanceType() {
  MonitoredResource.Builder monitoredResourceBuilder = DEFAULT_RESOURCE_WITH_PROJECT_ID.clone();
  Map<String, String> resourceLabels = new HashMap<String, String>();
  resourceLabels.put(CloudResource.ACCOUNT_ID_KEY, "proj1");
  resourceLabels.put(CloudResource.PROVIDER_KEY, CloudResource.PROVIDER_GCP);
  resourceLabels.put(HostResource.ID_KEY, "inst1");
  resourceLabels.put(CloudResource.ZONE_KEY, "zone1");
  resourceLabels.put("extra_key", "must be ignored");
  Map<String, String> expectedResourceLabels = new HashMap<String, String>();
  expectedResourceLabels.put("project_id", "proj1");
  expectedResourceLabels.put("instance_id", "inst1");
  expectedResourceLabels.put("zone", "zone1");
  Resource resource = Resource.create(HostResource.TYPE, resourceLabels);

  StackdriverExportUtils.setResourceForBuilder(monitoredResourceBuilder, resource);

  assertThat(monitoredResourceBuilder.getType()).isNotNull();
  assertThat(monitoredResourceBuilder.getLabelsMap()).isNotEmpty();
  assertThat(monitoredResourceBuilder.getType()).isEqualTo("gce_instance");
  assertThat(monitoredResourceBuilder.getLabelsMap().size()).isEqualTo(3);
  assertThat(monitoredResourceBuilder.getLabelsMap())
      .containsExactlyEntriesIn(expectedResourceLabels);
}
 
Example #5
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createTimeSeriesList_withCustomMonitoredResource() {
  MonitoredResource resource =
      MonitoredResource.newBuilder().setType("global").putLabels("key", "value").build();
  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          METRIC, resource, CUSTOM_OPENCENSUS_DOMAIN, PROJECT_ID, DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList)
      .containsExactly(
          TimeSeries.newBuilder()
              .setMetricKind(MetricKind.CUMULATIVE)
              .setValueType(MetricDescriptor.ValueType.DOUBLE)
              .setMetric(
                  StackdriverExportUtils.createMetric(
                      METRIC_DESCRIPTOR,
                      LABEL_VALUE,
                      CUSTOM_OPENCENSUS_DOMAIN,
                      DEFAULT_CONSTANT_LABELS))
              .setResource(resource)
              .addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2))
              .build());
}
 
Example #6
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createTimeSeriesList_Cumulative() {
  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          METRIC,
          DEFAULT_RESOURCE,
          CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList).hasSize(1);
  TimeSeries expectedTimeSeries =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.CUMULATIVE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  METRIC_DESCRIPTOR,
                  LABEL_VALUE,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2))
          .build();
  assertThat(timeSeriesList).containsExactly(expectedTimeSeries);
}
 
Example #7
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static MonitoredResource getDefaultResource() {
  MonitoredResource.Builder builder = MonitoredResource.newBuilder();
  // Populate internal resource label for defaulting project_id label.
  // This allows stats from other projects (e.g from GAE running in another project) to be
  // collected.
  if (MetadataConfig.getProjectId() != null) {
    builder.putLabels(STACKDRIVER_PROJECT_ID_KEY, MetadataConfig.getProjectId());
  }

  Resource autoDetectedResource = ResourceUtils.detectResource();
  if (autoDetectedResource == null || autoDetectedResource.getType() == null) {
    builder.setType(GLOBAL);
    return builder.build();
  }

  setResourceForBuilder(builder, autoDetectedResource);
  return builder.build();
}
 
Example #8
Source File: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private StackdriverStatsExporter(
    String projectId,
    MetricServiceClient metricServiceClient,
    Duration exportInterval,
    MonitoredResource monitoredResource,
    @Nullable String metricNamePrefix,
    Map<LabelKey, LabelValue> constantLabels) {
  IntervalMetricReader.Options.Builder intervalMetricReaderOptionsBuilder =
      IntervalMetricReader.Options.builder();
  intervalMetricReaderOptionsBuilder.setExportInterval(exportInterval);
  intervalMetricReader =
      IntervalMetricReader.create(
          new CreateMetricDescriptorExporter(
              projectId,
              metricServiceClient,
              metricNamePrefix,
              constantLabels,
              new CreateTimeSeriesExporter(
                  projectId,
                  metricServiceClient,
                  monitoredResource,
                  metricNamePrefix,
                  constantLabels)),
          MetricReader.create(
              MetricReader.Options.builder()
                  .setMetricProducerManager(
                      Metrics.getExportComponent().getMetricProducerManager())
                  .setSpanName(EXPORTER_SPAN_NAME)
                  .build()),
          intervalMetricReaderOptionsBuilder.build());
}
 
Example #9
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
static List<TimeSeries> createTimeSeriesList(
    io.opencensus.metrics.export.Metric metric,
    MonitoredResource monitoredResource,
    String domain,
    String projectId,
    Map<LabelKey, LabelValue> constantLabels) {
  List<TimeSeries> timeSeriesList = Lists.newArrayList();
  io.opencensus.metrics.export.MetricDescriptor metricDescriptor = metric.getMetricDescriptor();

  if (!projectId.equals(cachedProjectIdForExemplar)) {
    cachedProjectIdForExemplar = projectId;
  }

  // Shared fields for all TimeSeries generated from the same Metric
  TimeSeries.Builder shared = TimeSeries.newBuilder();
  shared.setMetricKind(createMetricKind(metricDescriptor.getType()));
  shared.setResource(monitoredResource);
  shared.setValueType(createValueType(metricDescriptor.getType()));

  // Each entry in timeSeriesList will be converted into an independent TimeSeries object
  for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) {
    // TODO(mayurkale): Consider using setPoints instead of builder clone and addPoints.
    TimeSeries.Builder builder = shared.clone();
    builder.setMetric(
        createMetric(metricDescriptor, timeSeries.getLabelValues(), domain, constantLabels));

    io.opencensus.common.Timestamp startTimeStamp = timeSeries.getStartTimestamp();
    for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) {
      builder.addPoints(createPoint(point, startTimeStamp));
    }
    timeSeriesList.add(builder.build());
  }
  return timeSeriesList;
}
 
Example #10
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 #11
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void setResourceForBuilder_K8sInstanceType() {
  MonitoredResource.Builder monitoredResourceBuilder = DEFAULT_RESOURCE_WITH_PROJECT_ID.clone();
  Map<String, String> resourceLabels = new HashMap<String, String>();
  resourceLabels.put(CloudResource.ZONE_KEY, "zone1");
  resourceLabels.put(HostResource.ID_KEY, "instance1");
  resourceLabels.put(K8sResource.CLUSTER_NAME_KEY, "cluster1");
  resourceLabels.put(ContainerResource.NAME_KEY, "container1");
  resourceLabels.put(K8sResource.NAMESPACE_NAME_KEY, "namespace1");
  resourceLabels.put(K8sResource.POD_NAME_KEY, "pod1");
  resourceLabels.put("extra_key", "must be ignored");
  Map<String, String> expectedResourceLabels = new HashMap<String, String>();
  expectedResourceLabels.put("project_id", "proj1");
  expectedResourceLabels.put("location", "zone1");
  expectedResourceLabels.put("cluster_name", "cluster1");
  expectedResourceLabels.put("namespace_name", "namespace1");
  expectedResourceLabels.put("pod_name", "pod1");
  expectedResourceLabels.put("container_name", "container1");
  Resource resource = Resource.create(ContainerResource.TYPE, resourceLabels);

  StackdriverExportUtils.setResourceForBuilder(monitoredResourceBuilder, resource);

  assertThat(monitoredResourceBuilder.getType()).isNotNull();
  assertThat(monitoredResourceBuilder.getLabelsMap()).isNotEmpty();
  assertThat(monitoredResourceBuilder.getType()).isEqualTo("k8s_container");
  assertThat(monitoredResourceBuilder.getLabelsMap().size()).isEqualTo(6);
  assertThat(monitoredResourceBuilder.getLabelsMap())
      .containsExactlyEntriesIn(expectedResourceLabels);
}
 
Example #12
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void setResourceForBuilder_AwsInstanceType() {
  MonitoredResource.Builder monitoredResourceBuilder = DEFAULT_RESOURCE_WITH_PROJECT_ID.clone();
  Map<String, String> resourceLabels = new HashMap<String, String>();
  resourceLabels.put(CloudResource.REGION_KEY, "region1");
  resourceLabels.put(CloudResource.PROVIDER_KEY, CloudResource.PROVIDER_AWS);
  resourceLabels.put(CloudResource.ACCOUNT_ID_KEY, "account1");
  resourceLabels.put(HostResource.ID_KEY, "instance1");
  resourceLabels.put("extra_key", "must be ignored");
  Map<String, String> expectedResourceLabels = new HashMap<String, String>();
  expectedResourceLabels.put("project_id", "proj1");
  expectedResourceLabels.put("instance_id", "instance1");
  expectedResourceLabels.put(
      "region", StackdriverExportUtils.AWS_REGION_VALUE_PREFIX + "region1");
  expectedResourceLabels.put("aws_account", "account1");

  Resource resource = Resource.create(HostResource.TYPE, resourceLabels);

  StackdriverExportUtils.setResourceForBuilder(monitoredResourceBuilder, resource);

  assertThat(monitoredResourceBuilder.getType()).isNotNull();
  assertThat(monitoredResourceBuilder.getLabelsMap()).isNotEmpty();
  assertThat(monitoredResourceBuilder.getType()).isEqualTo("aws_ec2_instance");
  assertThat(monitoredResourceBuilder.getLabelsMap().size()).isEqualTo(4);
  assertThat(monitoredResourceBuilder.getLabelsMap())
      .containsExactlyEntriesIn(expectedResourceLabels);
}
 
Example #13
Source File: StackdriverMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private TimeSeries createTimeSeries(Meter.Id id, TypedValue typedValue, MetricDescriptor.ValueType valueType,
                                    @Nullable String statistic) {
    if (client != null)
        createMetricDescriptorIfNecessary(client, id, valueType, statistic);

    String metricType = metricType(id, statistic);

    Map<String, String> metricLabels = getConventionTags(id).stream()
            .collect(Collectors.toMap(Tag::getKey, Tag::getValue));

    return TimeSeries.newBuilder()
            .setMetric(Metric.newBuilder()
                    .setType(metricType)
                    .putAllLabels(metricLabels)
                    .build())
            .setResource(MonitoredResource.newBuilder()
                    .setType(config.resourceType())
                    .putLabels("project_id", config.projectId())
                    .putAllLabels(config.resourceLabels())
                    .build())
            .setMetricKind(MetricDescriptor.MetricKind.GAUGE) // https://cloud.google.com/monitoring/api/v3/metrics-details#metric-kinds
            .setValueType(valueType)
            .addPoints(Point.newBuilder()
                    .setInterval(interval)
                    .setValue(typedValue)
                    .build())
            .build();
}
 
Example #14
Source File: StackdriverExportUtils.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static void setResourceForBuilder(
    MonitoredResource.Builder builder, Resource autoDetectedResource) {
  String type = autoDetectedResource.getType();
  if (type == null) {
    return;
  }
  String sdType = GLOBAL;

  Map<String, String> mappings = null;
  if (HostResource.TYPE.equals(type)) {
    String provider = autoDetectedResource.getLabels().get(CloudResource.PROVIDER_KEY);
    if (CloudResource.PROVIDER_GCP.equals(provider)) {
      sdType = GCP_GCE_INSTANCE;
      mappings = GCP_RESOURCE_MAPPING;
    } else if (CloudResource.PROVIDER_AWS.equals(provider)) {
      sdType = AWS_EC2_INSTANCE;
      mappings = AWS_RESOURCE_MAPPING;
    }
  } else if (ContainerResource.TYPE.equals(type)) {
    sdType = K8S_CONTAINER;
    mappings = K8S_RESOURCE_MAPPING;
  }

  builder.setType(sdType);

  if (GLOBAL.equals(sdType) || mappings == null) {
    return;
  }

  Map<String, String> resLabels = autoDetectedResource.getLabels();
  for (Map.Entry<String, String> entry : mappings.entrySet()) {
    if (entry.getValue() != null && resLabels.containsKey(entry.getValue())) {
      String resourceLabelKey = entry.getKey();
      String resourceLabelValue = resLabels.get(entry.getValue());
      if (AWS_EC2_INSTANCE.equals(sdType) && "region".equals(resourceLabelKey)) {
        // Add "aws:" prefix to AWS EC2 region label. This is Stackdriver specific requirement.
        resourceLabelValue = AWS_REGION_VALUE_PREFIX + resourceLabelValue;
      }
      builder.putLabels(resourceLabelKey, resourceLabelValue);
    }
  }
}
 
Example #15
Source File: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a Stackdriver Stats exporter with an explicit project ID and a custom Monitored
 * Resource.
 *
 * <p>Only one Stackdriver exporter can be created.
 *
 * <p>Please refer to cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource
 * for a list of valid {@code MonitoredResource}s.
 *
 * <p>This uses the default application credentials. See {@link
 * GoogleCredentials#getApplicationDefault}.
 *
 * @param projectId the cloud project id.
 * @param exportInterval the interval between pushing stats to StackDriver.
 * @param monitoredResource the Monitored Resource used by exporter.
 * @throws IllegalStateException if a Stackdriver exporter is already created.
 * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}.
 * @since 0.10
 */
@Deprecated
public static void createAndRegisterWithProjectIdAndMonitoredResource(
    String projectId, Duration exportInterval, MonitoredResource monitoredResource)
    throws IOException {
  checkNotNull(projectId, "projectId");
  checkNotNull(exportInterval, "exportInterval");
  checkNotNull(monitoredResource, "monitoredResource");
  createInternal(
      null,
      projectId,
      exportInterval,
      monitoredResource,
      null,
      DEFAULT_CONSTANT_LABELS,
      DEFAULT_DEADLINE,
      null);
}
 
Example #16
Source File: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a Stackdriver Stats exporter with a custom Monitored Resource.
 *
 * <p>Only one Stackdriver exporter can be created.
 *
 * <p>Please refer to cloud.google.com/monitoring/custom-metrics/creating-metrics#which-resource
 * for a list of valid {@code MonitoredResource}s.
 *
 * <p>This uses the default application credentials. See {@link
 * GoogleCredentials#getApplicationDefault}.
 *
 * <p>This uses the default project ID configured see {@link ServiceOptions#getDefaultProjectId}.
 *
 * @param exportInterval the interval between pushing stats to StackDriver.
 * @param monitoredResource the Monitored Resource used by exporter.
 * @throws IllegalStateException if a Stackdriver exporter is already created.
 * @deprecated in favor of {@link #createAndRegister(StackdriverStatsConfiguration)}.
 * @since 0.10
 */
@Deprecated
public static void createAndRegisterWithMonitoredResource(
    Duration exportInterval, MonitoredResource monitoredResource) throws IOException {
  checkNotNull(exportInterval, "exportInterval");
  checkNotNull(monitoredResource, "monitoredResource");
  checkArgument(
      !DEFAULT_PROJECT_ID.isEmpty(), "Cannot find a project ID from application default.");
  createInternal(
      null,
      DEFAULT_PROJECT_ID,
      exportInterval,
      monitoredResource,
      null,
      DEFAULT_CONSTANT_LABELS,
      DEFAULT_DEADLINE,
      null);
}
 
Example #17
Source File: MonitoringService.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 4 votes vote down vote up
private MonitoringService(String projectId, IMonitoringEvent[] monitoredEvents,
    HttpRequestFactory requestFactory) throws IOException {
  client = MetricServiceClient.create();

  aggregateEvents = new HashMap<>();

  this.projectId = projectId;
  this.monitoredEvents = monitoredEvents;

  // configure Resource
  MonitoredResource.Builder resourceBuilder = MonitoredResource.newBuilder();
  Map<String, String> resourceLabels = new HashMap<>();
  resourceLabels.put("project_id", this.projectId);

  Map<String, String> env = System.getenv();
  String podName = env.get("ENV_POD_NAME");
  String namespaceName = env.get("ENV_POD_NAMESPACE");
  String containerName = env.get("ENV_CONTAINER_NAME");
  String clusterName = GcpMetadataUtil.get(requestFactory, META_CLUSTER_NAME);
  String location = GcpMetadataUtil.get(requestFactory, META_LOCATION);
  if (location != null) {
    // GCPMetadata returns locations as "projects/[NUMERIC_PROJECT_ID]/zones/[ZONE]"
    // Only last part is necessary here.
    location = location.substring(location.lastIndexOf('/') + 1);
  }

  if (podName != null && namespaceName != null && containerName != null &&
      clusterName != null && location != null) {
    resourceLabels.put("pod_name", podName);
    resourceLabels.put("namespace_name", namespaceName);
    resourceLabels.put("container_name", containerName);
    resourceLabels.put("cluster_name", clusterName);
    resourceLabels.put("location", location);
    resourceBuilder.setType("k8s_container");
  } else {
    resourceBuilder.setType("global");
  }

  this.monitoredResource = resourceBuilder.putAllLabels(resourceLabels).build();
  log.info("monitoredResource = {}", monitoredResource);

  service = Executors.newSingleThreadScheduledExecutor();
  service.scheduleWithFixedDelay(MonitoringService.this::flush,
      DELAY, DELAY, TimeUnit.SECONDS);
}
 
Example #18
Source File: StackdriverExportUtilsTest.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createTimeSeriesList_Gauge() {
  io.opencensus.metrics.export.Metric metric =
      io.opencensus.metrics.export.Metric.create(
          GAUGE_METRIC_DESCRIPTOR, Arrays.asList(GAUGE_TIME_SERIES, GAUGE_TIME_SERIES_2));

  List<TimeSeries> timeSeriesList =
      StackdriverExportUtils.createTimeSeriesList(
          metric,
          DEFAULT_RESOURCE,
          CUSTOM_OPENCENSUS_DOMAIN,
          PROJECT_ID,
          DEFAULT_CONSTANT_LABELS);
  assertThat(timeSeriesList).hasSize(2);
  TimeSeries expected1 =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  GAUGE_METRIC_DESCRIPTOR,
                  LABEL_VALUE,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT, null))
          .build();
  TimeSeries expected2 =
      TimeSeries.newBuilder()
          .setMetricKind(MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .setMetric(
              StackdriverExportUtils.createMetric(
                  GAUGE_METRIC_DESCRIPTOR,
                  LABEL_VALUE_2,
                  CUSTOM_OPENCENSUS_DOMAIN,
                  DEFAULT_CONSTANT_LABELS))
          .setResource(MonitoredResource.newBuilder().setType("global"))
          .addPoints(StackdriverExportUtils.createPoint(POINT_2, null))
          .build();
  assertThat(timeSeriesList).containsExactly(expected1, expected2);
}
 
Example #19
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 #20
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 #21
Source File: StackdriverStatsConfiguration.java    From opencensus-java with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the {@link MonitoredResource}.
 *
 * @param monitoredResource the Stackdriver {@code MonitoredResource}.
 * @return this.
 * @since 0.11
 */
public abstract Builder setMonitoredResource(MonitoredResource monitoredResource);
 
Example #22
Source File: StackdriverStatsConfiguration.java    From opencensus-java with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the Stackdriver {@link MonitoredResource}.
 *
 * @return the {@code MonitoredResource}.
 * @since 0.11
 */
public abstract MonitoredResource getMonitoredResource();