Java Code Examples for com.google.cloud.monitoring.v3.MetricServiceClient#create()

The following examples show how to use com.google.cloud.monitoring.v3.MetricServiceClient#create() . 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: ClearCustomMetricDescriptors.java    From micrometer with Apache License 2.0 6 votes vote down vote up
public static void clearCustomMetricDescriptors(MetricServiceSettings settings, String projectId) {
    try {
        MetricServiceClient client = MetricServiceClient.create(settings);

        Iterable<MetricServiceClient.ListMetricDescriptorsPage> listMetricDescriptorsPages = client.listMetricDescriptors(ListMetricDescriptorsRequest.newBuilder()
                .setName("projects/" + projectId)
                .setFilter("metric.type = starts_with(\"custom.googleapis.com/\")")
                .build()).iteratePages();

        int deleted = 0;
        for (MetricServiceClient.ListMetricDescriptorsPage page : listMetricDescriptorsPages) {
            for (MetricDescriptor metricDescriptor : page.getValues()) {
                System.out.println("deleting " + metricDescriptor.getName());
                client.deleteMetricDescriptor(metricDescriptor.getName());
                deleted++;
            }
        }

        System.out.println("Deleted " + deleted + " custom metric descriptors");
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 2
Source File: BigQueryRunnerTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  bout = new ByteArrayOutputStream();
  PrintStream out = new PrintStream(bout);

  MetricServiceClient metricsClient = MetricServiceClient.create(metricsServiceStub);
  app = new BigQueryRunner(metricsClient, BigQueryOptions.getDefaultInstance().getService(), out);

  when(metricsServiceStub.listMetricDescriptorsPagedCallable()).thenReturn(listCallable);
  when(listCallable.call(any(ListMetricDescriptorsRequest.class))).thenReturn(listResponse);
  when(listResponse.iterateAll()).thenReturn(Collections.EMPTY_LIST);

  when(metricsServiceStub.createMetricDescriptorCallable()).thenReturn(createMetricCallable);
  when(createMetricCallable.call(any(CreateMetricDescriptorRequest.class))).thenReturn(null);

  when(metricsServiceStub.createTimeSeriesCallable()).thenReturn(createTimeSeriesCallable);
  when(createTimeSeriesCallable.call(any(CreateTimeSeriesRequest.class)))
      .thenReturn(Empty.getDefaultInstance());
}
 
Example 3
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 4
Source File: StackdriverStatsExporter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@GuardedBy("monitor")
@VisibleForTesting
static MetricServiceClient createMetricServiceClient(
    @Nullable Credentials credentials, Duration deadline) throws IOException {
  MetricServiceSettings.Builder settingsBuilder =
      MetricServiceSettings.newBuilder()
          .setTransportChannelProvider(
              InstantiatingGrpcChannelProvider.newBuilder()
                  .setHeaderProvider(OPENCENSUS_USER_AGENT_HEADER_PROVIDER)
                  .build());
  if (credentials != null) {
    settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
  }

  org.threeten.bp.Duration stackdriverDuration =
      org.threeten.bp.Duration.ofMillis(deadline.toMillis());
  // We use createMetricDescriptor and createTimeSeries APIs in this exporter.
  settingsBuilder.createMetricDescriptorSettings().setSimpleTimeoutNoRetries(stackdriverDuration);
  settingsBuilder.createTimeSeriesSettings().setSimpleTimeoutNoRetries(stackdriverDuration);

  return MetricServiceClient.create(settingsBuilder.build());
}
 
Example 5
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 6
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 7
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Gets full information for a monitored resource.
 *
 * @param type The resource type
 */
void describeMonitoredResources(String type) throws IOException {
  // [START monitoring_get_descriptor]
  // Your Google Cloud Platform project ID
  String projectId = System.getProperty("projectId");

  final MetricServiceClient client = MetricServiceClient.create();
  MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.of(projectId, type);
  MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name);

  System.out.println("Printing monitored resource descriptor: ");
  System.out.println(response);
  // [END monitoring_get_descriptor]
}
 
Example 8
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
void getMonitoredResource(String resourceId) throws IOException {
  String projectId = System.getProperty("projectId");
  MetricServiceClient client = MetricServiceClient.create();
  MonitoredResourceDescriptorName name =
      MonitoredResourceDescriptorName.of(projectId, resourceId);
  MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name);
  System.out.println("Retrieved Monitored Resource: " + gson.toJson(response));
}
 
Example 9
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 10
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 11
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 12
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 13
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 14
Source File: Snippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Delete a metric descriptor.
 *
 * @param name Name of metric descriptor to delete
 */
void deleteMetricDescriptor(String name) throws IOException {
  // [START monitoring_delete_metric]
  String projectId = System.getProperty("projectId");
  final MetricServiceClient client = MetricServiceClient.create();
  MetricDescriptorName metricName = MetricDescriptorName.of(projectId, name);
  client.deleteMetricDescriptor(metricName);
  System.out.println("Deleted descriptor " + name);
  // [END monitoring_delete_metric]
}
 
Example 15
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 16
Source File: StackdriverMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
public void start(ThreadFactory threadFactory) {
    if (config.enabled()) {
        if (metricServiceSettings == null) {
            logger.error("unable to start stackdriver, service settings are not available");
        } else {
            try {
                this.client = MetricServiceClient.create(metricServiceSettings);
                super.start(threadFactory);
            } catch (Exception e) {
                logger.error("unable to create stackdriver client", e);
            }
        }
    }
}
 
Example 17
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 18
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 19
Source File: BigQueryRunner.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
private BigQueryRunner() throws IOException {
  this(
      MetricServiceClient.create(),
      BigQueryOptions.getDefaultInstance().getService(),
      System.out);
}
 
Example 20
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);
}