001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.metrics;
019
020import java.util.Collection;
021import org.apache.hadoop.hbase.testclassification.MetricsTests;
022import org.apache.hadoop.hbase.testclassification.SmallTests;
023import org.apache.hadoop.metrics2.AbstractMetric;
024import org.apache.hadoop.metrics2.MetricsRecord;
025import org.apache.hadoop.metrics2.impl.MetricsExportHelper;
026import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
027import org.junit.jupiter.api.Assertions;
028import org.junit.jupiter.api.Tag;
029import org.junit.jupiter.api.Test;
030
031@Tag(MetricsTests.TAG)
032@Tag(SmallTests.TAG)
033public class TestMetricsExportHelper {
034
035  @Test
036  public void testExportHelper() {
037    DefaultMetricsSystem.initialize("exportHelperTestSystem");
038    DefaultMetricsSystem.instance().start();
039
040    String metricsName = "exportMetricsTestGrp";
041    String gaugeName = "exportMetricsTestGauge";
042    String counterName = "exportMetricsTestCounter";
043
044    BaseSourceImpl baseSource = new BaseSourceImpl(metricsName, "", metricsName, metricsName);
045
046    baseSource.setGauge(gaugeName, 0);
047    baseSource.incCounters(counterName, 1);
048
049    Collection<MetricsRecord> metrics = MetricsExportHelper.export();
050    DefaultMetricsSystem.instance().stop();
051
052    Assertions.assertTrue(metrics.stream().anyMatch(mr -> mr.name().equals(metricsName)));
053    Assertions.assertTrue(contains(metrics, metricsName, gaugeName),
054      gaugeName + " is missing in the export");
055    Assertions.assertTrue(contains(metrics, metricsName, counterName),
056      counterName + " is missing in the export");
057  }
058
059  private boolean contains(Collection<MetricsRecord> metrics, String metricsName,
060    String metricName) {
061    return metrics.stream().filter(mr -> mr.name().equals(metricsName)).anyMatch(mr -> {
062      for (AbstractMetric metric : mr.metrics()) {
063        if (metric.name().equals(metricName)) {
064          return true;
065        }
066      }
067      return false;
068    });
069  }
070}