You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@accumulo.apache.org by GitBox <gi...@apache.org> on 2020/02/27 23:54:03 UTC

[GitHub] [accumulo] EdColeman opened a new pull request #1536: Improve master metrics rported via hadoop metrics

EdColeman opened a new pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536
 
 
   Adds FATE transaction state and op types
   Improves metrics tests
   Add IT to verify that enabling legacy metrics does not crash master

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385875211
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/LegacyMetricsIT.java
 ##########
 @@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Basic functional test to verify enabling legacy metrics does not kill master.
+ */
+public class LegacyMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(LegacyMetricsIT.class);
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 1;
+
+  private long maxWait = 15_000;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "true");
+  }
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Before
+  public void setup() {}
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void useMaster() {
+
+    boolean legacyMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    assertTrue(legacyMetricsEnabled);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
+
+    // use calls that should need the master
+
+    try {
+
+      getConnector().instanceOperations().waitForBalance();
+
+      Map<String,String> configs = getConnector().instanceOperations().getSystemConfiguration();
+      assertTrue("master config should not be empty", !configs.isEmpty());
+
+    } catch (AccumuloException | AccumuloSecurityException ex) {
+      fail("Could not get config from master");
+    }
+
+    // clean-up cancel running compactions
+    for (SlowOps t : tables) {
+      try {
+        getConnector().tableOperations().cancelCompaction(t.getTableName());
+        // block if compaction still running
+        boolean cancelled = t.blockWhileCompactionRunning();
+        if (!cancelled) {
+          log.info("Failed to cancel compaction during multiple compaction test clean-up for {}",
+              t.getTableName());
+        }
+      } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) {
+        log.debug("Exception thrown during multiple table test clean-up", ex);
+      }
+    }
+  }
+
+  /**
+   * Pause for manual testing - allow time to connect with jconsole after launch.
+   *
+   * @param sleep_ms
+   *          sleep duration in milliseconds
+   */
+  private void manual_test_pause(int sleep_ms) {
 
 Review comment:
   Being that I must be the only one that finds these markers helpful for recalling a good place to put a pause for manual testing with jconsole, I've removed the code.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385789086
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/MasterMetricsIT.java
 ##########
 @@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.metrics.MetricsFileTailer;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Functional test that uses a hadoop metrics 2 file sink to read published metrics for
+ * verification.
+ */
+public class MasterMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(MasterMetricsIT.class);
+
+  private static final int NUM_TAIL_ATTEMPTS = 20;
+  private static final long TAIL_DELAY = 5_000;
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 4;
+
+  private long maxWait;
+
+  private static final Set<String> REQUIRED_METRIC_KEYS =
+      new HashSet<>(Arrays.asList("currentFateOps", "totalFateOps", "totalZkConnErrors",
+          "FateTxState_NEW", "FateTxState_IN_PROGRESS", "FateTxState_FAILED_IN_PROGRESS",
+          "FateTxState_FAILED", "FateTxState_SUCCESSFUL", "FateTxState_UNKNOWN"));
+
+  private static final Set<String> OPTIONAL_METRIC_KEYS =
+      new HashSet<>(Collections.singletonList("FateTxOpType_CompactRange"));
+
+  private MetricsFileTailer metricsTail = null;
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "false");
+    cfg.setProperty(Property.MASTER_FATE_METRICS_ENABLED, "true");
+  }
+
+  @Before
+  public void setup() {
+
+    if (testDisabled()) {
+      return;
+    }
+
+    // accumuloClient = Accumulo.newClient().from(getClientProps()).build();
 
 Review comment:
   A glimpse into the future?? Haha

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385763440
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateHadoop2Metrics.java
 ##########
 @@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.accumulo.master.metrics.fate;
+
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.accumulo.server.metrics.Metrics;
+import org.apache.accumulo.server.metrics.MetricsSystemHelper;
+import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
+import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.impl.MsInfo;
+import org.apache.hadoop.metrics2.lib.Interns;
+import org.apache.hadoop.metrics2.lib.MetricsRegistry;
+import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FateHadoop2Metrics implements Metrics, MetricsSource {
+
+  private static final Logger log = LoggerFactory.getLogger(FateHadoop2Metrics.class);
+
+  // limit calls to update fate counters to guard against hammering zookeeper.
+  private static final long DEFAULT_MIN_REFRESH_DELAY = TimeUnit.SECONDS.toMillis(10);
+
+  private volatile long minimumRefreshDelay;
+
+  // metrics tag / labels
+  public static final String NAME = MASTER_NAME + ",sub=Fate";
+  public static final String DESCRIPTION = "Fate Metrics";
+  public static final String CONTEXT = "master";
+  public static final String RECORD = "fate";
+
+  // metric value names
+  public static final String CUR_FATE_OPS = "currentFateOps";
+  public static final String TOTAL_FATE_OPS = "totalFateOps";
+  public static final String TOTAL_ZK_CONN_ERRORS = "totalZkConnErrors";
+  private static final String FATE_TX_STATE_METRIC_PREFIX = "FateTxState_";
+  private static final String FATE_OP_TYPE_METRIC_PREFIX = "FateTxOpType_";
+
+  // metric values
+  private final MutableGaugeLong currentFateOps;
+  private final MutableGaugeLong zkChildFateOpsTotal;
+  private final MutableGaugeLong zkConnectionErrorsTotal;
+  private final Map<String,MutableGaugeLong> fateTypeCounts = new TreeMap<>();
+  private final Map<String,MutableGaugeLong> fateOpCounts = new TreeMap<>();
+
+  private FateMetricSnapshot metricSnapshot;
+
+  private final String instanceId;
+  private final MetricsSystem metricsSystem;
+  private final MetricsRegistry registry;
+
+  private final Lock metricsValuesLock = new ReentrantLock();
+  private volatile long lastUpdate = 0;
+
+  private final ZooReaderWriter zoo;
+
+  public FateHadoop2Metrics(final String instanceId, final MetricsSystem metricsSystem,
+      final long minimumRefreshDelay) {
+
+    this.instanceId = instanceId;
+
+    zoo = ZooReaderWriter.getInstance();
+
+    this.minimumRefreshDelay = Math.max(DEFAULT_MIN_REFRESH_DELAY, minimumRefreshDelay);
+
+    this.metricsSystem = metricsSystem;
+    this.registry = new MetricsRegistry(Interns.info(NAME, DESCRIPTION));
+    this.registry.tag(MsInfo.ProcessName, MetricsSystemHelper.getProcessName());
+
+    currentFateOps = registry.newGauge(CUR_FATE_OPS, "Current number of FATE Ops", 0L);
+    zkChildFateOpsTotal = registry.newGauge(TOTAL_FATE_OPS, "Total FATE Ops", 0L);
+    zkConnectionErrorsTotal =
+        registry.newGauge(TOTAL_ZK_CONN_ERRORS, "Total ZK Connection Errors", 0L);
+
+  }
+
+  /**
+   * For testing only: allow refresh delay to be set to any value, over riding the enforced minimum.
+   *
+   * @param minimumRefreshDelay
+   *          set new min refresh value, in seconds.
+   */
+  void overrideRefresh(final long minimumRefreshDelay) {
+    long delay = Math.max(0, minimumRefreshDelay);
+    this.minimumRefreshDelay = TimeUnit.SECONDS.toMillis(delay);
+  }
+
+  @Override
+  public void register() {
+    metricsSystem.register(NAME, DESCRIPTION, this);
+  }
+
+  @Override
+  public void add(String name, long time) {
+    throw new UnsupportedOperationException("add() is not implemented");
+  }
+
+  @Override
+  public boolean isEnabled() {
+    return true;
+  }
+
+  protected void prepareMetrics() {
+
+    metricsValuesLock.lock();
+    try {
+
+      long now = System.currentTimeMillis();
+
+      if ((lastUpdate + minimumRefreshDelay) < now) {
+
+        log.trace("Update fate metrics, lastUpdate: {}, now {}", lastUpdate, now);
+
+        metricSnapshot = FateMetricSnapshot.getFromZooKeeper(instanceId, zoo);
+        lastUpdate = now;
+
+        recordValues();
+      }
+    } finally {
+      metricsValuesLock.unlock();
+    }
+  }
+
+  /**
+   * Update the metrics gauges from the measured values - this method assumes that concurrent access
+   * is control externally to this method with the metricsValueLock, and that the lock has been
+   * acquired before calling this method.
+   */
+  private void recordValues() {
+
+    // update individual gauges that are reported.
+    currentFateOps.set(metricSnapshot.getCurrentFateOps());
+    zkChildFateOpsTotal.set(metricSnapshot.getZkFateChildOpsTotal());
+    zkConnectionErrorsTotal.set(metricSnapshot.getZkConnectionErrors());
+
+    // the number FATE Tx states (NEW< IN_PROGRESS...) are fixed - the underlying
+    // getTxStateCounters call will return a current valid count for each possible state.
+    Map<String,Long> states = metricSnapshot.getTxStateCounters();
+
+    states.forEach((key, value) -> {
+      MutableGaugeLong v = fateTypeCounts.get(key);
+      if (v != null) {
+        v.set(value);
+      } else {
+        v = registry.newGauge(metricNameHelper(FATE_TX_STATE_METRIC_PREFIX, key),
+            "By transaction state count for " + key, value);
+        fateTypeCounts.put(key, v);
 
 Review comment:
   I think this could be simplified with a ```computeIfAbsent()```

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on issue #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on issue #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#issuecomment-592550667
 
 
   I am taking a look at this pull request but wanted to clarify that these changes are new to both 1.9 and master?  

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385793782
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/MasterMetricsIT.java
 ##########
 @@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.metrics.MetricsFileTailer;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Functional test that uses a hadoop metrics 2 file sink to read published metrics for
+ * verification.
+ */
+public class MasterMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(MasterMetricsIT.class);
+
+  private static final int NUM_TAIL_ATTEMPTS = 20;
+  private static final long TAIL_DELAY = 5_000;
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 4;
+
+  private long maxWait;
+
+  private static final Set<String> REQUIRED_METRIC_KEYS =
+      new HashSet<>(Arrays.asList("currentFateOps", "totalFateOps", "totalZkConnErrors",
+          "FateTxState_NEW", "FateTxState_IN_PROGRESS", "FateTxState_FAILED_IN_PROGRESS",
+          "FateTxState_FAILED", "FateTxState_SUCCESSFUL", "FateTxState_UNKNOWN"));
+
+  private static final Set<String> OPTIONAL_METRIC_KEYS =
+      new HashSet<>(Collections.singletonList("FateTxOpType_CompactRange"));
+
+  private MetricsFileTailer metricsTail = null;
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "false");
+    cfg.setProperty(Property.MASTER_FATE_METRICS_ENABLED, "true");
+  }
+
+  @Before
+  public void setup() {
+
+    if (testDisabled()) {
+      return;
+    }
+
+    // accumuloClient = Accumulo.newClient().from(getClientProps()).build();
+    maxWait = defaultTimeoutSeconds() <= 0 ? 60_000 : ((defaultTimeoutSeconds() * 1000) / 2);
+
+    metricsTail = new MetricsFileTailer("accumulo.sink.file-master");
+    Thread t1 = new Thread(metricsTail);
+    t1.start();
+
+  }
+
+  @After
+  public void cleanup() {
+    if (metricsTail != null) {
+      metricsTail.close();
+    }
+  }
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void metricsPublished() {
+
+    if (testDisabled()) {
+      log.info("Skipping test - master metrics not enabled.");
+      return;
+    }
+
+    // throw away first update - could be from previous test (possible with cluster
+    // restarts in each test)
+    MetricsFileTailer.LineUpdate firstUpdate =
+        metricsTail.waitForUpdate(-1, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    firstUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    Map<String,Long> firstSeenMap = parseLine(firstUpdate.getLine());
+
+    log.debug("Line received: {}", firstUpdate.getLine());
+    log.info("Expected metrics count: {}", REQUIRED_METRIC_KEYS.size());
+    log.info("Received metrics count: {},  values:{}", firstSeenMap.size(), firstSeenMap);
+
+    assertTrue(lookForExpectedKeys(firstSeenMap));
+    sanity(firstSeenMap);
+
+    MetricsFileTailer.LineUpdate nextUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    Map<String,Long> updateSeenMap = parseLine(nextUpdate.getLine());
+
+    log.debug("Line received:{}", nextUpdate.getLine());
+    log.trace("Mapped values:{}", updateSeenMap);
+
+    assertTrue(lookForExpectedKeys(updateSeenMap));
+    sanity(updateSeenMap);
+
+    validate(firstSeenMap, updateSeenMap);
+  }
+
+  /**
+   * Run a few compactions - this should trigger the a dynamic op type to be included in the
+   * metrics.
+   */
+  @Test
+  public void compactionMetrics() {
+
+    if (testDisabled()) {
+      log.info("Skipping test - MASTER_FATE_METRICS_ENABLED is not enabled");
+      return;
+    }
+
+    MetricsFileTailer.LineUpdate firstUpdate =
+        metricsTail.waitForUpdate(-1, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
+
+    // check file tailer here....
+    MetricsFileTailer.LineUpdate nextUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    log.info("Received metrics {}", nextUpdate);
+
+    Map<String,String> results = blockForRequiredTables();
+
+    assertFalse(results.isEmpty());
+    log.info("IN_PROGRESS: {}", results.get("FateTxState_IN_PROGRESS"));
+
+    assertTrue(Long.parseLong(results.get("FateTxState_IN_PROGRESS")) >= tableCount);
+    assertTrue(Long.parseLong(results.get("FateTxOpType_CompactRange")) >= tableCount);
+
+    for (String k : OPTIONAL_METRIC_KEYS) {
+      assertTrue(results.containsKey(k));
+      assertTrue(Long.parseLong(results.get(k)) >= tableCount);
+    }
+
+    manual_test_pause(60_000);
+
+    // clean-up cancel running compactions
+    for (SlowOps t : tables) {
+      try {
+        getConnector().tableOperations().cancelCompaction(t.getTableName());
+        // block if compaction still running
+        boolean cancelled = t.blockWhileCompactionRunning();
+        if (!cancelled) {
+          log.info("Failed to cancel compaction during multiple compaction test clean-up for {}",
+              t.getTableName());
+        }
+      } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) {
+        log.debug("Exception thrown during multiple table test clean-up", ex);
+      }
+    }
+
+    // wait for one more metrics update after compactions cancelled.
+    MetricsFileTailer.LineUpdate update =
+        metricsTail.waitForUpdate(0L, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    metricsTail.waitForUpdate(update.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    results = metricsTail.parseLine("");
+
+    log.info("Received metrics {}", results);
+
+    manual_test_pause(300_000);
+  }
+
+  /**
+   * Pause for manual testing - allow time to connect with jconsole after launch.
+   *
+   * @param sleep_ms
+   *          sleep duration in milliseconds
+   */
+  private void manual_test_pause(int sleep_ms) {
+    if (!PAUSE_FOR_MANUAL_TEST) {
+      return;
+    }
+    try {
+      Thread.sleep(sleep_ms);
+    } catch (InterruptedException ex) {
+      Thread.currentThread().interrupt();
+    }
+  }
+
+  private Map<String,String> blockForRequiredTables() {
+
+    MetricsFileTailer.LineUpdate update =
+        metricsTail.waitForUpdate(0L, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    for (int i = 0; i < 20; i++) {
+
+      update = metricsTail.waitForUpdate(update.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+      log.info("Received metrics update {}", update);
+
+      Map<String,String> results = metricsTail.parseLine("");
+
+      if (results != null && results.size() > 0
+          && Long.parseLong(results.get("currentFateOps")) >= tableCount) {
+        log.info("Found required number of fate operations");
+        return results;
+      }
+      try {
+        Thread.sleep(10_000);
+      } catch (InterruptedException iex) {
+        Thread.currentThread().interrupt();
+        return Collections.emptyMap();
+      }
+
+    }
+    return Collections.emptyMap();
+  }
+
+  /**
+   * Validate metrics for consistency with in a run cycle.
+   *
+   * @param values
+   *          map of values from one run cycle.
+   */
+  private void sanity(final Map<String,Long> values) {
+
+    assertTrue(values.get("currentFateOps") <= values.get("totalFateOps"));
+
+    long total = values.entrySet().stream().filter(x -> x.getKey().startsWith("FateTxState_"))
+        .mapToLong(Map.Entry::getValue).sum();
+
+    assertTrue(total >= values.get("currentFateOps"));
+  }
+
+  /**
+   * A series of sanity checks for the metrics between different update cycles, some values should
+   * be at least different, and some of the checks can include ordering.
+   *
+   * @param firstSeen
+   *          map of first metric update
+   * @param nextSeen
+   *          map of a later metric update.
+   */
+  private void validate(Map<String,Long> firstSeen, Map<String,Long> nextSeen) {
+    // total fate ops should not decrease.
+    log.debug("Total fate ops.  Before:{}, Update:{}", firstSeen.get("totalFateOps"),
+        nextSeen.get("totalFateOps"));
+    assertTrue(firstSeen.get("totalFateOps") <= nextSeen.get("totalFateOps"));
+  }
+
+  /**
+   * The hadoop metrics file sink published records as a line with comma separated key=value pairs.
+   * This method parses the line and extracts the key, value pair from metrics that start with AccGc
+   * and returns them in a sort map.
+   *
+   * @param line
+   *          a line from the metrics system file sink.
+   * @return a map of the metrics that match REQUIRED_METRICS_KEYS
+   */
+  private Map<String,Long> parseLine(final String line) {
+
+    if (line == null) {
+      return Collections.emptyMap();
+    }
+
+    Map<String,Long> m = new TreeMap<>();
+
+    String[] csvTokens = line.split(",");
+
+    for (String token : csvTokens) {
+      token = token.trim();
+      String[] parts = token.split("=");
+      if (REQUIRED_METRIC_KEYS.contains(parts[0])) {
+        m.put(parts[0], Long.parseLong(parts[1]));
+      }
+    }
+    return m;
+  }
+
+  private boolean lookForExpectedKeys(final Map<String,Long> received) {
+
+    for (String e : REQUIRED_METRIC_KEYS) {
+      if (!received.containsKey(e)) {
+        log.info("Couldn't find {}", e);
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  /**
+   * FATE metrics only valid when MASTER_FATE_METRICS_ENABLED=true and GENERAL_LEGACY_METRICS=flase
+   *
+   * @return true if test should run
+   */
+  private boolean testDisabled() {
+
+    boolean fateMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.MASTER_FATE_METRICS_ENABLED);
+
+    boolean useLegacyMetrics =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    if (!fateMetricsEnabled || useLegacyMetrics) {
+
+      log.info("master fate metrics are disabled - MASTER_FATE_METRICS_ENABLED={}, "
+          + "GENERAL_LEGACY_METRICS={}", fateMetricsEnabled, useLegacyMetrics);
 
 Review comment:
   Shouldn't this configuration validation be done in MasterMetricsFactory when the properties are read by the Master?  I didn't see any actual check for this.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385740458
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateLegacyJMXMetricsMBean.java
 ##########
 @@ -16,12 +16,12 @@
  */
 package org.apache.accumulo.master.metrics.fate;
 
-public interface FateMetricsMBean {
+public interface FateLegacyJMXMetricsMBean {
 
 Review comment:
   Since a lot of these legacy classes were removed in 2.x, I am not sure how productive it is to refactor them.  If it helps to differentiate between the legacy and the Hadoop2 metrics then I guess it is ok.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] EdColeman merged pull request #1536: Improve master metrics reported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
EdColeman merged pull request #1536: Improve master metrics reported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536
 
 
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385826753
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateLegacyJMXMetricsMBean.java
 ##########
 @@ -16,12 +16,12 @@
  */
 package org.apache.accumulo.master.metrics.fate;
 
-public interface FateMetricsMBean {
+public interface FateLegacyJMXMetricsMBean {
 
 Review comment:
   This was a rename so that on the merge forward, these JMX specific classes are drooped and hadoop2 metrics classes the can be named FateMetrics.  The interface name needed to change to match the JMX required naming convention

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385786752
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/LegacyMetricsIT.java
 ##########
 @@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Basic functional test to verify enabling legacy metrics does not kill master.
+ */
+public class LegacyMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(LegacyMetricsIT.class);
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 1;
+
+  private long maxWait = 15_000;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "true");
+  }
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Before
+  public void setup() {}
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void useMaster() {
+
+    boolean legacyMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    assertTrue(legacyMetricsEnabled);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
+
+    // use calls that should need the master
+
+    try {
+
+      getConnector().instanceOperations().waitForBalance();
+
+      Map<String,String> configs = getConnector().instanceOperations().getSystemConfiguration();
+      assertTrue("master config should not be empty", !configs.isEmpty());
+
+    } catch (AccumuloException | AccumuloSecurityException ex) {
+      fail("Could not get config from master");
+    }
+
+    // clean-up cancel running compactions
+    for (SlowOps t : tables) {
+      try {
+        getConnector().tableOperations().cancelCompaction(t.getTableName());
+        // block if compaction still running
+        boolean cancelled = t.blockWhileCompactionRunning();
+        if (!cancelled) {
+          log.info("Failed to cancel compaction during multiple compaction test clean-up for {}",
+              t.getTableName());
+        }
+      } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) {
+        log.debug("Exception thrown during multiple table test clean-up", ex);
+      }
+    }
+  }
+
+  /**
+   * Pause for manual testing - allow time to connect with jconsole after launch.
+   *
+   * @param sleep_ms
+   *          sleep duration in milliseconds
+   */
+  private void manual_test_pause(int sleep_ms) {
 
 Review comment:
   Method is unused.  You could always call it in the test since you are checking the boolean.  You could also make the one in MastMetricsIT static to reuse it between the ITs and pass in the boolean.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385787252
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/LegacyMetricsIT.java
 ##########
 @@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Basic functional test to verify enabling legacy metrics does not kill master.
+ */
+public class LegacyMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(LegacyMetricsIT.class);
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 1;
+
+  private long maxWait = 15_000;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "true");
+  }
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Before
+  public void setup() {}
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void useMaster() {
+
+    boolean legacyMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    assertTrue(legacyMetricsEnabled);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
 
 Review comment:
   Do you need the SlowOps to just verify Master is up and running?  Seems like this would just make the IT run longer.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385763791
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateHadoop2Metrics.java
 ##########
 @@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.accumulo.master.metrics.fate;
+
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.accumulo.server.metrics.Metrics;
+import org.apache.accumulo.server.metrics.MetricsSystemHelper;
+import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
+import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.impl.MsInfo;
+import org.apache.hadoop.metrics2.lib.Interns;
+import org.apache.hadoop.metrics2.lib.MetricsRegistry;
+import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FateHadoop2Metrics implements Metrics, MetricsSource {
+
+  private static final Logger log = LoggerFactory.getLogger(FateHadoop2Metrics.class);
+
+  // limit calls to update fate counters to guard against hammering zookeeper.
+  private static final long DEFAULT_MIN_REFRESH_DELAY = TimeUnit.SECONDS.toMillis(10);
+
+  private volatile long minimumRefreshDelay;
+
+  // metrics tag / labels
+  public static final String NAME = MASTER_NAME + ",sub=Fate";
+  public static final String DESCRIPTION = "Fate Metrics";
+  public static final String CONTEXT = "master";
+  public static final String RECORD = "fate";
+
+  // metric value names
+  public static final String CUR_FATE_OPS = "currentFateOps";
+  public static final String TOTAL_FATE_OPS = "totalFateOps";
+  public static final String TOTAL_ZK_CONN_ERRORS = "totalZkConnErrors";
+  private static final String FATE_TX_STATE_METRIC_PREFIX = "FateTxState_";
+  private static final String FATE_OP_TYPE_METRIC_PREFIX = "FateTxOpType_";
+
+  // metric values
+  private final MutableGaugeLong currentFateOps;
+  private final MutableGaugeLong zkChildFateOpsTotal;
+  private final MutableGaugeLong zkConnectionErrorsTotal;
+  private final Map<String,MutableGaugeLong> fateTypeCounts = new TreeMap<>();
+  private final Map<String,MutableGaugeLong> fateOpCounts = new TreeMap<>();
+
+  private FateMetricSnapshot metricSnapshot;
+
+  private final String instanceId;
+  private final MetricsSystem metricsSystem;
+  private final MetricsRegistry registry;
+
+  private final Lock metricsValuesLock = new ReentrantLock();
+  private volatile long lastUpdate = 0;
+
+  private final ZooReaderWriter zoo;
+
+  public FateHadoop2Metrics(final String instanceId, final MetricsSystem metricsSystem,
+      final long minimumRefreshDelay) {
+
+    this.instanceId = instanceId;
+
+    zoo = ZooReaderWriter.getInstance();
+
+    this.minimumRefreshDelay = Math.max(DEFAULT_MIN_REFRESH_DELAY, minimumRefreshDelay);
+
+    this.metricsSystem = metricsSystem;
+    this.registry = new MetricsRegistry(Interns.info(NAME, DESCRIPTION));
+    this.registry.tag(MsInfo.ProcessName, MetricsSystemHelper.getProcessName());
+
+    currentFateOps = registry.newGauge(CUR_FATE_OPS, "Current number of FATE Ops", 0L);
+    zkChildFateOpsTotal = registry.newGauge(TOTAL_FATE_OPS, "Total FATE Ops", 0L);
+    zkConnectionErrorsTotal =
+        registry.newGauge(TOTAL_ZK_CONN_ERRORS, "Total ZK Connection Errors", 0L);
+
+  }
+
+  /**
+   * For testing only: allow refresh delay to be set to any value, over riding the enforced minimum.
+   *
+   * @param minimumRefreshDelay
+   *          set new min refresh value, in seconds.
+   */
+  void overrideRefresh(final long minimumRefreshDelay) {
+    long delay = Math.max(0, minimumRefreshDelay);
+    this.minimumRefreshDelay = TimeUnit.SECONDS.toMillis(delay);
+  }
+
+  @Override
+  public void register() {
+    metricsSystem.register(NAME, DESCRIPTION, this);
+  }
+
+  @Override
+  public void add(String name, long time) {
+    throw new UnsupportedOperationException("add() is not implemented");
+  }
+
+  @Override
+  public boolean isEnabled() {
+    return true;
+  }
+
+  protected void prepareMetrics() {
+
+    metricsValuesLock.lock();
+    try {
+
+      long now = System.currentTimeMillis();
+
+      if ((lastUpdate + minimumRefreshDelay) < now) {
+
+        log.trace("Update fate metrics, lastUpdate: {}, now {}", lastUpdate, now);
+
+        metricSnapshot = FateMetricSnapshot.getFromZooKeeper(instanceId, zoo);
+        lastUpdate = now;
+
+        recordValues();
+      }
+    } finally {
+      metricsValuesLock.unlock();
+    }
+  }
+
+  /**
+   * Update the metrics gauges from the measured values - this method assumes that concurrent access
+   * is control externally to this method with the metricsValueLock, and that the lock has been
+   * acquired before calling this method.
+   */
+  private void recordValues() {
+
+    // update individual gauges that are reported.
+    currentFateOps.set(metricSnapshot.getCurrentFateOps());
+    zkChildFateOpsTotal.set(metricSnapshot.getZkFateChildOpsTotal());
+    zkConnectionErrorsTotal.set(metricSnapshot.getZkConnectionErrors());
+
+    // the number FATE Tx states (NEW< IN_PROGRESS...) are fixed - the underlying
+    // getTxStateCounters call will return a current valid count for each possible state.
+    Map<String,Long> states = metricSnapshot.getTxStateCounters();
+
+    states.forEach((key, value) -> {
+      MutableGaugeLong v = fateTypeCounts.get(key);
+      if (v != null) {
+        v.set(value);
+      } else {
+        v = registry.newGauge(metricNameHelper(FATE_TX_STATE_METRIC_PREFIX, key),
+            "By transaction state count for " + key, value);
+        fateTypeCounts.put(key, v);
+      }
+    });
+
+    // the op types are dynamic and the metric gauges generated when first seen. After
+    // that the values need to be cleared and set any new values present. This is so
+    // that the metrics system will report "known" values once seen. In operation, the
+    // number of types will be a fairly small set and should populate with normal operations.
+
+    // clear current values.
+    fateOpCounts.forEach((key, value) -> value.set(0));
+
+    // update new counts, create new gauge if first time seen.
+    Map<String,Long> opTypes = metricSnapshot.getOpTypeCounters();
+
+    log.trace("OP Counts Before: prev {}, updates {}", fateOpCounts, opTypes);
+
+    opTypes.forEach((key, value) -> {
+      MutableGaugeLong g = fateOpCounts.get(key);
+      if (g != null) {
+        g.set(value);
+      } else {
+        g = registry.newGauge(metricNameHelper(FATE_OP_TYPE_METRIC_PREFIX, key),
+            "By transaction op type count for " + key, value);
+        fateOpCounts.put(key, g);
 
 Review comment:
   I think this could be simplified with a ```computeIfAbsent()```

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385740458
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateLegacyJMXMetricsMBean.java
 ##########
 @@ -16,12 +16,12 @@
  */
 package org.apache.accumulo.master.metrics.fate;
 
-public interface FateMetricsMBean {
+public interface FateLegacyJMXMetricsMBean {
 
 Review comment:
   Since a lot of these legacy classes were removed in 2.x, I am not sure how productive it is to refactor them.  Ff it helps to differentiate between the legacy and the Hadoop2 metrics then I guess it is ok.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385740801
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateMetricSnapshot.java
 ##########
 @@ -0,0 +1,250 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.accumulo.master.metrics.fate;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.StringJoiner;
+import java.util.TreeMap;
+
+import org.apache.accumulo.core.Constants;
+import org.apache.accumulo.core.zookeeper.ZooUtil;
+import org.apache.accumulo.fate.AdminUtil;
+import org.apache.accumulo.fate.ReadOnlyTStore;
+import org.apache.accumulo.fate.ZooStore;
+import org.apache.accumulo.fate.zookeeper.ZooReaderWriter;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Immutable class that holds a snapshot of fate metric values - use builder to instantiate
+ * instance.
+ */
+class FateMetricSnapshot {
+
+  private static final Logger log = LoggerFactory.getLogger(FateLegacyJMXMetrics.class);
 
 Review comment:
   Logger name is wrong.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385874365
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/MasterMetricsIT.java
 ##########
 @@ -0,0 +1,372 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.metrics.MetricsFileTailer;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Functional test that uses a hadoop metrics 2 file sink to read published metrics for
+ * verification.
+ */
+public class MasterMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(MasterMetricsIT.class);
+
+  private static final int NUM_TAIL_ATTEMPTS = 20;
+  private static final long TAIL_DELAY = 5_000;
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 4;
+
+  private long maxWait;
+
+  private static final Set<String> REQUIRED_METRIC_KEYS =
+      new HashSet<>(Arrays.asList("currentFateOps", "totalFateOps", "totalZkConnErrors",
+          "FateTxState_NEW", "FateTxState_IN_PROGRESS", "FateTxState_FAILED_IN_PROGRESS",
+          "FateTxState_FAILED", "FateTxState_SUCCESSFUL", "FateTxState_UNKNOWN"));
+
+  private static final Set<String> OPTIONAL_METRIC_KEYS =
+      new HashSet<>(Collections.singletonList("FateTxOpType_CompactRange"));
+
+  private MetricsFileTailer metricsTail = null;
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "false");
+    cfg.setProperty(Property.MASTER_FATE_METRICS_ENABLED, "true");
+  }
+
+  @Before
+  public void setup() {
+
+    if (testDisabled()) {
+      return;
+    }
+
+    // accumuloClient = Accumulo.newClient().from(getClientProps()).build();
+    maxWait = defaultTimeoutSeconds() <= 0 ? 60_000 : ((defaultTimeoutSeconds() * 1000) / 2);
+
+    metricsTail = new MetricsFileTailer("accumulo.sink.file-master");
+    Thread t1 = new Thread(metricsTail);
+    t1.start();
+
+  }
+
+  @After
+  public void cleanup() {
+    if (metricsTail != null) {
+      metricsTail.close();
+    }
+  }
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void metricsPublished() {
+
+    if (testDisabled()) {
+      log.info("Skipping test - master metrics not enabled.");
+      return;
+    }
+
+    // throw away first update - could be from previous test (possible with cluster
+    // restarts in each test)
+    MetricsFileTailer.LineUpdate firstUpdate =
+        metricsTail.waitForUpdate(-1, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    firstUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    Map<String,Long> firstSeenMap = parseLine(firstUpdate.getLine());
+
+    log.debug("Line received: {}", firstUpdate.getLine());
+    log.info("Expected metrics count: {}", REQUIRED_METRIC_KEYS.size());
+    log.info("Received metrics count: {},  values:{}", firstSeenMap.size(), firstSeenMap);
+
+    assertTrue(lookForExpectedKeys(firstSeenMap));
+    sanity(firstSeenMap);
+
+    MetricsFileTailer.LineUpdate nextUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    Map<String,Long> updateSeenMap = parseLine(nextUpdate.getLine());
+
+    log.debug("Line received:{}", nextUpdate.getLine());
+    log.trace("Mapped values:{}", updateSeenMap);
+
+    assertTrue(lookForExpectedKeys(updateSeenMap));
+    sanity(updateSeenMap);
+
+    validate(firstSeenMap, updateSeenMap);
+  }
+
+  /**
+   * Run a few compactions - this should trigger the a dynamic op type to be included in the
+   * metrics.
+   */
+  @Test
+  public void compactionMetrics() {
+
+    if (testDisabled()) {
+      log.info("Skipping test - MASTER_FATE_METRICS_ENABLED is not enabled");
+      return;
+    }
+
+    MetricsFileTailer.LineUpdate firstUpdate =
+        metricsTail.waitForUpdate(-1, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
+
+    // check file tailer here....
+    MetricsFileTailer.LineUpdate nextUpdate =
+        metricsTail.waitForUpdate(firstUpdate.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    log.info("Received metrics {}", nextUpdate);
+
+    Map<String,String> results = blockForRequiredTables();
+
+    assertFalse(results.isEmpty());
+    log.info("IN_PROGRESS: {}", results.get("FateTxState_IN_PROGRESS"));
+
+    assertTrue(Long.parseLong(results.get("FateTxState_IN_PROGRESS")) >= tableCount);
+    assertTrue(Long.parseLong(results.get("FateTxOpType_CompactRange")) >= tableCount);
+
+    for (String k : OPTIONAL_METRIC_KEYS) {
+      assertTrue(results.containsKey(k));
+      assertTrue(Long.parseLong(results.get(k)) >= tableCount);
+    }
+
+    manual_test_pause(60_000);
+
+    // clean-up cancel running compactions
+    for (SlowOps t : tables) {
+      try {
+        getConnector().tableOperations().cancelCompaction(t.getTableName());
+        // block if compaction still running
+        boolean cancelled = t.blockWhileCompactionRunning();
+        if (!cancelled) {
+          log.info("Failed to cancel compaction during multiple compaction test clean-up for {}",
+              t.getTableName());
+        }
+      } catch (AccumuloSecurityException | TableNotFoundException | AccumuloException ex) {
+        log.debug("Exception thrown during multiple table test clean-up", ex);
+      }
+    }
+
+    // wait for one more metrics update after compactions cancelled.
+    MetricsFileTailer.LineUpdate update =
+        metricsTail.waitForUpdate(0L, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    metricsTail.waitForUpdate(update.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    results = metricsTail.parseLine("");
+
+    log.info("Received metrics {}", results);
+
+    manual_test_pause(300_000);
+  }
+
+  /**
+   * Pause for manual testing - allow time to connect with jconsole after launch.
+   *
+   * @param sleep_ms
+   *          sleep duration in milliseconds
+   */
+  private void manual_test_pause(int sleep_ms) {
+    if (!PAUSE_FOR_MANUAL_TEST) {
+      return;
+    }
+    try {
+      Thread.sleep(sleep_ms);
+    } catch (InterruptedException ex) {
+      Thread.currentThread().interrupt();
+    }
+  }
+
+  private Map<String,String> blockForRequiredTables() {
+
+    MetricsFileTailer.LineUpdate update =
+        metricsTail.waitForUpdate(0L, NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+    for (int i = 0; i < 20; i++) {
+
+      update = metricsTail.waitForUpdate(update.getLastUpdate(), NUM_TAIL_ATTEMPTS, TAIL_DELAY);
+
+      log.info("Received metrics update {}", update);
+
+      Map<String,String> results = metricsTail.parseLine("");
+
+      if (results != null && results.size() > 0
+          && Long.parseLong(results.get("currentFateOps")) >= tableCount) {
+        log.info("Found required number of fate operations");
+        return results;
+      }
+      try {
+        Thread.sleep(10_000);
+      } catch (InterruptedException iex) {
+        Thread.currentThread().interrupt();
+        return Collections.emptyMap();
+      }
+
+    }
+    return Collections.emptyMap();
+  }
+
+  /**
+   * Validate metrics for consistency with in a run cycle.
+   *
+   * @param values
+   *          map of values from one run cycle.
+   */
+  private void sanity(final Map<String,Long> values) {
+
+    assertTrue(values.get("currentFateOps") <= values.get("totalFateOps"));
+
+    long total = values.entrySet().stream().filter(x -> x.getKey().startsWith("FateTxState_"))
+        .mapToLong(Map.Entry::getValue).sum();
+
+    assertTrue(total >= values.get("currentFateOps"));
+  }
+
+  /**
+   * A series of sanity checks for the metrics between different update cycles, some values should
+   * be at least different, and some of the checks can include ordering.
+   *
+   * @param firstSeen
+   *          map of first metric update
+   * @param nextSeen
+   *          map of a later metric update.
+   */
+  private void validate(Map<String,Long> firstSeen, Map<String,Long> nextSeen) {
+    // total fate ops should not decrease.
+    log.debug("Total fate ops.  Before:{}, Update:{}", firstSeen.get("totalFateOps"),
+        nextSeen.get("totalFateOps"));
+    assertTrue(firstSeen.get("totalFateOps") <= nextSeen.get("totalFateOps"));
+  }
+
+  /**
+   * The hadoop metrics file sink published records as a line with comma separated key=value pairs.
+   * This method parses the line and extracts the key, value pair from metrics that start with AccGc
+   * and returns them in a sort map.
+   *
+   * @param line
+   *          a line from the metrics system file sink.
+   * @return a map of the metrics that match REQUIRED_METRICS_KEYS
+   */
+  private Map<String,Long> parseLine(final String line) {
+
+    if (line == null) {
+      return Collections.emptyMap();
+    }
+
+    Map<String,Long> m = new TreeMap<>();
+
+    String[] csvTokens = line.split(",");
+
+    for (String token : csvTokens) {
+      token = token.trim();
+      String[] parts = token.split("=");
+      if (REQUIRED_METRIC_KEYS.contains(parts[0])) {
+        m.put(parts[0], Long.parseLong(parts[1]));
+      }
+    }
+    return m;
+  }
+
+  private boolean lookForExpectedKeys(final Map<String,Long> received) {
+
+    for (String e : REQUIRED_METRIC_KEYS) {
+      if (!received.containsKey(e)) {
+        log.info("Couldn't find {}", e);
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+  /**
+   * FATE metrics only valid when MASTER_FATE_METRICS_ENABLED=true and GENERAL_LEGACY_METRICS=flase
+   *
+   * @return true if test should run
+   */
+  private boolean testDisabled() {
+
+    boolean fateMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.MASTER_FATE_METRICS_ENABLED);
+
+    boolean useLegacyMetrics =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    if (!fateMetricsEnabled || useLegacyMetrics) {
+
+      log.info("master fate metrics are disabled - MASTER_FATE_METRICS_ENABLED={}, "
+          + "GENERAL_LEGACY_METRICS={}", fateMetricsEnabled, useLegacyMetrics);
 
 Review comment:
   The tests are only valid with hadoop2 metrics - this prevents test failures if legancy metrics were enabled during the testing.  Added a warning if legacy metrics are enabled that additional FATE metrics added by this PR will not be available.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385908955
 
 

 ##########
 File path: test/src/main/java/org/apache/accumulo/test/functional/LegacyMetricsIT.java
 ##########
 @@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.test.functional;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.accumulo.core.client.AccumuloException;
+import org.apache.accumulo.core.client.AccumuloSecurityException;
+import org.apache.accumulo.core.client.TableNotFoundException;
+import org.apache.accumulo.core.conf.Property;
+import org.apache.accumulo.harness.AccumuloClusterHarness;
+import org.apache.accumulo.minicluster.impl.MiniAccumuloConfigImpl;
+import org.apache.accumulo.test.util.SlowOps;
+import org.apache.hadoop.conf.Configuration;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Basic functional test to verify enabling legacy metrics does not kill master.
+ */
+public class LegacyMetricsIT extends AccumuloClusterHarness {
+
+  private static final Logger log = LoggerFactory.getLogger(LegacyMetricsIT.class);
+
+  // number of tables / concurrent compactions used during testing.
+  private final int tableCount = 1;
+
+  private long maxWait = 15_000;
+
+  @Override
+  public void configureMiniCluster(MiniAccumuloConfigImpl cfg, Configuration hadoopCoreSite) {
+    cfg.setProperty(Property.GENERAL_LEGACY_METRICS, "true");
+  }
+
+  /**
+   * MANUAL TESTS ONLY - forces pause to allow jconsole connection
+   */
+  private final boolean PAUSE_FOR_MANUAL_TEST = false;
+
+  @Before
+  public void setup() {}
+
+  @Override
+  protected int defaultTimeoutSeconds() {
+    return 4 * 60;
+  }
+
+  /**
+   * Validates that the expected metrics are published - this excludes the dynamic metrics derived
+   * from operation types.
+   */
+  @Test
+  public void useMaster() {
+
+    boolean legacyMetricsEnabled =
+        cluster.getSiteConfiguration().getBoolean(Property.GENERAL_LEGACY_METRICS);
+
+    assertTrue(legacyMetricsEnabled);
+
+    List<SlowOps> tables = new ArrayList<>();
+
+    for (int i = 0; i < tableCount; i++) {
+      String uniqueName = getUniqueNames(1)[0] + "_" + i;
+      SlowOps gen = new SlowOps(getConnector(), uniqueName, maxWait, tableCount);
+      tables.add(gen);
+      gen.startCompactTask();
+    }
 
 Review comment:
   Changed to use table create / delete so master / tablets did have some work required.  The compaction only ran for a short while, but create/delete should be quicker.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [accumulo] milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics

Posted by GitBox <gi...@apache.org>.
milleruntime commented on a change in pull request #1536: Improve master metrics rported via hadoop metrics
URL: https://github.com/apache/accumulo/pull/1536#discussion_r385756204
 
 

 ##########
 File path: server/master/src/main/java/org/apache/accumulo/master/metrics/fate/FateHadoop2Metrics.java
 ##########
 @@ -0,0 +1,218 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.accumulo.master.metrics.fate;
+
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.accumulo.server.metrics.Metrics;
+import org.apache.accumulo.server.metrics.MetricsSystemHelper;
+import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
+import org.apache.hadoop.metrics2.MetricsCollector;
+import org.apache.hadoop.metrics2.MetricsRecordBuilder;
+import org.apache.hadoop.metrics2.MetricsSource;
+import org.apache.hadoop.metrics2.MetricsSystem;
+import org.apache.hadoop.metrics2.impl.MsInfo;
+import org.apache.hadoop.metrics2.lib.Interns;
+import org.apache.hadoop.metrics2.lib.MetricsRegistry;
+import org.apache.hadoop.metrics2.lib.MutableGaugeLong;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FateHadoop2Metrics implements Metrics, MetricsSource {
+
+  private static final Logger log = LoggerFactory.getLogger(FateHadoop2Metrics.class);
+
+  // limit calls to update fate counters to guard against hammering zookeeper.
+  private static final long DEFAULT_MIN_REFRESH_DELAY = TimeUnit.SECONDS.toMillis(10);
+
+  private volatile long minimumRefreshDelay;
+
+  // metrics tag / labels
+  public static final String NAME = MASTER_NAME + ",sub=Fate";
+  public static final String DESCRIPTION = "Fate Metrics";
+  public static final String CONTEXT = "master";
+  public static final String RECORD = "fate";
+
+  // metric value names
+  public static final String CUR_FATE_OPS = "currentFateOps";
+  public static final String TOTAL_FATE_OPS = "totalFateOps";
+  public static final String TOTAL_ZK_CONN_ERRORS = "totalZkConnErrors";
+  private static final String FATE_TX_STATE_METRIC_PREFIX = "FateTxState_";
+  private static final String FATE_OP_TYPE_METRIC_PREFIX = "FateTxOpType_";
+
+  // metric values
+  private final MutableGaugeLong currentFateOps;
+  private final MutableGaugeLong zkChildFateOpsTotal;
+  private final MutableGaugeLong zkConnectionErrorsTotal;
+  private final Map<String,MutableGaugeLong> fateTypeCounts = new TreeMap<>();
+  private final Map<String,MutableGaugeLong> fateOpCounts = new TreeMap<>();
+
+  private FateMetricSnapshot metricSnapshot;
+
+  private final String instanceId;
+  private final MetricsSystem metricsSystem;
+  private final MetricsRegistry registry;
+
+  private final Lock metricsValuesLock = new ReentrantLock();
+  private volatile long lastUpdate = 0;
+
+  private final ZooReaderWriter zoo;
+
+  public FateHadoop2Metrics(final String instanceId, final MetricsSystem metricsSystem,
+      final long minimumRefreshDelay) {
+
+    this.instanceId = instanceId;
+
+    zoo = ZooReaderWriter.getInstance();
+
+    this.minimumRefreshDelay = Math.max(DEFAULT_MIN_REFRESH_DELAY, minimumRefreshDelay);
+
+    this.metricsSystem = metricsSystem;
+    this.registry = new MetricsRegistry(Interns.info(NAME, DESCRIPTION));
+    this.registry.tag(MsInfo.ProcessName, MetricsSystemHelper.getProcessName());
+
+    currentFateOps = registry.newGauge(CUR_FATE_OPS, "Current number of FATE Ops", 0L);
+    zkChildFateOpsTotal = registry.newGauge(TOTAL_FATE_OPS, "Total FATE Ops", 0L);
+    zkConnectionErrorsTotal =
+        registry.newGauge(TOTAL_ZK_CONN_ERRORS, "Total ZK Connection Errors", 0L);
+
+  }
+
+  /**
+   * For testing only: allow refresh delay to be set to any value, over riding the enforced minimum.
+   *
+   * @param minimumRefreshDelay
+   *          set new min refresh value, in seconds.
+   */
+  void overrideRefresh(final long minimumRefreshDelay) {
+    long delay = Math.max(0, minimumRefreshDelay);
+    this.minimumRefreshDelay = TimeUnit.SECONDS.toMillis(delay);
+  }
+
+  @Override
+  public void register() {
+    metricsSystem.register(NAME, DESCRIPTION, this);
+  }
+
+  @Override
+  public void add(String name, long time) {
+    throw new UnsupportedOperationException("add() is not implemented");
+  }
+
+  @Override
+  public boolean isEnabled() {
+    return true;
+  }
+
+  protected void prepareMetrics() {
+
+    metricsValuesLock.lock();
+    try {
+
+      long now = System.currentTimeMillis();
+
+      if ((lastUpdate + minimumRefreshDelay) < now) {
+
+        log.trace("Update fate metrics, lastUpdate: {}, now {}", lastUpdate, now);
+
+        metricSnapshot = FateMetricSnapshot.getFromZooKeeper(instanceId, zoo);
+        lastUpdate = now;
+
+        recordValues();
+      }
+    } finally {
+      metricsValuesLock.unlock();
+    }
+  }
+
+  /**
+   * Update the metrics gauges from the measured values - this method assumes that concurrent access
+   * is control externally to this method with the metricsValueLock, and that the lock has been
 
 Review comment:
   Javadoc typo.  

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services